babylon.max.js 2.8 MB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842268432684426845268462684726848268492685026851268522685326854268552685626857268582685926860268612686226863268642686526866268672686826869268702687126872268732687426875268762687726878268792688026881268822688326884268852688626887268882688926890268912689226893268942689526896268972689826899269002690126902269032690426905269062690726908269092691026911269122691326914269152691626917269182691926920269212692226923269242692526926269272692826929269302693126932269332693426935269362693726938269392694026941269422694326944269452694626947269482694926950269512695226953269542695526956269572695826959269602696126962269632696426965269662696726968269692697026971269722697326974269752697626977269782697926980269812698226983269842698526986269872698826989269902699126992269932699426995269962699726998269992700027001270022700327004270052700627007270082700927010270112701227013270142701527016270172701827019270202702127022270232702427025270262702727028270292703027031270322703327034270352703627037270382703927040270412704227043270442704527046270472704827049270502705127052270532705427055270562705727058270592706027061270622706327064270652706627067270682706927070270712707227073270742707527076270772707827079270802708127082270832708427085270862708727088270892709027091270922709327094270952709627097270982709927100271012710227103271042710527106271072710827109271102711127112271132711427115271162711727118271192712027121271222712327124271252712627127271282712927130271312713227133271342713527136271372713827139271402714127142271432714427145271462714727148271492715027151271522715327154271552715627157271582715927160271612716227163271642716527166271672716827169271702717127172271732717427175271762717727178271792718027181271822718327184271852718627187271882718927190271912719227193271942719527196271972719827199272002720127202272032720427205272062720727208272092721027211272122721327214272152721627217272182721927220272212722227223272242722527226272272722827229272302723127232272332723427235272362723727238272392724027241272422724327244272452724627247272482724927250272512725227253272542725527256272572725827259272602726127262272632726427265272662726727268272692727027271272722727327274272752727627277272782727927280272812728227283272842728527286272872728827289272902729127292272932729427295272962729727298272992730027301273022730327304273052730627307273082730927310273112731227313273142731527316273172731827319273202732127322273232732427325273262732727328273292733027331273322733327334273352733627337273382733927340273412734227343273442734527346273472734827349273502735127352273532735427355273562735727358273592736027361273622736327364273652736627367273682736927370273712737227373273742737527376273772737827379273802738127382273832738427385273862738727388273892739027391273922739327394273952739627397273982739927400274012740227403274042740527406274072740827409274102741127412274132741427415274162741727418274192742027421274222742327424274252742627427274282742927430274312743227433274342743527436274372743827439274402744127442274432744427445274462744727448274492745027451274522745327454274552745627457274582745927460274612746227463274642746527466274672746827469274702747127472274732747427475274762747727478274792748027481274822748327484274852748627487274882748927490274912749227493274942749527496274972749827499275002750127502275032750427505275062750727508275092751027511275122751327514275152751627517275182751927520275212752227523275242752527526275272752827529275302753127532275332753427535275362753727538275392754027541275422754327544275452754627547275482754927550275512755227553275542755527556275572755827559275602756127562275632756427565275662756727568275692757027571275722757327574275752757627577275782757927580275812758227583275842758527586275872758827589275902759127592275932759427595275962759727598275992760027601276022760327604276052760627607276082760927610276112761227613276142761527616276172761827619276202762127622276232762427625276262762727628276292763027631276322763327634276352763627637276382763927640276412764227643276442764527646276472764827649276502765127652276532765427655276562765727658276592766027661276622766327664276652766627667276682766927670276712767227673276742767527676276772767827679276802768127682276832768427685276862768727688276892769027691276922769327694276952769627697276982769927700277012770227703277042770527706277072770827709277102771127712277132771427715277162771727718277192772027721277222772327724277252772627727277282772927730277312773227733277342773527736277372773827739277402774127742277432774427745277462774727748277492775027751277522775327754277552775627757277582775927760277612776227763277642776527766277672776827769277702777127772277732777427775277762777727778277792778027781277822778327784277852778627787277882778927790277912779227793277942779527796277972779827799278002780127802278032780427805278062780727808278092781027811278122781327814278152781627817278182781927820278212782227823278242782527826278272782827829278302783127832278332783427835278362783727838278392784027841278422784327844278452784627847278482784927850278512785227853278542785527856278572785827859278602786127862278632786427865278662786727868278692787027871278722787327874278752787627877278782787927880278812788227883278842788527886278872788827889278902789127892278932789427895278962789727898278992790027901279022790327904279052790627907279082790927910279112791227913279142791527916279172791827919279202792127922279232792427925279262792727928279292793027931279322793327934279352793627937279382793927940279412794227943279442794527946279472794827949279502795127952279532795427955279562795727958279592796027961279622796327964279652796627967279682796927970279712797227973279742797527976279772797827979279802798127982279832798427985279862798727988279892799027991279922799327994279952799627997279982799928000280012800228003280042800528006280072800828009280102801128012280132801428015280162801728018280192802028021280222802328024280252802628027280282802928030280312803228033280342803528036280372803828039280402804128042280432804428045280462804728048280492805028051280522805328054280552805628057280582805928060280612806228063280642806528066280672806828069280702807128072280732807428075280762807728078280792808028081280822808328084280852808628087280882808928090280912809228093280942809528096280972809828099281002810128102281032810428105281062810728108281092811028111281122811328114281152811628117281182811928120281212812228123281242812528126281272812828129281302813128132281332813428135281362813728138281392814028141281422814328144281452814628147281482814928150281512815228153281542815528156281572815828159281602816128162281632816428165281662816728168281692817028171281722817328174281752817628177281782817928180281812818228183281842818528186281872818828189281902819128192281932819428195281962819728198281992820028201282022820328204282052820628207282082820928210282112821228213282142821528216282172821828219282202822128222282232822428225282262822728228282292823028231282322823328234282352823628237282382823928240282412824228243282442824528246282472824828249282502825128252282532825428255282562825728258282592826028261282622826328264282652826628267282682826928270282712827228273282742827528276282772827828279282802828128282282832828428285282862828728288282892829028291282922829328294282952829628297282982829928300283012830228303283042830528306283072830828309283102831128312283132831428315283162831728318283192832028321283222832328324283252832628327283282832928330283312833228333283342833528336283372833828339283402834128342283432834428345283462834728348283492835028351283522835328354283552835628357283582835928360283612836228363283642836528366283672836828369283702837128372283732837428375283762837728378283792838028381283822838328384283852838628387283882838928390283912839228393283942839528396283972839828399284002840128402284032840428405284062840728408284092841028411284122841328414284152841628417284182841928420284212842228423284242842528426284272842828429284302843128432284332843428435284362843728438284392844028441284422844328444284452844628447284482844928450284512845228453284542845528456284572845828459284602846128462284632846428465284662846728468284692847028471284722847328474284752847628477284782847928480284812848228483284842848528486284872848828489284902849128492284932849428495284962849728498284992850028501285022850328504285052850628507285082850928510285112851228513285142851528516285172851828519285202852128522285232852428525285262852728528285292853028531285322853328534285352853628537285382853928540285412854228543285442854528546285472854828549285502855128552285532855428555285562855728558285592856028561285622856328564285652856628567285682856928570285712857228573285742857528576285772857828579285802858128582285832858428585285862858728588285892859028591285922859328594285952859628597285982859928600286012860228603286042860528606286072860828609286102861128612286132861428615286162861728618286192862028621286222862328624286252862628627286282862928630286312863228633286342863528636286372863828639286402864128642286432864428645286462864728648286492865028651286522865328654286552865628657286582865928660286612866228663286642866528666286672866828669286702867128672286732867428675286762867728678286792868028681286822868328684286852868628687286882868928690286912869228693286942869528696286972869828699287002870128702287032870428705287062870728708287092871028711287122871328714287152871628717287182871928720287212872228723287242872528726287272872828729287302873128732287332873428735287362873728738287392874028741287422874328744287452874628747287482874928750287512875228753287542875528756287572875828759287602876128762287632876428765287662876728768287692877028771287722877328774287752877628777287782877928780287812878228783287842878528786287872878828789287902879128792287932879428795287962879728798287992880028801288022880328804288052880628807288082880928810288112881228813288142881528816288172881828819288202882128822288232882428825288262882728828288292883028831288322883328834288352883628837288382883928840288412884228843288442884528846288472884828849288502885128852288532885428855288562885728858288592886028861288622886328864288652886628867288682886928870288712887228873288742887528876288772887828879288802888128882288832888428885288862888728888288892889028891288922889328894288952889628897288982889928900289012890228903289042890528906289072890828909289102891128912289132891428915289162891728918289192892028921289222892328924289252892628927289282892928930289312893228933289342893528936289372893828939289402894128942289432894428945289462894728948289492895028951289522895328954289552895628957289582895928960289612896228963289642896528966289672896828969289702897128972289732897428975289762897728978289792898028981289822898328984289852898628987289882898928990289912899228993289942899528996289972899828999290002900129002290032900429005290062900729008290092901029011290122901329014290152901629017290182901929020290212902229023290242902529026290272902829029290302903129032290332903429035290362903729038290392904029041290422904329044290452904629047290482904929050290512905229053290542905529056290572905829059290602906129062290632906429065290662906729068290692907029071290722907329074290752907629077290782907929080290812908229083290842908529086290872908829089290902909129092290932909429095290962909729098290992910029101291022910329104291052910629107291082910929110291112911229113291142911529116291172911829119291202912129122291232912429125291262912729128291292913029131291322913329134291352913629137291382913929140291412914229143291442914529146291472914829149291502915129152291532915429155291562915729158291592916029161291622916329164291652916629167291682916929170291712917229173291742917529176291772917829179291802918129182291832918429185291862918729188291892919029191291922919329194291952919629197291982919929200292012920229203292042920529206292072920829209292102921129212292132921429215292162921729218292192922029221292222922329224292252922629227292282922929230292312923229233292342923529236292372923829239292402924129242292432924429245292462924729248292492925029251292522925329254292552925629257292582925929260292612926229263292642926529266292672926829269292702927129272292732927429275292762927729278292792928029281292822928329284292852928629287292882928929290292912929229293292942929529296292972929829299293002930129302293032930429305293062930729308293092931029311293122931329314293152931629317293182931929320293212932229323293242932529326293272932829329293302933129332293332933429335293362933729338293392934029341293422934329344293452934629347293482934929350293512935229353293542935529356293572935829359293602936129362293632936429365293662936729368293692937029371293722937329374293752937629377293782937929380293812938229383293842938529386293872938829389293902939129392293932939429395293962939729398293992940029401294022940329404294052940629407294082940929410294112941229413294142941529416294172941829419294202942129422294232942429425294262942729428294292943029431294322943329434294352943629437294382943929440294412944229443294442944529446294472944829449294502945129452294532945429455294562945729458294592946029461294622946329464294652946629467294682946929470294712947229473294742947529476294772947829479294802948129482294832948429485294862948729488294892949029491294922949329494294952949629497294982949929500295012950229503295042950529506295072950829509295102951129512295132951429515295162951729518295192952029521295222952329524295252952629527295282952929530295312953229533295342953529536295372953829539295402954129542295432954429545295462954729548295492955029551295522955329554295552955629557295582955929560295612956229563295642956529566295672956829569295702957129572295732957429575295762957729578295792958029581295822958329584295852958629587295882958929590295912959229593295942959529596295972959829599296002960129602296032960429605296062960729608296092961029611296122961329614296152961629617296182961929620296212962229623296242962529626296272962829629296302963129632296332963429635296362963729638296392964029641296422964329644296452964629647296482964929650296512965229653296542965529656296572965829659296602966129662296632966429665296662966729668296692967029671296722967329674296752967629677296782967929680296812968229683296842968529686296872968829689296902969129692296932969429695296962969729698296992970029701297022970329704297052970629707297082970929710297112971229713297142971529716297172971829719297202972129722297232972429725297262972729728297292973029731297322973329734297352973629737297382973929740297412974229743297442974529746297472974829749297502975129752297532975429755297562975729758297592976029761297622976329764297652976629767297682976929770297712977229773297742977529776297772977829779297802978129782297832978429785297862978729788297892979029791297922979329794297952979629797297982979929800298012980229803298042980529806298072980829809298102981129812298132981429815298162981729818298192982029821298222982329824298252982629827298282982929830298312983229833298342983529836298372983829839298402984129842298432984429845298462984729848298492985029851298522985329854298552985629857298582985929860298612986229863298642986529866298672986829869298702987129872298732987429875298762987729878298792988029881298822988329884298852988629887298882988929890298912989229893298942989529896298972989829899299002990129902299032990429905299062990729908299092991029911299122991329914299152991629917299182991929920299212992229923299242992529926299272992829929299302993129932299332993429935299362993729938299392994029941299422994329944299452994629947299482994929950299512995229953299542995529956299572995829959299602996129962299632996429965299662996729968299692997029971299722997329974299752997629977299782997929980299812998229983299842998529986299872998829989299902999129992299932999429995299962999729998299993000030001300023000330004300053000630007300083000930010300113001230013300143001530016300173001830019300203002130022300233002430025300263002730028300293003030031300323003330034300353003630037300383003930040300413004230043300443004530046300473004830049300503005130052300533005430055300563005730058300593006030061300623006330064300653006630067300683006930070300713007230073300743007530076300773007830079300803008130082300833008430085300863008730088300893009030091300923009330094300953009630097300983009930100301013010230103301043010530106301073010830109301103011130112301133011430115301163011730118301193012030121301223012330124301253012630127301283012930130301313013230133301343013530136301373013830139301403014130142301433014430145301463014730148301493015030151301523015330154301553015630157301583015930160301613016230163301643016530166301673016830169301703017130172301733017430175301763017730178301793018030181301823018330184301853018630187301883018930190301913019230193301943019530196301973019830199302003020130202302033020430205302063020730208302093021030211302123021330214302153021630217302183021930220302213022230223302243022530226302273022830229302303023130232302333023430235302363023730238302393024030241302423024330244302453024630247302483024930250302513025230253302543025530256302573025830259302603026130262302633026430265302663026730268302693027030271302723027330274302753027630277302783027930280302813028230283302843028530286302873028830289302903029130292302933029430295302963029730298302993030030301303023030330304303053030630307303083030930310303113031230313303143031530316303173031830319303203032130322303233032430325303263032730328303293033030331303323033330334303353033630337303383033930340303413034230343303443034530346303473034830349303503035130352303533035430355303563035730358303593036030361303623036330364303653036630367303683036930370303713037230373303743037530376303773037830379303803038130382303833038430385303863038730388303893039030391303923039330394303953039630397303983039930400304013040230403304043040530406304073040830409304103041130412304133041430415304163041730418304193042030421304223042330424304253042630427304283042930430304313043230433304343043530436304373043830439304403044130442304433044430445304463044730448304493045030451304523045330454304553045630457304583045930460304613046230463304643046530466304673046830469304703047130472304733047430475304763047730478304793048030481304823048330484304853048630487304883048930490304913049230493304943049530496304973049830499305003050130502305033050430505305063050730508305093051030511305123051330514305153051630517305183051930520305213052230523305243052530526305273052830529305303053130532305333053430535305363053730538305393054030541305423054330544305453054630547305483054930550305513055230553305543055530556305573055830559305603056130562305633056430565305663056730568305693057030571305723057330574305753057630577305783057930580305813058230583305843058530586305873058830589305903059130592305933059430595305963059730598305993060030601306023060330604306053060630607306083060930610306113061230613306143061530616306173061830619306203062130622306233062430625306263062730628306293063030631306323063330634306353063630637306383063930640306413064230643306443064530646306473064830649306503065130652306533065430655306563065730658306593066030661306623066330664306653066630667306683066930670306713067230673306743067530676306773067830679306803068130682306833068430685306863068730688306893069030691306923069330694306953069630697306983069930700307013070230703307043070530706307073070830709307103071130712307133071430715307163071730718307193072030721307223072330724307253072630727307283072930730307313073230733307343073530736307373073830739307403074130742307433074430745307463074730748307493075030751307523075330754307553075630757307583075930760307613076230763307643076530766307673076830769307703077130772307733077430775307763077730778307793078030781307823078330784307853078630787307883078930790307913079230793307943079530796307973079830799308003080130802308033080430805308063080730808308093081030811308123081330814308153081630817308183081930820308213082230823308243082530826308273082830829308303083130832308333083430835308363083730838308393084030841308423084330844308453084630847308483084930850308513085230853308543085530856308573085830859308603086130862308633086430865308663086730868308693087030871308723087330874308753087630877308783087930880308813088230883308843088530886308873088830889308903089130892308933089430895308963089730898308993090030901309023090330904309053090630907309083090930910309113091230913309143091530916309173091830919309203092130922309233092430925309263092730928309293093030931309323093330934309353093630937309383093930940309413094230943309443094530946309473094830949309503095130952309533095430955309563095730958309593096030961309623096330964309653096630967309683096930970309713097230973309743097530976309773097830979309803098130982309833098430985309863098730988309893099030991309923099330994309953099630997309983099931000310013100231003310043100531006310073100831009310103101131012310133101431015310163101731018310193102031021310223102331024310253102631027310283102931030310313103231033310343103531036310373103831039310403104131042310433104431045310463104731048310493105031051310523105331054310553105631057310583105931060310613106231063310643106531066310673106831069310703107131072310733107431075310763107731078310793108031081310823108331084310853108631087310883108931090310913109231093310943109531096310973109831099311003110131102311033110431105311063110731108311093111031111311123111331114311153111631117311183111931120311213112231123311243112531126311273112831129311303113131132311333113431135311363113731138311393114031141311423114331144311453114631147311483114931150311513115231153311543115531156311573115831159311603116131162311633116431165311663116731168311693117031171311723117331174311753117631177311783117931180311813118231183311843118531186311873118831189311903119131192311933119431195311963119731198311993120031201312023120331204312053120631207312083120931210312113121231213312143121531216312173121831219312203122131222312233122431225312263122731228312293123031231312323123331234312353123631237312383123931240312413124231243312443124531246312473124831249312503125131252312533125431255312563125731258312593126031261312623126331264312653126631267312683126931270312713127231273312743127531276312773127831279312803128131282312833128431285312863128731288312893129031291312923129331294312953129631297312983129931300313013130231303313043130531306313073130831309313103131131312313133131431315313163131731318313193132031321313223132331324313253132631327313283132931330313313133231333313343133531336313373133831339313403134131342313433134431345313463134731348313493135031351313523135331354313553135631357313583135931360313613136231363313643136531366313673136831369313703137131372313733137431375313763137731378313793138031381313823138331384313853138631387313883138931390313913139231393313943139531396313973139831399314003140131402314033140431405314063140731408314093141031411314123141331414314153141631417314183141931420314213142231423314243142531426314273142831429314303143131432314333143431435314363143731438314393144031441314423144331444314453144631447314483144931450314513145231453314543145531456314573145831459314603146131462314633146431465314663146731468314693147031471314723147331474314753147631477314783147931480314813148231483314843148531486314873148831489314903149131492314933149431495314963149731498314993150031501315023150331504315053150631507315083150931510315113151231513315143151531516315173151831519315203152131522315233152431525315263152731528315293153031531315323153331534315353153631537315383153931540315413154231543315443154531546315473154831549315503155131552315533155431555315563155731558315593156031561315623156331564315653156631567315683156931570315713157231573315743157531576315773157831579315803158131582315833158431585315863158731588315893159031591315923159331594315953159631597315983159931600316013160231603316043160531606316073160831609316103161131612316133161431615316163161731618316193162031621316223162331624316253162631627316283162931630316313163231633316343163531636316373163831639316403164131642316433164431645316463164731648316493165031651316523165331654316553165631657316583165931660316613166231663316643166531666316673166831669316703167131672316733167431675316763167731678316793168031681316823168331684316853168631687316883168931690316913169231693316943169531696316973169831699317003170131702317033170431705317063170731708317093171031711317123171331714317153171631717317183171931720317213172231723317243172531726317273172831729317303173131732317333173431735317363173731738317393174031741317423174331744317453174631747317483174931750317513175231753317543175531756317573175831759317603176131762317633176431765317663176731768317693177031771317723177331774317753177631777317783177931780317813178231783317843178531786317873178831789317903179131792317933179431795317963179731798317993180031801318023180331804318053180631807318083180931810318113181231813318143181531816318173181831819318203182131822318233182431825318263182731828318293183031831318323183331834318353183631837318383183931840318413184231843318443184531846318473184831849318503185131852318533185431855318563185731858318593186031861318623186331864318653186631867318683186931870318713187231873318743187531876318773187831879318803188131882318833188431885318863188731888318893189031891318923189331894318953189631897318983189931900319013190231903319043190531906319073190831909319103191131912319133191431915319163191731918319193192031921319223192331924319253192631927319283192931930319313193231933319343193531936319373193831939319403194131942319433194431945319463194731948319493195031951319523195331954319553195631957319583195931960319613196231963319643196531966319673196831969319703197131972319733197431975319763197731978319793198031981319823198331984319853198631987319883198931990319913199231993319943199531996319973199831999320003200132002320033200432005320063200732008320093201032011320123201332014320153201632017320183201932020320213202232023320243202532026320273202832029320303203132032320333203432035320363203732038320393204032041320423204332044320453204632047320483204932050320513205232053320543205532056320573205832059320603206132062320633206432065320663206732068320693207032071320723207332074320753207632077320783207932080320813208232083320843208532086320873208832089320903209132092320933209432095320963209732098320993210032101321023210332104321053210632107321083210932110321113211232113321143211532116321173211832119321203212132122321233212432125321263212732128321293213032131321323213332134321353213632137321383213932140321413214232143321443214532146321473214832149321503215132152321533215432155321563215732158321593216032161321623216332164321653216632167321683216932170321713217232173321743217532176321773217832179321803218132182321833218432185321863218732188321893219032191321923219332194321953219632197321983219932200322013220232203322043220532206322073220832209322103221132212322133221432215322163221732218322193222032221322223222332224322253222632227322283222932230322313223232233322343223532236322373223832239322403224132242322433224432245322463224732248322493225032251322523225332254322553225632257322583225932260322613226232263322643226532266322673226832269322703227132272322733227432275322763227732278322793228032281322823228332284322853228632287322883228932290322913229232293322943229532296322973229832299323003230132302323033230432305323063230732308323093231032311323123231332314323153231632317323183231932320323213232232323323243232532326323273232832329323303233132332323333233432335323363233732338323393234032341323423234332344323453234632347323483234932350323513235232353323543235532356323573235832359323603236132362323633236432365323663236732368323693237032371323723237332374323753237632377323783237932380323813238232383323843238532386323873238832389323903239132392323933239432395323963239732398323993240032401324023240332404324053240632407324083240932410324113241232413324143241532416324173241832419324203242132422324233242432425324263242732428324293243032431324323243332434324353243632437324383243932440324413244232443324443244532446324473244832449324503245132452324533245432455324563245732458324593246032461324623246332464324653246632467324683246932470324713247232473324743247532476324773247832479324803248132482324833248432485324863248732488324893249032491324923249332494324953249632497324983249932500325013250232503325043250532506325073250832509325103251132512325133251432515325163251732518325193252032521325223252332524325253252632527325283252932530325313253232533325343253532536325373253832539325403254132542325433254432545325463254732548325493255032551325523255332554325553255632557325583255932560325613256232563325643256532566325673256832569325703257132572325733257432575325763257732578325793258032581325823258332584325853258632587325883258932590325913259232593325943259532596325973259832599326003260132602326033260432605326063260732608326093261032611326123261332614326153261632617326183261932620326213262232623326243262532626326273262832629326303263132632326333263432635326363263732638326393264032641326423264332644326453264632647326483264932650326513265232653326543265532656326573265832659326603266132662326633266432665326663266732668326693267032671326723267332674326753267632677326783267932680326813268232683326843268532686326873268832689326903269132692326933269432695326963269732698326993270032701327023270332704327053270632707327083270932710327113271232713327143271532716327173271832719327203272132722327233272432725327263272732728327293273032731327323273332734327353273632737327383273932740327413274232743327443274532746327473274832749327503275132752327533275432755327563275732758327593276032761327623276332764327653276632767327683276932770327713277232773327743277532776327773277832779327803278132782327833278432785327863278732788327893279032791327923279332794327953279632797327983279932800328013280232803328043280532806328073280832809328103281132812328133281432815328163281732818328193282032821328223282332824328253282632827328283282932830328313283232833328343283532836328373283832839328403284132842328433284432845328463284732848328493285032851328523285332854328553285632857328583285932860328613286232863328643286532866328673286832869328703287132872328733287432875328763287732878328793288032881328823288332884328853288632887328883288932890328913289232893328943289532896328973289832899329003290132902329033290432905329063290732908329093291032911329123291332914329153291632917329183291932920329213292232923329243292532926329273292832929329303293132932329333293432935329363293732938329393294032941329423294332944329453294632947329483294932950329513295232953329543295532956329573295832959329603296132962329633296432965329663296732968329693297032971329723297332974329753297632977329783297932980329813298232983329843298532986329873298832989329903299132992329933299432995329963299732998329993300033001330023300333004330053300633007330083300933010330113301233013330143301533016330173301833019330203302133022330233302433025330263302733028330293303033031330323303333034330353303633037330383303933040330413304233043330443304533046330473304833049330503305133052330533305433055330563305733058330593306033061330623306333064330653306633067330683306933070330713307233073330743307533076330773307833079330803308133082330833308433085330863308733088330893309033091330923309333094330953309633097330983309933100331013310233103331043310533106331073310833109331103311133112331133311433115331163311733118331193312033121331223312333124331253312633127331283312933130331313313233133331343313533136331373313833139331403314133142331433314433145331463314733148331493315033151331523315333154331553315633157331583315933160331613316233163331643316533166331673316833169331703317133172331733317433175331763317733178331793318033181331823318333184331853318633187331883318933190331913319233193331943319533196331973319833199332003320133202332033320433205332063320733208332093321033211332123321333214332153321633217332183321933220332213322233223332243322533226332273322833229332303323133232332333323433235332363323733238332393324033241332423324333244332453324633247332483324933250332513325233253332543325533256332573325833259332603326133262332633326433265332663326733268332693327033271332723327333274332753327633277332783327933280332813328233283332843328533286332873328833289332903329133292332933329433295332963329733298332993330033301333023330333304333053330633307333083330933310333113331233313333143331533316333173331833319333203332133322333233332433325333263332733328333293333033331333323333333334333353333633337333383333933340333413334233343333443334533346333473334833349333503335133352333533335433355333563335733358333593336033361333623336333364333653336633367333683336933370333713337233373333743337533376333773337833379333803338133382333833338433385333863338733388333893339033391333923339333394333953339633397333983339933400334013340233403334043340533406334073340833409334103341133412334133341433415334163341733418334193342033421334223342333424334253342633427334283342933430334313343233433334343343533436334373343833439334403344133442334433344433445334463344733448334493345033451334523345333454334553345633457334583345933460334613346233463334643346533466334673346833469334703347133472334733347433475334763347733478334793348033481334823348333484334853348633487334883348933490334913349233493334943349533496334973349833499335003350133502335033350433505335063350733508335093351033511335123351333514335153351633517335183351933520335213352233523335243352533526335273352833529335303353133532335333353433535335363353733538335393354033541335423354333544335453354633547335483354933550335513355233553335543355533556335573355833559335603356133562335633356433565335663356733568335693357033571335723357333574335753357633577335783357933580335813358233583335843358533586335873358833589335903359133592335933359433595335963359733598335993360033601336023360333604336053360633607336083360933610336113361233613336143361533616336173361833619336203362133622336233362433625336263362733628336293363033631336323363333634336353363633637336383363933640336413364233643336443364533646336473364833649336503365133652336533365433655336563365733658336593366033661336623366333664336653366633667336683366933670336713367233673336743367533676336773367833679336803368133682336833368433685336863368733688336893369033691336923369333694336953369633697336983369933700337013370233703337043370533706337073370833709337103371133712337133371433715337163371733718337193372033721337223372333724337253372633727337283372933730337313373233733337343373533736337373373833739337403374133742337433374433745337463374733748337493375033751337523375333754337553375633757337583375933760337613376233763337643376533766337673376833769337703377133772337733377433775337763377733778337793378033781337823378333784337853378633787337883378933790337913379233793337943379533796337973379833799338003380133802338033380433805338063380733808338093381033811338123381333814338153381633817338183381933820338213382233823338243382533826338273382833829338303383133832338333383433835338363383733838338393384033841338423384333844338453384633847338483384933850338513385233853338543385533856338573385833859338603386133862338633386433865338663386733868338693387033871338723387333874338753387633877338783387933880338813388233883338843388533886338873388833889338903389133892338933389433895338963389733898338993390033901339023390333904339053390633907339083390933910339113391233913339143391533916339173391833919339203392133922339233392433925339263392733928339293393033931339323393333934339353393633937339383393933940339413394233943339443394533946339473394833949339503395133952339533395433955339563395733958339593396033961339623396333964339653396633967339683396933970339713397233973339743397533976339773397833979339803398133982339833398433985339863398733988339893399033991339923399333994339953399633997339983399934000340013400234003340043400534006340073400834009340103401134012340133401434015340163401734018340193402034021340223402334024340253402634027340283402934030340313403234033340343403534036340373403834039340403404134042340433404434045340463404734048340493405034051340523405334054340553405634057340583405934060340613406234063340643406534066340673406834069340703407134072340733407434075340763407734078340793408034081340823408334084340853408634087340883408934090340913409234093340943409534096340973409834099341003410134102341033410434105341063410734108341093411034111341123411334114341153411634117341183411934120341213412234123341243412534126341273412834129341303413134132341333413434135341363413734138341393414034141341423414334144341453414634147341483414934150341513415234153341543415534156341573415834159341603416134162341633416434165341663416734168341693417034171341723417334174341753417634177341783417934180341813418234183341843418534186341873418834189341903419134192341933419434195341963419734198341993420034201342023420334204342053420634207342083420934210342113421234213342143421534216342173421834219342203422134222342233422434225342263422734228342293423034231342323423334234342353423634237342383423934240342413424234243342443424534246342473424834249342503425134252342533425434255342563425734258342593426034261342623426334264342653426634267342683426934270342713427234273342743427534276342773427834279342803428134282342833428434285342863428734288342893429034291342923429334294342953429634297342983429934300343013430234303343043430534306343073430834309343103431134312343133431434315343163431734318343193432034321343223432334324343253432634327343283432934330343313433234333343343433534336343373433834339343403434134342343433434434345343463434734348343493435034351343523435334354343553435634357343583435934360343613436234363343643436534366343673436834369343703437134372343733437434375343763437734378343793438034381343823438334384343853438634387343883438934390343913439234393343943439534396343973439834399344003440134402344033440434405344063440734408344093441034411344123441334414344153441634417344183441934420344213442234423344243442534426344273442834429344303443134432344333443434435344363443734438344393444034441344423444334444344453444634447344483444934450344513445234453344543445534456344573445834459344603446134462344633446434465344663446734468344693447034471344723447334474344753447634477344783447934480344813448234483344843448534486344873448834489344903449134492344933449434495344963449734498344993450034501345023450334504345053450634507345083450934510345113451234513345143451534516345173451834519345203452134522345233452434525345263452734528345293453034531345323453334534345353453634537345383453934540345413454234543345443454534546345473454834549345503455134552345533455434555345563455734558345593456034561345623456334564345653456634567345683456934570345713457234573345743457534576345773457834579345803458134582345833458434585345863458734588345893459034591345923459334594345953459634597345983459934600346013460234603346043460534606346073460834609346103461134612346133461434615346163461734618346193462034621346223462334624346253462634627346283462934630346313463234633346343463534636346373463834639346403464134642346433464434645346463464734648346493465034651346523465334654346553465634657346583465934660346613466234663346643466534666346673466834669346703467134672346733467434675346763467734678346793468034681346823468334684346853468634687346883468934690346913469234693346943469534696346973469834699347003470134702347033470434705347063470734708347093471034711347123471334714347153471634717347183471934720347213472234723347243472534726347273472834729347303473134732347333473434735347363473734738347393474034741347423474334744347453474634747347483474934750347513475234753347543475534756347573475834759347603476134762347633476434765347663476734768347693477034771347723477334774347753477634777347783477934780347813478234783347843478534786347873478834789347903479134792347933479434795347963479734798347993480034801348023480334804348053480634807348083480934810348113481234813348143481534816348173481834819348203482134822348233482434825348263482734828348293483034831348323483334834348353483634837348383483934840348413484234843348443484534846348473484834849348503485134852348533485434855348563485734858348593486034861348623486334864348653486634867348683486934870348713487234873348743487534876348773487834879348803488134882348833488434885348863488734888348893489034891348923489334894348953489634897348983489934900349013490234903349043490534906349073490834909349103491134912349133491434915349163491734918349193492034921349223492334924349253492634927349283492934930349313493234933349343493534936349373493834939349403494134942349433494434945349463494734948349493495034951349523495334954349553495634957349583495934960349613496234963349643496534966349673496834969349703497134972349733497434975349763497734978349793498034981349823498334984349853498634987349883498934990349913499234993349943499534996349973499834999350003500135002350033500435005350063500735008350093501035011350123501335014350153501635017350183501935020350213502235023350243502535026350273502835029350303503135032350333503435035350363503735038350393504035041350423504335044350453504635047350483504935050350513505235053350543505535056350573505835059350603506135062350633506435065350663506735068350693507035071350723507335074350753507635077350783507935080350813508235083350843508535086350873508835089350903509135092350933509435095350963509735098350993510035101351023510335104351053510635107351083510935110351113511235113351143511535116351173511835119351203512135122351233512435125351263512735128351293513035131351323513335134351353513635137351383513935140351413514235143351443514535146351473514835149351503515135152351533515435155351563515735158351593516035161351623516335164351653516635167351683516935170351713517235173351743517535176351773517835179351803518135182351833518435185351863518735188351893519035191351923519335194351953519635197351983519935200352013520235203352043520535206352073520835209352103521135212352133521435215352163521735218352193522035221352223522335224352253522635227352283522935230352313523235233352343523535236352373523835239352403524135242352433524435245352463524735248352493525035251352523525335254352553525635257352583525935260352613526235263352643526535266352673526835269352703527135272352733527435275352763527735278352793528035281352823528335284352853528635287352883528935290352913529235293352943529535296352973529835299353003530135302353033530435305353063530735308353093531035311353123531335314353153531635317353183531935320353213532235323353243532535326353273532835329353303533135332353333533435335353363533735338353393534035341353423534335344353453534635347353483534935350353513535235353353543535535356353573535835359353603536135362353633536435365353663536735368353693537035371353723537335374353753537635377353783537935380353813538235383353843538535386353873538835389353903539135392353933539435395353963539735398353993540035401354023540335404354053540635407354083540935410354113541235413354143541535416354173541835419354203542135422354233542435425354263542735428354293543035431354323543335434354353543635437354383543935440354413544235443354443544535446354473544835449354503545135452354533545435455354563545735458354593546035461354623546335464354653546635467354683546935470354713547235473354743547535476354773547835479354803548135482354833548435485354863548735488354893549035491354923549335494354953549635497354983549935500355013550235503355043550535506355073550835509355103551135512355133551435515355163551735518355193552035521355223552335524355253552635527355283552935530355313553235533355343553535536355373553835539355403554135542355433554435545355463554735548355493555035551355523555335554355553555635557355583555935560355613556235563355643556535566355673556835569355703557135572355733557435575355763557735578355793558035581355823558335584355853558635587355883558935590355913559235593355943559535596355973559835599356003560135602356033560435605356063560735608356093561035611356123561335614356153561635617356183561935620356213562235623356243562535626356273562835629356303563135632356333563435635356363563735638356393564035641356423564335644356453564635647356483564935650356513565235653356543565535656356573565835659356603566135662356633566435665356663566735668356693567035671356723567335674356753567635677356783567935680356813568235683356843568535686356873568835689356903569135692356933569435695356963569735698356993570035701357023570335704357053570635707357083570935710357113571235713357143571535716357173571835719357203572135722357233572435725357263572735728357293573035731357323573335734357353573635737357383573935740357413574235743357443574535746357473574835749357503575135752357533575435755357563575735758357593576035761357623576335764357653576635767357683576935770357713577235773357743577535776357773577835779357803578135782357833578435785357863578735788357893579035791357923579335794357953579635797357983579935800358013580235803358043580535806358073580835809358103581135812358133581435815358163581735818358193582035821358223582335824358253582635827358283582935830358313583235833358343583535836358373583835839358403584135842358433584435845358463584735848358493585035851358523585335854358553585635857358583585935860358613586235863358643586535866358673586835869358703587135872358733587435875358763587735878358793588035881358823588335884358853588635887358883588935890358913589235893358943589535896358973589835899359003590135902359033590435905359063590735908359093591035911359123591335914359153591635917359183591935920359213592235923359243592535926359273592835929359303593135932359333593435935359363593735938359393594035941359423594335944359453594635947359483594935950359513595235953359543595535956359573595835959359603596135962359633596435965359663596735968359693597035971359723597335974359753597635977359783597935980359813598235983359843598535986359873598835989359903599135992359933599435995359963599735998359993600036001360023600336004360053600636007360083600936010360113601236013360143601536016360173601836019360203602136022360233602436025360263602736028360293603036031360323603336034360353603636037360383603936040360413604236043360443604536046360473604836049360503605136052360533605436055360563605736058360593606036061360623606336064360653606636067360683606936070360713607236073360743607536076360773607836079360803608136082360833608436085360863608736088360893609036091360923609336094360953609636097360983609936100361013610236103361043610536106361073610836109361103611136112361133611436115361163611736118361193612036121361223612336124361253612636127361283612936130361313613236133361343613536136361373613836139361403614136142361433614436145361463614736148361493615036151361523615336154361553615636157361583615936160361613616236163361643616536166361673616836169361703617136172361733617436175361763617736178361793618036181361823618336184361853618636187361883618936190361913619236193361943619536196361973619836199362003620136202362033620436205362063620736208362093621036211362123621336214362153621636217362183621936220362213622236223362243622536226362273622836229362303623136232362333623436235362363623736238362393624036241362423624336244362453624636247362483624936250362513625236253362543625536256362573625836259362603626136262362633626436265362663626736268362693627036271362723627336274362753627636277362783627936280362813628236283362843628536286362873628836289362903629136292362933629436295362963629736298362993630036301363023630336304363053630636307363083630936310363113631236313363143631536316363173631836319363203632136322363233632436325363263632736328363293633036331363323633336334363353633636337363383633936340363413634236343363443634536346363473634836349363503635136352363533635436355363563635736358363593636036361363623636336364363653636636367363683636936370363713637236373363743637536376363773637836379363803638136382363833638436385363863638736388363893639036391363923639336394363953639636397363983639936400364013640236403364043640536406364073640836409364103641136412364133641436415364163641736418364193642036421364223642336424364253642636427364283642936430364313643236433364343643536436364373643836439364403644136442364433644436445364463644736448364493645036451364523645336454364553645636457364583645936460364613646236463364643646536466364673646836469364703647136472364733647436475364763647736478364793648036481364823648336484364853648636487364883648936490364913649236493364943649536496364973649836499365003650136502365033650436505365063650736508365093651036511365123651336514365153651636517365183651936520365213652236523365243652536526365273652836529365303653136532365333653436535365363653736538365393654036541365423654336544365453654636547365483654936550365513655236553365543655536556365573655836559365603656136562365633656436565365663656736568365693657036571365723657336574365753657636577365783657936580365813658236583365843658536586365873658836589365903659136592365933659436595365963659736598365993660036601366023660336604366053660636607366083660936610366113661236613366143661536616366173661836619366203662136622366233662436625366263662736628366293663036631366323663336634366353663636637366383663936640366413664236643366443664536646366473664836649366503665136652366533665436655366563665736658366593666036661366623666336664366653666636667366683666936670366713667236673366743667536676366773667836679366803668136682366833668436685366863668736688366893669036691366923669336694366953669636697366983669936700367013670236703367043670536706367073670836709367103671136712367133671436715367163671736718367193672036721367223672336724367253672636727367283672936730367313673236733367343673536736367373673836739367403674136742367433674436745367463674736748367493675036751367523675336754367553675636757367583675936760367613676236763367643676536766367673676836769367703677136772367733677436775367763677736778367793678036781367823678336784367853678636787367883678936790367913679236793367943679536796367973679836799368003680136802368033680436805368063680736808368093681036811368123681336814368153681636817368183681936820368213682236823368243682536826368273682836829368303683136832368333683436835368363683736838368393684036841368423684336844368453684636847368483684936850368513685236853368543685536856368573685836859368603686136862368633686436865368663686736868368693687036871368723687336874368753687636877368783687936880368813688236883368843688536886368873688836889368903689136892368933689436895368963689736898368993690036901369023690336904369053690636907369083690936910369113691236913369143691536916369173691836919369203692136922369233692436925369263692736928369293693036931369323693336934369353693636937369383693936940369413694236943369443694536946369473694836949369503695136952369533695436955369563695736958369593696036961369623696336964369653696636967369683696936970369713697236973369743697536976369773697836979369803698136982369833698436985369863698736988369893699036991369923699336994369953699636997369983699937000370013700237003370043700537006370073700837009370103701137012370133701437015370163701737018370193702037021370223702337024370253702637027370283702937030370313703237033370343703537036370373703837039370403704137042370433704437045370463704737048370493705037051370523705337054370553705637057370583705937060370613706237063370643706537066370673706837069370703707137072370733707437075370763707737078370793708037081370823708337084370853708637087370883708937090370913709237093370943709537096370973709837099371003710137102371033710437105371063710737108371093711037111371123711337114371153711637117371183711937120371213712237123371243712537126371273712837129371303713137132371333713437135371363713737138371393714037141371423714337144371453714637147371483714937150371513715237153371543715537156371573715837159371603716137162371633716437165371663716737168371693717037171371723717337174371753717637177371783717937180371813718237183371843718537186371873718837189371903719137192371933719437195371963719737198371993720037201372023720337204372053720637207372083720937210372113721237213372143721537216372173721837219372203722137222372233722437225372263722737228372293723037231372323723337234372353723637237372383723937240372413724237243372443724537246372473724837249372503725137252372533725437255372563725737258372593726037261372623726337264372653726637267372683726937270372713727237273372743727537276372773727837279372803728137282372833728437285372863728737288372893729037291372923729337294372953729637297372983729937300373013730237303373043730537306373073730837309373103731137312373133731437315373163731737318373193732037321373223732337324373253732637327373283732937330373313733237333373343733537336373373733837339373403734137342373433734437345373463734737348373493735037351373523735337354373553735637357373583735937360373613736237363373643736537366373673736837369373703737137372373733737437375373763737737378373793738037381373823738337384373853738637387373883738937390373913739237393373943739537396373973739837399374003740137402374033740437405374063740737408374093741037411374123741337414374153741637417374183741937420374213742237423374243742537426374273742837429374303743137432374333743437435374363743737438374393744037441374423744337444374453744637447374483744937450374513745237453374543745537456374573745837459374603746137462374633746437465374663746737468374693747037471374723747337474374753747637477374783747937480374813748237483374843748537486374873748837489374903749137492374933749437495374963749737498374993750037501375023750337504375053750637507375083750937510375113751237513375143751537516375173751837519375203752137522375233752437525375263752737528375293753037531375323753337534375353753637537375383753937540375413754237543375443754537546375473754837549375503755137552375533755437555375563755737558375593756037561375623756337564375653756637567375683756937570375713757237573375743757537576375773757837579375803758137582375833758437585375863758737588375893759037591375923759337594375953759637597375983759937600376013760237603376043760537606376073760837609376103761137612376133761437615376163761737618376193762037621376223762337624376253762637627376283762937630376313763237633376343763537636376373763837639376403764137642376433764437645376463764737648376493765037651376523765337654376553765637657376583765937660376613766237663376643766537666376673766837669376703767137672376733767437675376763767737678376793768037681376823768337684376853768637687376883768937690376913769237693376943769537696376973769837699377003770137702377033770437705377063770737708377093771037711377123771337714377153771637717377183771937720377213772237723377243772537726377273772837729377303773137732377333773437735377363773737738377393774037741377423774337744377453774637747377483774937750377513775237753377543775537756377573775837759377603776137762377633776437765377663776737768377693777037771377723777337774377753777637777377783777937780377813778237783377843778537786377873778837789377903779137792377933779437795377963779737798377993780037801378023780337804378053780637807378083780937810378113781237813378143781537816378173781837819378203782137822378233782437825378263782737828378293783037831378323783337834378353783637837378383783937840378413784237843378443784537846378473784837849378503785137852378533785437855378563785737858378593786037861378623786337864378653786637867378683786937870378713787237873378743787537876378773787837879378803788137882378833788437885378863788737888378893789037891378923789337894378953789637897378983789937900379013790237903379043790537906379073790837909379103791137912379133791437915379163791737918379193792037921379223792337924379253792637927379283792937930379313793237933379343793537936379373793837939379403794137942379433794437945379463794737948379493795037951379523795337954379553795637957379583795937960379613796237963379643796537966379673796837969379703797137972379733797437975379763797737978379793798037981379823798337984379853798637987379883798937990379913799237993379943799537996379973799837999380003800138002380033800438005380063800738008380093801038011380123801338014380153801638017380183801938020380213802238023380243802538026380273802838029380303803138032380333803438035380363803738038380393804038041380423804338044380453804638047380483804938050380513805238053380543805538056380573805838059380603806138062380633806438065380663806738068380693807038071380723807338074380753807638077380783807938080380813808238083380843808538086380873808838089380903809138092380933809438095380963809738098380993810038101381023810338104381053810638107381083810938110381113811238113381143811538116381173811838119381203812138122381233812438125381263812738128381293813038131381323813338134381353813638137381383813938140381413814238143381443814538146381473814838149381503815138152381533815438155381563815738158381593816038161381623816338164381653816638167381683816938170381713817238173381743817538176381773817838179381803818138182381833818438185381863818738188381893819038191381923819338194381953819638197381983819938200382013820238203382043820538206382073820838209382103821138212382133821438215382163821738218382193822038221382223822338224382253822638227382283822938230382313823238233382343823538236382373823838239382403824138242382433824438245382463824738248382493825038251382523825338254382553825638257382583825938260382613826238263382643826538266382673826838269382703827138272382733827438275382763827738278382793828038281382823828338284382853828638287382883828938290382913829238293382943829538296382973829838299383003830138302383033830438305383063830738308383093831038311383123831338314383153831638317383183831938320383213832238323383243832538326383273832838329383303833138332383333833438335383363833738338383393834038341383423834338344383453834638347383483834938350383513835238353383543835538356383573835838359383603836138362383633836438365383663836738368383693837038371383723837338374383753837638377383783837938380383813838238383383843838538386383873838838389383903839138392383933839438395383963839738398383993840038401384023840338404384053840638407384083840938410384113841238413384143841538416384173841838419384203842138422384233842438425384263842738428384293843038431384323843338434384353843638437384383843938440384413844238443384443844538446384473844838449384503845138452384533845438455384563845738458384593846038461384623846338464384653846638467384683846938470384713847238473384743847538476384773847838479384803848138482384833848438485384863848738488384893849038491384923849338494384953849638497384983849938500385013850238503385043850538506385073850838509385103851138512385133851438515385163851738518385193852038521385223852338524385253852638527385283852938530385313853238533385343853538536385373853838539385403854138542385433854438545385463854738548385493855038551385523855338554385553855638557385583855938560385613856238563385643856538566385673856838569385703857138572385733857438575385763857738578385793858038581385823858338584385853858638587385883858938590385913859238593385943859538596385973859838599386003860138602386033860438605386063860738608386093861038611386123861338614386153861638617386183861938620386213862238623386243862538626386273862838629386303863138632386333863438635386363863738638386393864038641386423864338644386453864638647386483864938650386513865238653386543865538656386573865838659386603866138662386633866438665386663866738668386693867038671386723867338674386753867638677386783867938680386813868238683386843868538686386873868838689386903869138692386933869438695386963869738698386993870038701387023870338704387053870638707387083870938710387113871238713387143871538716387173871838719387203872138722387233872438725387263872738728387293873038731387323873338734387353873638737387383873938740387413874238743387443874538746387473874838749387503875138752387533875438755387563875738758387593876038761387623876338764387653876638767387683876938770387713877238773387743877538776387773877838779387803878138782387833878438785387863878738788387893879038791387923879338794387953879638797387983879938800388013880238803388043880538806388073880838809388103881138812388133881438815388163881738818388193882038821388223882338824388253882638827388283882938830388313883238833388343883538836388373883838839388403884138842388433884438845388463884738848388493885038851388523885338854388553885638857388583885938860388613886238863388643886538866388673886838869388703887138872388733887438875388763887738878388793888038881388823888338884388853888638887388883888938890388913889238893388943889538896388973889838899389003890138902389033890438905389063890738908389093891038911389123891338914389153891638917389183891938920389213892238923389243892538926389273892838929389303893138932389333893438935389363893738938389393894038941389423894338944389453894638947389483894938950389513895238953389543895538956389573895838959389603896138962389633896438965389663896738968389693897038971389723897338974389753897638977389783897938980389813898238983389843898538986389873898838989389903899138992389933899438995389963899738998389993900039001390023900339004390053900639007390083900939010390113901239013390143901539016390173901839019390203902139022390233902439025390263902739028390293903039031390323903339034390353903639037390383903939040390413904239043390443904539046390473904839049390503905139052390533905439055390563905739058390593906039061390623906339064390653906639067390683906939070390713907239073390743907539076390773907839079390803908139082390833908439085390863908739088390893909039091390923909339094390953909639097390983909939100391013910239103391043910539106391073910839109391103911139112391133911439115391163911739118391193912039121391223912339124391253912639127391283912939130391313913239133391343913539136391373913839139391403914139142391433914439145391463914739148391493915039151391523915339154391553915639157391583915939160391613916239163391643916539166391673916839169391703917139172391733917439175391763917739178391793918039181391823918339184391853918639187391883918939190391913919239193391943919539196391973919839199392003920139202392033920439205392063920739208392093921039211392123921339214392153921639217392183921939220392213922239223392243922539226392273922839229392303923139232392333923439235392363923739238392393924039241392423924339244392453924639247392483924939250392513925239253392543925539256392573925839259392603926139262392633926439265392663926739268392693927039271392723927339274392753927639277392783927939280392813928239283392843928539286392873928839289392903929139292392933929439295392963929739298392993930039301393023930339304393053930639307393083930939310393113931239313393143931539316393173931839319393203932139322393233932439325393263932739328393293933039331393323933339334393353933639337393383933939340393413934239343393443934539346393473934839349393503935139352393533935439355393563935739358393593936039361393623936339364393653936639367393683936939370393713937239373393743937539376393773937839379393803938139382393833938439385393863938739388393893939039391393923939339394393953939639397393983939939400394013940239403394043940539406394073940839409394103941139412394133941439415394163941739418394193942039421394223942339424394253942639427394283942939430394313943239433394343943539436394373943839439394403944139442394433944439445394463944739448394493945039451394523945339454394553945639457394583945939460394613946239463394643946539466394673946839469394703947139472394733947439475394763947739478394793948039481394823948339484394853948639487394883948939490394913949239493394943949539496394973949839499395003950139502395033950439505395063950739508395093951039511395123951339514395153951639517395183951939520395213952239523395243952539526395273952839529395303953139532395333953439535395363953739538395393954039541395423954339544395453954639547395483954939550395513955239553395543955539556395573955839559395603956139562395633956439565395663956739568395693957039571395723957339574395753957639577395783957939580395813958239583395843958539586395873958839589395903959139592395933959439595395963959739598395993960039601396023960339604396053960639607396083960939610396113961239613396143961539616396173961839619396203962139622396233962439625396263962739628396293963039631396323963339634396353963639637396383963939640396413964239643396443964539646396473964839649396503965139652396533965439655396563965739658396593966039661396623966339664396653966639667396683966939670396713967239673396743967539676396773967839679396803968139682396833968439685396863968739688396893969039691396923969339694396953969639697396983969939700397013970239703397043970539706397073970839709397103971139712397133971439715397163971739718397193972039721397223972339724397253972639727397283972939730397313973239733397343973539736397373973839739397403974139742397433974439745397463974739748397493975039751397523975339754397553975639757397583975939760397613976239763397643976539766397673976839769397703977139772397733977439775397763977739778397793978039781397823978339784397853978639787397883978939790397913979239793397943979539796397973979839799398003980139802398033980439805398063980739808398093981039811398123981339814398153981639817398183981939820398213982239823398243982539826398273982839829398303983139832398333983439835398363983739838398393984039841398423984339844398453984639847398483984939850398513985239853398543985539856398573985839859398603986139862398633986439865398663986739868398693987039871398723987339874398753987639877398783987939880398813988239883398843988539886398873988839889398903989139892398933989439895398963989739898398993990039901399023990339904399053990639907399083990939910399113991239913399143991539916399173991839919399203992139922399233992439925399263992739928399293993039931399323993339934399353993639937399383993939940399413994239943399443994539946399473994839949399503995139952399533995439955399563995739958399593996039961399623996339964399653996639967399683996939970399713997239973399743997539976399773997839979399803998139982399833998439985399863998739988399893999039991399923999339994399953999639997399983999940000400014000240003400044000540006400074000840009400104001140012400134001440015400164001740018400194002040021400224002340024400254002640027400284002940030400314003240033400344003540036400374003840039400404004140042400434004440045400464004740048400494005040051400524005340054400554005640057400584005940060400614006240063400644006540066400674006840069400704007140072400734007440075400764007740078400794008040081400824008340084400854008640087400884008940090400914009240093400944009540096400974009840099401004010140102401034010440105401064010740108401094011040111401124011340114401154011640117401184011940120401214012240123401244012540126401274012840129401304013140132401334013440135401364013740138401394014040141401424014340144401454014640147401484014940150401514015240153401544015540156401574015840159401604016140162401634016440165401664016740168401694017040171401724017340174401754017640177401784017940180401814018240183401844018540186401874018840189401904019140192401934019440195401964019740198401994020040201402024020340204402054020640207402084020940210402114021240213402144021540216402174021840219402204022140222402234022440225402264022740228402294023040231402324023340234402354023640237402384023940240402414024240243402444024540246402474024840249402504025140252402534025440255402564025740258402594026040261402624026340264402654026640267402684026940270402714027240273402744027540276402774027840279402804028140282402834028440285402864028740288402894029040291402924029340294402954029640297402984029940300403014030240303403044030540306403074030840309403104031140312403134031440315403164031740318403194032040321403224032340324403254032640327403284032940330403314033240333403344033540336403374033840339403404034140342403434034440345403464034740348403494035040351403524035340354403554035640357403584035940360403614036240363403644036540366403674036840369403704037140372403734037440375403764037740378403794038040381403824038340384403854038640387403884038940390403914039240393403944039540396403974039840399404004040140402404034040440405404064040740408404094041040411404124041340414404154041640417404184041940420404214042240423404244042540426404274042840429404304043140432404334043440435404364043740438404394044040441404424044340444404454044640447404484044940450404514045240453404544045540456404574045840459404604046140462404634046440465404664046740468404694047040471404724047340474404754047640477404784047940480404814048240483404844048540486404874048840489404904049140492404934049440495404964049740498404994050040501405024050340504405054050640507405084050940510405114051240513405144051540516405174051840519405204052140522405234052440525405264052740528405294053040531405324053340534405354053640537405384053940540405414054240543405444054540546405474054840549405504055140552405534055440555405564055740558405594056040561405624056340564405654056640567405684056940570405714057240573405744057540576405774057840579405804058140582405834058440585405864058740588405894059040591405924059340594405954059640597405984059940600406014060240603406044060540606406074060840609406104061140612406134061440615406164061740618406194062040621406224062340624406254062640627406284062940630406314063240633406344063540636406374063840639406404064140642406434064440645406464064740648406494065040651406524065340654406554065640657406584065940660406614066240663406644066540666406674066840669406704067140672406734067440675406764067740678406794068040681406824068340684406854068640687406884068940690406914069240693406944069540696406974069840699407004070140702407034070440705407064070740708407094071040711407124071340714407154071640717407184071940720407214072240723407244072540726407274072840729407304073140732407334073440735407364073740738407394074040741407424074340744407454074640747407484074940750407514075240753407544075540756407574075840759407604076140762407634076440765407664076740768407694077040771407724077340774407754077640777407784077940780407814078240783407844078540786407874078840789407904079140792407934079440795407964079740798407994080040801408024080340804408054080640807408084080940810408114081240813408144081540816408174081840819408204082140822408234082440825408264082740828408294083040831408324083340834408354083640837408384083940840408414084240843408444084540846408474084840849408504085140852408534085440855408564085740858408594086040861408624086340864408654086640867408684086940870408714087240873408744087540876408774087840879408804088140882408834088440885408864088740888408894089040891408924089340894408954089640897408984089940900409014090240903409044090540906409074090840909409104091140912409134091440915409164091740918409194092040921409224092340924409254092640927409284092940930409314093240933409344093540936409374093840939409404094140942409434094440945409464094740948409494095040951409524095340954409554095640957409584095940960409614096240963409644096540966409674096840969409704097140972409734097440975409764097740978409794098040981409824098340984409854098640987409884098940990409914099240993409944099540996409974099840999410004100141002410034100441005410064100741008410094101041011410124101341014410154101641017410184101941020410214102241023410244102541026410274102841029410304103141032410334103441035410364103741038410394104041041410424104341044410454104641047410484104941050410514105241053410544105541056410574105841059410604106141062410634106441065410664106741068410694107041071410724107341074410754107641077410784107941080410814108241083410844108541086410874108841089410904109141092410934109441095410964109741098410994110041101411024110341104411054110641107411084110941110411114111241113411144111541116411174111841119411204112141122411234112441125411264112741128411294113041131411324113341134411354113641137411384113941140411414114241143411444114541146411474114841149411504115141152411534115441155411564115741158411594116041161411624116341164411654116641167411684116941170411714117241173411744117541176411774117841179411804118141182411834118441185411864118741188411894119041191411924119341194411954119641197411984119941200412014120241203412044120541206412074120841209412104121141212412134121441215412164121741218412194122041221412224122341224412254122641227412284122941230412314123241233412344123541236412374123841239412404124141242412434124441245412464124741248412494125041251412524125341254412554125641257412584125941260412614126241263412644126541266412674126841269412704127141272412734127441275412764127741278412794128041281412824128341284412854128641287412884128941290412914129241293412944129541296412974129841299413004130141302413034130441305413064130741308413094131041311413124131341314413154131641317413184131941320413214132241323413244132541326413274132841329413304133141332413334133441335413364133741338413394134041341413424134341344413454134641347413484134941350413514135241353413544135541356413574135841359413604136141362413634136441365413664136741368413694137041371413724137341374413754137641377413784137941380413814138241383413844138541386413874138841389413904139141392413934139441395413964139741398413994140041401414024140341404414054140641407414084140941410414114141241413414144141541416414174141841419414204142141422414234142441425414264142741428414294143041431414324143341434414354143641437414384143941440414414144241443414444144541446414474144841449414504145141452414534145441455414564145741458414594146041461414624146341464414654146641467414684146941470414714147241473414744147541476414774147841479414804148141482414834148441485414864148741488414894149041491414924149341494414954149641497414984149941500415014150241503415044150541506415074150841509415104151141512415134151441515415164151741518415194152041521415224152341524415254152641527415284152941530415314153241533415344153541536415374153841539415404154141542415434154441545415464154741548415494155041551415524155341554415554155641557415584155941560415614156241563415644156541566415674156841569415704157141572415734157441575415764157741578415794158041581415824158341584415854158641587415884158941590415914159241593415944159541596415974159841599416004160141602416034160441605416064160741608416094161041611416124161341614416154161641617416184161941620416214162241623416244162541626416274162841629416304163141632416334163441635416364163741638416394164041641416424164341644416454164641647416484164941650416514165241653416544165541656416574165841659416604166141662416634166441665416664166741668416694167041671416724167341674416754167641677416784167941680416814168241683416844168541686416874168841689416904169141692416934169441695416964169741698416994170041701417024170341704417054170641707417084170941710417114171241713417144171541716417174171841719417204172141722417234172441725417264172741728417294173041731417324173341734417354173641737417384173941740417414174241743417444174541746417474174841749417504175141752417534175441755417564175741758417594176041761417624176341764417654176641767417684176941770417714177241773417744177541776417774177841779417804178141782417834178441785417864178741788417894179041791417924179341794417954179641797417984179941800418014180241803418044180541806418074180841809418104181141812418134181441815418164181741818418194182041821418224182341824418254182641827418284182941830418314183241833418344183541836418374183841839418404184141842418434184441845418464184741848418494185041851418524185341854418554185641857418584185941860418614186241863418644186541866418674186841869418704187141872418734187441875418764187741878418794188041881418824188341884418854188641887418884188941890418914189241893418944189541896418974189841899419004190141902419034190441905419064190741908419094191041911419124191341914419154191641917419184191941920419214192241923419244192541926419274192841929419304193141932419334193441935419364193741938419394194041941419424194341944419454194641947419484194941950419514195241953419544195541956419574195841959419604196141962419634196441965419664196741968419694197041971419724197341974419754197641977419784197941980419814198241983419844198541986419874198841989419904199141992419934199441995419964199741998419994200042001420024200342004420054200642007420084200942010420114201242013420144201542016420174201842019420204202142022420234202442025420264202742028420294203042031420324203342034420354203642037420384203942040420414204242043420444204542046420474204842049420504205142052420534205442055420564205742058420594206042061420624206342064420654206642067420684206942070420714207242073420744207542076420774207842079420804208142082420834208442085420864208742088420894209042091420924209342094420954209642097420984209942100421014210242103421044210542106421074210842109421104211142112421134211442115421164211742118421194212042121421224212342124421254212642127421284212942130421314213242133421344213542136421374213842139421404214142142421434214442145421464214742148421494215042151421524215342154421554215642157421584215942160421614216242163421644216542166421674216842169421704217142172421734217442175421764217742178421794218042181421824218342184421854218642187421884218942190421914219242193421944219542196421974219842199422004220142202422034220442205422064220742208422094221042211422124221342214422154221642217422184221942220422214222242223422244222542226422274222842229422304223142232422334223442235422364223742238422394224042241422424224342244422454224642247422484224942250422514225242253422544225542256422574225842259422604226142262422634226442265422664226742268422694227042271422724227342274422754227642277422784227942280422814228242283422844228542286422874228842289422904229142292422934229442295422964229742298422994230042301423024230342304423054230642307423084230942310423114231242313423144231542316423174231842319423204232142322423234232442325423264232742328423294233042331423324233342334423354233642337423384233942340423414234242343423444234542346423474234842349423504235142352423534235442355423564235742358423594236042361423624236342364423654236642367423684236942370423714237242373423744237542376423774237842379423804238142382423834238442385423864238742388423894239042391423924239342394423954239642397423984239942400424014240242403424044240542406424074240842409424104241142412424134241442415424164241742418424194242042421424224242342424424254242642427424284242942430424314243242433424344243542436424374243842439424404244142442424434244442445424464244742448424494245042451424524245342454424554245642457424584245942460424614246242463424644246542466424674246842469424704247142472424734247442475424764247742478424794248042481424824248342484424854248642487424884248942490424914249242493424944249542496424974249842499425004250142502425034250442505425064250742508425094251042511425124251342514425154251642517425184251942520425214252242523425244252542526425274252842529425304253142532425334253442535425364253742538425394254042541425424254342544425454254642547425484254942550425514255242553425544255542556425574255842559425604256142562425634256442565425664256742568425694257042571425724257342574425754257642577425784257942580425814258242583425844258542586425874258842589425904259142592425934259442595425964259742598425994260042601426024260342604426054260642607426084260942610426114261242613426144261542616426174261842619426204262142622426234262442625426264262742628426294263042631426324263342634426354263642637426384263942640426414264242643426444264542646426474264842649426504265142652426534265442655426564265742658426594266042661426624266342664426654266642667426684266942670426714267242673426744267542676426774267842679426804268142682426834268442685426864268742688426894269042691426924269342694426954269642697426984269942700427014270242703427044270542706427074270842709427104271142712427134271442715427164271742718427194272042721427224272342724427254272642727427284272942730427314273242733427344273542736427374273842739427404274142742427434274442745427464274742748427494275042751427524275342754427554275642757427584275942760427614276242763427644276542766427674276842769427704277142772427734277442775427764277742778427794278042781427824278342784427854278642787427884278942790427914279242793427944279542796427974279842799428004280142802428034280442805428064280742808428094281042811428124281342814428154281642817428184281942820428214282242823428244282542826428274282842829428304283142832428334283442835428364283742838428394284042841428424284342844428454284642847428484284942850428514285242853428544285542856428574285842859428604286142862428634286442865428664286742868428694287042871428724287342874428754287642877428784287942880428814288242883428844288542886428874288842889428904289142892428934289442895428964289742898428994290042901429024290342904429054290642907429084290942910429114291242913429144291542916429174291842919429204292142922429234292442925429264292742928429294293042931429324293342934429354293642937429384293942940429414294242943429444294542946429474294842949429504295142952429534295442955429564295742958429594296042961429624296342964429654296642967429684296942970429714297242973429744297542976429774297842979429804298142982429834298442985429864298742988429894299042991429924299342994429954299642997429984299943000430014300243003430044300543006430074300843009430104301143012430134301443015430164301743018430194302043021430224302343024430254302643027430284302943030430314303243033430344303543036430374303843039430404304143042430434304443045430464304743048430494305043051430524305343054430554305643057430584305943060430614306243063430644306543066430674306843069430704307143072430734307443075430764307743078430794308043081430824308343084430854308643087430884308943090430914309243093430944309543096430974309843099431004310143102431034310443105431064310743108431094311043111431124311343114431154311643117431184311943120431214312243123431244312543126431274312843129431304313143132431334313443135431364313743138431394314043141431424314343144431454314643147431484314943150431514315243153431544315543156431574315843159431604316143162431634316443165431664316743168431694317043171431724317343174431754317643177431784317943180431814318243183431844318543186431874318843189431904319143192431934319443195431964319743198431994320043201432024320343204432054320643207432084320943210432114321243213432144321543216432174321843219432204322143222432234322443225432264322743228432294323043231432324323343234432354323643237432384323943240432414324243243432444324543246432474324843249432504325143252432534325443255432564325743258432594326043261432624326343264432654326643267432684326943270432714327243273432744327543276432774327843279432804328143282432834328443285432864328743288432894329043291432924329343294432954329643297432984329943300433014330243303433044330543306433074330843309433104331143312433134331443315433164331743318433194332043321433224332343324433254332643327433284332943330433314333243333433344333543336433374333843339433404334143342433434334443345433464334743348433494335043351433524335343354433554335643357433584335943360433614336243363433644336543366433674336843369433704337143372433734337443375433764337743378433794338043381433824338343384433854338643387433884338943390433914339243393433944339543396433974339843399434004340143402434034340443405434064340743408434094341043411434124341343414434154341643417434184341943420434214342243423434244342543426434274342843429434304343143432434334343443435434364343743438434394344043441434424344343444434454344643447434484344943450434514345243453434544345543456434574345843459434604346143462434634346443465434664346743468434694347043471434724347343474434754347643477434784347943480434814348243483434844348543486434874348843489434904349143492434934349443495434964349743498434994350043501435024350343504435054350643507435084350943510435114351243513435144351543516435174351843519435204352143522435234352443525435264352743528435294353043531435324353343534435354353643537435384353943540435414354243543435444354543546435474354843549435504355143552435534355443555435564355743558435594356043561435624356343564435654356643567435684356943570435714357243573435744357543576435774357843579435804358143582435834358443585435864358743588435894359043591435924359343594435954359643597435984359943600436014360243603436044360543606436074360843609436104361143612436134361443615436164361743618436194362043621436224362343624436254362643627436284362943630436314363243633436344363543636436374363843639436404364143642436434364443645436464364743648436494365043651436524365343654436554365643657436584365943660436614366243663436644366543666436674366843669436704367143672436734367443675436764367743678436794368043681436824368343684436854368643687436884368943690436914369243693436944369543696436974369843699437004370143702437034370443705437064370743708437094371043711437124371343714437154371643717437184371943720437214372243723437244372543726437274372843729437304373143732437334373443735437364373743738437394374043741437424374343744437454374643747437484374943750437514375243753437544375543756437574375843759437604376143762437634376443765437664376743768437694377043771437724377343774437754377643777437784377943780437814378243783437844378543786437874378843789437904379143792437934379443795437964379743798437994380043801438024380343804438054380643807438084380943810438114381243813438144381543816438174381843819438204382143822438234382443825438264382743828438294383043831438324383343834438354383643837438384383943840438414384243843438444384543846438474384843849438504385143852438534385443855438564385743858438594386043861438624386343864438654386643867438684386943870438714387243873438744387543876438774387843879438804388143882438834388443885438864388743888438894389043891438924389343894438954389643897438984389943900439014390243903439044390543906439074390843909439104391143912439134391443915439164391743918439194392043921439224392343924439254392643927439284392943930439314393243933439344393543936439374393843939439404394143942439434394443945439464394743948439494395043951439524395343954439554395643957439584395943960439614396243963439644396543966439674396843969439704397143972439734397443975439764397743978439794398043981439824398343984439854398643987439884398943990439914399243993439944399543996439974399843999440004400144002440034400444005440064400744008440094401044011440124401344014440154401644017440184401944020440214402244023440244402544026440274402844029440304403144032440334403444035440364403744038440394404044041440424404344044440454404644047440484404944050440514405244053440544405544056440574405844059440604406144062440634406444065440664406744068440694407044071440724407344074440754407644077440784407944080440814408244083440844408544086440874408844089440904409144092440934409444095440964409744098440994410044101441024410344104441054410644107441084410944110441114411244113441144411544116441174411844119441204412144122441234412444125441264412744128441294413044131441324413344134441354413644137441384413944140441414414244143441444414544146441474414844149441504415144152441534415444155441564415744158441594416044161441624416344164441654416644167441684416944170441714417244173441744417544176441774417844179441804418144182441834418444185441864418744188441894419044191441924419344194441954419644197441984419944200442014420244203442044420544206442074420844209442104421144212442134421444215442164421744218442194422044221442224422344224442254422644227442284422944230442314423244233442344423544236442374423844239442404424144242442434424444245442464424744248442494425044251442524425344254442554425644257442584425944260442614426244263442644426544266442674426844269442704427144272442734427444275442764427744278442794428044281442824428344284442854428644287442884428944290442914429244293442944429544296442974429844299443004430144302443034430444305443064430744308443094431044311443124431344314443154431644317443184431944320443214432244323443244432544326443274432844329443304433144332443334433444335443364433744338443394434044341443424434344344443454434644347443484434944350443514435244353443544435544356443574435844359443604436144362443634436444365443664436744368443694437044371443724437344374443754437644377443784437944380443814438244383443844438544386443874438844389443904439144392443934439444395443964439744398443994440044401444024440344404444054440644407444084440944410444114441244413444144441544416444174441844419444204442144422444234442444425444264442744428444294443044431444324443344434444354443644437444384443944440444414444244443444444444544446444474444844449444504445144452444534445444455444564445744458444594446044461444624446344464444654446644467444684446944470444714447244473444744447544476444774447844479444804448144482444834448444485444864448744488444894449044491444924449344494444954449644497444984449944500445014450244503445044450544506445074450844509445104451144512445134451444515445164451744518445194452044521445224452344524445254452644527445284452944530445314453244533445344453544536445374453844539445404454144542445434454444545445464454744548445494455044551445524455344554445554455644557445584455944560445614456244563445644456544566445674456844569445704457144572445734457444575445764457744578445794458044581445824458344584445854458644587445884458944590445914459244593445944459544596445974459844599446004460144602446034460444605446064460744608446094461044611446124461344614446154461644617446184461944620446214462244623446244462544626446274462844629446304463144632446334463444635446364463744638446394464044641446424464344644446454464644647446484464944650446514465244653446544465544656446574465844659446604466144662446634466444665446664466744668446694467044671446724467344674446754467644677446784467944680446814468244683446844468544686446874468844689446904469144692446934469444695446964469744698446994470044701447024470344704447054470644707447084470944710447114471244713447144471544716447174471844719447204472144722447234472444725447264472744728447294473044731447324473344734447354473644737447384473944740447414474244743447444474544746447474474844749447504475144752447534475444755447564475744758447594476044761447624476344764447654476644767447684476944770447714477244773447744477544776447774477844779447804478144782447834478444785447864478744788447894479044791447924479344794447954479644797447984479944800448014480244803448044480544806448074480844809448104481144812448134481444815448164481744818448194482044821448224482344824448254482644827448284482944830448314483244833448344483544836448374483844839448404484144842448434484444845448464484744848448494485044851448524485344854448554485644857448584485944860448614486244863448644486544866448674486844869448704487144872448734487444875448764487744878448794488044881448824488344884448854488644887448884488944890448914489244893448944489544896448974489844899449004490144902449034490444905449064490744908449094491044911449124491344914449154491644917449184491944920449214492244923449244492544926449274492844929449304493144932449334493444935449364493744938449394494044941449424494344944449454494644947449484494944950449514495244953449544495544956449574495844959449604496144962449634496444965449664496744968449694497044971449724497344974449754497644977449784497944980449814498244983449844498544986449874498844989449904499144992449934499444995449964499744998449994500045001450024500345004450054500645007450084500945010450114501245013450144501545016450174501845019450204502145022450234502445025450264502745028450294503045031450324503345034450354503645037450384503945040450414504245043450444504545046450474504845049450504505145052450534505445055450564505745058450594506045061450624506345064450654506645067450684506945070450714507245073450744507545076450774507845079450804508145082450834508445085450864508745088450894509045091450924509345094450954509645097450984509945100451014510245103451044510545106451074510845109451104511145112451134511445115451164511745118451194512045121451224512345124451254512645127451284512945130451314513245133451344513545136451374513845139451404514145142451434514445145451464514745148451494515045151451524515345154451554515645157451584515945160451614516245163451644516545166451674516845169451704517145172451734517445175451764517745178451794518045181451824518345184451854518645187451884518945190451914519245193451944519545196451974519845199452004520145202452034520445205452064520745208452094521045211452124521345214452154521645217452184521945220452214522245223452244522545226452274522845229452304523145232452334523445235452364523745238452394524045241452424524345244452454524645247452484524945250452514525245253452544525545256452574525845259452604526145262452634526445265452664526745268452694527045271452724527345274452754527645277452784527945280452814528245283452844528545286452874528845289452904529145292452934529445295452964529745298452994530045301453024530345304453054530645307453084530945310453114531245313453144531545316453174531845319453204532145322453234532445325453264532745328453294533045331453324533345334453354533645337453384533945340453414534245343453444534545346453474534845349453504535145352453534535445355453564535745358453594536045361453624536345364453654536645367453684536945370453714537245373453744537545376453774537845379453804538145382453834538445385453864538745388453894539045391453924539345394453954539645397453984539945400454014540245403454044540545406454074540845409454104541145412454134541445415454164541745418454194542045421454224542345424454254542645427454284542945430454314543245433454344543545436454374543845439454404544145442454434544445445454464544745448454494545045451454524545345454454554545645457454584545945460454614546245463454644546545466454674546845469454704547145472454734547445475454764547745478454794548045481454824548345484454854548645487454884548945490454914549245493454944549545496454974549845499455004550145502455034550445505455064550745508455094551045511455124551345514455154551645517455184551945520455214552245523455244552545526455274552845529455304553145532455334553445535455364553745538455394554045541455424554345544455454554645547455484554945550455514555245553455544555545556455574555845559455604556145562455634556445565455664556745568455694557045571455724557345574455754557645577455784557945580455814558245583455844558545586455874558845589455904559145592455934559445595455964559745598455994560045601456024560345604456054560645607456084560945610456114561245613456144561545616456174561845619456204562145622456234562445625456264562745628456294563045631456324563345634456354563645637456384563945640456414564245643456444564545646456474564845649456504565145652456534565445655456564565745658456594566045661456624566345664456654566645667456684566945670456714567245673456744567545676456774567845679456804568145682456834568445685456864568745688456894569045691456924569345694456954569645697456984569945700457014570245703457044570545706457074570845709457104571145712457134571445715457164571745718457194572045721457224572345724457254572645727457284572945730457314573245733457344573545736457374573845739457404574145742457434574445745457464574745748457494575045751457524575345754457554575645757457584575945760457614576245763457644576545766457674576845769457704577145772457734577445775457764577745778457794578045781457824578345784457854578645787457884578945790457914579245793457944579545796457974579845799458004580145802458034580445805458064580745808458094581045811458124581345814458154581645817458184581945820458214582245823458244582545826458274582845829458304583145832458334583445835458364583745838458394584045841458424584345844458454584645847458484584945850458514585245853458544585545856458574585845859458604586145862458634586445865458664586745868458694587045871458724587345874458754587645877458784587945880458814588245883458844588545886458874588845889458904589145892458934589445895458964589745898458994590045901459024590345904459054590645907459084590945910459114591245913459144591545916459174591845919459204592145922459234592445925459264592745928459294593045931459324593345934459354593645937459384593945940459414594245943459444594545946459474594845949459504595145952459534595445955459564595745958459594596045961459624596345964459654596645967459684596945970459714597245973459744597545976459774597845979459804598145982459834598445985459864598745988459894599045991459924599345994459954599645997459984599946000460014600246003460044600546006460074600846009460104601146012460134601446015460164601746018460194602046021460224602346024460254602646027460284602946030460314603246033460344603546036460374603846039460404604146042460434604446045460464604746048460494605046051460524605346054460554605646057460584605946060460614606246063460644606546066460674606846069460704607146072460734607446075460764607746078460794608046081460824608346084460854608646087460884608946090460914609246093460944609546096460974609846099461004610146102461034610446105461064610746108461094611046111461124611346114461154611646117461184611946120461214612246123461244612546126461274612846129461304613146132461334613446135461364613746138461394614046141461424614346144461454614646147461484614946150461514615246153461544615546156461574615846159461604616146162461634616446165461664616746168461694617046171461724617346174461754617646177461784617946180461814618246183461844618546186461874618846189461904619146192461934619446195461964619746198461994620046201462024620346204462054620646207462084620946210462114621246213462144621546216462174621846219462204622146222462234622446225462264622746228462294623046231462324623346234462354623646237462384623946240462414624246243462444624546246462474624846249462504625146252462534625446255462564625746258462594626046261462624626346264462654626646267462684626946270462714627246273462744627546276462774627846279462804628146282462834628446285462864628746288462894629046291462924629346294462954629646297462984629946300463014630246303463044630546306463074630846309463104631146312463134631446315463164631746318463194632046321463224632346324463254632646327463284632946330463314633246333463344633546336463374633846339463404634146342463434634446345463464634746348463494635046351463524635346354463554635646357463584635946360463614636246363463644636546366463674636846369463704637146372463734637446375463764637746378463794638046381463824638346384463854638646387463884638946390463914639246393463944639546396463974639846399464004640146402464034640446405464064640746408464094641046411464124641346414464154641646417464184641946420464214642246423464244642546426464274642846429464304643146432464334643446435464364643746438464394644046441464424644346444464454644646447464484644946450464514645246453464544645546456464574645846459464604646146462464634646446465464664646746468464694647046471464724647346474464754647646477464784647946480464814648246483464844648546486464874648846489464904649146492464934649446495464964649746498464994650046501465024650346504465054650646507465084650946510465114651246513465144651546516465174651846519465204652146522465234652446525465264652746528465294653046531465324653346534465354653646537465384653946540465414654246543465444654546546465474654846549465504655146552465534655446555465564655746558465594656046561465624656346564465654656646567465684656946570465714657246573465744657546576465774657846579465804658146582465834658446585465864658746588465894659046591465924659346594465954659646597465984659946600466014660246603466044660546606466074660846609466104661146612466134661446615466164661746618466194662046621466224662346624466254662646627466284662946630466314663246633466344663546636466374663846639466404664146642466434664446645466464664746648466494665046651466524665346654466554665646657466584665946660466614666246663466644666546666466674666846669466704667146672466734667446675466764667746678466794668046681466824668346684466854668646687466884668946690466914669246693466944669546696466974669846699467004670146702467034670446705467064670746708467094671046711467124671346714467154671646717467184671946720467214672246723467244672546726467274672846729467304673146732467334673446735467364673746738467394674046741467424674346744467454674646747467484674946750467514675246753467544675546756467574675846759467604676146762467634676446765467664676746768467694677046771467724677346774467754677646777467784677946780467814678246783467844678546786467874678846789467904679146792467934679446795467964679746798467994680046801468024680346804468054680646807468084680946810468114681246813468144681546816468174681846819468204682146822468234682446825468264682746828468294683046831468324683346834468354683646837468384683946840468414684246843468444684546846468474684846849468504685146852468534685446855468564685746858468594686046861468624686346864468654686646867468684686946870468714687246873468744687546876468774687846879468804688146882468834688446885468864688746888468894689046891468924689346894468954689646897468984689946900469014690246903469044690546906469074690846909469104691146912469134691446915469164691746918469194692046921469224692346924469254692646927469284692946930469314693246933469344693546936469374693846939469404694146942469434694446945469464694746948469494695046951469524695346954469554695646957469584695946960469614696246963469644696546966469674696846969469704697146972469734697446975469764697746978469794698046981469824698346984469854698646987469884698946990469914699246993469944699546996469974699846999470004700147002470034700447005470064700747008470094701047011470124701347014470154701647017470184701947020470214702247023470244702547026470274702847029470304703147032470334703447035470364703747038470394704047041470424704347044470454704647047470484704947050470514705247053470544705547056470574705847059470604706147062470634706447065470664706747068470694707047071470724707347074470754707647077470784707947080470814708247083470844708547086470874708847089470904709147092470934709447095470964709747098470994710047101471024710347104471054710647107471084710947110471114711247113471144711547116471174711847119471204712147122471234712447125471264712747128471294713047131471324713347134471354713647137471384713947140471414714247143471444714547146471474714847149471504715147152471534715447155471564715747158471594716047161471624716347164471654716647167471684716947170471714717247173471744717547176471774717847179471804718147182471834718447185471864718747188471894719047191471924719347194471954719647197471984719947200472014720247203472044720547206472074720847209472104721147212472134721447215472164721747218472194722047221472224722347224472254722647227472284722947230472314723247233472344723547236472374723847239472404724147242472434724447245472464724747248472494725047251472524725347254472554725647257472584725947260472614726247263472644726547266472674726847269472704727147272472734727447275472764727747278472794728047281472824728347284472854728647287472884728947290472914729247293472944729547296472974729847299473004730147302473034730447305473064730747308473094731047311473124731347314473154731647317473184731947320473214732247323473244732547326473274732847329473304733147332473334733447335473364733747338473394734047341473424734347344473454734647347473484734947350473514735247353473544735547356473574735847359473604736147362473634736447365473664736747368473694737047371473724737347374473754737647377473784737947380473814738247383473844738547386473874738847389473904739147392473934739447395473964739747398473994740047401474024740347404474054740647407474084740947410474114741247413474144741547416474174741847419474204742147422474234742447425474264742747428474294743047431474324743347434474354743647437474384743947440474414744247443474444744547446474474744847449474504745147452474534745447455474564745747458474594746047461474624746347464474654746647467474684746947470474714747247473474744747547476474774747847479474804748147482474834748447485474864748747488474894749047491474924749347494474954749647497474984749947500475014750247503475044750547506475074750847509475104751147512475134751447515475164751747518475194752047521475224752347524475254752647527475284752947530475314753247533475344753547536475374753847539475404754147542475434754447545475464754747548475494755047551475524755347554475554755647557475584755947560475614756247563475644756547566475674756847569475704757147572475734757447575475764757747578475794758047581475824758347584475854758647587475884758947590475914759247593475944759547596475974759847599476004760147602476034760447605476064760747608476094761047611476124761347614476154761647617476184761947620476214762247623476244762547626476274762847629476304763147632476334763447635476364763747638476394764047641476424764347644476454764647647476484764947650476514765247653476544765547656476574765847659476604766147662476634766447665476664766747668476694767047671476724767347674476754767647677476784767947680476814768247683476844768547686476874768847689476904769147692476934769447695476964769747698476994770047701477024770347704477054770647707477084770947710477114771247713477144771547716477174771847719477204772147722477234772447725477264772747728477294773047731477324773347734477354773647737477384773947740477414774247743477444774547746477474774847749477504775147752477534775447755477564775747758477594776047761477624776347764477654776647767477684776947770477714777247773477744777547776477774777847779477804778147782477834778447785477864778747788477894779047791477924779347794477954779647797477984779947800478014780247803478044780547806478074780847809478104781147812478134781447815478164781747818478194782047821478224782347824478254782647827478284782947830478314783247833478344783547836478374783847839478404784147842478434784447845478464784747848478494785047851478524785347854478554785647857478584785947860478614786247863478644786547866478674786847869478704787147872478734787447875478764787747878478794788047881478824788347884478854788647887478884788947890478914789247893478944789547896478974789847899479004790147902479034790447905479064790747908479094791047911479124791347914479154791647917479184791947920479214792247923479244792547926479274792847929479304793147932479334793447935479364793747938479394794047941479424794347944479454794647947479484794947950479514795247953479544795547956479574795847959479604796147962479634796447965479664796747968479694797047971479724797347974479754797647977479784797947980479814798247983479844798547986479874798847989479904799147992479934799447995479964799747998479994800048001480024800348004480054800648007480084800948010480114801248013480144801548016480174801848019480204802148022480234802448025480264802748028480294803048031480324803348034480354803648037480384803948040480414804248043480444804548046480474804848049480504805148052480534805448055480564805748058480594806048061480624806348064480654806648067480684806948070480714807248073480744807548076480774807848079480804808148082480834808448085480864808748088480894809048091480924809348094480954809648097480984809948100481014810248103481044810548106481074810848109481104811148112481134811448115481164811748118481194812048121481224812348124481254812648127481284812948130481314813248133481344813548136481374813848139481404814148142481434814448145481464814748148481494815048151481524815348154481554815648157481584815948160481614816248163481644816548166481674816848169481704817148172481734817448175481764817748178481794818048181481824818348184481854818648187481884818948190481914819248193481944819548196481974819848199482004820148202482034820448205482064820748208482094821048211482124821348214482154821648217482184821948220482214822248223482244822548226482274822848229482304823148232482334823448235482364823748238482394824048241482424824348244482454824648247482484824948250482514825248253482544825548256482574825848259482604826148262482634826448265482664826748268482694827048271482724827348274482754827648277482784827948280482814828248283482844828548286482874828848289482904829148292482934829448295482964829748298482994830048301483024830348304483054830648307483084830948310483114831248313483144831548316483174831848319483204832148322483234832448325483264832748328483294833048331483324833348334483354833648337483384833948340483414834248343483444834548346483474834848349483504835148352483534835448355483564835748358483594836048361483624836348364483654836648367483684836948370483714837248373483744837548376483774837848379483804838148382483834838448385483864838748388483894839048391483924839348394483954839648397483984839948400484014840248403484044840548406484074840848409484104841148412484134841448415484164841748418484194842048421484224842348424484254842648427484284842948430484314843248433484344843548436484374843848439484404844148442484434844448445484464844748448484494845048451484524845348454484554845648457484584845948460484614846248463484644846548466484674846848469484704847148472484734847448475484764847748478484794848048481484824848348484484854848648487484884848948490484914849248493484944849548496484974849848499485004850148502485034850448505485064850748508485094851048511485124851348514485154851648517485184851948520485214852248523485244852548526485274852848529485304853148532485334853448535485364853748538485394854048541485424854348544485454854648547485484854948550485514855248553485544855548556485574855848559485604856148562485634856448565485664856748568485694857048571485724857348574485754857648577485784857948580485814858248583485844858548586485874858848589485904859148592485934859448595485964859748598485994860048601486024860348604486054860648607486084860948610486114861248613486144861548616486174861848619486204862148622486234862448625486264862748628486294863048631486324863348634486354863648637486384863948640486414864248643486444864548646486474864848649486504865148652486534865448655486564865748658486594866048661486624866348664486654866648667486684866948670486714867248673486744867548676486774867848679486804868148682486834868448685486864868748688486894869048691486924869348694486954869648697486984869948700487014870248703487044870548706487074870848709487104871148712487134871448715487164871748718487194872048721487224872348724487254872648727487284872948730487314873248733487344873548736487374873848739487404874148742487434874448745487464874748748487494875048751487524875348754487554875648757487584875948760487614876248763487644876548766487674876848769487704877148772487734877448775487764877748778487794878048781487824878348784487854878648787487884878948790487914879248793487944879548796487974879848799488004880148802488034880448805488064880748808488094881048811488124881348814488154881648817488184881948820488214882248823488244882548826488274882848829488304883148832488334883448835488364883748838488394884048841488424884348844488454884648847488484884948850488514885248853488544885548856488574885848859488604886148862488634886448865488664886748868488694887048871488724887348874488754887648877488784887948880488814888248883488844888548886488874888848889488904889148892488934889448895488964889748898488994890048901489024890348904489054890648907489084890948910489114891248913489144891548916489174891848919489204892148922489234892448925489264892748928489294893048931489324893348934489354893648937489384893948940489414894248943489444894548946489474894848949489504895148952489534895448955489564895748958489594896048961489624896348964489654896648967489684896948970489714897248973489744897548976489774897848979489804898148982489834898448985489864898748988489894899048991489924899348994489954899648997489984899949000490014900249003490044900549006490074900849009490104901149012490134901449015490164901749018490194902049021490224902349024490254902649027490284902949030490314903249033490344903549036490374903849039490404904149042490434904449045490464904749048490494905049051490524905349054490554905649057490584905949060490614906249063490644906549066490674906849069490704907149072490734907449075490764907749078490794908049081490824908349084490854908649087490884908949090490914909249093490944909549096490974909849099491004910149102491034910449105491064910749108491094911049111491124911349114491154911649117491184911949120491214912249123491244912549126491274912849129491304913149132491334913449135491364913749138491394914049141491424914349144491454914649147491484914949150491514915249153491544915549156491574915849159491604916149162491634916449165491664916749168491694917049171491724917349174491754917649177491784917949180491814918249183491844918549186491874918849189491904919149192491934919449195491964919749198491994920049201492024920349204492054920649207492084920949210492114921249213492144921549216492174921849219492204922149222492234922449225492264922749228492294923049231492324923349234492354923649237492384923949240492414924249243492444924549246492474924849249492504925149252492534925449255492564925749258492594926049261492624926349264492654926649267492684926949270492714927249273492744927549276492774927849279492804928149282492834928449285492864928749288492894929049291492924929349294492954929649297492984929949300493014930249303493044930549306493074930849309493104931149312493134931449315493164931749318493194932049321493224932349324493254932649327493284932949330493314933249333493344933549336493374933849339493404934149342493434934449345493464934749348493494935049351493524935349354493554935649357493584935949360493614936249363493644936549366493674936849369493704937149372493734937449375493764937749378493794938049381493824938349384493854938649387493884938949390493914939249393493944939549396493974939849399494004940149402494034940449405494064940749408494094941049411494124941349414494154941649417494184941949420494214942249423494244942549426494274942849429494304943149432494334943449435494364943749438494394944049441494424944349444494454944649447494484944949450494514945249453494544945549456494574945849459494604946149462494634946449465494664946749468494694947049471494724947349474494754947649477494784947949480494814948249483494844948549486494874948849489494904949149492494934949449495494964949749498494994950049501495024950349504495054950649507495084950949510495114951249513495144951549516495174951849519495204952149522495234952449525495264952749528495294953049531495324953349534495354953649537495384953949540495414954249543495444954549546495474954849549495504955149552495534955449555495564955749558495594956049561495624956349564495654956649567495684956949570495714957249573495744957549576495774957849579495804958149582495834958449585495864958749588495894959049591495924959349594495954959649597495984959949600496014960249603496044960549606496074960849609496104961149612496134961449615496164961749618496194962049621496224962349624496254962649627496284962949630496314963249633496344963549636496374963849639496404964149642496434964449645496464964749648496494965049651496524965349654496554965649657496584965949660496614966249663496644966549666496674966849669496704967149672496734967449675496764967749678496794968049681496824968349684496854968649687496884968949690496914969249693496944969549696496974969849699497004970149702497034970449705497064970749708497094971049711497124971349714497154971649717497184971949720497214972249723497244972549726497274972849729497304973149732497334973449735497364973749738497394974049741497424974349744497454974649747497484974949750497514975249753497544975549756497574975849759497604976149762497634976449765497664976749768497694977049771497724977349774497754977649777497784977949780497814978249783497844978549786497874978849789497904979149792497934979449795497964979749798497994980049801498024980349804498054980649807498084980949810498114981249813498144981549816498174981849819498204982149822498234982449825498264982749828498294983049831498324983349834498354983649837498384983949840498414984249843498444984549846498474984849849498504985149852498534985449855498564985749858498594986049861498624986349864498654986649867498684986949870498714987249873498744987549876498774987849879498804988149882498834988449885498864988749888498894989049891498924989349894498954989649897498984989949900499014990249903499044990549906499074990849909499104991149912499134991449915499164991749918499194992049921499224992349924499254992649927499284992949930499314993249933499344993549936499374993849939499404994149942499434994449945499464994749948499494995049951499524995349954499554995649957499584995949960499614996249963499644996549966499674996849969499704997149972499734997449975499764997749978499794998049981499824998349984499854998649987499884998949990499914999249993499944999549996499974999849999500005000150002500035000450005500065000750008500095001050011500125001350014500155001650017500185001950020500215002250023500245002550026500275002850029500305003150032500335003450035500365003750038500395004050041500425004350044500455004650047500485004950050500515005250053500545005550056500575005850059500605006150062500635006450065500665006750068500695007050071500725007350074500755007650077500785007950080500815008250083500845008550086500875008850089500905009150092500935009450095500965009750098500995010050101501025010350104501055010650107501085010950110501115011250113501145011550116501175011850119501205012150122501235012450125501265012750128501295013050131501325013350134501355013650137501385013950140501415014250143501445014550146501475014850149501505015150152501535015450155501565015750158501595016050161501625016350164501655016650167501685016950170501715017250173501745017550176501775017850179501805018150182501835018450185501865018750188501895019050191501925019350194501955019650197501985019950200502015020250203502045020550206502075020850209502105021150212502135021450215502165021750218502195022050221502225022350224502255022650227502285022950230502315023250233502345023550236502375023850239502405024150242502435024450245502465024750248502495025050251502525025350254502555025650257502585025950260502615026250263502645026550266502675026850269502705027150272502735027450275502765027750278502795028050281502825028350284502855028650287502885028950290502915029250293502945029550296502975029850299503005030150302503035030450305503065030750308503095031050311503125031350314503155031650317503185031950320503215032250323503245032550326503275032850329503305033150332503335033450335503365033750338503395034050341503425034350344503455034650347503485034950350503515035250353503545035550356503575035850359503605036150362503635036450365503665036750368503695037050371503725037350374503755037650377503785037950380503815038250383503845038550386503875038850389503905039150392503935039450395503965039750398503995040050401504025040350404504055040650407504085040950410504115041250413504145041550416504175041850419504205042150422504235042450425504265042750428504295043050431504325043350434504355043650437504385043950440504415044250443504445044550446504475044850449504505045150452504535045450455504565045750458504595046050461504625046350464504655046650467504685046950470504715047250473504745047550476504775047850479504805048150482504835048450485504865048750488504895049050491504925049350494504955049650497504985049950500505015050250503505045050550506505075050850509505105051150512505135051450515505165051750518505195052050521505225052350524505255052650527505285052950530505315053250533505345053550536505375053850539505405054150542505435054450545505465054750548505495055050551505525055350554505555055650557505585055950560505615056250563505645056550566505675056850569505705057150572505735057450575505765057750578505795058050581505825058350584505855058650587505885058950590505915059250593505945059550596505975059850599506005060150602506035060450605506065060750608506095061050611506125061350614506155061650617506185061950620506215062250623506245062550626506275062850629506305063150632506335063450635506365063750638506395064050641506425064350644506455064650647506485064950650506515065250653506545065550656506575065850659506605066150662506635066450665506665066750668506695067050671506725067350674506755067650677506785067950680506815068250683506845068550686506875068850689506905069150692506935069450695506965069750698506995070050701507025070350704507055070650707507085070950710507115071250713507145071550716507175071850719507205072150722507235072450725507265072750728507295073050731507325073350734507355073650737507385073950740507415074250743507445074550746507475074850749507505075150752507535075450755507565075750758507595076050761507625076350764507655076650767507685076950770507715077250773507745077550776507775077850779507805078150782507835078450785507865078750788507895079050791507925079350794507955079650797507985079950800508015080250803508045080550806508075080850809508105081150812508135081450815508165081750818508195082050821508225082350824508255082650827508285082950830508315083250833508345083550836508375083850839508405084150842508435084450845508465084750848508495085050851508525085350854508555085650857508585085950860508615086250863508645086550866508675086850869508705087150872508735087450875508765087750878508795088050881508825088350884508855088650887508885088950890508915089250893508945089550896508975089850899509005090150902509035090450905509065090750908509095091050911509125091350914509155091650917509185091950920509215092250923509245092550926509275092850929509305093150932509335093450935509365093750938509395094050941509425094350944509455094650947509485094950950509515095250953509545095550956509575095850959509605096150962509635096450965509665096750968509695097050971509725097350974509755097650977509785097950980509815098250983509845098550986509875098850989509905099150992509935099450995509965099750998509995100051001510025100351004510055100651007510085100951010510115101251013510145101551016510175101851019510205102151022510235102451025510265102751028510295103051031510325103351034510355103651037510385103951040510415104251043510445104551046510475104851049510505105151052510535105451055510565105751058510595106051061510625106351064510655106651067510685106951070510715107251073510745107551076510775107851079510805108151082510835108451085510865108751088510895109051091510925109351094510955109651097510985109951100511015110251103511045110551106511075110851109511105111151112511135111451115511165111751118511195112051121511225112351124511255112651127511285112951130511315113251133511345113551136511375113851139511405114151142511435114451145511465114751148511495115051151511525115351154511555115651157511585115951160511615116251163511645116551166511675116851169511705117151172511735117451175511765117751178511795118051181511825118351184511855118651187511885118951190511915119251193511945119551196511975119851199512005120151202512035120451205512065120751208512095121051211512125121351214512155121651217512185121951220512215122251223512245122551226512275122851229512305123151232512335123451235512365123751238512395124051241512425124351244512455124651247512485124951250512515125251253512545125551256512575125851259512605126151262512635126451265512665126751268512695127051271512725127351274512755127651277512785127951280512815128251283512845128551286512875128851289512905129151292512935129451295512965129751298512995130051301513025130351304513055130651307513085130951310513115131251313513145131551316513175131851319513205132151322513235132451325513265132751328513295133051331513325133351334513355133651337513385133951340513415134251343513445134551346513475134851349513505135151352513535135451355513565135751358513595136051361513625136351364513655136651367513685136951370513715137251373513745137551376513775137851379513805138151382513835138451385513865138751388513895139051391513925139351394513955139651397513985139951400514015140251403514045140551406514075140851409514105141151412514135141451415514165141751418514195142051421514225142351424514255142651427514285142951430514315143251433514345143551436514375143851439514405144151442514435144451445514465144751448514495145051451514525145351454514555145651457514585145951460514615146251463514645146551466514675146851469514705147151472514735147451475514765147751478514795148051481514825148351484514855148651487514885148951490514915149251493514945149551496514975149851499515005150151502515035150451505515065150751508515095151051511515125151351514515155151651517515185151951520515215152251523515245152551526515275152851529515305153151532515335153451535515365153751538515395154051541515425154351544515455154651547515485154951550515515155251553515545155551556515575155851559515605156151562515635156451565515665156751568515695157051571515725157351574515755157651577515785157951580515815158251583515845158551586515875158851589515905159151592515935159451595515965159751598515995160051601516025160351604516055160651607516085160951610516115161251613516145161551616516175161851619516205162151622516235162451625516265162751628516295163051631516325163351634516355163651637516385163951640516415164251643516445164551646516475164851649516505165151652516535165451655516565165751658516595166051661516625166351664516655166651667516685166951670516715167251673516745167551676516775167851679516805168151682516835168451685516865168751688516895169051691516925169351694516955169651697516985169951700517015170251703517045170551706517075170851709517105171151712517135171451715517165171751718517195172051721517225172351724517255172651727517285172951730517315173251733517345173551736517375173851739517405174151742517435174451745517465174751748517495175051751517525175351754517555175651757517585175951760517615176251763517645176551766517675176851769517705177151772517735177451775517765177751778517795178051781517825178351784517855178651787517885178951790517915179251793517945179551796517975179851799518005180151802518035180451805518065180751808518095181051811518125181351814518155181651817518185181951820518215182251823518245182551826518275182851829518305183151832518335183451835518365183751838518395184051841518425184351844518455184651847518485184951850518515185251853518545185551856518575185851859518605186151862518635186451865518665186751868518695187051871518725187351874518755187651877518785187951880518815188251883518845188551886518875188851889518905189151892518935189451895518965189751898518995190051901519025190351904519055190651907519085190951910519115191251913519145191551916519175191851919519205192151922519235192451925519265192751928519295193051931519325193351934519355193651937519385193951940519415194251943519445194551946519475194851949519505195151952519535195451955519565195751958519595196051961519625196351964519655196651967519685196951970519715197251973519745197551976519775197851979519805198151982519835198451985519865198751988519895199051991519925199351994519955199651997519985199952000520015200252003520045200552006520075200852009520105201152012520135201452015520165201752018520195202052021520225202352024520255202652027520285202952030520315203252033520345203552036520375203852039520405204152042520435204452045520465204752048520495205052051520525205352054520555205652057520585205952060520615206252063520645206552066520675206852069520705207152072520735207452075520765207752078520795208052081520825208352084520855208652087520885208952090520915209252093520945209552096520975209852099521005210152102521035210452105521065210752108521095211052111521125211352114521155211652117521185211952120521215212252123521245212552126521275212852129521305213152132521335213452135521365213752138521395214052141521425214352144521455214652147521485214952150521515215252153521545215552156521575215852159521605216152162521635216452165521665216752168521695217052171521725217352174521755217652177521785217952180521815218252183521845218552186521875218852189521905219152192521935219452195521965219752198521995220052201522025220352204522055220652207522085220952210522115221252213522145221552216522175221852219522205222152222522235222452225522265222752228522295223052231522325223352234522355223652237522385223952240522415224252243522445224552246522475224852249522505225152252522535225452255522565225752258522595226052261522625226352264522655226652267522685226952270522715227252273522745227552276522775227852279522805228152282522835228452285522865228752288522895229052291522925229352294522955229652297522985229952300523015230252303523045230552306523075230852309523105231152312523135231452315523165231752318523195232052321523225232352324523255232652327523285232952330523315233252333523345233552336523375233852339523405234152342523435234452345523465234752348523495235052351523525235352354523555235652357523585235952360523615236252363523645236552366523675236852369523705237152372523735237452375523765237752378523795238052381523825238352384523855238652387523885238952390523915239252393523945239552396523975239852399524005240152402524035240452405524065240752408524095241052411524125241352414524155241652417524185241952420524215242252423524245242552426524275242852429524305243152432524335243452435524365243752438524395244052441524425244352444524455244652447524485244952450524515245252453524545245552456524575245852459524605246152462524635246452465524665246752468524695247052471524725247352474524755247652477524785247952480524815248252483524845248552486524875248852489524905249152492524935249452495524965249752498524995250052501525025250352504525055250652507525085250952510525115251252513525145251552516525175251852519525205252152522525235252452525525265252752528525295253052531525325253352534525355253652537525385253952540525415254252543525445254552546525475254852549525505255152552525535255452555525565255752558525595256052561525625256352564525655256652567525685256952570525715257252573525745257552576525775257852579525805258152582525835258452585525865258752588525895259052591525925259352594525955259652597525985259952600526015260252603526045260552606526075260852609526105261152612526135261452615526165261752618526195262052621526225262352624526255262652627526285262952630526315263252633526345263552636526375263852639526405264152642526435264452645526465264752648526495265052651526525265352654526555265652657526585265952660526615266252663526645266552666526675266852669526705267152672526735267452675526765267752678526795268052681526825268352684526855268652687526885268952690526915269252693526945269552696526975269852699527005270152702527035270452705527065270752708527095271052711527125271352714527155271652717527185271952720527215272252723527245272552726527275272852729527305273152732527335273452735527365273752738527395274052741527425274352744527455274652747527485274952750527515275252753527545275552756527575275852759527605276152762527635276452765527665276752768527695277052771527725277352774527755277652777527785277952780527815278252783527845278552786527875278852789527905279152792527935279452795527965279752798527995280052801528025280352804528055280652807528085280952810528115281252813528145281552816528175281852819528205282152822528235282452825528265282752828528295283052831528325283352834528355283652837528385283952840528415284252843528445284552846528475284852849528505285152852528535285452855528565285752858528595286052861528625286352864528655286652867528685286952870528715287252873528745287552876528775287852879528805288152882528835288452885528865288752888528895289052891528925289352894528955289652897528985289952900529015290252903529045290552906529075290852909529105291152912529135291452915529165291752918529195292052921529225292352924529255292652927529285292952930529315293252933529345293552936529375293852939529405294152942529435294452945529465294752948529495295052951529525295352954529555295652957529585295952960529615296252963529645296552966529675296852969529705297152972529735297452975529765297752978529795298052981529825298352984529855298652987529885298952990529915299252993529945299552996529975299852999530005300153002530035300453005530065300753008530095301053011530125301353014530155301653017530185301953020530215302253023530245302553026530275302853029530305303153032530335303453035530365303753038530395304053041530425304353044530455304653047530485304953050530515305253053530545305553056530575305853059530605306153062530635306453065530665306753068530695307053071530725307353074530755307653077530785307953080530815308253083530845308553086530875308853089530905309153092530935309453095530965309753098530995310053101531025310353104531055310653107531085310953110531115311253113531145311553116531175311853119531205312153122531235312453125531265312753128531295313053131531325313353134531355313653137531385313953140531415314253143531445314553146531475314853149531505315153152531535315453155531565315753158531595316053161531625316353164531655316653167531685316953170531715317253173531745317553176531775317853179531805318153182531835318453185531865318753188531895319053191531925319353194531955319653197531985319953200532015320253203532045320553206532075320853209532105321153212532135321453215532165321753218532195322053221532225322353224532255322653227532285322953230532315323253233532345323553236532375323853239532405324153242532435324453245532465324753248532495325053251532525325353254532555325653257532585325953260532615326253263532645326553266532675326853269532705327153272532735327453275532765327753278532795328053281532825328353284532855328653287532885328953290532915329253293532945329553296532975329853299533005330153302533035330453305533065330753308533095331053311533125331353314533155331653317533185331953320533215332253323533245332553326533275332853329533305333153332533335333453335533365333753338533395334053341533425334353344533455334653347533485334953350533515335253353533545335553356533575335853359533605336153362533635336453365533665336753368533695337053371533725337353374533755337653377533785337953380533815338253383533845338553386533875338853389533905339153392533935339453395533965339753398533995340053401534025340353404534055340653407534085340953410534115341253413534145341553416534175341853419534205342153422534235342453425534265342753428534295343053431534325343353434534355343653437534385343953440534415344253443534445344553446534475344853449534505345153452534535345453455534565345753458534595346053461534625346353464534655346653467534685346953470534715347253473534745347553476534775347853479534805348153482534835348453485534865348753488534895349053491534925349353494534955349653497534985349953500535015350253503535045350553506535075350853509535105351153512535135351453515535165351753518535195352053521535225352353524535255352653527535285352953530535315353253533535345353553536535375353853539535405354153542535435354453545535465354753548535495355053551535525355353554535555355653557535585355953560535615356253563535645356553566535675356853569535705357153572535735357453575535765357753578535795358053581535825358353584535855358653587535885358953590535915359253593535945359553596535975359853599536005360153602536035360453605536065360753608536095361053611536125361353614536155361653617536185361953620536215362253623536245362553626536275362853629536305363153632536335363453635536365363753638536395364053641536425364353644536455364653647536485364953650536515365253653536545365553656536575365853659536605366153662536635366453665536665366753668536695367053671536725367353674536755367653677536785367953680536815368253683536845368553686536875368853689536905369153692536935369453695536965369753698536995370053701537025370353704537055370653707537085370953710537115371253713537145371553716537175371853719537205372153722537235372453725537265372753728537295373053731537325373353734537355373653737537385373953740537415374253743537445374553746537475374853749537505375153752537535375453755537565375753758537595376053761537625376353764537655376653767537685376953770537715377253773537745377553776537775377853779537805378153782537835378453785537865378753788537895379053791537925379353794537955379653797537985379953800538015380253803538045380553806538075380853809538105381153812538135381453815538165381753818538195382053821538225382353824538255382653827538285382953830538315383253833538345383553836538375383853839538405384153842538435384453845538465384753848538495385053851538525385353854538555385653857538585385953860538615386253863538645386553866538675386853869538705387153872538735387453875538765387753878538795388053881538825388353884538855388653887538885388953890538915389253893538945389553896538975389853899539005390153902539035390453905539065390753908539095391053911539125391353914539155391653917539185391953920539215392253923539245392553926539275392853929539305393153932539335393453935539365393753938539395394053941539425394353944539455394653947539485394953950539515395253953539545395553956539575395853959539605396153962539635396453965539665396753968539695397053971539725397353974539755397653977539785397953980539815398253983539845398553986539875398853989539905399153992539935399453995539965399753998539995400054001540025400354004540055400654007540085400954010540115401254013540145401554016540175401854019540205402154022540235402454025540265402754028540295403054031540325403354034540355403654037540385403954040540415404254043540445404554046540475404854049540505405154052540535405454055540565405754058540595406054061540625406354064540655406654067540685406954070540715407254073540745407554076540775407854079540805408154082540835408454085540865408754088540895409054091540925409354094540955409654097540985409954100541015410254103541045410554106541075410854109541105411154112541135411454115541165411754118541195412054121541225412354124541255412654127541285412954130541315413254133541345413554136541375413854139541405414154142541435414454145541465414754148541495415054151541525415354154541555415654157541585415954160541615416254163541645416554166541675416854169541705417154172541735417454175541765417754178541795418054181541825418354184541855418654187541885418954190541915419254193541945419554196541975419854199542005420154202542035420454205542065420754208542095421054211542125421354214542155421654217542185421954220542215422254223542245422554226542275422854229542305423154232542335423454235542365423754238542395424054241542425424354244542455424654247542485424954250542515425254253542545425554256542575425854259542605426154262542635426454265542665426754268542695427054271542725427354274542755427654277542785427954280542815428254283542845428554286542875428854289542905429154292542935429454295542965429754298542995430054301543025430354304543055430654307543085430954310543115431254313543145431554316543175431854319543205432154322543235432454325543265432754328543295433054331543325433354334543355433654337543385433954340543415434254343543445434554346543475434854349543505435154352543535435454355543565435754358543595436054361543625436354364543655436654367543685436954370543715437254373543745437554376543775437854379543805438154382543835438454385543865438754388543895439054391543925439354394543955439654397543985439954400544015440254403544045440554406544075440854409544105441154412544135441454415544165441754418544195442054421544225442354424544255442654427544285442954430544315443254433544345443554436544375443854439544405444154442544435444454445544465444754448544495445054451544525445354454544555445654457544585445954460544615446254463544645446554466544675446854469544705447154472544735447454475544765447754478544795448054481544825448354484544855448654487544885448954490544915449254493544945449554496544975449854499545005450154502545035450454505545065450754508545095451054511545125451354514545155451654517545185451954520545215452254523545245452554526545275452854529545305453154532545335453454535545365453754538545395454054541545425454354544545455454654547545485454954550545515455254553545545455554556545575455854559545605456154562545635456454565545665456754568545695457054571545725457354574545755457654577545785457954580545815458254583545845458554586545875458854589545905459154592545935459454595545965459754598545995460054601546025460354604546055460654607546085460954610546115461254613546145461554616546175461854619546205462154622546235462454625546265462754628546295463054631546325463354634546355463654637546385463954640546415464254643546445464554646546475464854649546505465154652546535465454655546565465754658546595466054661546625466354664546655466654667546685466954670546715467254673546745467554676546775467854679546805468154682546835468454685546865468754688546895469054691546925469354694546955469654697546985469954700547015470254703547045470554706547075470854709547105471154712547135471454715547165471754718547195472054721547225472354724547255472654727547285472954730547315473254733547345473554736547375473854739547405474154742547435474454745547465474754748547495475054751547525475354754547555475654757547585475954760547615476254763547645476554766547675476854769547705477154772547735477454775547765477754778547795478054781547825478354784547855478654787547885478954790547915479254793547945479554796547975479854799548005480154802548035480454805548065480754808548095481054811548125481354814548155481654817548185481954820548215482254823548245482554826548275482854829548305483154832548335483454835548365483754838548395484054841548425484354844548455484654847548485484954850548515485254853548545485554856548575485854859548605486154862548635486454865548665486754868548695487054871548725487354874548755487654877548785487954880548815488254883548845488554886548875488854889548905489154892548935489454895548965489754898548995490054901549025490354904549055490654907549085490954910549115491254913549145491554916549175491854919549205492154922549235492454925549265492754928549295493054931549325493354934549355493654937549385493954940549415494254943549445494554946549475494854949549505495154952549535495454955549565495754958549595496054961549625496354964549655496654967549685496954970549715497254973549745497554976549775497854979549805498154982549835498454985549865498754988549895499054991549925499354994549955499654997549985499955000550015500255003550045500555006550075500855009550105501155012550135501455015550165501755018550195502055021550225502355024550255502655027550285502955030550315503255033550345503555036550375503855039550405504155042550435504455045550465504755048550495505055051550525505355054550555505655057550585505955060550615506255063550645506555066550675506855069550705507155072550735507455075550765507755078550795508055081550825508355084550855508655087550885508955090550915509255093550945509555096550975509855099551005510155102551035510455105551065510755108551095511055111551125511355114551155511655117551185511955120551215512255123551245512555126551275512855129551305513155132551335513455135551365513755138551395514055141551425514355144551455514655147551485514955150551515515255153551545515555156551575515855159551605516155162551635516455165551665516755168551695517055171551725517355174551755517655177551785517955180551815518255183551845518555186551875518855189551905519155192551935519455195551965519755198551995520055201552025520355204552055520655207552085520955210552115521255213552145521555216552175521855219552205522155222552235522455225552265522755228552295523055231552325523355234552355523655237552385523955240552415524255243552445524555246552475524855249552505525155252552535525455255552565525755258552595526055261552625526355264552655526655267552685526955270552715527255273552745527555276552775527855279552805528155282552835528455285552865528755288552895529055291552925529355294552955529655297552985529955300553015530255303553045530555306553075530855309553105531155312553135531455315553165531755318553195532055321553225532355324553255532655327553285532955330553315533255333553345533555336553375533855339553405534155342553435534455345553465534755348553495535055351553525535355354553555535655357553585535955360553615536255363553645536555366553675536855369553705537155372553735537455375553765537755378553795538055381553825538355384553855538655387553885538955390553915539255393553945539555396553975539855399554005540155402554035540455405554065540755408554095541055411554125541355414554155541655417554185541955420554215542255423554245542555426554275542855429554305543155432554335543455435554365543755438554395544055441554425544355444554455544655447554485544955450554515545255453554545545555456554575545855459554605546155462554635546455465554665546755468554695547055471554725547355474554755547655477554785547955480554815548255483554845548555486554875548855489554905549155492554935549455495554965549755498554995550055501555025550355504555055550655507555085550955510555115551255513555145551555516555175551855519555205552155522555235552455525555265552755528555295553055531555325553355534555355553655537555385553955540555415554255543555445554555546555475554855549555505555155552555535555455555555565555755558555595556055561555625556355564555655556655567555685556955570555715557255573555745557555576555775557855579555805558155582555835558455585555865558755588555895559055591555925559355594555955559655597555985559955600556015560255603556045560555606556075560855609556105561155612556135561455615556165561755618556195562055621556225562355624556255562655627556285562955630556315563255633556345563555636556375563855639556405564155642556435564455645556465564755648556495565055651556525565355654556555565655657556585565955660556615566255663556645566555666556675566855669556705567155672556735567455675556765567755678556795568055681556825568355684556855568655687556885568955690556915569255693556945569555696556975569855699557005570155702557035570455705557065570755708557095571055711557125571355714557155571655717557185571955720557215572255723557245572555726557275572855729557305573155732557335573455735557365573755738557395574055741557425574355744557455574655747557485574955750557515575255753557545575555756557575575855759557605576155762557635576455765557665576755768557695577055771557725577355774557755577655777557785577955780557815578255783557845578555786557875578855789557905579155792557935579455795557965579755798557995580055801558025580355804558055580655807558085580955810558115581255813558145581555816558175581855819558205582155822558235582455825558265582755828558295583055831558325583355834558355583655837558385583955840558415584255843558445584555846558475584855849558505585155852558535585455855558565585755858558595586055861558625586355864558655586655867558685586955870558715587255873558745587555876558775587855879558805588155882558835588455885558865588755888558895589055891558925589355894558955589655897558985589955900559015590255903559045590555906559075590855909559105591155912559135591455915559165591755918559195592055921559225592355924559255592655927559285592955930559315593255933559345593555936559375593855939559405594155942559435594455945559465594755948559495595055951559525595355954559555595655957559585595955960559615596255963559645596555966559675596855969559705597155972559735597455975559765597755978559795598055981559825598355984559855598655987559885598955990559915599255993559945599555996559975599855999560005600156002560035600456005560065600756008560095601056011560125601356014560155601656017560185601956020560215602256023560245602556026560275602856029560305603156032560335603456035560365603756038560395604056041560425604356044560455604656047560485604956050560515605256053560545605556056560575605856059560605606156062560635606456065560665606756068560695607056071560725607356074560755607656077560785607956080560815608256083560845608556086560875608856089560905609156092560935609456095560965609756098560995610056101561025610356104
  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 (d, b) {
  8. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  9. function __() { this.constructor = d; }
  10. __.prototype = b.prototype;
  11. d.prototype = new __();
  12. };
  13. var BABYLON;
  14. (function (BABYLON) {
  15. BABYLON.ToGammaSpace = 1 / 2.2;
  16. BABYLON.ToLinearSpace = 2.2;
  17. BABYLON.Epsilon = 0.001;
  18. var MathTools = (function () {
  19. function MathTools() {
  20. }
  21. MathTools.WithinEpsilon = function (a, b, epsilon) {
  22. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  23. var num = a - b;
  24. return -epsilon <= num && num <= epsilon;
  25. };
  26. MathTools.ToHex = function (i) {
  27. var str = i.toString(16);
  28. if (i <= 15) {
  29. return ("0" + str).toUpperCase();
  30. }
  31. return str.toUpperCase();
  32. };
  33. // Returns -1 when value is a negative number and
  34. // +1 when value is a positive number.
  35. MathTools.Sign = function (value) {
  36. value = +value; // convert to a number
  37. if (value === 0 || isNaN(value))
  38. return value;
  39. return value > 0 ? 1 : -1;
  40. };
  41. MathTools.Clamp = function (value, min, max) {
  42. if (min === void 0) { min = 0; }
  43. if (max === void 0) { max = 1; }
  44. return Math.min(max, Math.max(min, value));
  45. };
  46. return MathTools;
  47. }());
  48. BABYLON.MathTools = MathTools;
  49. var Color3 = (function () {
  50. function Color3(r, g, b) {
  51. if (r === void 0) { r = 0; }
  52. if (g === void 0) { g = 0; }
  53. if (b === void 0) { b = 0; }
  54. this.r = r;
  55. this.g = g;
  56. this.b = b;
  57. }
  58. Color3.prototype.toString = function () {
  59. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  60. };
  61. Color3.prototype.getClassName = function () {
  62. return "Color3";
  63. };
  64. Color3.prototype.getHashCode = function () {
  65. var hash = this.r || 0;
  66. hash = (hash * 397) ^ (this.g || 0);
  67. hash = (hash * 397) ^ (this.b || 0);
  68. return hash;
  69. };
  70. // Operators
  71. Color3.prototype.toArray = function (array, index) {
  72. if (index === undefined) {
  73. index = 0;
  74. }
  75. array[index] = this.r;
  76. array[index + 1] = this.g;
  77. array[index + 2] = this.b;
  78. return this;
  79. };
  80. Color3.prototype.toColor4 = function (alpha) {
  81. if (alpha === void 0) { alpha = 1; }
  82. return new Color4(this.r, this.g, this.b, alpha);
  83. };
  84. Color3.prototype.asArray = function () {
  85. var result = [];
  86. this.toArray(result, 0);
  87. return result;
  88. };
  89. Color3.prototype.toLuminance = function () {
  90. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  91. };
  92. Color3.prototype.multiply = function (otherColor) {
  93. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  94. };
  95. Color3.prototype.multiplyToRef = function (otherColor, result) {
  96. result.r = this.r * otherColor.r;
  97. result.g = this.g * otherColor.g;
  98. result.b = this.b * otherColor.b;
  99. return this;
  100. };
  101. Color3.prototype.equals = function (otherColor) {
  102. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  103. };
  104. Color3.prototype.equalsFloats = function (r, g, b) {
  105. return this.r === r && this.g === g && this.b === b;
  106. };
  107. Color3.prototype.scale = function (scale) {
  108. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  109. };
  110. Color3.prototype.scaleToRef = function (scale, result) {
  111. result.r = this.r * scale;
  112. result.g = this.g * scale;
  113. result.b = this.b * scale;
  114. return this;
  115. };
  116. Color3.prototype.add = function (otherColor) {
  117. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  118. };
  119. Color3.prototype.addToRef = function (otherColor, result) {
  120. result.r = this.r + otherColor.r;
  121. result.g = this.g + otherColor.g;
  122. result.b = this.b + otherColor.b;
  123. return this;
  124. };
  125. Color3.prototype.subtract = function (otherColor) {
  126. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  127. };
  128. Color3.prototype.subtractToRef = function (otherColor, result) {
  129. result.r = this.r - otherColor.r;
  130. result.g = this.g - otherColor.g;
  131. result.b = this.b - otherColor.b;
  132. return this;
  133. };
  134. Color3.prototype.clone = function () {
  135. return new Color3(this.r, this.g, this.b);
  136. };
  137. Color3.prototype.copyFrom = function (source) {
  138. this.r = source.r;
  139. this.g = source.g;
  140. this.b = source.b;
  141. return this;
  142. };
  143. Color3.prototype.copyFromFloats = function (r, g, b) {
  144. this.r = r;
  145. this.g = g;
  146. this.b = b;
  147. return this;
  148. };
  149. Color3.prototype.toHexString = function () {
  150. var intR = (this.r * 255) | 0;
  151. var intG = (this.g * 255) | 0;
  152. var intB = (this.b * 255) | 0;
  153. return "#" + MathTools.ToHex(intR) + MathTools.ToHex(intG) + MathTools.ToHex(intB);
  154. };
  155. Color3.prototype.toLinearSpace = function () {
  156. var convertedColor = new Color3();
  157. this.toLinearSpaceToRef(convertedColor);
  158. return convertedColor;
  159. };
  160. Color3.prototype.toLinearSpaceToRef = function (convertedColor) {
  161. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  162. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  163. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  164. return this;
  165. };
  166. Color3.prototype.toGammaSpace = function () {
  167. var convertedColor = new Color3();
  168. this.toGammaSpaceToRef(convertedColor);
  169. return convertedColor;
  170. };
  171. Color3.prototype.toGammaSpaceToRef = function (convertedColor) {
  172. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  173. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  174. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  175. return this;
  176. };
  177. // Statics
  178. Color3.FromHexString = function (hex) {
  179. if (hex.substring(0, 1) !== "#" || hex.length !== 7) {
  180. //Tools.Warn("Color3.FromHexString must be called with a string like #FFFFFF");
  181. return new Color3(0, 0, 0);
  182. }
  183. var r = parseInt(hex.substring(1, 3), 16);
  184. var g = parseInt(hex.substring(3, 5), 16);
  185. var b = parseInt(hex.substring(5, 7), 16);
  186. return Color3.FromInts(r, g, b);
  187. };
  188. Color3.FromArray = function (array, offset) {
  189. if (offset === void 0) { offset = 0; }
  190. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  191. };
  192. Color3.FromInts = function (r, g, b) {
  193. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  194. };
  195. Color3.Lerp = function (start, end, amount) {
  196. var r = start.r + ((end.r - start.r) * amount);
  197. var g = start.g + ((end.g - start.g) * amount);
  198. var b = start.b + ((end.b - start.b) * amount);
  199. return new Color3(r, g, b);
  200. };
  201. Color3.Red = function () { return new Color3(1, 0, 0); };
  202. Color3.Green = function () { return new Color3(0, 1, 0); };
  203. Color3.Blue = function () { return new Color3(0, 0, 1); };
  204. Color3.Black = function () { return new Color3(0, 0, 0); };
  205. Color3.White = function () { return new Color3(1, 1, 1); };
  206. Color3.Purple = function () { return new Color3(0.5, 0, 0.5); };
  207. Color3.Magenta = function () { return new Color3(1, 0, 1); };
  208. Color3.Yellow = function () { return new Color3(1, 1, 0); };
  209. Color3.Gray = function () { return new Color3(0.5, 0.5, 0.5); };
  210. Color3.Random = function () { return new Color3(Math.random(), Math.random(), Math.random()); };
  211. return Color3;
  212. }());
  213. BABYLON.Color3 = Color3;
  214. var Color4 = (function () {
  215. function Color4(r, g, b, a) {
  216. this.r = r;
  217. this.g = g;
  218. this.b = b;
  219. this.a = a;
  220. }
  221. // Operators
  222. Color4.prototype.addInPlace = function (right) {
  223. this.r += right.r;
  224. this.g += right.g;
  225. this.b += right.b;
  226. this.a += right.a;
  227. return this;
  228. };
  229. Color4.prototype.asArray = function () {
  230. var result = [];
  231. this.toArray(result, 0);
  232. return result;
  233. };
  234. Color4.prototype.toArray = function (array, index) {
  235. if (index === undefined) {
  236. index = 0;
  237. }
  238. array[index] = this.r;
  239. array[index + 1] = this.g;
  240. array[index + 2] = this.b;
  241. array[index + 3] = this.a;
  242. return this;
  243. };
  244. Color4.prototype.add = function (right) {
  245. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  246. };
  247. Color4.prototype.subtract = function (right) {
  248. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  249. };
  250. Color4.prototype.subtractToRef = function (right, result) {
  251. result.r = this.r - right.r;
  252. result.g = this.g - right.g;
  253. result.b = this.b - right.b;
  254. result.a = this.a - right.a;
  255. return this;
  256. };
  257. Color4.prototype.scale = function (scale) {
  258. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  259. };
  260. Color4.prototype.scaleToRef = function (scale, result) {
  261. result.r = this.r * scale;
  262. result.g = this.g * scale;
  263. result.b = this.b * scale;
  264. result.a = this.a * scale;
  265. return this;
  266. };
  267. /**
  268. * Multipy an RGBA Color4 value by another and return a new Color4 object
  269. * @param color The Color4 (RGBA) value to multiply by
  270. * @returns A new Color4.
  271. */
  272. Color4.prototype.multiply = function (color) {
  273. return new Color4(this.r * color.r, this.g * color.g, this.b * color.b, this.a * color.a);
  274. };
  275. /**
  276. * Multipy an RGBA Color4 value by another and push the result in a reference value
  277. * @param color The Color4 (RGBA) value to multiply by
  278. * @param result The Color4 (RGBA) to fill the result in
  279. * @returns the result Color4.
  280. */
  281. Color4.prototype.multiplyToRef = function (color, result) {
  282. result.r = this.r * color.r;
  283. result.g = this.g * color.g;
  284. result.b = this.b * color.b;
  285. result.a = this.a * color.a;
  286. return result;
  287. };
  288. Color4.prototype.toString = function () {
  289. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  290. };
  291. Color4.prototype.getClassName = function () {
  292. return "Color4";
  293. };
  294. Color4.prototype.getHashCode = function () {
  295. var hash = this.r || 0;
  296. hash = (hash * 397) ^ (this.g || 0);
  297. hash = (hash * 397) ^ (this.b || 0);
  298. hash = (hash * 397) ^ (this.a || 0);
  299. return hash;
  300. };
  301. Color4.prototype.clone = function () {
  302. return new Color4(this.r, this.g, this.b, this.a);
  303. };
  304. Color4.prototype.copyFrom = function (source) {
  305. this.r = source.r;
  306. this.g = source.g;
  307. this.b = source.b;
  308. this.a = source.a;
  309. return this;
  310. };
  311. Color4.prototype.toHexString = function () {
  312. var intR = (this.r * 255) | 0;
  313. var intG = (this.g * 255) | 0;
  314. var intB = (this.b * 255) | 0;
  315. var intA = (this.a * 255) | 0;
  316. return "#" + MathTools.ToHex(intR) + MathTools.ToHex(intG) + MathTools.ToHex(intB) + MathTools.ToHex(intA);
  317. };
  318. // Statics
  319. Color4.FromHexString = function (hex) {
  320. if (hex.substring(0, 1) !== "#" || hex.length !== 9) {
  321. //Tools.Warn("Color4.FromHexString must be called with a string like #FFFFFFFF");
  322. return new Color4(0, 0, 0, 0);
  323. }
  324. var r = parseInt(hex.substring(1, 3), 16);
  325. var g = parseInt(hex.substring(3, 5), 16);
  326. var b = parseInt(hex.substring(5, 7), 16);
  327. var a = parseInt(hex.substring(7, 9), 16);
  328. return Color4.FromInts(r, g, b, a);
  329. };
  330. Color4.Lerp = function (left, right, amount) {
  331. var result = new Color4(0, 0, 0, 0);
  332. Color4.LerpToRef(left, right, amount, result);
  333. return result;
  334. };
  335. Color4.LerpToRef = function (left, right, amount, result) {
  336. result.r = left.r + (right.r - left.r) * amount;
  337. result.g = left.g + (right.g - left.g) * amount;
  338. result.b = left.b + (right.b - left.b) * amount;
  339. result.a = left.a + (right.a - left.a) * amount;
  340. };
  341. Color4.FromArray = function (array, offset) {
  342. if (offset === void 0) { offset = 0; }
  343. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  344. };
  345. Color4.FromInts = function (r, g, b, a) {
  346. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  347. };
  348. Color4.CheckColors4 = function (colors, count) {
  349. // Check if color3 was used
  350. if (colors.length === count * 3) {
  351. var colors4 = [];
  352. for (var index = 0; index < colors.length; index += 3) {
  353. var newIndex = (index / 3) * 4;
  354. colors4[newIndex] = colors[index];
  355. colors4[newIndex + 1] = colors[index + 1];
  356. colors4[newIndex + 2] = colors[index + 2];
  357. colors4[newIndex + 3] = 1.0;
  358. }
  359. return colors4;
  360. }
  361. return colors;
  362. };
  363. return Color4;
  364. }());
  365. BABYLON.Color4 = Color4;
  366. var Vector2 = (function () {
  367. function Vector2(x, y) {
  368. this.x = x;
  369. this.y = y;
  370. }
  371. Vector2.prototype.toString = function () {
  372. return "{X: " + this.x + " Y:" + this.y + "}";
  373. };
  374. Vector2.prototype.getClassName = function () {
  375. return "Vector2";
  376. };
  377. Vector2.prototype.getHashCode = function () {
  378. var hash = this.x || 0;
  379. hash = (hash * 397) ^ (this.y || 0);
  380. return hash;
  381. };
  382. // Operators
  383. Vector2.prototype.toArray = function (array, index) {
  384. if (index === void 0) { index = 0; }
  385. array[index] = this.x;
  386. array[index + 1] = this.y;
  387. return this;
  388. };
  389. Vector2.prototype.asArray = function () {
  390. var result = [];
  391. this.toArray(result, 0);
  392. return result;
  393. };
  394. Vector2.prototype.copyFrom = function (source) {
  395. this.x = source.x;
  396. this.y = source.y;
  397. return this;
  398. };
  399. Vector2.prototype.copyFromFloats = function (x, y) {
  400. this.x = x;
  401. this.y = y;
  402. return this;
  403. };
  404. Vector2.prototype.add = function (otherVector) {
  405. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  406. };
  407. Vector2.prototype.addToRef = function (otherVector, result) {
  408. result.x = this.x + otherVector.x;
  409. result.y = this.y + otherVector.y;
  410. return this;
  411. };
  412. Vector2.prototype.addInPlace = function (otherVector) {
  413. this.x += otherVector.x;
  414. this.y += otherVector.y;
  415. return this;
  416. };
  417. Vector2.prototype.addVector3 = function (otherVector) {
  418. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  419. };
  420. Vector2.prototype.subtract = function (otherVector) {
  421. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  422. };
  423. Vector2.prototype.subtractToRef = function (otherVector, result) {
  424. result.x = this.x - otherVector.x;
  425. result.y = this.y - otherVector.y;
  426. return this;
  427. };
  428. Vector2.prototype.subtractInPlace = function (otherVector) {
  429. this.x -= otherVector.x;
  430. this.y -= otherVector.y;
  431. return this;
  432. };
  433. Vector2.prototype.multiplyInPlace = function (otherVector) {
  434. this.x *= otherVector.x;
  435. this.y *= otherVector.y;
  436. return this;
  437. };
  438. Vector2.prototype.multiply = function (otherVector) {
  439. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  440. };
  441. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  442. result.x = this.x * otherVector.x;
  443. result.y = this.y * otherVector.y;
  444. return this;
  445. };
  446. Vector2.prototype.multiplyByFloats = function (x, y) {
  447. return new Vector2(this.x * x, this.y * y);
  448. };
  449. Vector2.prototype.divide = function (otherVector) {
  450. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  451. };
  452. Vector2.prototype.divideToRef = function (otherVector, result) {
  453. result.x = this.x / otherVector.x;
  454. result.y = this.y / otherVector.y;
  455. return this;
  456. };
  457. Vector2.prototype.negate = function () {
  458. return new Vector2(-this.x, -this.y);
  459. };
  460. Vector2.prototype.scaleInPlace = function (scale) {
  461. this.x *= scale;
  462. this.y *= scale;
  463. return this;
  464. };
  465. Vector2.prototype.scale = function (scale) {
  466. return new Vector2(this.x * scale, this.y * scale);
  467. };
  468. Vector2.prototype.equals = function (otherVector) {
  469. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  470. };
  471. Vector2.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  472. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  473. return otherVector && MathTools.WithinEpsilon(this.x, otherVector.x, epsilon) && MathTools.WithinEpsilon(this.y, otherVector.y, epsilon);
  474. };
  475. // Properties
  476. Vector2.prototype.length = function () {
  477. return Math.sqrt(this.x * this.x + this.y * this.y);
  478. };
  479. Vector2.prototype.lengthSquared = function () {
  480. return (this.x * this.x + this.y * this.y);
  481. };
  482. // Methods
  483. Vector2.prototype.normalize = function () {
  484. var len = this.length();
  485. if (len === 0)
  486. return this;
  487. var num = 1.0 / len;
  488. this.x *= num;
  489. this.y *= num;
  490. return this;
  491. };
  492. Vector2.prototype.clone = function () {
  493. return new Vector2(this.x, this.y);
  494. };
  495. // Statics
  496. Vector2.Zero = function () {
  497. return new Vector2(0, 0);
  498. };
  499. Vector2.FromArray = function (array, offset) {
  500. if (offset === void 0) { offset = 0; }
  501. return new Vector2(array[offset], array[offset + 1]);
  502. };
  503. Vector2.FromArrayToRef = function (array, offset, result) {
  504. result.x = array[offset];
  505. result.y = array[offset + 1];
  506. };
  507. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  508. var squared = amount * amount;
  509. var cubed = amount * squared;
  510. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  511. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  512. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  513. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  514. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  515. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  516. return new Vector2(x, y);
  517. };
  518. Vector2.Clamp = function (value, min, max) {
  519. var x = value.x;
  520. x = (x > max.x) ? max.x : x;
  521. x = (x < min.x) ? min.x : x;
  522. var y = value.y;
  523. y = (y > max.y) ? max.y : y;
  524. y = (y < min.y) ? min.y : y;
  525. return new Vector2(x, y);
  526. };
  527. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  528. var squared = amount * amount;
  529. var cubed = amount * squared;
  530. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  531. var part2 = (-2.0 * cubed) + (3.0 * squared);
  532. var part3 = (cubed - (2.0 * squared)) + amount;
  533. var part4 = cubed - squared;
  534. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  535. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  536. return new Vector2(x, y);
  537. };
  538. Vector2.Lerp = function (start, end, amount) {
  539. var x = start.x + ((end.x - start.x) * amount);
  540. var y = start.y + ((end.y - start.y) * amount);
  541. return new Vector2(x, y);
  542. };
  543. Vector2.Dot = function (left, right) {
  544. return left.x * right.x + left.y * right.y;
  545. };
  546. Vector2.Normalize = function (vector) {
  547. var newVector = vector.clone();
  548. newVector.normalize();
  549. return newVector;
  550. };
  551. Vector2.Minimize = function (left, right) {
  552. var x = (left.x < right.x) ? left.x : right.x;
  553. var y = (left.y < right.y) ? left.y : right.y;
  554. return new Vector2(x, y);
  555. };
  556. Vector2.Maximize = function (left, right) {
  557. var x = (left.x > right.x) ? left.x : right.x;
  558. var y = (left.y > right.y) ? left.y : right.y;
  559. return new Vector2(x, y);
  560. };
  561. Vector2.Transform = function (vector, transformation) {
  562. var r = Vector2.Zero();
  563. Vector2.TransformToRef(vector, transformation, r);
  564. return r;
  565. };
  566. Vector2.TransformToRef = function (vector, transformation, result) {
  567. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + transformation.m[12];
  568. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + transformation.m[13];
  569. result.x = x;
  570. result.y = y;
  571. };
  572. Vector2.PointInTriangle = function (p, p0, p1, p2) {
  573. var a = 1 / 2 * (-p1.y * p2.x + p0.y * (-p1.x + p2.x) + p0.x * (p1.y - p2.y) + p1.x * p2.y);
  574. var sign = a < 0 ? -1 : 1;
  575. var s = (p0.y * p2.x - p0.x * p2.y + (p2.y - p0.y) * p.x + (p0.x - p2.x) * p.y) * sign;
  576. var t = (p0.x * p1.y - p0.y * p1.x + (p0.y - p1.y) * p.x + (p1.x - p0.x) * p.y) * sign;
  577. return s > 0 && t > 0 && (s + t) < 2 * a * sign;
  578. };
  579. Vector2.Distance = function (value1, value2) {
  580. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  581. };
  582. Vector2.DistanceSquared = function (value1, value2) {
  583. var x = value1.x - value2.x;
  584. var y = value1.y - value2.y;
  585. return (x * x) + (y * y);
  586. };
  587. Vector2.Center = function (value1, value2) {
  588. var center = value1.add(value2);
  589. center.scaleInPlace(0.5);
  590. return center;
  591. };
  592. Vector2.DistanceOfPointFromSegment = function (p, segA, segB) {
  593. var l2 = Vector2.DistanceSquared(segA, segB);
  594. if (l2 === 0.0) {
  595. return Vector2.Distance(p, segA);
  596. }
  597. var v = segB.subtract(segA);
  598. var t = Math.max(0, Math.min(1, Vector2.Dot(p.subtract(segA), v) / l2));
  599. var proj = segA.add(v.multiplyByFloats(t, t));
  600. return Vector2.Distance(p, proj);
  601. };
  602. return Vector2;
  603. }());
  604. BABYLON.Vector2 = Vector2;
  605. var Vector3 = (function () {
  606. function Vector3(x, y, z) {
  607. this.x = x;
  608. this.y = y;
  609. this.z = z;
  610. }
  611. Vector3.prototype.toString = function () {
  612. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  613. };
  614. Vector3.prototype.getClassName = function () {
  615. return "Vector3";
  616. };
  617. Vector3.prototype.getHashCode = function () {
  618. var hash = this.x || 0;
  619. hash = (hash * 397) ^ (this.y || 0);
  620. hash = (hash * 397) ^ (this.z || 0);
  621. return hash;
  622. };
  623. // Operators
  624. Vector3.prototype.asArray = function () {
  625. var result = [];
  626. this.toArray(result, 0);
  627. return result;
  628. };
  629. Vector3.prototype.toArray = function (array, index) {
  630. if (index === void 0) { index = 0; }
  631. array[index] = this.x;
  632. array[index + 1] = this.y;
  633. array[index + 2] = this.z;
  634. return this;
  635. };
  636. Vector3.prototype.toQuaternion = function () {
  637. var result = new Quaternion(0, 0, 0, 1);
  638. var cosxPlusz = Math.cos((this.x + this.z) * 0.5);
  639. var sinxPlusz = Math.sin((this.x + this.z) * 0.5);
  640. var coszMinusx = Math.cos((this.z - this.x) * 0.5);
  641. var sinzMinusx = Math.sin((this.z - this.x) * 0.5);
  642. var cosy = Math.cos(this.y * 0.5);
  643. var siny = Math.sin(this.y * 0.5);
  644. result.x = coszMinusx * siny;
  645. result.y = -sinzMinusx * siny;
  646. result.z = sinxPlusz * cosy;
  647. result.w = cosxPlusz * cosy;
  648. return result;
  649. };
  650. Vector3.prototype.addInPlace = function (otherVector) {
  651. this.x += otherVector.x;
  652. this.y += otherVector.y;
  653. this.z += otherVector.z;
  654. return this;
  655. };
  656. Vector3.prototype.add = function (otherVector) {
  657. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  658. };
  659. Vector3.prototype.addToRef = function (otherVector, result) {
  660. result.x = this.x + otherVector.x;
  661. result.y = this.y + otherVector.y;
  662. result.z = this.z + otherVector.z;
  663. return this;
  664. };
  665. Vector3.prototype.subtractInPlace = function (otherVector) {
  666. this.x -= otherVector.x;
  667. this.y -= otherVector.y;
  668. this.z -= otherVector.z;
  669. return this;
  670. };
  671. Vector3.prototype.subtract = function (otherVector) {
  672. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  673. };
  674. Vector3.prototype.subtractToRef = function (otherVector, result) {
  675. result.x = this.x - otherVector.x;
  676. result.y = this.y - otherVector.y;
  677. result.z = this.z - otherVector.z;
  678. return this;
  679. };
  680. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  681. return new Vector3(this.x - x, this.y - y, this.z - z);
  682. };
  683. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  684. result.x = this.x - x;
  685. result.y = this.y - y;
  686. result.z = this.z - z;
  687. return this;
  688. };
  689. Vector3.prototype.negate = function () {
  690. return new Vector3(-this.x, -this.y, -this.z);
  691. };
  692. Vector3.prototype.scaleInPlace = function (scale) {
  693. this.x *= scale;
  694. this.y *= scale;
  695. this.z *= scale;
  696. return this;
  697. };
  698. Vector3.prototype.scale = function (scale) {
  699. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  700. };
  701. Vector3.prototype.scaleToRef = function (scale, result) {
  702. result.x = this.x * scale;
  703. result.y = this.y * scale;
  704. result.z = this.z * scale;
  705. };
  706. Vector3.prototype.equals = function (otherVector) {
  707. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  708. };
  709. Vector3.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  710. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  711. return otherVector && MathTools.WithinEpsilon(this.x, otherVector.x, epsilon) && MathTools.WithinEpsilon(this.y, otherVector.y, epsilon) && MathTools.WithinEpsilon(this.z, otherVector.z, epsilon);
  712. };
  713. Vector3.prototype.equalsToFloats = function (x, y, z) {
  714. return this.x === x && this.y === y && this.z === z;
  715. };
  716. Vector3.prototype.multiplyInPlace = function (otherVector) {
  717. this.x *= otherVector.x;
  718. this.y *= otherVector.y;
  719. this.z *= otherVector.z;
  720. return this;
  721. };
  722. Vector3.prototype.multiply = function (otherVector) {
  723. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  724. };
  725. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  726. result.x = this.x * otherVector.x;
  727. result.y = this.y * otherVector.y;
  728. result.z = this.z * otherVector.z;
  729. return this;
  730. };
  731. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  732. return new Vector3(this.x * x, this.y * y, this.z * z);
  733. };
  734. Vector3.prototype.divide = function (otherVector) {
  735. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  736. };
  737. Vector3.prototype.divideToRef = function (otherVector, result) {
  738. result.x = this.x / otherVector.x;
  739. result.y = this.y / otherVector.y;
  740. result.z = this.z / otherVector.z;
  741. return this;
  742. };
  743. Vector3.prototype.MinimizeInPlace = function (other) {
  744. if (other.x < this.x)
  745. this.x = other.x;
  746. if (other.y < this.y)
  747. this.y = other.y;
  748. if (other.z < this.z)
  749. this.z = other.z;
  750. return this;
  751. };
  752. Vector3.prototype.MaximizeInPlace = function (other) {
  753. if (other.x > this.x)
  754. this.x = other.x;
  755. if (other.y > this.y)
  756. this.y = other.y;
  757. if (other.z > this.z)
  758. this.z = other.z;
  759. return this;
  760. };
  761. // Properties
  762. Vector3.prototype.length = function () {
  763. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  764. };
  765. Vector3.prototype.lengthSquared = function () {
  766. return (this.x * this.x + this.y * this.y + this.z * this.z);
  767. };
  768. // Methods
  769. Vector3.prototype.normalize = function () {
  770. var len = this.length();
  771. if (len === 0 || len === 1.0)
  772. return this;
  773. var num = 1.0 / len;
  774. this.x *= num;
  775. this.y *= num;
  776. this.z *= num;
  777. return this;
  778. };
  779. Vector3.prototype.clone = function () {
  780. return new Vector3(this.x, this.y, this.z);
  781. };
  782. Vector3.prototype.copyFrom = function (source) {
  783. this.x = source.x;
  784. this.y = source.y;
  785. this.z = source.z;
  786. return this;
  787. };
  788. Vector3.prototype.copyFromFloats = function (x, y, z) {
  789. this.x = x;
  790. this.y = y;
  791. this.z = z;
  792. return this;
  793. };
  794. // Statics
  795. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  796. var d0 = Vector3.Dot(vector0, axis) - size;
  797. var d1 = Vector3.Dot(vector1, axis) - size;
  798. var s = d0 / (d0 - d1);
  799. return s;
  800. };
  801. Vector3.FromArray = function (array, offset) {
  802. if (!offset) {
  803. offset = 0;
  804. }
  805. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  806. };
  807. Vector3.FromFloatArray = function (array, offset) {
  808. if (!offset) {
  809. offset = 0;
  810. }
  811. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  812. };
  813. Vector3.FromArrayToRef = function (array, offset, result) {
  814. result.x = array[offset];
  815. result.y = array[offset + 1];
  816. result.z = array[offset + 2];
  817. };
  818. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  819. result.x = array[offset];
  820. result.y = array[offset + 1];
  821. result.z = array[offset + 2];
  822. };
  823. Vector3.FromFloatsToRef = function (x, y, z, result) {
  824. result.x = x;
  825. result.y = y;
  826. result.z = z;
  827. };
  828. Vector3.Zero = function () {
  829. return new Vector3(0, 0, 0);
  830. };
  831. Vector3.Up = function () {
  832. return new Vector3(0, 1.0, 0);
  833. };
  834. Vector3.Forward = function () {
  835. return new Vector3(0, 0, 1.0);
  836. };
  837. Vector3.Right = function () {
  838. return new Vector3(1.0, 0, 0);
  839. };
  840. Vector3.Left = function () {
  841. return new Vector3(-1.0, 0, 0);
  842. };
  843. Vector3.TransformCoordinates = function (vector, transformation) {
  844. var result = Vector3.Zero();
  845. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  846. return result;
  847. };
  848. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  849. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  850. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  851. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  852. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  853. result.x = x / w;
  854. result.y = y / w;
  855. result.z = z / w;
  856. };
  857. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  858. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  859. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  860. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  861. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  862. result.x = rx / rw;
  863. result.y = ry / rw;
  864. result.z = rz / rw;
  865. };
  866. Vector3.TransformNormal = function (vector, transformation) {
  867. var result = Vector3.Zero();
  868. Vector3.TransformNormalToRef(vector, transformation, result);
  869. return result;
  870. };
  871. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  872. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  873. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  874. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  875. result.x = x;
  876. result.y = y;
  877. result.z = z;
  878. };
  879. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  880. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  881. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  882. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  883. };
  884. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  885. var squared = amount * amount;
  886. var cubed = amount * squared;
  887. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  888. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  889. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  890. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  891. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  892. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  893. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  894. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  895. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  896. return new Vector3(x, y, z);
  897. };
  898. Vector3.Clamp = function (value, min, max) {
  899. var x = value.x;
  900. x = (x > max.x) ? max.x : x;
  901. x = (x < min.x) ? min.x : x;
  902. var y = value.y;
  903. y = (y > max.y) ? max.y : y;
  904. y = (y < min.y) ? min.y : y;
  905. var z = value.z;
  906. z = (z > max.z) ? max.z : z;
  907. z = (z < min.z) ? min.z : z;
  908. return new Vector3(x, y, z);
  909. };
  910. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  911. var squared = amount * amount;
  912. var cubed = amount * squared;
  913. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  914. var part2 = (-2.0 * cubed) + (3.0 * squared);
  915. var part3 = (cubed - (2.0 * squared)) + amount;
  916. var part4 = cubed - squared;
  917. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  918. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  919. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  920. return new Vector3(x, y, z);
  921. };
  922. Vector3.Lerp = function (start, end, amount) {
  923. var result = new Vector3(0, 0, 0);
  924. Vector3.LerpToRef(start, end, amount, result);
  925. return result;
  926. };
  927. Vector3.LerpToRef = function (start, end, amount, result) {
  928. result.x = start.x + ((end.x - start.x) * amount);
  929. result.y = start.y + ((end.y - start.y) * amount);
  930. result.z = start.z + ((end.z - start.z) * amount);
  931. };
  932. Vector3.Dot = function (left, right) {
  933. return (left.x * right.x + left.y * right.y + left.z * right.z);
  934. };
  935. Vector3.Cross = function (left, right) {
  936. var result = Vector3.Zero();
  937. Vector3.CrossToRef(left, right, result);
  938. return result;
  939. };
  940. Vector3.CrossToRef = function (left, right, result) {
  941. Tmp.Vector3[0].x = left.y * right.z - left.z * right.y;
  942. Tmp.Vector3[0].y = left.z * right.x - left.x * right.z;
  943. Tmp.Vector3[0].z = left.x * right.y - left.y * right.x;
  944. result.copyFrom(Tmp.Vector3[0]);
  945. };
  946. Vector3.Normalize = function (vector) {
  947. var result = Vector3.Zero();
  948. Vector3.NormalizeToRef(vector, result);
  949. return result;
  950. };
  951. Vector3.NormalizeToRef = function (vector, result) {
  952. result.copyFrom(vector);
  953. result.normalize();
  954. };
  955. Vector3.Project = function (vector, world, transform, viewport) {
  956. var cw = viewport.width;
  957. var ch = viewport.height;
  958. var cx = viewport.x;
  959. var cy = viewport.y;
  960. var viewportMatrix = Vector3._viewportMatrixCache ? Vector3._viewportMatrixCache : (Vector3._viewportMatrixCache = new Matrix());
  961. 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);
  962. var matrix = Vector3._matrixCache ? Vector3._matrixCache : (Vector3._matrixCache = new Matrix());
  963. world.multiplyToRef(transform, matrix);
  964. matrix.multiplyToRef(viewportMatrix, matrix);
  965. return Vector3.TransformCoordinates(vector, matrix);
  966. };
  967. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  968. var matrix = Vector3._matrixCache ? Vector3._matrixCache : (Vector3._matrixCache = new Matrix());
  969. world.multiplyToRef(transform, matrix);
  970. matrix.invert();
  971. source.x = source.x / viewportWidth * 2 - 1;
  972. source.y = -(source.y / viewportHeight * 2 - 1);
  973. var vector = Vector3.TransformCoordinates(source, matrix);
  974. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  975. if (MathTools.WithinEpsilon(num, 1.0)) {
  976. vector = vector.scale(1.0 / num);
  977. }
  978. return vector;
  979. };
  980. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  981. var matrix = Vector3._matrixCache ? Vector3._matrixCache : (Vector3._matrixCache = new Matrix());
  982. world.multiplyToRef(view, matrix);
  983. matrix.multiplyToRef(projection, matrix);
  984. matrix.invert();
  985. var screenSource = new Vector3(source.x / viewportWidth * 2 - 1, -(source.y / viewportHeight * 2 - 1), 2 * source.z - 1.0);
  986. var vector = Vector3.TransformCoordinates(screenSource, matrix);
  987. var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15];
  988. if (MathTools.WithinEpsilon(num, 1.0)) {
  989. vector = vector.scale(1.0 / num);
  990. }
  991. return vector;
  992. };
  993. Vector3.Minimize = function (left, right) {
  994. var min = left.clone();
  995. min.MinimizeInPlace(right);
  996. return min;
  997. };
  998. Vector3.Maximize = function (left, right) {
  999. var max = left.clone();
  1000. max.MaximizeInPlace(right);
  1001. return max;
  1002. };
  1003. Vector3.Distance = function (value1, value2) {
  1004. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  1005. };
  1006. Vector3.DistanceSquared = function (value1, value2) {
  1007. var x = value1.x - value2.x;
  1008. var y = value1.y - value2.y;
  1009. var z = value1.z - value2.z;
  1010. return (x * x) + (y * y) + (z * z);
  1011. };
  1012. Vector3.Center = function (value1, value2) {
  1013. var center = value1.add(value2);
  1014. center.scaleInPlace(0.5);
  1015. return center;
  1016. };
  1017. /**
  1018. * Given three orthogonal normalized left-handed oriented Vector3 axis in space (target system),
  1019. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  1020. * to something in order to rotate it from its local system to the given target system.
  1021. */
  1022. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  1023. var rotation = Vector3.Zero();
  1024. Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
  1025. return rotation;
  1026. };
  1027. /**
  1028. * The same than RotationFromAxis but updates the passed ref Vector3 parameter.
  1029. */
  1030. Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
  1031. var u = axis1.normalize();
  1032. var w = axis3.normalize();
  1033. // world axis
  1034. var X = Axis.X;
  1035. var Y = Axis.Y;
  1036. // equation unknowns and vars
  1037. var yaw = 0.0;
  1038. var pitch = 0.0;
  1039. var roll = 0.0;
  1040. var x = 0.0;
  1041. var y = 0.0;
  1042. var z = 0.0;
  1043. var t = 0.0;
  1044. var sign = -1.0;
  1045. var nbRevert = 0;
  1046. var cross = Tmp.Vector3[0];
  1047. var dot = 0.0;
  1048. // step 1 : rotation around w
  1049. // Rv3(u) = u1, and u1 belongs to plane xOz
  1050. // Rv3(w) = w1 = w invariant
  1051. var u1 = Tmp.Vector3[1];
  1052. if (MathTools.WithinEpsilon(w.z, 0, BABYLON.Epsilon)) {
  1053. z = 1.0;
  1054. }
  1055. else if (MathTools.WithinEpsilon(w.x, 0, BABYLON.Epsilon)) {
  1056. x = 1.0;
  1057. }
  1058. else {
  1059. t = w.z / w.x;
  1060. x = -t * Math.sqrt(1 / (1 + t * t));
  1061. z = Math.sqrt(1 / (1 + t * t));
  1062. }
  1063. u1.x = x;
  1064. u1.y = y;
  1065. u1.z = z;
  1066. u1.normalize();
  1067. Vector3.CrossToRef(u, u1, cross); // returns same direction as w (=local z) if positive angle : cross(source, image)
  1068. cross.normalize();
  1069. if (Vector3.Dot(w, cross) < 0) {
  1070. sign = 1.0;
  1071. }
  1072. dot = Vector3.Dot(u, u1);
  1073. dot = (Math.min(1.0, Math.max(-1.0, dot))); // to force dot to be in the range [-1, 1]
  1074. roll = Math.acos(dot) * sign;
  1075. if (Vector3.Dot(u1, X) < 0) {
  1076. roll = Math.PI + roll;
  1077. u1 = u1.scaleInPlace(-1);
  1078. nbRevert++;
  1079. }
  1080. // step 2 : rotate around u1
  1081. // Ru1(w1) = Ru1(w) = w2, and w2 belongs to plane xOz
  1082. // u1 is yet in xOz and invariant by Ru1, so after this step u1 and w2 will be in xOz
  1083. var w2 = Tmp.Vector3[2];
  1084. var v2 = Tmp.Vector3[3];
  1085. x = 0.0;
  1086. y = 0.0;
  1087. z = 0.0;
  1088. sign = -1.0;
  1089. if (MathTools.WithinEpsilon(w.z, 0, BABYLON.Epsilon)) {
  1090. x = 1.0;
  1091. }
  1092. else {
  1093. t = u1.z / u1.x;
  1094. x = -t * Math.sqrt(1 / (1 + t * t));
  1095. z = Math.sqrt(1 / (1 + t * t));
  1096. }
  1097. w2.x = x;
  1098. w2.y = y;
  1099. w2.z = z;
  1100. w2.normalize();
  1101. Vector3.CrossToRef(w2, u1, v2); // v2 image of v1 through rotation around u1
  1102. v2.normalize();
  1103. Vector3.CrossToRef(w, w2, cross); // returns same direction as u1 (=local x) if positive angle : cross(source, image)
  1104. cross.normalize();
  1105. if (Vector3.Dot(u1, cross) < 0) {
  1106. sign = 1.0;
  1107. }
  1108. dot = Vector3.Dot(w, w2);
  1109. dot = (Math.min(1.0, Math.max(-1.0, dot))); // to force dot to be in the range [-1, 1]
  1110. pitch = Math.acos(dot) * sign;
  1111. if (Vector3.Dot(v2, Y) < 0) {
  1112. pitch = Math.PI + pitch;
  1113. nbRevert++;
  1114. }
  1115. // step 3 : rotate around v2
  1116. // Rv2(u1) = X, same as Rv2(w2) = Z, with X=(1,0,0) and Z=(0,0,1)
  1117. sign = -1.0;
  1118. Vector3.CrossToRef(X, u1, cross); // returns same direction as Y if positive angle : cross(source, image)
  1119. cross.normalize();
  1120. if (Vector3.Dot(cross, Y) < 0) {
  1121. sign = 1.0;
  1122. }
  1123. dot = Vector3.Dot(u1, X);
  1124. dot = (Math.min(1.0, Math.max(-1.0, dot))); // to force dot to be in the range [-1, 1]
  1125. yaw = -Math.acos(dot) * sign; // negative : plane zOx oriented clockwise
  1126. if (dot < 0 && nbRevert < 2) {
  1127. yaw = Math.PI + yaw;
  1128. }
  1129. ref.x = pitch;
  1130. ref.y = yaw;
  1131. ref.z = roll;
  1132. };
  1133. return Vector3;
  1134. }());
  1135. BABYLON.Vector3 = Vector3;
  1136. //Vector4 class created for EulerAngle class conversion to Quaternion
  1137. var Vector4 = (function () {
  1138. function Vector4(x, y, z, w) {
  1139. this.x = x;
  1140. this.y = y;
  1141. this.z = z;
  1142. this.w = w;
  1143. }
  1144. Vector4.prototype.toString = function () {
  1145. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  1146. };
  1147. Vector4.prototype.getClassName = function () {
  1148. return "Vector4";
  1149. };
  1150. Vector4.prototype.getHashCode = function () {
  1151. var hash = this.x || 0;
  1152. hash = (hash * 397) ^ (this.y || 0);
  1153. hash = (hash * 397) ^ (this.z || 0);
  1154. hash = (hash * 397) ^ (this.w || 0);
  1155. return hash;
  1156. };
  1157. // Operators
  1158. Vector4.prototype.asArray = function () {
  1159. var result = [];
  1160. this.toArray(result, 0);
  1161. return result;
  1162. };
  1163. Vector4.prototype.toArray = function (array, index) {
  1164. if (index === undefined) {
  1165. index = 0;
  1166. }
  1167. array[index] = this.x;
  1168. array[index + 1] = this.y;
  1169. array[index + 2] = this.z;
  1170. array[index + 3] = this.w;
  1171. return this;
  1172. };
  1173. Vector4.prototype.addInPlace = function (otherVector) {
  1174. this.x += otherVector.x;
  1175. this.y += otherVector.y;
  1176. this.z += otherVector.z;
  1177. this.w += otherVector.w;
  1178. return this;
  1179. };
  1180. Vector4.prototype.add = function (otherVector) {
  1181. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  1182. };
  1183. Vector4.prototype.addToRef = function (otherVector, result) {
  1184. result.x = this.x + otherVector.x;
  1185. result.y = this.y + otherVector.y;
  1186. result.z = this.z + otherVector.z;
  1187. result.w = this.w + otherVector.w;
  1188. return this;
  1189. };
  1190. Vector4.prototype.subtractInPlace = function (otherVector) {
  1191. this.x -= otherVector.x;
  1192. this.y -= otherVector.y;
  1193. this.z -= otherVector.z;
  1194. this.w -= otherVector.w;
  1195. return this;
  1196. };
  1197. Vector4.prototype.subtract = function (otherVector) {
  1198. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  1199. };
  1200. Vector4.prototype.subtractToRef = function (otherVector, result) {
  1201. result.x = this.x - otherVector.x;
  1202. result.y = this.y - otherVector.y;
  1203. result.z = this.z - otherVector.z;
  1204. result.w = this.w - otherVector.w;
  1205. return this;
  1206. };
  1207. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  1208. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  1209. };
  1210. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  1211. result.x = this.x - x;
  1212. result.y = this.y - y;
  1213. result.z = this.z - z;
  1214. result.w = this.w - w;
  1215. return this;
  1216. };
  1217. Vector4.prototype.negate = function () {
  1218. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  1219. };
  1220. Vector4.prototype.scaleInPlace = function (scale) {
  1221. this.x *= scale;
  1222. this.y *= scale;
  1223. this.z *= scale;
  1224. this.w *= scale;
  1225. return this;
  1226. };
  1227. Vector4.prototype.scale = function (scale) {
  1228. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  1229. };
  1230. Vector4.prototype.scaleToRef = function (scale, result) {
  1231. result.x = this.x * scale;
  1232. result.y = this.y * scale;
  1233. result.z = this.z * scale;
  1234. result.w = this.w * scale;
  1235. };
  1236. Vector4.prototype.equals = function (otherVector) {
  1237. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  1238. };
  1239. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  1240. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  1241. return otherVector
  1242. && MathTools.WithinEpsilon(this.x, otherVector.x, epsilon)
  1243. && MathTools.WithinEpsilon(this.y, otherVector.y, epsilon)
  1244. && MathTools.WithinEpsilon(this.z, otherVector.z, epsilon)
  1245. && MathTools.WithinEpsilon(this.w, otherVector.w, epsilon);
  1246. };
  1247. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  1248. return this.x === x && this.y === y && this.z === z && this.w === w;
  1249. };
  1250. Vector4.prototype.multiplyInPlace = function (otherVector) {
  1251. this.x *= otherVector.x;
  1252. this.y *= otherVector.y;
  1253. this.z *= otherVector.z;
  1254. this.w *= otherVector.w;
  1255. return this;
  1256. };
  1257. Vector4.prototype.multiply = function (otherVector) {
  1258. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  1259. };
  1260. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  1261. result.x = this.x * otherVector.x;
  1262. result.y = this.y * otherVector.y;
  1263. result.z = this.z * otherVector.z;
  1264. result.w = this.w * otherVector.w;
  1265. return this;
  1266. };
  1267. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  1268. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  1269. };
  1270. Vector4.prototype.divide = function (otherVector) {
  1271. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  1272. };
  1273. Vector4.prototype.divideToRef = function (otherVector, result) {
  1274. result.x = this.x / otherVector.x;
  1275. result.y = this.y / otherVector.y;
  1276. result.z = this.z / otherVector.z;
  1277. result.w = this.w / otherVector.w;
  1278. return this;
  1279. };
  1280. Vector4.prototype.MinimizeInPlace = function (other) {
  1281. if (other.x < this.x)
  1282. this.x = other.x;
  1283. if (other.y < this.y)
  1284. this.y = other.y;
  1285. if (other.z < this.z)
  1286. this.z = other.z;
  1287. if (other.w < this.w)
  1288. this.w = other.w;
  1289. return this;
  1290. };
  1291. Vector4.prototype.MaximizeInPlace = function (other) {
  1292. if (other.x > this.x)
  1293. this.x = other.x;
  1294. if (other.y > this.y)
  1295. this.y = other.y;
  1296. if (other.z > this.z)
  1297. this.z = other.z;
  1298. if (other.w > this.w)
  1299. this.w = other.w;
  1300. return this;
  1301. };
  1302. // Properties
  1303. Vector4.prototype.length = function () {
  1304. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  1305. };
  1306. Vector4.prototype.lengthSquared = function () {
  1307. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  1308. };
  1309. // Methods
  1310. Vector4.prototype.normalize = function () {
  1311. var len = this.length();
  1312. if (len === 0)
  1313. return this;
  1314. var num = 1.0 / len;
  1315. this.x *= num;
  1316. this.y *= num;
  1317. this.z *= num;
  1318. this.w *= num;
  1319. return this;
  1320. };
  1321. Vector4.prototype.toVector3 = function () {
  1322. return new Vector3(this.x, this.y, this.z);
  1323. };
  1324. Vector4.prototype.clone = function () {
  1325. return new Vector4(this.x, this.y, this.z, this.w);
  1326. };
  1327. Vector4.prototype.copyFrom = function (source) {
  1328. this.x = source.x;
  1329. this.y = source.y;
  1330. this.z = source.z;
  1331. this.w = source.w;
  1332. return this;
  1333. };
  1334. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  1335. this.x = x;
  1336. this.y = y;
  1337. this.z = z;
  1338. this.w = w;
  1339. return this;
  1340. };
  1341. // Statics
  1342. Vector4.FromArray = function (array, offset) {
  1343. if (!offset) {
  1344. offset = 0;
  1345. }
  1346. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  1347. };
  1348. Vector4.FromArrayToRef = function (array, offset, result) {
  1349. result.x = array[offset];
  1350. result.y = array[offset + 1];
  1351. result.z = array[offset + 2];
  1352. result.w = array[offset + 3];
  1353. };
  1354. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  1355. result.x = array[offset];
  1356. result.y = array[offset + 1];
  1357. result.z = array[offset + 2];
  1358. result.w = array[offset + 3];
  1359. };
  1360. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  1361. result.x = x;
  1362. result.y = y;
  1363. result.z = z;
  1364. result.w = w;
  1365. };
  1366. Vector4.Zero = function () {
  1367. return new Vector4(0, 0, 0, 0);
  1368. };
  1369. Vector4.Normalize = function (vector) {
  1370. var result = Vector4.Zero();
  1371. Vector4.NormalizeToRef(vector, result);
  1372. return result;
  1373. };
  1374. Vector4.NormalizeToRef = function (vector, result) {
  1375. result.copyFrom(vector);
  1376. result.normalize();
  1377. };
  1378. Vector4.Minimize = function (left, right) {
  1379. var min = left.clone();
  1380. min.MinimizeInPlace(right);
  1381. return min;
  1382. };
  1383. Vector4.Maximize = function (left, right) {
  1384. var max = left.clone();
  1385. max.MaximizeInPlace(right);
  1386. return max;
  1387. };
  1388. Vector4.Distance = function (value1, value2) {
  1389. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  1390. };
  1391. Vector4.DistanceSquared = function (value1, value2) {
  1392. var x = value1.x - value2.x;
  1393. var y = value1.y - value2.y;
  1394. var z = value1.z - value2.z;
  1395. var w = value1.w - value2.w;
  1396. return (x * x) + (y * y) + (z * z) + (w * w);
  1397. };
  1398. Vector4.Center = function (value1, value2) {
  1399. var center = value1.add(value2);
  1400. center.scaleInPlace(0.5);
  1401. return center;
  1402. };
  1403. return Vector4;
  1404. }());
  1405. BABYLON.Vector4 = Vector4;
  1406. var Size = (function () {
  1407. function Size(width, height) {
  1408. this.width = width;
  1409. this.height = height;
  1410. }
  1411. Size.prototype.toString = function () {
  1412. return "{W: " + this.width + ", H: " + this.height + "}";
  1413. };
  1414. Size.prototype.getClassName = function () {
  1415. return "Size";
  1416. };
  1417. Size.prototype.getHashCode = function () {
  1418. var hash = this.width || 0;
  1419. hash = (hash * 397) ^ (this.height || 0);
  1420. return hash;
  1421. };
  1422. Size.prototype.copyFrom = function (src) {
  1423. this.width = src.width;
  1424. this.height = src.height;
  1425. };
  1426. Size.prototype.copyFromFloats = function (width, height) {
  1427. this.width = width;
  1428. this.height = height;
  1429. };
  1430. Size.prototype.multiplyByFloats = function (w, h) {
  1431. return new Size(this.width * w, this.height * h);
  1432. };
  1433. Size.prototype.clone = function () {
  1434. return new Size(this.width, this.height);
  1435. };
  1436. Size.prototype.equals = function (other) {
  1437. if (!other) {
  1438. return false;
  1439. }
  1440. return (this.width === other.width) && (this.height === other.height);
  1441. };
  1442. Object.defineProperty(Size.prototype, "surface", {
  1443. get: function () {
  1444. return this.width * this.height;
  1445. },
  1446. enumerable: true,
  1447. configurable: true
  1448. });
  1449. Size.Zero = function () {
  1450. return new Size(0, 0);
  1451. };
  1452. Size.prototype.add = function (otherSize) {
  1453. var r = new Size(this.width + otherSize.width, this.height + otherSize.height);
  1454. return r;
  1455. };
  1456. Size.prototype.subtract = function (otherSize) {
  1457. var r = new Size(this.width - otherSize.width, this.height - otherSize.height);
  1458. return r;
  1459. };
  1460. Size.Lerp = function (start, end, amount) {
  1461. var w = start.width + ((end.width - start.width) * amount);
  1462. var h = start.height + ((end.height - start.height) * amount);
  1463. return new Size(w, h);
  1464. };
  1465. return Size;
  1466. }());
  1467. BABYLON.Size = Size;
  1468. var Quaternion = (function () {
  1469. function Quaternion(x, y, z, w) {
  1470. if (x === void 0) { x = 0; }
  1471. if (y === void 0) { y = 0; }
  1472. if (z === void 0) { z = 0; }
  1473. if (w === void 0) { w = 1; }
  1474. this.x = x;
  1475. this.y = y;
  1476. this.z = z;
  1477. this.w = w;
  1478. }
  1479. Quaternion.prototype.toString = function () {
  1480. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  1481. };
  1482. Quaternion.prototype.getClassName = function () {
  1483. return "Quaternion";
  1484. };
  1485. Quaternion.prototype.getHashCode = function () {
  1486. var hash = this.x || 0;
  1487. hash = (hash * 397) ^ (this.y || 0);
  1488. hash = (hash * 397) ^ (this.z || 0);
  1489. hash = (hash * 397) ^ (this.w || 0);
  1490. return hash;
  1491. };
  1492. Quaternion.prototype.asArray = function () {
  1493. return [this.x, this.y, this.z, this.w];
  1494. };
  1495. Quaternion.prototype.equals = function (otherQuaternion) {
  1496. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  1497. };
  1498. Quaternion.prototype.clone = function () {
  1499. return new Quaternion(this.x, this.y, this.z, this.w);
  1500. };
  1501. Quaternion.prototype.copyFrom = function (other) {
  1502. this.x = other.x;
  1503. this.y = other.y;
  1504. this.z = other.z;
  1505. this.w = other.w;
  1506. return this;
  1507. };
  1508. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  1509. this.x = x;
  1510. this.y = y;
  1511. this.z = z;
  1512. this.w = w;
  1513. return this;
  1514. };
  1515. Quaternion.prototype.add = function (other) {
  1516. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  1517. };
  1518. Quaternion.prototype.subtract = function (other) {
  1519. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  1520. };
  1521. Quaternion.prototype.scale = function (value) {
  1522. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  1523. };
  1524. Quaternion.prototype.multiply = function (q1) {
  1525. var result = new Quaternion(0, 0, 0, 1.0);
  1526. this.multiplyToRef(q1, result);
  1527. return result;
  1528. };
  1529. Quaternion.prototype.multiplyToRef = function (q1, result) {
  1530. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  1531. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  1532. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  1533. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  1534. result.copyFromFloats(x, y, z, w);
  1535. return this;
  1536. };
  1537. Quaternion.prototype.multiplyInPlace = function (q1) {
  1538. this.multiplyToRef(q1, this);
  1539. return this;
  1540. };
  1541. Quaternion.prototype.conjugateToRef = function (ref) {
  1542. ref.copyFromFloats(-this.x, -this.y, -this.z, this.w);
  1543. return this;
  1544. };
  1545. Quaternion.prototype.conjugateInPlace = function () {
  1546. this.x *= -1;
  1547. this.y *= -1;
  1548. this.z *= -1;
  1549. return this;
  1550. };
  1551. Quaternion.prototype.conjugate = function () {
  1552. var result = new Quaternion(-this.x, -this.y, -this.z, this.w);
  1553. return result;
  1554. };
  1555. Quaternion.prototype.length = function () {
  1556. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  1557. };
  1558. Quaternion.prototype.normalize = function () {
  1559. var length = 1.0 / this.length();
  1560. this.x *= length;
  1561. this.y *= length;
  1562. this.z *= length;
  1563. this.w *= length;
  1564. return this;
  1565. };
  1566. Quaternion.prototype.toEulerAngles = function (order) {
  1567. if (order === void 0) { order = "YZX"; }
  1568. var result = Vector3.Zero();
  1569. this.toEulerAnglesToRef(result, order);
  1570. return result;
  1571. };
  1572. Quaternion.prototype.toEulerAnglesToRef = function (result, order) {
  1573. if (order === void 0) { order = "YZX"; }
  1574. var qz = this.z;
  1575. var qx = this.x;
  1576. var qy = this.y;
  1577. var qw = this.w;
  1578. var sqw = qw * qw;
  1579. var sqz = qz * qz;
  1580. var sqx = qx * qx;
  1581. var sqy = qy * qy;
  1582. var zAxisY = qy * qz - qx * qw;
  1583. var limit = .4999999;
  1584. if (zAxisY < -limit) {
  1585. result.y = 2 * Math.atan2(qy, qw);
  1586. result.x = Math.PI / 2;
  1587. result.z = 0;
  1588. }
  1589. else if (zAxisY > limit) {
  1590. result.y = 2 * Math.atan2(qy, qw);
  1591. result.x = -Math.PI / 2;
  1592. result.z = 0;
  1593. }
  1594. else {
  1595. result.z = Math.atan2(2.0 * (qx * qy + qz * qw), (-sqz - sqx + sqy + sqw));
  1596. result.x = Math.asin(-2.0 * (qz * qy - qx * qw));
  1597. result.y = Math.atan2(2.0 * (qz * qx + qy * qw), (sqz - sqx - sqy + sqw));
  1598. }
  1599. return this;
  1600. };
  1601. Quaternion.prototype.toRotationMatrix = function (result) {
  1602. var xx = this.x * this.x;
  1603. var yy = this.y * this.y;
  1604. var zz = this.z * this.z;
  1605. var xy = this.x * this.y;
  1606. var zw = this.z * this.w;
  1607. var zx = this.z * this.x;
  1608. var yw = this.y * this.w;
  1609. var yz = this.y * this.z;
  1610. var xw = this.x * this.w;
  1611. result.m[0] = 1.0 - (2.0 * (yy + zz));
  1612. result.m[1] = 2.0 * (xy + zw);
  1613. result.m[2] = 2.0 * (zx - yw);
  1614. result.m[3] = 0;
  1615. result.m[4] = 2.0 * (xy - zw);
  1616. result.m[5] = 1.0 - (2.0 * (zz + xx));
  1617. result.m[6] = 2.0 * (yz + xw);
  1618. result.m[7] = 0;
  1619. result.m[8] = 2.0 * (zx + yw);
  1620. result.m[9] = 2.0 * (yz - xw);
  1621. result.m[10] = 1.0 - (2.0 * (yy + xx));
  1622. result.m[11] = 0;
  1623. result.m[12] = 0;
  1624. result.m[13] = 0;
  1625. result.m[14] = 0;
  1626. result.m[15] = 1.0;
  1627. return this;
  1628. };
  1629. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  1630. Quaternion.FromRotationMatrixToRef(matrix, this);
  1631. return this;
  1632. };
  1633. // Statics
  1634. Quaternion.FromRotationMatrix = function (matrix) {
  1635. var result = new Quaternion();
  1636. Quaternion.FromRotationMatrixToRef(matrix, result);
  1637. return result;
  1638. };
  1639. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  1640. var data = matrix.m;
  1641. var m11 = data[0], m12 = data[4], m13 = data[8];
  1642. var m21 = data[1], m22 = data[5], m23 = data[9];
  1643. var m31 = data[2], m32 = data[6], m33 = data[10];
  1644. var trace = m11 + m22 + m33;
  1645. var s;
  1646. if (trace > 0) {
  1647. s = 0.5 / Math.sqrt(trace + 1.0);
  1648. result.w = 0.25 / s;
  1649. result.x = (m32 - m23) * s;
  1650. result.y = (m13 - m31) * s;
  1651. result.z = (m21 - m12) * s;
  1652. }
  1653. else if (m11 > m22 && m11 > m33) {
  1654. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  1655. result.w = (m32 - m23) / s;
  1656. result.x = 0.25 * s;
  1657. result.y = (m12 + m21) / s;
  1658. result.z = (m13 + m31) / s;
  1659. }
  1660. else if (m22 > m33) {
  1661. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  1662. result.w = (m13 - m31) / s;
  1663. result.x = (m12 + m21) / s;
  1664. result.y = 0.25 * s;
  1665. result.z = (m23 + m32) / s;
  1666. }
  1667. else {
  1668. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  1669. result.w = (m21 - m12) / s;
  1670. result.x = (m13 + m31) / s;
  1671. result.y = (m23 + m32) / s;
  1672. result.z = 0.25 * s;
  1673. }
  1674. };
  1675. Quaternion.Inverse = function (q) {
  1676. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  1677. };
  1678. Quaternion.Identity = function () {
  1679. return new Quaternion(0, 0, 0, 1);
  1680. };
  1681. Quaternion.RotationAxis = function (axis, angle) {
  1682. return Quaternion.RotationAxisToRef(axis, angle, new Quaternion());
  1683. };
  1684. Quaternion.RotationAxisToRef = function (axis, angle, result) {
  1685. var sin = Math.sin(angle / 2);
  1686. axis.normalize();
  1687. result.w = Math.cos(angle / 2);
  1688. result.x = axis.x * sin;
  1689. result.y = axis.y * sin;
  1690. result.z = axis.z * sin;
  1691. return result;
  1692. };
  1693. Quaternion.FromArray = function (array, offset) {
  1694. if (!offset) {
  1695. offset = 0;
  1696. }
  1697. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  1698. };
  1699. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  1700. var q = new Quaternion();
  1701. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, q);
  1702. return q;
  1703. };
  1704. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  1705. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  1706. var halfRoll = roll * 0.5;
  1707. var halfPitch = pitch * 0.5;
  1708. var halfYaw = yaw * 0.5;
  1709. var sinRoll = Math.sin(halfRoll);
  1710. var cosRoll = Math.cos(halfRoll);
  1711. var sinPitch = Math.sin(halfPitch);
  1712. var cosPitch = Math.cos(halfPitch);
  1713. var sinYaw = Math.sin(halfYaw);
  1714. var cosYaw = Math.cos(halfYaw);
  1715. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  1716. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  1717. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  1718. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  1719. };
  1720. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  1721. var result = new Quaternion();
  1722. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  1723. return result;
  1724. };
  1725. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  1726. // Produces a quaternion from Euler angles in the z-x-z orientation
  1727. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  1728. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  1729. var halfBeta = beta * 0.5;
  1730. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  1731. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  1732. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  1733. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  1734. };
  1735. Quaternion.Slerp = function (left, right, amount) {
  1736. var result = Quaternion.Identity();
  1737. Quaternion.SlerpToRef(left, right, amount, result);
  1738. return result;
  1739. };
  1740. Quaternion.SlerpToRef = function (left, right, amount, result) {
  1741. var num2;
  1742. var num3;
  1743. var num = amount;
  1744. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  1745. var flag = false;
  1746. if (num4 < 0) {
  1747. flag = true;
  1748. num4 = -num4;
  1749. }
  1750. if (num4 > 0.999999) {
  1751. num3 = 1 - num;
  1752. num2 = flag ? -num : num;
  1753. }
  1754. else {
  1755. var num5 = Math.acos(num4);
  1756. var num6 = (1.0 / Math.sin(num5));
  1757. num3 = (Math.sin((1.0 - num) * num5)) * num6;
  1758. num2 = flag ? ((-Math.sin(num * num5)) * num6) : ((Math.sin(num * num5)) * num6);
  1759. }
  1760. result.x = (num3 * left.x) + (num2 * right.x);
  1761. result.y = (num3 * left.y) + (num2 * right.y);
  1762. result.z = (num3 * left.z) + (num2 * right.z);
  1763. result.w = (num3 * left.w) + (num2 * right.w);
  1764. };
  1765. return Quaternion;
  1766. }());
  1767. BABYLON.Quaternion = Quaternion;
  1768. var Matrix = (function () {
  1769. function Matrix() {
  1770. this.m = new Float32Array(16);
  1771. }
  1772. // Properties
  1773. Matrix.prototype.isIdentity = function () {
  1774. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[10] !== 1.0 || this.m[15] !== 1.0)
  1775. return false;
  1776. if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  1777. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  1778. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  1779. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0)
  1780. return false;
  1781. return true;
  1782. };
  1783. Matrix.prototype.determinant = function () {
  1784. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  1785. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  1786. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  1787. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  1788. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  1789. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  1790. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  1791. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  1792. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  1793. };
  1794. // Methods
  1795. Matrix.prototype.toArray = function () {
  1796. return this.m;
  1797. };
  1798. Matrix.prototype.asArray = function () {
  1799. return this.toArray();
  1800. };
  1801. Matrix.prototype.invert = function () {
  1802. this.invertToRef(this);
  1803. return this;
  1804. };
  1805. Matrix.prototype.reset = function () {
  1806. for (var index = 0; index < 16; index++) {
  1807. this.m[index] = 0;
  1808. }
  1809. return this;
  1810. };
  1811. Matrix.prototype.add = function (other) {
  1812. var result = new Matrix();
  1813. this.addToRef(other, result);
  1814. return result;
  1815. };
  1816. Matrix.prototype.addToRef = function (other, result) {
  1817. for (var index = 0; index < 16; index++) {
  1818. result.m[index] = this.m[index] + other.m[index];
  1819. }
  1820. return this;
  1821. };
  1822. Matrix.prototype.addToSelf = function (other) {
  1823. for (var index = 0; index < 16; index++) {
  1824. this.m[index] += other.m[index];
  1825. }
  1826. return this;
  1827. };
  1828. Matrix.prototype.invertToRef = function (other) {
  1829. var l1 = this.m[0];
  1830. var l2 = this.m[1];
  1831. var l3 = this.m[2];
  1832. var l4 = this.m[3];
  1833. var l5 = this.m[4];
  1834. var l6 = this.m[5];
  1835. var l7 = this.m[6];
  1836. var l8 = this.m[7];
  1837. var l9 = this.m[8];
  1838. var l10 = this.m[9];
  1839. var l11 = this.m[10];
  1840. var l12 = this.m[11];
  1841. var l13 = this.m[12];
  1842. var l14 = this.m[13];
  1843. var l15 = this.m[14];
  1844. var l16 = this.m[15];
  1845. var l17 = (l11 * l16) - (l12 * l15);
  1846. var l18 = (l10 * l16) - (l12 * l14);
  1847. var l19 = (l10 * l15) - (l11 * l14);
  1848. var l20 = (l9 * l16) - (l12 * l13);
  1849. var l21 = (l9 * l15) - (l11 * l13);
  1850. var l22 = (l9 * l14) - (l10 * l13);
  1851. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  1852. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  1853. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  1854. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  1855. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  1856. var l28 = (l7 * l16) - (l8 * l15);
  1857. var l29 = (l6 * l16) - (l8 * l14);
  1858. var l30 = (l6 * l15) - (l7 * l14);
  1859. var l31 = (l5 * l16) - (l8 * l13);
  1860. var l32 = (l5 * l15) - (l7 * l13);
  1861. var l33 = (l5 * l14) - (l6 * l13);
  1862. var l34 = (l7 * l12) - (l8 * l11);
  1863. var l35 = (l6 * l12) - (l8 * l10);
  1864. var l36 = (l6 * l11) - (l7 * l10);
  1865. var l37 = (l5 * l12) - (l8 * l9);
  1866. var l38 = (l5 * l11) - (l7 * l9);
  1867. var l39 = (l5 * l10) - (l6 * l9);
  1868. other.m[0] = l23 * l27;
  1869. other.m[4] = l24 * l27;
  1870. other.m[8] = l25 * l27;
  1871. other.m[12] = l26 * l27;
  1872. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  1873. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  1874. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  1875. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  1876. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  1877. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  1878. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  1879. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  1880. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  1881. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  1882. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  1883. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  1884. return this;
  1885. };
  1886. Matrix.prototype.setTranslation = function (vector3) {
  1887. this.m[12] = vector3.x;
  1888. this.m[13] = vector3.y;
  1889. this.m[14] = vector3.z;
  1890. return this;
  1891. };
  1892. Matrix.prototype.getTranslation = function () {
  1893. return new Vector3(this.m[12], this.m[13], this.m[14]);
  1894. };
  1895. Matrix.prototype.multiply = function (other) {
  1896. var result = new Matrix();
  1897. this.multiplyToRef(other, result);
  1898. return result;
  1899. };
  1900. Matrix.prototype.copyFrom = function (other) {
  1901. for (var index = 0; index < 16; index++) {
  1902. this.m[index] = other.m[index];
  1903. }
  1904. return this;
  1905. };
  1906. Matrix.prototype.copyToArray = function (array, offset) {
  1907. if (offset === void 0) { offset = 0; }
  1908. for (var index = 0; index < 16; index++) {
  1909. array[offset + index] = this.m[index];
  1910. }
  1911. return this;
  1912. };
  1913. Matrix.prototype.multiplyToRef = function (other, result) {
  1914. this.multiplyToArray(other, result.m, 0);
  1915. return this;
  1916. };
  1917. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  1918. var tm0 = this.m[0];
  1919. var tm1 = this.m[1];
  1920. var tm2 = this.m[2];
  1921. var tm3 = this.m[3];
  1922. var tm4 = this.m[4];
  1923. var tm5 = this.m[5];
  1924. var tm6 = this.m[6];
  1925. var tm7 = this.m[7];
  1926. var tm8 = this.m[8];
  1927. var tm9 = this.m[9];
  1928. var tm10 = this.m[10];
  1929. var tm11 = this.m[11];
  1930. var tm12 = this.m[12];
  1931. var tm13 = this.m[13];
  1932. var tm14 = this.m[14];
  1933. var tm15 = this.m[15];
  1934. var om0 = other.m[0];
  1935. var om1 = other.m[1];
  1936. var om2 = other.m[2];
  1937. var om3 = other.m[3];
  1938. var om4 = other.m[4];
  1939. var om5 = other.m[5];
  1940. var om6 = other.m[6];
  1941. var om7 = other.m[7];
  1942. var om8 = other.m[8];
  1943. var om9 = other.m[9];
  1944. var om10 = other.m[10];
  1945. var om11 = other.m[11];
  1946. var om12 = other.m[12];
  1947. var om13 = other.m[13];
  1948. var om14 = other.m[14];
  1949. var om15 = other.m[15];
  1950. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  1951. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  1952. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  1953. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  1954. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  1955. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  1956. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  1957. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  1958. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  1959. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  1960. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  1961. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  1962. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  1963. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  1964. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  1965. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  1966. return this;
  1967. };
  1968. Matrix.prototype.equals = function (value) {
  1969. return value &&
  1970. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  1971. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  1972. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  1973. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  1974. };
  1975. Matrix.prototype.clone = function () {
  1976. 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]);
  1977. };
  1978. Matrix.prototype.getClassName = function () {
  1979. return "Matrix";
  1980. };
  1981. Matrix.prototype.getHashCode = function () {
  1982. var hash = this.m[0] || 0;
  1983. for (var i = 1; i < 16; i++) {
  1984. hash = (hash * 397) ^ (this.m[i] || 0);
  1985. }
  1986. return hash;
  1987. };
  1988. Matrix.prototype.decompose = function (scale, rotation, translation) {
  1989. translation.x = this.m[12];
  1990. translation.y = this.m[13];
  1991. translation.z = this.m[14];
  1992. var xs = MathTools.Sign(this.m[0] * this.m[1] * this.m[2] * this.m[3]) < 0 ? -1 : 1;
  1993. var ys = MathTools.Sign(this.m[4] * this.m[5] * this.m[6] * this.m[7]) < 0 ? -1 : 1;
  1994. var zs = MathTools.Sign(this.m[8] * this.m[9] * this.m[10] * this.m[11]) < 0 ? -1 : 1;
  1995. scale.x = xs * Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  1996. scale.y = ys * Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  1997. scale.z = zs * Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  1998. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  1999. rotation.x = 0;
  2000. rotation.y = 0;
  2001. rotation.z = 0;
  2002. rotation.w = 1;
  2003. return false;
  2004. }
  2005. 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, Tmp.Matrix[0]);
  2006. Quaternion.FromRotationMatrixToRef(Tmp.Matrix[0], rotation);
  2007. return true;
  2008. };
  2009. Matrix.prototype.getRotationMatrix = function () {
  2010. var result = Matrix.Identity();
  2011. this.getRotationMatrixToRef(result);
  2012. return result;
  2013. };
  2014. Matrix.prototype.getRotationMatrixToRef = function (result) {
  2015. var m = this.m;
  2016. var xs = m[0] * m[1] * m[2] * m[3] < 0 ? -1 : 1;
  2017. var ys = m[4] * m[5] * m[6] * m[7] < 0 ? -1 : 1;
  2018. var zs = m[8] * m[9] * m[10] * m[11] < 0 ? -1 : 1;
  2019. var sx = xs * Math.sqrt(m[0] * m[0] + m[1] * m[1] + m[2] * m[2]);
  2020. var sy = ys * Math.sqrt(m[4] * m[4] + m[5] * m[5] + m[6] * m[6]);
  2021. var sz = zs * Math.sqrt(m[8] * m[8] + m[9] * m[9] + m[10] * m[10]);
  2022. 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);
  2023. };
  2024. // Statics
  2025. Matrix.FromArray = function (array, offset) {
  2026. var result = new Matrix();
  2027. if (!offset) {
  2028. offset = 0;
  2029. }
  2030. Matrix.FromArrayToRef(array, offset, result);
  2031. return result;
  2032. };
  2033. Matrix.FromArrayToRef = function (array, offset, result) {
  2034. for (var index = 0; index < 16; index++) {
  2035. result.m[index] = array[index + offset];
  2036. }
  2037. };
  2038. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  2039. for (var index = 0; index < 16; index++) {
  2040. result.m[index] = array[index + offset] * scale;
  2041. }
  2042. };
  2043. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  2044. result.m[0] = initialM11;
  2045. result.m[1] = initialM12;
  2046. result.m[2] = initialM13;
  2047. result.m[3] = initialM14;
  2048. result.m[4] = initialM21;
  2049. result.m[5] = initialM22;
  2050. result.m[6] = initialM23;
  2051. result.m[7] = initialM24;
  2052. result.m[8] = initialM31;
  2053. result.m[9] = initialM32;
  2054. result.m[10] = initialM33;
  2055. result.m[11] = initialM34;
  2056. result.m[12] = initialM41;
  2057. result.m[13] = initialM42;
  2058. result.m[14] = initialM43;
  2059. result.m[15] = initialM44;
  2060. };
  2061. Matrix.prototype.getRow = function (index) {
  2062. if (index < 0 || index > 3) {
  2063. return null;
  2064. }
  2065. var i = index * 4;
  2066. return new Vector4(this.m[i + 0], this.m[i + 1], this.m[i + 2], this.m[i + 3]);
  2067. };
  2068. Matrix.prototype.setRow = function (index, row) {
  2069. if (index < 0 || index > 3) {
  2070. return this;
  2071. }
  2072. var i = index * 4;
  2073. this.m[i + 0] = row.x;
  2074. this.m[i + 1] = row.y;
  2075. this.m[i + 2] = row.z;
  2076. this.m[i + 3] = row.w;
  2077. return this;
  2078. };
  2079. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  2080. var result = new Matrix();
  2081. result.m[0] = initialM11;
  2082. result.m[1] = initialM12;
  2083. result.m[2] = initialM13;
  2084. result.m[3] = initialM14;
  2085. result.m[4] = initialM21;
  2086. result.m[5] = initialM22;
  2087. result.m[6] = initialM23;
  2088. result.m[7] = initialM24;
  2089. result.m[8] = initialM31;
  2090. result.m[9] = initialM32;
  2091. result.m[10] = initialM33;
  2092. result.m[11] = initialM34;
  2093. result.m[12] = initialM41;
  2094. result.m[13] = initialM42;
  2095. result.m[14] = initialM43;
  2096. result.m[15] = initialM44;
  2097. return result;
  2098. };
  2099. Matrix.Compose = function (scale, rotation, translation) {
  2100. var result = Matrix.FromValues(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1);
  2101. var rotationMatrix = Matrix.Identity();
  2102. rotation.toRotationMatrix(rotationMatrix);
  2103. result = result.multiply(rotationMatrix);
  2104. result.setTranslation(translation);
  2105. return result;
  2106. };
  2107. Matrix.Identity = function () {
  2108. return Matrix.FromValues(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0);
  2109. };
  2110. Matrix.IdentityToRef = function (result) {
  2111. Matrix.FromValuesToRef(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, result);
  2112. };
  2113. Matrix.Zero = function () {
  2114. return Matrix.FromValues(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
  2115. };
  2116. Matrix.RotationX = function (angle) {
  2117. var result = new Matrix();
  2118. Matrix.RotationXToRef(angle, result);
  2119. return result;
  2120. };
  2121. Matrix.Invert = function (source) {
  2122. var result = new Matrix();
  2123. source.invertToRef(result);
  2124. return result;
  2125. };
  2126. Matrix.RotationXToRef = function (angle, result) {
  2127. var s = Math.sin(angle);
  2128. var c = Math.cos(angle);
  2129. result.m[0] = 1.0;
  2130. result.m[15] = 1.0;
  2131. result.m[5] = c;
  2132. result.m[10] = c;
  2133. result.m[9] = -s;
  2134. result.m[6] = s;
  2135. result.m[1] = 0;
  2136. result.m[2] = 0;
  2137. result.m[3] = 0;
  2138. result.m[4] = 0;
  2139. result.m[7] = 0;
  2140. result.m[8] = 0;
  2141. result.m[11] = 0;
  2142. result.m[12] = 0;
  2143. result.m[13] = 0;
  2144. result.m[14] = 0;
  2145. };
  2146. Matrix.RotationY = function (angle) {
  2147. var result = new Matrix();
  2148. Matrix.RotationYToRef(angle, result);
  2149. return result;
  2150. };
  2151. Matrix.RotationYToRef = function (angle, result) {
  2152. var s = Math.sin(angle);
  2153. var c = Math.cos(angle);
  2154. result.m[5] = 1.0;
  2155. result.m[15] = 1.0;
  2156. result.m[0] = c;
  2157. result.m[2] = -s;
  2158. result.m[8] = s;
  2159. result.m[10] = c;
  2160. result.m[1] = 0;
  2161. result.m[3] = 0;
  2162. result.m[4] = 0;
  2163. result.m[6] = 0;
  2164. result.m[7] = 0;
  2165. result.m[9] = 0;
  2166. result.m[11] = 0;
  2167. result.m[12] = 0;
  2168. result.m[13] = 0;
  2169. result.m[14] = 0;
  2170. };
  2171. Matrix.RotationZ = function (angle) {
  2172. var result = new Matrix();
  2173. Matrix.RotationZToRef(angle, result);
  2174. return result;
  2175. };
  2176. Matrix.RotationZToRef = function (angle, result) {
  2177. var s = Math.sin(angle);
  2178. var c = Math.cos(angle);
  2179. result.m[10] = 1.0;
  2180. result.m[15] = 1.0;
  2181. result.m[0] = c;
  2182. result.m[1] = s;
  2183. result.m[4] = -s;
  2184. result.m[5] = c;
  2185. result.m[2] = 0;
  2186. result.m[3] = 0;
  2187. result.m[6] = 0;
  2188. result.m[7] = 0;
  2189. result.m[8] = 0;
  2190. result.m[9] = 0;
  2191. result.m[11] = 0;
  2192. result.m[12] = 0;
  2193. result.m[13] = 0;
  2194. result.m[14] = 0;
  2195. };
  2196. Matrix.RotationAxis = function (axis, angle) {
  2197. var result = Matrix.Zero();
  2198. Matrix.RotationAxisToRef(axis, angle, result);
  2199. return result;
  2200. };
  2201. Matrix.RotationAxisToRef = function (axis, angle, result) {
  2202. var s = Math.sin(-angle);
  2203. var c = Math.cos(-angle);
  2204. var c1 = 1 - c;
  2205. axis.normalize();
  2206. result.m[0] = (axis.x * axis.x) * c1 + c;
  2207. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  2208. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  2209. result.m[3] = 0.0;
  2210. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  2211. result.m[5] = (axis.y * axis.y) * c1 + c;
  2212. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  2213. result.m[7] = 0.0;
  2214. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  2215. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  2216. result.m[10] = (axis.z * axis.z) * c1 + c;
  2217. result.m[11] = 0.0;
  2218. result.m[15] = 1.0;
  2219. };
  2220. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  2221. var result = new Matrix();
  2222. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  2223. return result;
  2224. };
  2225. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  2226. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  2227. this._tempQuaternion.toRotationMatrix(result);
  2228. };
  2229. Matrix.Scaling = function (x, y, z) {
  2230. var result = Matrix.Zero();
  2231. Matrix.ScalingToRef(x, y, z, result);
  2232. return result;
  2233. };
  2234. Matrix.ScalingToRef = function (x, y, z, result) {
  2235. result.m[0] = x;
  2236. result.m[1] = 0;
  2237. result.m[2] = 0;
  2238. result.m[3] = 0;
  2239. result.m[4] = 0;
  2240. result.m[5] = y;
  2241. result.m[6] = 0;
  2242. result.m[7] = 0;
  2243. result.m[8] = 0;
  2244. result.m[9] = 0;
  2245. result.m[10] = z;
  2246. result.m[11] = 0;
  2247. result.m[12] = 0;
  2248. result.m[13] = 0;
  2249. result.m[14] = 0;
  2250. result.m[15] = 1.0;
  2251. };
  2252. Matrix.Translation = function (x, y, z) {
  2253. var result = Matrix.Identity();
  2254. Matrix.TranslationToRef(x, y, z, result);
  2255. return result;
  2256. };
  2257. Matrix.TranslationToRef = function (x, y, z, result) {
  2258. Matrix.FromValuesToRef(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, x, y, z, 1.0, result);
  2259. };
  2260. Matrix.Lerp = function (startValue, endValue, gradient) {
  2261. var result = Matrix.Zero();
  2262. for (var index = 0; index < 16; index++) {
  2263. result.m[index] = startValue.m[index] * (1.0 - gradient) + endValue.m[index] * gradient;
  2264. }
  2265. return result;
  2266. };
  2267. Matrix.DecomposeLerp = function (startValue, endValue, gradient) {
  2268. var startScale = new Vector3(0, 0, 0);
  2269. var startRotation = new Quaternion();
  2270. var startTranslation = new Vector3(0, 0, 0);
  2271. startValue.decompose(startScale, startRotation, startTranslation);
  2272. var endScale = new Vector3(0, 0, 0);
  2273. var endRotation = new Quaternion();
  2274. var endTranslation = new Vector3(0, 0, 0);
  2275. endValue.decompose(endScale, endRotation, endTranslation);
  2276. var resultScale = Vector3.Lerp(startScale, endScale, gradient);
  2277. var resultRotation = Quaternion.Slerp(startRotation, endRotation, gradient);
  2278. var resultTranslation = Vector3.Lerp(startTranslation, endTranslation, gradient);
  2279. return Matrix.Compose(resultScale, resultRotation, resultTranslation);
  2280. };
  2281. Matrix.LookAtLH = function (eye, target, up) {
  2282. var result = Matrix.Zero();
  2283. Matrix.LookAtLHToRef(eye, target, up, result);
  2284. return result;
  2285. };
  2286. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  2287. // Z axis
  2288. target.subtractToRef(eye, this._zAxis);
  2289. this._zAxis.normalize();
  2290. // X axis
  2291. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  2292. if (this._xAxis.lengthSquared() === 0) {
  2293. this._xAxis.x = 1.0;
  2294. }
  2295. else {
  2296. this._xAxis.normalize();
  2297. }
  2298. // Y axis
  2299. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  2300. this._yAxis.normalize();
  2301. // Eye angles
  2302. var ex = -Vector3.Dot(this._xAxis, eye);
  2303. var ey = -Vector3.Dot(this._yAxis, eye);
  2304. var ez = -Vector3.Dot(this._zAxis, eye);
  2305. 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);
  2306. };
  2307. Matrix.LookAtRH = function (eye, target, up) {
  2308. var result = Matrix.Zero();
  2309. Matrix.LookAtRHToRef(eye, target, up, result);
  2310. return result;
  2311. };
  2312. Matrix.LookAtRHToRef = function (eye, target, up, result) {
  2313. // Z axis
  2314. eye.subtractToRef(target, this._zAxis);
  2315. this._zAxis.normalize();
  2316. // X axis
  2317. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  2318. if (this._xAxis.lengthSquared() === 0) {
  2319. this._xAxis.x = 1.0;
  2320. }
  2321. else {
  2322. this._xAxis.normalize();
  2323. }
  2324. // Y axis
  2325. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  2326. this._yAxis.normalize();
  2327. // Eye angles
  2328. var ex = -Vector3.Dot(this._xAxis, eye);
  2329. var ey = -Vector3.Dot(this._yAxis, eye);
  2330. var ez = -Vector3.Dot(this._zAxis, eye);
  2331. 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);
  2332. };
  2333. Matrix.OrthoLH = function (width, height, znear, zfar) {
  2334. var matrix = Matrix.Zero();
  2335. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  2336. return matrix;
  2337. };
  2338. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  2339. var n = znear;
  2340. var f = zfar;
  2341. var a = 2.0 / width;
  2342. var b = 2.0 / height;
  2343. var c = 2.0 / (f - n);
  2344. var d = -(f + n) / (f - n);
  2345. BABYLON.Matrix.FromValuesToRef(a, 0, 0, 0, 0, b, 0, 0, 0, 0, c, 0, 0, 0, d, 1, result);
  2346. };
  2347. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  2348. var matrix = Matrix.Zero();
  2349. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  2350. return matrix;
  2351. };
  2352. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  2353. var n = znear;
  2354. var f = zfar;
  2355. var a = 2.0 / (right - left);
  2356. var b = 2.0 / (top - bottom);
  2357. var c = 2.0 / (f - n);
  2358. var d = -(f + n) / (f - n);
  2359. var i0 = (left + right) / (left - right);
  2360. var i1 = (top + bottom) / (bottom - top);
  2361. BABYLON.Matrix.FromValuesToRef(a, 0, 0, 0, 0, b, 0, 0, 0, 0, c, 0, i0, i1, d, 1, result);
  2362. };
  2363. Matrix.OrthoOffCenterRH = function (left, right, bottom, top, znear, zfar) {
  2364. var matrix = Matrix.Zero();
  2365. Matrix.OrthoOffCenterRHToRef(left, right, bottom, top, znear, zfar, matrix);
  2366. return matrix;
  2367. };
  2368. Matrix.OrthoOffCenterRHToRef = function (left, right, bottom, top, znear, zfar, result) {
  2369. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, result);
  2370. result.m[10] *= -1.0;
  2371. };
  2372. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  2373. var matrix = Matrix.Zero();
  2374. var n = znear;
  2375. var f = zfar;
  2376. var a = 2.0 * n / width;
  2377. var b = 2.0 * n / height;
  2378. var c = (f + n) / (f - n);
  2379. var d = -2.0 * f * n / (f - n);
  2380. BABYLON.Matrix.FromValuesToRef(a, 0, 0, 0, 0, b, 0, 0, 0, 0, c, 1, 0, 0, d, 0, matrix);
  2381. return matrix;
  2382. };
  2383. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  2384. var matrix = Matrix.Zero();
  2385. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  2386. return matrix;
  2387. };
  2388. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  2389. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  2390. var n = znear;
  2391. var f = zfar;
  2392. var t = 1.0 / (Math.tan(fov * 0.5));
  2393. var a = isVerticalFovFixed ? (t / aspect) : t;
  2394. var b = isVerticalFovFixed ? t : (t * aspect);
  2395. var c = (f + n) / (f - n);
  2396. var d = -2.0 * f * n / (f - n);
  2397. BABYLON.Matrix.FromValuesToRef(a, 0, 0, 0, 0, b, 0, 0, 0, 0, c, 1, 0, 0, d, 0, result);
  2398. };
  2399. Matrix.PerspectiveFovRH = function (fov, aspect, znear, zfar) {
  2400. var matrix = Matrix.Zero();
  2401. Matrix.PerspectiveFovRHToRef(fov, aspect, znear, zfar, matrix);
  2402. return matrix;
  2403. };
  2404. Matrix.PerspectiveFovRHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  2405. //alternatively this could be expressed as:
  2406. // m = PerspectiveFovLHToRef
  2407. // m[10] *= -1.0;
  2408. // m[11] *= -1.0;
  2409. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  2410. var n = znear;
  2411. var f = zfar;
  2412. var t = 1.0 / (Math.tan(fov * 0.5));
  2413. var a = isVerticalFovFixed ? (t / aspect) : t;
  2414. var b = isVerticalFovFixed ? t : (t * aspect);
  2415. var c = -(f + n) / (f - n);
  2416. var d = -2 * f * n / (f - n);
  2417. BABYLON.Matrix.FromValuesToRef(a, 0, 0, 0, 0, b, 0, 0, 0, 0, c, -1, 0, 0, d, 0, result);
  2418. };
  2419. Matrix.PerspectiveFovWebVRToRef = function (fov, znear, zfar, result, isVerticalFovFixed) {
  2420. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  2421. //left handed
  2422. var upTan = Math.tan(fov.upDegrees * Math.PI / 180.0);
  2423. var downTan = Math.tan(fov.downDegrees * Math.PI / 180.0);
  2424. var leftTan = Math.tan(fov.leftDegrees * Math.PI / 180.0);
  2425. var rightTan = Math.tan(fov.rightDegrees * Math.PI / 180.0);
  2426. var xScale = 2.0 / (leftTan + rightTan);
  2427. var yScale = 2.0 / (upTan + downTan);
  2428. result.m[0] = xScale;
  2429. result.m[1] = result.m[2] = result.m[3] = result.m[4] = 0.0;
  2430. result.m[5] = yScale;
  2431. result.m[6] = result.m[7] = 0.0;
  2432. result.m[8] = ((leftTan - rightTan) * xScale * 0.5);
  2433. result.m[9] = -((upTan - downTan) * yScale * 0.5);
  2434. result.m[10] = -(znear + zfar) / (zfar - znear);
  2435. // result.m[10] = -zfar / (znear - zfar);
  2436. result.m[11] = 1.0;
  2437. result.m[12] = result.m[13] = result.m[15] = 0.0;
  2438. result.m[14] = -(2.0 * zfar * znear) / (zfar - znear);
  2439. // result.m[14] = (znear * zfar) / (znear - zfar);
  2440. };
  2441. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  2442. var cw = viewport.width;
  2443. var ch = viewport.height;
  2444. var cx = viewport.x;
  2445. var cy = viewport.y;
  2446. var viewportMatrix = Matrix.FromValues(cw / 2.0, 0, 0, 0, 0, -ch / 2.0, 0, 0, 0, 0, zmax - zmin, 0, cx + cw / 2.0, ch / 2.0 + cy, zmin, 1);
  2447. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  2448. };
  2449. Matrix.GetAsMatrix2x2 = function (matrix) {
  2450. return new Float32Array([
  2451. matrix.m[0], matrix.m[1],
  2452. matrix.m[4], matrix.m[5]
  2453. ]);
  2454. };
  2455. Matrix.GetAsMatrix3x3 = function (matrix) {
  2456. return new Float32Array([
  2457. matrix.m[0], matrix.m[1], matrix.m[2],
  2458. matrix.m[4], matrix.m[5], matrix.m[6],
  2459. matrix.m[8], matrix.m[9], matrix.m[10]
  2460. ]);
  2461. };
  2462. Matrix.Transpose = function (matrix) {
  2463. var result = new Matrix();
  2464. result.m[0] = matrix.m[0];
  2465. result.m[1] = matrix.m[4];
  2466. result.m[2] = matrix.m[8];
  2467. result.m[3] = matrix.m[12];
  2468. result.m[4] = matrix.m[1];
  2469. result.m[5] = matrix.m[5];
  2470. result.m[6] = matrix.m[9];
  2471. result.m[7] = matrix.m[13];
  2472. result.m[8] = matrix.m[2];
  2473. result.m[9] = matrix.m[6];
  2474. result.m[10] = matrix.m[10];
  2475. result.m[11] = matrix.m[14];
  2476. result.m[12] = matrix.m[3];
  2477. result.m[13] = matrix.m[7];
  2478. result.m[14] = matrix.m[11];
  2479. result.m[15] = matrix.m[15];
  2480. return result;
  2481. };
  2482. Matrix.Reflection = function (plane) {
  2483. var matrix = new Matrix();
  2484. Matrix.ReflectionToRef(plane, matrix);
  2485. return matrix;
  2486. };
  2487. Matrix.ReflectionToRef = function (plane, result) {
  2488. plane.normalize();
  2489. var x = plane.normal.x;
  2490. var y = plane.normal.y;
  2491. var z = plane.normal.z;
  2492. var temp = -2 * x;
  2493. var temp2 = -2 * y;
  2494. var temp3 = -2 * z;
  2495. result.m[0] = (temp * x) + 1;
  2496. result.m[1] = temp2 * x;
  2497. result.m[2] = temp3 * x;
  2498. result.m[3] = 0.0;
  2499. result.m[4] = temp * y;
  2500. result.m[5] = (temp2 * y) + 1;
  2501. result.m[6] = temp3 * y;
  2502. result.m[7] = 0.0;
  2503. result.m[8] = temp * z;
  2504. result.m[9] = temp2 * z;
  2505. result.m[10] = (temp3 * z) + 1;
  2506. result.m[11] = 0.0;
  2507. result.m[12] = temp * plane.d;
  2508. result.m[13] = temp2 * plane.d;
  2509. result.m[14] = temp3 * plane.d;
  2510. result.m[15] = 1.0;
  2511. };
  2512. Matrix.FromXYZAxesToRef = function (xaxis, yaxis, zaxis, mat) {
  2513. mat.m[0] = xaxis.x;
  2514. mat.m[1] = xaxis.y;
  2515. mat.m[2] = xaxis.z;
  2516. mat.m[3] = 0;
  2517. mat.m[4] = yaxis.x;
  2518. mat.m[5] = yaxis.y;
  2519. mat.m[6] = yaxis.z;
  2520. mat.m[7] = 0;
  2521. mat.m[8] = zaxis.x;
  2522. mat.m[9] = zaxis.y;
  2523. mat.m[10] = zaxis.z;
  2524. mat.m[11] = 0;
  2525. mat.m[12] = 0;
  2526. mat.m[13] = 0;
  2527. mat.m[14] = 0;
  2528. mat.m[15] = 1;
  2529. };
  2530. Matrix.FromQuaternionToRef = function (quat, result) {
  2531. var xx = quat.x * quat.x;
  2532. var yy = quat.y * quat.y;
  2533. var zz = quat.z * quat.z;
  2534. var xy = quat.x * quat.y;
  2535. var zw = quat.z * quat.w;
  2536. var zx = quat.z * quat.x;
  2537. var yw = quat.y * quat.w;
  2538. var yz = quat.y * quat.z;
  2539. var xw = quat.x * quat.w;
  2540. result.m[0] = 1.0 - (2.0 * (yy + zz));
  2541. result.m[1] = 2.0 * (xy + zw);
  2542. result.m[2] = 2.0 * (zx - yw);
  2543. result.m[3] = 0;
  2544. result.m[4] = 2.0 * (xy - zw);
  2545. result.m[5] = 1.0 - (2.0 * (zz + xx));
  2546. result.m[6] = 2.0 * (yz + xw);
  2547. result.m[7] = 0;
  2548. result.m[8] = 2.0 * (zx + yw);
  2549. result.m[9] = 2.0 * (yz - xw);
  2550. result.m[10] = 1.0 - (2.0 * (yy + xx));
  2551. result.m[11] = 0;
  2552. result.m[12] = 0;
  2553. result.m[13] = 0;
  2554. result.m[14] = 0;
  2555. result.m[15] = 1.0;
  2556. };
  2557. return Matrix;
  2558. }());
  2559. Matrix._tempQuaternion = new Quaternion();
  2560. Matrix._xAxis = Vector3.Zero();
  2561. Matrix._yAxis = Vector3.Zero();
  2562. Matrix._zAxis = Vector3.Zero();
  2563. BABYLON.Matrix = Matrix;
  2564. var Plane = (function () {
  2565. function Plane(a, b, c, d) {
  2566. this.normal = new Vector3(a, b, c);
  2567. this.d = d;
  2568. }
  2569. Plane.prototype.asArray = function () {
  2570. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  2571. };
  2572. // Methods
  2573. Plane.prototype.clone = function () {
  2574. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  2575. };
  2576. Plane.prototype.getClassName = function () {
  2577. return "Plane";
  2578. };
  2579. Plane.prototype.getHashCode = function () {
  2580. var hash = this.normal.getHashCode();
  2581. hash = (hash * 397) ^ (this.d || 0);
  2582. return hash;
  2583. };
  2584. Plane.prototype.normalize = function () {
  2585. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  2586. var magnitude = 0;
  2587. if (norm !== 0) {
  2588. magnitude = 1.0 / norm;
  2589. }
  2590. this.normal.x *= magnitude;
  2591. this.normal.y *= magnitude;
  2592. this.normal.z *= magnitude;
  2593. this.d *= magnitude;
  2594. return this;
  2595. };
  2596. Plane.prototype.transform = function (transformation) {
  2597. var transposedMatrix = Matrix.Transpose(transformation);
  2598. var x = this.normal.x;
  2599. var y = this.normal.y;
  2600. var z = this.normal.z;
  2601. var d = this.d;
  2602. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  2603. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  2604. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  2605. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  2606. return new Plane(normalX, normalY, normalZ, finalD);
  2607. };
  2608. Plane.prototype.dotCoordinate = function (point) {
  2609. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  2610. };
  2611. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  2612. var x1 = point2.x - point1.x;
  2613. var y1 = point2.y - point1.y;
  2614. var z1 = point2.z - point1.z;
  2615. var x2 = point3.x - point1.x;
  2616. var y2 = point3.y - point1.y;
  2617. var z2 = point3.z - point1.z;
  2618. var yz = (y1 * z2) - (z1 * y2);
  2619. var xz = (z1 * x2) - (x1 * z2);
  2620. var xy = (x1 * y2) - (y1 * x2);
  2621. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  2622. var invPyth;
  2623. if (pyth !== 0) {
  2624. invPyth = 1.0 / pyth;
  2625. }
  2626. else {
  2627. invPyth = 0;
  2628. }
  2629. this.normal.x = yz * invPyth;
  2630. this.normal.y = xz * invPyth;
  2631. this.normal.z = xy * invPyth;
  2632. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  2633. return this;
  2634. };
  2635. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  2636. var dot = Vector3.Dot(this.normal, direction);
  2637. return (dot <= epsilon);
  2638. };
  2639. Plane.prototype.signedDistanceTo = function (point) {
  2640. return Vector3.Dot(point, this.normal) + this.d;
  2641. };
  2642. // Statics
  2643. Plane.FromArray = function (array) {
  2644. return new Plane(array[0], array[1], array[2], array[3]);
  2645. };
  2646. Plane.FromPoints = function (point1, point2, point3) {
  2647. var result = new Plane(0, 0, 0, 0);
  2648. result.copyFromPoints(point1, point2, point3);
  2649. return result;
  2650. };
  2651. Plane.FromPositionAndNormal = function (origin, normal) {
  2652. var result = new Plane(0, 0, 0, 0);
  2653. normal.normalize();
  2654. result.normal = normal;
  2655. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  2656. return result;
  2657. };
  2658. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  2659. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  2660. return Vector3.Dot(point, normal) + d;
  2661. };
  2662. return Plane;
  2663. }());
  2664. BABYLON.Plane = Plane;
  2665. var Viewport = (function () {
  2666. function Viewport(x, y, width, height) {
  2667. this.x = x;
  2668. this.y = y;
  2669. this.width = width;
  2670. this.height = height;
  2671. }
  2672. Viewport.prototype.toGlobal = function (renderWidth, renderHeight) {
  2673. return new Viewport(this.x * renderWidth, this.y * renderHeight, this.width * renderWidth, this.height * renderHeight);
  2674. };
  2675. return Viewport;
  2676. }());
  2677. BABYLON.Viewport = Viewport;
  2678. var Frustum = (function () {
  2679. function Frustum() {
  2680. }
  2681. Frustum.GetPlanes = function (transform) {
  2682. var frustumPlanes = [];
  2683. for (var index = 0; index < 6; index++) {
  2684. frustumPlanes.push(new Plane(0, 0, 0, 0));
  2685. }
  2686. Frustum.GetPlanesToRef(transform, frustumPlanes);
  2687. return frustumPlanes;
  2688. };
  2689. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  2690. // Near
  2691. frustumPlanes[0].normal.x = transform.m[3] + transform.m[2];
  2692. frustumPlanes[0].normal.y = transform.m[7] + transform.m[6];
  2693. frustumPlanes[0].normal.z = transform.m[11] + transform.m[10];
  2694. frustumPlanes[0].d = transform.m[15] + transform.m[14];
  2695. frustumPlanes[0].normalize();
  2696. // Far
  2697. frustumPlanes[1].normal.x = transform.m[3] - transform.m[2];
  2698. frustumPlanes[1].normal.y = transform.m[7] - transform.m[6];
  2699. frustumPlanes[1].normal.z = transform.m[11] - transform.m[10];
  2700. frustumPlanes[1].d = transform.m[15] - transform.m[14];
  2701. frustumPlanes[1].normalize();
  2702. // Left
  2703. frustumPlanes[2].normal.x = transform.m[3] + transform.m[0];
  2704. frustumPlanes[2].normal.y = transform.m[7] + transform.m[4];
  2705. frustumPlanes[2].normal.z = transform.m[11] + transform.m[8];
  2706. frustumPlanes[2].d = transform.m[15] + transform.m[12];
  2707. frustumPlanes[2].normalize();
  2708. // Right
  2709. frustumPlanes[3].normal.x = transform.m[3] - transform.m[0];
  2710. frustumPlanes[3].normal.y = transform.m[7] - transform.m[4];
  2711. frustumPlanes[3].normal.z = transform.m[11] - transform.m[8];
  2712. frustumPlanes[3].d = transform.m[15] - transform.m[12];
  2713. frustumPlanes[3].normalize();
  2714. // Top
  2715. frustumPlanes[4].normal.x = transform.m[3] - transform.m[1];
  2716. frustumPlanes[4].normal.y = transform.m[7] - transform.m[5];
  2717. frustumPlanes[4].normal.z = transform.m[11] - transform.m[9];
  2718. frustumPlanes[4].d = transform.m[15] - transform.m[13];
  2719. frustumPlanes[4].normalize();
  2720. // Bottom
  2721. frustumPlanes[5].normal.x = transform.m[3] + transform.m[1];
  2722. frustumPlanes[5].normal.y = transform.m[7] + transform.m[5];
  2723. frustumPlanes[5].normal.z = transform.m[11] + transform.m[9];
  2724. frustumPlanes[5].d = transform.m[15] + transform.m[13];
  2725. frustumPlanes[5].normalize();
  2726. };
  2727. return Frustum;
  2728. }());
  2729. BABYLON.Frustum = Frustum;
  2730. var Space;
  2731. (function (Space) {
  2732. Space[Space["LOCAL"] = 0] = "LOCAL";
  2733. Space[Space["WORLD"] = 1] = "WORLD";
  2734. })(Space = BABYLON.Space || (BABYLON.Space = {}));
  2735. var Axis = (function () {
  2736. function Axis() {
  2737. }
  2738. return Axis;
  2739. }());
  2740. Axis.X = new Vector3(1, 0, 0);
  2741. Axis.Y = new Vector3(0, 1, 0);
  2742. Axis.Z = new Vector3(0, 0, 1);
  2743. BABYLON.Axis = Axis;
  2744. ;
  2745. var BezierCurve = (function () {
  2746. function BezierCurve() {
  2747. }
  2748. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  2749. // Extract X (which is equal to time here)
  2750. var f0 = 1 - 3 * x2 + 3 * x1;
  2751. var f1 = 3 * x2 - 6 * x1;
  2752. var f2 = 3 * x1;
  2753. var refinedT = t;
  2754. for (var i = 0; i < 5; i++) {
  2755. var refinedT2 = refinedT * refinedT;
  2756. var refinedT3 = refinedT2 * refinedT;
  2757. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  2758. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  2759. refinedT -= (x - t) * slope;
  2760. refinedT = Math.min(1, Math.max(0, refinedT));
  2761. }
  2762. // Resolve cubic bezier for the given x
  2763. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  2764. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  2765. Math.pow(refinedT, 3);
  2766. };
  2767. return BezierCurve;
  2768. }());
  2769. BABYLON.BezierCurve = BezierCurve;
  2770. var Orientation;
  2771. (function (Orientation) {
  2772. Orientation[Orientation["CW"] = 0] = "CW";
  2773. Orientation[Orientation["CCW"] = 1] = "CCW";
  2774. })(Orientation = BABYLON.Orientation || (BABYLON.Orientation = {}));
  2775. var Angle = (function () {
  2776. function Angle(radians) {
  2777. var _this = this;
  2778. this.degrees = function () { return _this._radians * 180 / Math.PI; };
  2779. this.radians = function () { return _this._radians; };
  2780. this._radians = radians;
  2781. if (this._radians < 0)
  2782. this._radians += (2 * Math.PI);
  2783. }
  2784. Angle.BetweenTwoPoints = function (a, b) {
  2785. var delta = b.subtract(a);
  2786. var theta = Math.atan2(delta.y, delta.x);
  2787. return new Angle(theta);
  2788. };
  2789. Angle.FromRadians = function (radians) {
  2790. return new Angle(radians);
  2791. };
  2792. Angle.FromDegrees = function (degrees) {
  2793. return new Angle(degrees * Math.PI / 180);
  2794. };
  2795. return Angle;
  2796. }());
  2797. BABYLON.Angle = Angle;
  2798. var Arc2 = (function () {
  2799. function Arc2(startPoint, midPoint, endPoint) {
  2800. this.startPoint = startPoint;
  2801. this.midPoint = midPoint;
  2802. this.endPoint = endPoint;
  2803. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  2804. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  2805. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  2806. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  2807. 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);
  2808. this.radius = this.centerPoint.subtract(this.startPoint).length();
  2809. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  2810. var a1 = this.startAngle.degrees();
  2811. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  2812. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  2813. // angles correction
  2814. if (a2 - a1 > +180.0)
  2815. a2 -= 360.0;
  2816. if (a2 - a1 < -180.0)
  2817. a2 += 360.0;
  2818. if (a3 - a2 > +180.0)
  2819. a3 -= 360.0;
  2820. if (a3 - a2 < -180.0)
  2821. a3 += 360.0;
  2822. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  2823. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  2824. }
  2825. return Arc2;
  2826. }());
  2827. BABYLON.Arc2 = Arc2;
  2828. var Path2 = (function () {
  2829. function Path2(x, y) {
  2830. this._points = new Array();
  2831. this._length = 0;
  2832. this.closed = false;
  2833. this._points.push(new Vector2(x, y));
  2834. }
  2835. Path2.prototype.addLineTo = function (x, y) {
  2836. if (closed) {
  2837. //Tools.Error("cannot add lines to closed paths");
  2838. return this;
  2839. }
  2840. var newPoint = new Vector2(x, y);
  2841. var previousPoint = this._points[this._points.length - 1];
  2842. this._points.push(newPoint);
  2843. this._length += newPoint.subtract(previousPoint).length();
  2844. return this;
  2845. };
  2846. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  2847. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  2848. if (closed) {
  2849. //Tools.Error("cannot add arcs to closed paths");
  2850. return this;
  2851. }
  2852. var startPoint = this._points[this._points.length - 1];
  2853. var midPoint = new Vector2(midX, midY);
  2854. var endPoint = new Vector2(endX, endY);
  2855. var arc = new Arc2(startPoint, midPoint, endPoint);
  2856. var increment = arc.angle.radians() / numberOfSegments;
  2857. if (arc.orientation === Orientation.CW)
  2858. increment *= -1;
  2859. var currentAngle = arc.startAngle.radians() + increment;
  2860. for (var i = 0; i < numberOfSegments; i++) {
  2861. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  2862. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  2863. this.addLineTo(x, y);
  2864. currentAngle += increment;
  2865. }
  2866. return this;
  2867. };
  2868. Path2.prototype.close = function () {
  2869. this.closed = true;
  2870. return this;
  2871. };
  2872. Path2.prototype.length = function () {
  2873. var result = this._length;
  2874. if (!this.closed) {
  2875. var lastPoint = this._points[this._points.length - 1];
  2876. var firstPoint = this._points[0];
  2877. result += (firstPoint.subtract(lastPoint).length());
  2878. }
  2879. return result;
  2880. };
  2881. Path2.prototype.getPoints = function () {
  2882. return this._points;
  2883. };
  2884. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  2885. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  2886. //Tools.Error("normalized length position should be between 0 and 1.");
  2887. return Vector2.Zero();
  2888. }
  2889. var lengthPosition = normalizedLengthPosition * this.length();
  2890. var previousOffset = 0;
  2891. for (var i = 0; i < this._points.length; i++) {
  2892. var j = (i + 1) % this._points.length;
  2893. var a = this._points[i];
  2894. var b = this._points[j];
  2895. var bToA = b.subtract(a);
  2896. var nextOffset = (bToA.length() + previousOffset);
  2897. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  2898. var dir = bToA.normalize();
  2899. var localOffset = lengthPosition - previousOffset;
  2900. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  2901. }
  2902. previousOffset = nextOffset;
  2903. }
  2904. //Tools.Error("internal error");
  2905. return Vector2.Zero();
  2906. };
  2907. Path2.StartingAt = function (x, y) {
  2908. return new Path2(x, y);
  2909. };
  2910. return Path2;
  2911. }());
  2912. BABYLON.Path2 = Path2;
  2913. var Path3D = (function () {
  2914. /**
  2915. * new Path3D(path, normal, raw)
  2916. * Creates a Path3D. A Path3D is a logical math object, so not a mesh.
  2917. * please read the description in the tutorial : http://doc.babylonjs.com/tutorials/How_to_use_Path3D
  2918. * path : an array of Vector3, the curve axis of the Path3D
  2919. * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  2920. * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  2921. */
  2922. function Path3D(path, firstNormal, raw) {
  2923. this.path = path;
  2924. this._curve = new Array();
  2925. this._distances = new Array();
  2926. this._tangents = new Array();
  2927. this._normals = new Array();
  2928. this._binormals = new Array();
  2929. for (var p = 0; p < path.length; p++) {
  2930. this._curve[p] = path[p].clone(); // hard copy
  2931. }
  2932. this._raw = raw || false;
  2933. this._compute(firstNormal);
  2934. }
  2935. /**
  2936. * Returns the Path3D array of successive Vector3 designing its curve.
  2937. */
  2938. Path3D.prototype.getCurve = function () {
  2939. return this._curve;
  2940. };
  2941. /**
  2942. * Returns an array populated with tangent vectors on each Path3D curve point.
  2943. */
  2944. Path3D.prototype.getTangents = function () {
  2945. return this._tangents;
  2946. };
  2947. /**
  2948. * Returns an array populated with normal vectors on each Path3D curve point.
  2949. */
  2950. Path3D.prototype.getNormals = function () {
  2951. return this._normals;
  2952. };
  2953. /**
  2954. * Returns an array populated with binormal vectors on each Path3D curve point.
  2955. */
  2956. Path3D.prototype.getBinormals = function () {
  2957. return this._binormals;
  2958. };
  2959. /**
  2960. * Returns an array populated with distances (float) of the i-th point from the first curve point.
  2961. */
  2962. Path3D.prototype.getDistances = function () {
  2963. return this._distances;
  2964. };
  2965. /**
  2966. * Forces the Path3D tangent, normal, binormal and distance recomputation.
  2967. * Returns the same object updated.
  2968. */
  2969. Path3D.prototype.update = function (path, firstNormal) {
  2970. for (var p = 0; p < path.length; p++) {
  2971. this._curve[p].x = path[p].x;
  2972. this._curve[p].y = path[p].y;
  2973. this._curve[p].z = path[p].z;
  2974. }
  2975. this._compute(firstNormal);
  2976. return this;
  2977. };
  2978. // private function compute() : computes tangents, normals and binormals
  2979. Path3D.prototype._compute = function (firstNormal) {
  2980. var l = this._curve.length;
  2981. // first and last tangents
  2982. this._tangents[0] = this._getFirstNonNullVector(0);
  2983. if (!this._raw) {
  2984. this._tangents[0].normalize();
  2985. }
  2986. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  2987. if (!this._raw) {
  2988. this._tangents[l - 1].normalize();
  2989. }
  2990. // normals and binormals at first point : arbitrary vector with _normalVector()
  2991. var tg0 = this._tangents[0];
  2992. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  2993. this._normals[0] = pp0;
  2994. if (!this._raw) {
  2995. this._normals[0].normalize();
  2996. }
  2997. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  2998. if (!this._raw) {
  2999. this._binormals[0].normalize();
  3000. }
  3001. this._distances[0] = 0.0;
  3002. // normals and binormals : next points
  3003. var prev; // previous vector (segment)
  3004. var cur; // current vector (segment)
  3005. var curTang; // current tangent
  3006. // previous normal
  3007. var prevBinor; // previous binormal
  3008. for (var i = 1; i < l; i++) {
  3009. // tangents
  3010. prev = this._getLastNonNullVector(i);
  3011. if (i < l - 1) {
  3012. cur = this._getFirstNonNullVector(i);
  3013. this._tangents[i] = prev.add(cur);
  3014. this._tangents[i].normalize();
  3015. }
  3016. this._distances[i] = this._distances[i - 1] + prev.length();
  3017. // normals and binormals
  3018. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  3019. curTang = this._tangents[i];
  3020. prevBinor = this._binormals[i - 1];
  3021. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  3022. if (!this._raw) {
  3023. this._normals[i].normalize();
  3024. }
  3025. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  3026. if (!this._raw) {
  3027. this._binormals[i].normalize();
  3028. }
  3029. }
  3030. };
  3031. // private function getFirstNonNullVector(index)
  3032. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  3033. Path3D.prototype._getFirstNonNullVector = function (index) {
  3034. var i = 1;
  3035. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  3036. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  3037. i++;
  3038. nNVector = this._curve[index + i].subtract(this._curve[index]);
  3039. }
  3040. return nNVector;
  3041. };
  3042. // private function getLastNonNullVector(index)
  3043. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  3044. Path3D.prototype._getLastNonNullVector = function (index) {
  3045. var i = 1;
  3046. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  3047. while (nLVector.length() === 0 && index > i + 1) {
  3048. i++;
  3049. nLVector = this._curve[index].subtract(this._curve[index - i]);
  3050. }
  3051. return nLVector;
  3052. };
  3053. // private function normalVector(v0, vt, va) :
  3054. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  3055. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  3056. Path3D.prototype._normalVector = function (v0, vt, va) {
  3057. var normal0;
  3058. var tgl = vt.length();
  3059. if (tgl === 0.0) {
  3060. tgl = 1.0;
  3061. }
  3062. if (va === undefined || va === null) {
  3063. var point;
  3064. if (!MathTools.WithinEpsilon(Math.abs(vt.y) / tgl, 1.0, BABYLON.Epsilon)) {
  3065. point = new Vector3(0.0, -1.0, 0.0);
  3066. }
  3067. else if (!MathTools.WithinEpsilon(Math.abs(vt.x) / tgl, 1.0, BABYLON.Epsilon)) {
  3068. point = new Vector3(1.0, 0.0, 0.0);
  3069. }
  3070. else if (!MathTools.WithinEpsilon(Math.abs(vt.z) / tgl, 1.0, BABYLON.Epsilon)) {
  3071. point = new Vector3(0.0, 0.0, 1.0);
  3072. }
  3073. normal0 = Vector3.Cross(vt, point);
  3074. }
  3075. else {
  3076. normal0 = Vector3.Cross(vt, va);
  3077. Vector3.CrossToRef(normal0, vt, normal0);
  3078. }
  3079. normal0.normalize();
  3080. return normal0;
  3081. };
  3082. return Path3D;
  3083. }());
  3084. BABYLON.Path3D = Path3D;
  3085. var Curve3 = (function () {
  3086. /**
  3087. * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
  3088. * A Curve3 is designed from a series of successive Vector3.
  3089. * Tuto : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#curve3-object
  3090. */
  3091. function Curve3(points) {
  3092. this._length = 0.0;
  3093. this._points = points;
  3094. this._length = this._computeLength(points);
  3095. }
  3096. /**
  3097. * Returns a Curve3 object along a Quadratic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#quadratic-bezier-curve
  3098. * @param v0 (Vector3) the origin point of the Quadratic Bezier
  3099. * @param v1 (Vector3) the control point
  3100. * @param v2 (Vector3) the end point of the Quadratic Bezier
  3101. * @param nbPoints (integer) the wanted number of points in the curve
  3102. */
  3103. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  3104. nbPoints = nbPoints > 2 ? nbPoints : 3;
  3105. var bez = new Array();
  3106. var equation = function (t, val0, val1, val2) {
  3107. var res = (1.0 - t) * (1.0 - t) * val0 + 2.0 * t * (1.0 - t) * val1 + t * t * val2;
  3108. return res;
  3109. };
  3110. for (var i = 0; i <= nbPoints; i++) {
  3111. 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)));
  3112. }
  3113. return new Curve3(bez);
  3114. };
  3115. /**
  3116. * Returns a Curve3 object along a Cubic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#cubic-bezier-curve
  3117. * @param v0 (Vector3) the origin point of the Cubic Bezier
  3118. * @param v1 (Vector3) the first control point
  3119. * @param v2 (Vector3) the second control point
  3120. * @param v3 (Vector3) the end point of the Cubic Bezier
  3121. * @param nbPoints (integer) the wanted number of points in the curve
  3122. */
  3123. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  3124. nbPoints = nbPoints > 3 ? nbPoints : 4;
  3125. var bez = new Array();
  3126. var equation = function (t, val0, val1, val2, val3) {
  3127. 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;
  3128. return res;
  3129. };
  3130. for (var i = 0; i <= nbPoints; i++) {
  3131. 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)));
  3132. }
  3133. return new Curve3(bez);
  3134. };
  3135. /**
  3136. * Returns a Curve3 object along a Hermite Spline curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#hermite-spline
  3137. * @param p1 (Vector3) the origin point of the Hermite Spline
  3138. * @param t1 (Vector3) the tangent vector at the origin point
  3139. * @param p2 (Vector3) the end point of the Hermite Spline
  3140. * @param t2 (Vector3) the tangent vector at the end point
  3141. * @param nbPoints (integer) the wanted number of points in the curve
  3142. */
  3143. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  3144. var hermite = new Array();
  3145. var step = 1.0 / nbPoints;
  3146. for (var i = 0; i <= nbPoints; i++) {
  3147. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  3148. }
  3149. return new Curve3(hermite);
  3150. };
  3151. /**
  3152. * Returns the Curve3 stored array of successive Vector3
  3153. */
  3154. Curve3.prototype.getPoints = function () {
  3155. return this._points;
  3156. };
  3157. /**
  3158. * Returns the computed length (float) of the curve.
  3159. */
  3160. Curve3.prototype.length = function () {
  3161. return this._length;
  3162. };
  3163. /**
  3164. * Returns a new instance of Curve3 object : var curve = curveA.continue(curveB);
  3165. * This new Curve3 is built by translating and sticking the curveB at the end of the curveA.
  3166. * curveA and curveB keep unchanged.
  3167. */
  3168. Curve3.prototype.continue = function (curve) {
  3169. var lastPoint = this._points[this._points.length - 1];
  3170. var continuedPoints = this._points.slice();
  3171. var curvePoints = curve.getPoints();
  3172. for (var i = 1; i < curvePoints.length; i++) {
  3173. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  3174. }
  3175. var continuedCurve = new Curve3(continuedPoints);
  3176. return continuedCurve;
  3177. };
  3178. Curve3.prototype._computeLength = function (path) {
  3179. var l = 0;
  3180. for (var i = 1; i < path.length; i++) {
  3181. l += (path[i].subtract(path[i - 1])).length();
  3182. }
  3183. return l;
  3184. };
  3185. return Curve3;
  3186. }());
  3187. BABYLON.Curve3 = Curve3;
  3188. // SphericalHarmonics
  3189. var SphericalHarmonics = (function () {
  3190. function SphericalHarmonics() {
  3191. this.L00 = Vector3.Zero();
  3192. this.L1_1 = Vector3.Zero();
  3193. this.L10 = Vector3.Zero();
  3194. this.L11 = Vector3.Zero();
  3195. this.L2_2 = Vector3.Zero();
  3196. this.L2_1 = Vector3.Zero();
  3197. this.L20 = Vector3.Zero();
  3198. this.L21 = Vector3.Zero();
  3199. this.L22 = Vector3.Zero();
  3200. }
  3201. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  3202. var colorVector = new Vector3(color.r, color.g, color.b);
  3203. var c = colorVector.scale(deltaSolidAngle);
  3204. this.L00 = this.L00.add(c.scale(0.282095));
  3205. this.L1_1 = this.L1_1.add(c.scale(0.488603 * direction.y));
  3206. this.L10 = this.L10.add(c.scale(0.488603 * direction.z));
  3207. this.L11 = this.L11.add(c.scale(0.488603 * direction.x));
  3208. this.L2_2 = this.L2_2.add(c.scale(1.092548 * direction.x * direction.y));
  3209. this.L2_1 = this.L2_1.add(c.scale(1.092548 * direction.y * direction.z));
  3210. this.L21 = this.L21.add(c.scale(1.092548 * direction.x * direction.z));
  3211. this.L20 = this.L20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  3212. this.L22 = this.L22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  3213. };
  3214. SphericalHarmonics.prototype.scale = function (scale) {
  3215. this.L00 = this.L00.scale(scale);
  3216. this.L1_1 = this.L1_1.scale(scale);
  3217. this.L10 = this.L10.scale(scale);
  3218. this.L11 = this.L11.scale(scale);
  3219. this.L2_2 = this.L2_2.scale(scale);
  3220. this.L2_1 = this.L2_1.scale(scale);
  3221. this.L20 = this.L20.scale(scale);
  3222. this.L21 = this.L21.scale(scale);
  3223. this.L22 = this.L22.scale(scale);
  3224. };
  3225. return SphericalHarmonics;
  3226. }());
  3227. BABYLON.SphericalHarmonics = SphericalHarmonics;
  3228. // SphericalPolynomial
  3229. var SphericalPolynomial = (function () {
  3230. function SphericalPolynomial() {
  3231. this.x = Vector3.Zero();
  3232. this.y = Vector3.Zero();
  3233. this.z = Vector3.Zero();
  3234. this.xx = Vector3.Zero();
  3235. this.yy = Vector3.Zero();
  3236. this.zz = Vector3.Zero();
  3237. this.xy = Vector3.Zero();
  3238. this.yz = Vector3.Zero();
  3239. this.zx = Vector3.Zero();
  3240. }
  3241. SphericalPolynomial.prototype.addAmbient = function (color) {
  3242. var colorVector = new Vector3(color.r, color.g, color.b);
  3243. this.xx = this.xx.add(colorVector);
  3244. this.yy = this.yy.add(colorVector);
  3245. this.zz = this.zz.add(colorVector);
  3246. };
  3247. SphericalPolynomial.getSphericalPolynomialFromHarmonics = function (harmonics) {
  3248. var result = new SphericalPolynomial();
  3249. result.x = harmonics.L11.scale(1.02333);
  3250. result.y = harmonics.L1_1.scale(1.02333);
  3251. result.z = harmonics.L10.scale(1.02333);
  3252. result.xx = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).add(harmonics.L22.scale(0.429043));
  3253. result.yy = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).subtract(harmonics.L22.scale(0.429043));
  3254. result.zz = harmonics.L00.scale(0.886277).add(harmonics.L20.scale(0.495417));
  3255. result.yz = harmonics.L2_1.scale(0.858086);
  3256. result.zx = harmonics.L21.scale(0.858086);
  3257. result.xy = harmonics.L2_2.scale(0.858086);
  3258. return result;
  3259. };
  3260. return SphericalPolynomial;
  3261. }());
  3262. BABYLON.SphericalPolynomial = SphericalPolynomial;
  3263. // Vertex formats
  3264. var PositionNormalVertex = (function () {
  3265. function PositionNormalVertex(position, normal) {
  3266. if (position === void 0) { position = Vector3.Zero(); }
  3267. if (normal === void 0) { normal = Vector3.Up(); }
  3268. this.position = position;
  3269. this.normal = normal;
  3270. }
  3271. PositionNormalVertex.prototype.clone = function () {
  3272. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  3273. };
  3274. return PositionNormalVertex;
  3275. }());
  3276. BABYLON.PositionNormalVertex = PositionNormalVertex;
  3277. var PositionNormalTextureVertex = (function () {
  3278. function PositionNormalTextureVertex(position, normal, uv) {
  3279. if (position === void 0) { position = Vector3.Zero(); }
  3280. if (normal === void 0) { normal = Vector3.Up(); }
  3281. if (uv === void 0) { uv = Vector2.Zero(); }
  3282. this.position = position;
  3283. this.normal = normal;
  3284. this.uv = uv;
  3285. }
  3286. PositionNormalTextureVertex.prototype.clone = function () {
  3287. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  3288. };
  3289. return PositionNormalTextureVertex;
  3290. }());
  3291. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  3292. // Temporary pre-allocated objects for engine internal use
  3293. // usage in any internal function :
  3294. // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3
  3295. // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
  3296. var Tmp = (function () {
  3297. function Tmp() {
  3298. }
  3299. return Tmp;
  3300. }());
  3301. Tmp.Color3 = [Color3.Black(), Color3.Black(), Color3.Black()];
  3302. Tmp.Vector2 = [Vector2.Zero(), Vector2.Zero(), Vector2.Zero()]; // 3 temp Vector2 at once should be enough
  3303. Tmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(),
  3304. Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()]; // 9 temp Vector3 at once should be enough
  3305. Tmp.Vector4 = [Vector4.Zero(), Vector4.Zero(), Vector4.Zero()]; // 3 temp Vector4 at once should be enough
  3306. Tmp.Quaternion = [new Quaternion(0, 0, 0, 0)]; // 1 temp Quaternion at once should be enough
  3307. Tmp.Matrix = [Matrix.Zero(), Matrix.Zero(),
  3308. Matrix.Zero(), Matrix.Zero(),
  3309. Matrix.Zero(), Matrix.Zero(),
  3310. Matrix.Zero(), Matrix.Zero()]; // 6 temp Matrices at once should be enough
  3311. BABYLON.Tmp = Tmp;
  3312. })(BABYLON || (BABYLON = {}));
  3313. //# sourceMappingURL=babylon.math.js.map
  3314. //# sourceMappingURL=babylon.mixins.js.map
  3315. var BABYLON;
  3316. (function (BABYLON) {
  3317. function generateSerializableMember(type, sourceName) {
  3318. return function (target, propertyKey) {
  3319. if (!target.__serializableMembers) {
  3320. target.__serializableMembers = {};
  3321. }
  3322. if (!target.__serializableMembers[propertyKey]) {
  3323. target.__serializableMembers[propertyKey] = { type: type, sourceName: sourceName };
  3324. }
  3325. };
  3326. }
  3327. function serialize(sourceName) {
  3328. return generateSerializableMember(0, sourceName); // value member
  3329. }
  3330. BABYLON.serialize = serialize;
  3331. function serializeAsTexture(sourceName) {
  3332. return generateSerializableMember(1, sourceName); // texture member
  3333. }
  3334. BABYLON.serializeAsTexture = serializeAsTexture;
  3335. function serializeAsColor3(sourceName) {
  3336. return generateSerializableMember(2, sourceName); // color3 member
  3337. }
  3338. BABYLON.serializeAsColor3 = serializeAsColor3;
  3339. function serializeAsFresnelParameters(sourceName) {
  3340. return generateSerializableMember(3, sourceName); // fresnel parameters member
  3341. }
  3342. BABYLON.serializeAsFresnelParameters = serializeAsFresnelParameters;
  3343. function serializeAsVector2(sourceName) {
  3344. return generateSerializableMember(4, sourceName); // vector2 member
  3345. }
  3346. BABYLON.serializeAsVector2 = serializeAsVector2;
  3347. function serializeAsVector3(sourceName) {
  3348. return generateSerializableMember(5, sourceName); // vector3 member
  3349. }
  3350. BABYLON.serializeAsVector3 = serializeAsVector3;
  3351. function serializeAsMeshReference(sourceName) {
  3352. return generateSerializableMember(6, sourceName); // mesh reference member
  3353. }
  3354. BABYLON.serializeAsMeshReference = serializeAsMeshReference;
  3355. function serializeAsColorCurves(sourceName) {
  3356. return generateSerializableMember(7, sourceName); // color curves
  3357. }
  3358. BABYLON.serializeAsColorCurves = serializeAsColorCurves;
  3359. var SerializationHelper = (function () {
  3360. function SerializationHelper() {
  3361. }
  3362. SerializationHelper.Serialize = function (entity, serializationObject) {
  3363. if (!serializationObject) {
  3364. serializationObject = {};
  3365. }
  3366. // Tags
  3367. serializationObject.tags = BABYLON.Tags.GetTags(entity);
  3368. // Properties
  3369. for (var property in entity.__serializableMembers) {
  3370. var propertyDescriptor = entity.__serializableMembers[property];
  3371. var targetPropertyName = propertyDescriptor.sourceName || property;
  3372. var propertyType = propertyDescriptor.type;
  3373. var sourceProperty = entity[property];
  3374. if (sourceProperty !== undefined && sourceProperty !== null) {
  3375. switch (propertyType) {
  3376. case 0:
  3377. serializationObject[targetPropertyName] = sourceProperty;
  3378. break;
  3379. case 1:
  3380. serializationObject[targetPropertyName] = sourceProperty.serialize();
  3381. break;
  3382. case 2:
  3383. serializationObject[targetPropertyName] = sourceProperty.asArray();
  3384. break;
  3385. case 3:
  3386. serializationObject[targetPropertyName] = sourceProperty.serialize();
  3387. break;
  3388. case 4:
  3389. serializationObject[targetPropertyName] = sourceProperty.asArray();
  3390. break;
  3391. case 5:
  3392. serializationObject[targetPropertyName] = sourceProperty.asArray();
  3393. break;
  3394. case 6:
  3395. serializationObject[targetPropertyName] = sourceProperty.id;
  3396. break;
  3397. case 7:
  3398. serializationObject[targetPropertyName] = sourceProperty.serialize();
  3399. break;
  3400. }
  3401. }
  3402. }
  3403. return serializationObject;
  3404. };
  3405. SerializationHelper.Parse = function (creationFunction, source, scene, rootUrl) {
  3406. var destination = creationFunction();
  3407. // Tags
  3408. BABYLON.Tags.AddTagsTo(destination, source.tags);
  3409. // Properties
  3410. for (var property in destination.__serializableMembers) {
  3411. var propertyDescriptor = destination.__serializableMembers[property];
  3412. var sourceProperty = source[propertyDescriptor.sourceName || property];
  3413. var propertyType = propertyDescriptor.type;
  3414. if (sourceProperty !== undefined && sourceProperty !== null) {
  3415. switch (propertyType) {
  3416. case 0:
  3417. destination[property] = sourceProperty;
  3418. break;
  3419. case 1:
  3420. destination[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl);
  3421. break;
  3422. case 2:
  3423. destination[property] = BABYLON.Color3.FromArray(sourceProperty);
  3424. break;
  3425. case 3:
  3426. destination[property] = BABYLON.FresnelParameters.Parse(sourceProperty);
  3427. break;
  3428. case 4:
  3429. destination[property] = BABYLON.Vector2.FromArray(sourceProperty);
  3430. break;
  3431. case 5:
  3432. destination[property] = BABYLON.Vector3.FromArray(sourceProperty);
  3433. break;
  3434. case 6:
  3435. destination[property] = scene.getLastMeshByID(sourceProperty);
  3436. break;
  3437. case 7:
  3438. destination[property] = BABYLON.ColorCurves.Parse(sourceProperty);
  3439. break;
  3440. }
  3441. }
  3442. }
  3443. return destination;
  3444. };
  3445. SerializationHelper.Clone = function (creationFunction, source) {
  3446. var destination = creationFunction();
  3447. // Tags
  3448. BABYLON.Tags.AddTagsTo(destination, source.tags);
  3449. // Properties
  3450. for (var property in destination.__serializableMembers) {
  3451. var propertyDescriptor = destination.__serializableMembers[property];
  3452. var sourceProperty = source[property];
  3453. var propertyType = propertyDescriptor.type;
  3454. if (sourceProperty !== undefined && sourceProperty !== null) {
  3455. switch (propertyType) {
  3456. case 0: // Value
  3457. case 6:
  3458. destination[property] = sourceProperty;
  3459. break;
  3460. case 1: // Texture
  3461. case 2: // Color3
  3462. case 3: // FresnelParameters
  3463. case 4: // Vector2
  3464. case 5: // Vector3
  3465. case 7:
  3466. destination[property] = sourceProperty.clone();
  3467. break;
  3468. }
  3469. }
  3470. }
  3471. return destination;
  3472. };
  3473. return SerializationHelper;
  3474. }());
  3475. BABYLON.SerializationHelper = SerializationHelper;
  3476. })(BABYLON || (BABYLON = {}));
  3477. //# sourceMappingURL=babylon.decorators.js.map
  3478. var BABYLON;
  3479. (function (BABYLON) {
  3480. /**
  3481. * A class serves as a medium between the observable and its observers
  3482. */
  3483. var EventState = (function () {
  3484. /**
  3485. * If the callback of a given Observer set skipNextObservers to true the following observers will be ignored
  3486. */
  3487. function EventState(mask, skipNextObservers) {
  3488. if (skipNextObservers === void 0) { skipNextObservers = false; }
  3489. this.initalize(mask, skipNextObservers);
  3490. }
  3491. EventState.prototype.initalize = function (mask, skipNextObservers) {
  3492. if (skipNextObservers === void 0) { skipNextObservers = false; }
  3493. this.mask = mask;
  3494. this.skipNextObservers = skipNextObservers;
  3495. return this;
  3496. };
  3497. return EventState;
  3498. }());
  3499. BABYLON.EventState = EventState;
  3500. /**
  3501. * Represent an Observer registered to a given Observable object.
  3502. */
  3503. var Observer = (function () {
  3504. function Observer(callback, mask) {
  3505. this.callback = callback;
  3506. this.mask = mask;
  3507. }
  3508. return Observer;
  3509. }());
  3510. BABYLON.Observer = Observer;
  3511. /**
  3512. * The Observable class is a simple implementation of the Observable pattern.
  3513. * 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.
  3514. * This enable a more fine grained execution without having to rely on multiple different Observable objects.
  3515. * 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).
  3516. * 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.
  3517. */
  3518. var Observable = (function () {
  3519. function Observable() {
  3520. this._observers = new Array();
  3521. this._eventState = new EventState(0);
  3522. }
  3523. /**
  3524. * Create a new Observer with the specified callback
  3525. * @param callback the callback that will be executed for that Observer
  3526. * @param mask the mask used to filter observers
  3527. * @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.
  3528. */
  3529. Observable.prototype.add = function (callback, mask, insertFirst) {
  3530. if (mask === void 0) { mask = -1; }
  3531. if (insertFirst === void 0) { insertFirst = false; }
  3532. if (!callback) {
  3533. return null;
  3534. }
  3535. var observer = new Observer(callback, mask);
  3536. if (insertFirst) {
  3537. this._observers.unshift(observer);
  3538. }
  3539. else {
  3540. this._observers.push(observer);
  3541. }
  3542. return observer;
  3543. };
  3544. /**
  3545. * Remove an Observer from the Observable object
  3546. * @param observer the instance of the Observer to remove. If it doesn't belong to this Observable, false will be returned.
  3547. */
  3548. Observable.prototype.remove = function (observer) {
  3549. var index = this._observers.indexOf(observer);
  3550. if (index !== -1) {
  3551. this._observers.splice(index, 1);
  3552. return true;
  3553. }
  3554. return false;
  3555. };
  3556. /**
  3557. * Remove a callback from the Observable object
  3558. * @param callback the callback to remove. If it doesn't belong to this Observable, false will be returned.
  3559. */
  3560. Observable.prototype.removeCallback = function (callback) {
  3561. for (var index = 0; index < this._observers.length; index++) {
  3562. if (this._observers[index].callback === callback) {
  3563. this._observers.splice(index, 1);
  3564. return true;
  3565. }
  3566. }
  3567. return false;
  3568. };
  3569. /**
  3570. * Notify all Observers by calling their respective callback with the given data
  3571. * Will return true if all observers were executed, false if an observer set skipNextObservers to true, then prevent the subsequent ones to execute
  3572. * @param eventData
  3573. * @param mask
  3574. */
  3575. Observable.prototype.notifyObservers = function (eventData, mask) {
  3576. if (mask === void 0) { mask = -1; }
  3577. var state = this._eventState;
  3578. state.mask = mask;
  3579. state.skipNextObservers = false;
  3580. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  3581. var obs = _a[_i];
  3582. if (obs.mask & mask) {
  3583. obs.callback(eventData, state);
  3584. }
  3585. if (state.skipNextObservers) {
  3586. return false;
  3587. }
  3588. }
  3589. return true;
  3590. };
  3591. /**
  3592. * return true is the Observable has at least one Observer registered
  3593. */
  3594. Observable.prototype.hasObservers = function () {
  3595. return this._observers.length > 0;
  3596. };
  3597. /**
  3598. * Clear the list of observers
  3599. */
  3600. Observable.prototype.clear = function () {
  3601. this._observers = new Array();
  3602. };
  3603. /**
  3604. * Clone the current observable
  3605. */
  3606. Observable.prototype.clone = function () {
  3607. var result = new Observable();
  3608. result._observers = this._observers.slice(0);
  3609. return result;
  3610. };
  3611. return Observable;
  3612. }());
  3613. BABYLON.Observable = Observable;
  3614. })(BABYLON || (BABYLON = {}));
  3615. //# sourceMappingURL=babylon.observable.js.map
  3616. var BABYLON;
  3617. (function (BABYLON) {
  3618. var Database = (function () {
  3619. function Database(urlToScene, callbackManifestChecked) {
  3620. // Handling various flavors of prefixed version of IndexedDB
  3621. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  3622. this.callbackManifestChecked = callbackManifestChecked;
  3623. this.currentSceneUrl = Database.ReturnFullUrlLocation(urlToScene);
  3624. this.db = null;
  3625. this.enableSceneOffline = false;
  3626. this.enableTexturesOffline = false;
  3627. this.manifestVersionFound = 0;
  3628. this.mustUpdateRessources = false;
  3629. this.hasReachedQuota = false;
  3630. if (!Database.IDBStorageEnabled) {
  3631. this.callbackManifestChecked(true);
  3632. }
  3633. else {
  3634. this.checkManifestFile();
  3635. }
  3636. }
  3637. Database.prototype.checkManifestFile = function () {
  3638. var _this = this;
  3639. function noManifestFile() {
  3640. that.enableSceneOffline = false;
  3641. that.enableTexturesOffline = false;
  3642. that.callbackManifestChecked(false);
  3643. }
  3644. var that = this;
  3645. var timeStampUsed = false;
  3646. var manifestURL = this.currentSceneUrl + ".manifest";
  3647. var xhr = new XMLHttpRequest();
  3648. if (navigator.onLine) {
  3649. // Adding a timestamp to by-pass browsers' cache
  3650. timeStampUsed = true;
  3651. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  3652. }
  3653. xhr.open("GET", manifestURL, true);
  3654. xhr.addEventListener("load", function () {
  3655. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  3656. try {
  3657. var manifestFile = JSON.parse(xhr.response);
  3658. _this.enableSceneOffline = manifestFile.enableSceneOffline;
  3659. _this.enableTexturesOffline = manifestFile.enableTexturesOffline;
  3660. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  3661. _this.manifestVersionFound = manifestFile.version;
  3662. }
  3663. if (_this.callbackManifestChecked) {
  3664. _this.callbackManifestChecked(true);
  3665. }
  3666. }
  3667. catch (ex) {
  3668. noManifestFile();
  3669. }
  3670. }
  3671. else {
  3672. noManifestFile();
  3673. }
  3674. }, false);
  3675. xhr.addEventListener("error", function (event) {
  3676. if (timeStampUsed) {
  3677. timeStampUsed = false;
  3678. // Let's retry without the timeStamp
  3679. // It could fail when coupled with HTML5 Offline API
  3680. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  3681. xhr.open("GET", retryManifestURL, true);
  3682. xhr.send();
  3683. }
  3684. else {
  3685. noManifestFile();
  3686. }
  3687. }, false);
  3688. try {
  3689. xhr.send();
  3690. }
  3691. catch (ex) {
  3692. BABYLON.Tools.Error("Error on XHR send request.");
  3693. that.callbackManifestChecked(false);
  3694. }
  3695. };
  3696. Database.prototype.openAsync = function (successCallback, errorCallback) {
  3697. var _this = this;
  3698. function handleError() {
  3699. that.isSupported = false;
  3700. if (errorCallback)
  3701. errorCallback();
  3702. }
  3703. var that = this;
  3704. if (!this.idbFactory || !(this.enableSceneOffline || this.enableTexturesOffline)) {
  3705. // Your browser doesn't support IndexedDB
  3706. this.isSupported = false;
  3707. if (errorCallback)
  3708. errorCallback();
  3709. }
  3710. else {
  3711. // If the DB hasn't been opened or created yet
  3712. if (!this.db) {
  3713. this.hasReachedQuota = false;
  3714. this.isSupported = true;
  3715. var request = this.idbFactory.open("babylonjs", 1);
  3716. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  3717. request.onerror = function (event) {
  3718. handleError();
  3719. };
  3720. // executes when a version change transaction cannot complete due to other active transactions
  3721. request.onblocked = function (event) {
  3722. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  3723. handleError();
  3724. };
  3725. // DB has been opened successfully
  3726. request.onsuccess = function (event) {
  3727. _this.db = request.result;
  3728. successCallback();
  3729. };
  3730. // Initialization of the DB. Creating Scenes & Textures stores
  3731. request.onupgradeneeded = function (event) {
  3732. _this.db = (event.target).result;
  3733. try {
  3734. var scenesStore = _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  3735. var versionsStore = _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  3736. var texturesStore = _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  3737. }
  3738. catch (ex) {
  3739. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  3740. handleError();
  3741. }
  3742. };
  3743. }
  3744. else {
  3745. if (successCallback)
  3746. successCallback();
  3747. }
  3748. }
  3749. };
  3750. Database.prototype.loadImageFromDB = function (url, image) {
  3751. var _this = this;
  3752. var completeURL = Database.ReturnFullUrlLocation(url);
  3753. var saveAndLoadImage = function () {
  3754. if (!_this.hasReachedQuota && _this.db !== null) {
  3755. // the texture is not yet in the DB, let's try to save it
  3756. _this._saveImageIntoDBAsync(completeURL, image);
  3757. }
  3758. else {
  3759. image.src = url;
  3760. }
  3761. };
  3762. if (!this.mustUpdateRessources) {
  3763. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  3764. }
  3765. else {
  3766. saveAndLoadImage();
  3767. }
  3768. };
  3769. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  3770. if (this.isSupported && this.db !== null) {
  3771. var texture;
  3772. var transaction = this.db.transaction(["textures"]);
  3773. transaction.onabort = function (event) {
  3774. image.src = url;
  3775. };
  3776. transaction.oncomplete = function (event) {
  3777. var blobTextureURL;
  3778. if (texture) {
  3779. var URL = window.URL || window.webkitURL;
  3780. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  3781. image.onerror = function () {
  3782. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  3783. image.src = url;
  3784. };
  3785. image.src = blobTextureURL;
  3786. }
  3787. else {
  3788. notInDBCallback();
  3789. }
  3790. };
  3791. var getRequest = transaction.objectStore("textures").get(url);
  3792. getRequest.onsuccess = function (event) {
  3793. texture = (event.target).result;
  3794. };
  3795. getRequest.onerror = function (event) {
  3796. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  3797. image.src = url;
  3798. };
  3799. }
  3800. else {
  3801. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3802. image.src = url;
  3803. }
  3804. };
  3805. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  3806. var _this = this;
  3807. if (this.isSupported) {
  3808. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  3809. var generateBlobUrl = function () {
  3810. var blobTextureURL;
  3811. if (blob) {
  3812. var URL = window.URL || window.webkitURL;
  3813. try {
  3814. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  3815. }
  3816. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  3817. catch (ex) {
  3818. blobTextureURL = URL.createObjectURL(blob);
  3819. }
  3820. }
  3821. image.src = blobTextureURL;
  3822. };
  3823. if (Database.IsUASupportingBlobStorage) {
  3824. var xhr = new XMLHttpRequest(), blob;
  3825. xhr.open("GET", url, true);
  3826. xhr.responseType = "blob";
  3827. xhr.addEventListener("load", function () {
  3828. if (xhr.status === 200) {
  3829. // Blob as response (XHR2)
  3830. blob = xhr.response;
  3831. var transaction = _this.db.transaction(["textures"], "readwrite");
  3832. // the transaction could abort because of a QuotaExceededError error
  3833. transaction.onabort = function (event) {
  3834. try {
  3835. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  3836. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  3837. _this.hasReachedQuota = true;
  3838. }
  3839. }
  3840. catch (ex) { }
  3841. generateBlobUrl();
  3842. };
  3843. transaction.oncomplete = function (event) {
  3844. generateBlobUrl();
  3845. };
  3846. var newTexture = { textureUrl: url, data: blob };
  3847. try {
  3848. // Put the blob into the dabase
  3849. var addRequest = transaction.objectStore("textures").put(newTexture);
  3850. addRequest.onsuccess = function (event) {
  3851. };
  3852. addRequest.onerror = function (event) {
  3853. generateBlobUrl();
  3854. };
  3855. }
  3856. catch (ex) {
  3857. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  3858. if (ex.code === 25) {
  3859. Database.IsUASupportingBlobStorage = false;
  3860. }
  3861. image.src = url;
  3862. }
  3863. }
  3864. else {
  3865. image.src = url;
  3866. }
  3867. }, false);
  3868. xhr.addEventListener("error", function (event) {
  3869. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  3870. image.src = url;
  3871. }, false);
  3872. xhr.send();
  3873. }
  3874. else {
  3875. image.src = url;
  3876. }
  3877. }
  3878. else {
  3879. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3880. image.src = url;
  3881. }
  3882. };
  3883. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  3884. var _this = this;
  3885. var updateVersion = function (event) {
  3886. // the version is not yet in the DB or we need to update it
  3887. _this._saveVersionIntoDBAsync(url, versionLoaded);
  3888. };
  3889. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  3890. };
  3891. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  3892. var _this = this;
  3893. if (this.isSupported) {
  3894. var version;
  3895. try {
  3896. var transaction = this.db.transaction(["versions"]);
  3897. transaction.oncomplete = function (event) {
  3898. if (version) {
  3899. // If the version in the JSON file is > than the version in DB
  3900. if (_this.manifestVersionFound > version.data) {
  3901. _this.mustUpdateRessources = true;
  3902. updateInDBCallback();
  3903. }
  3904. else {
  3905. callback(version.data);
  3906. }
  3907. }
  3908. else {
  3909. _this.mustUpdateRessources = true;
  3910. updateInDBCallback();
  3911. }
  3912. };
  3913. transaction.onabort = function (event) {
  3914. callback(-1);
  3915. };
  3916. var getRequest = transaction.objectStore("versions").get(url);
  3917. getRequest.onsuccess = function (event) {
  3918. version = (event.target).result;
  3919. };
  3920. getRequest.onerror = function (event) {
  3921. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  3922. callback(-1);
  3923. };
  3924. }
  3925. catch (ex) {
  3926. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  3927. callback(-1);
  3928. }
  3929. }
  3930. else {
  3931. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3932. callback(-1);
  3933. }
  3934. };
  3935. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  3936. var _this = this;
  3937. if (this.isSupported && !this.hasReachedQuota) {
  3938. try {
  3939. // Open a transaction to the database
  3940. var transaction = this.db.transaction(["versions"], "readwrite");
  3941. // the transaction could abort because of a QuotaExceededError error
  3942. transaction.onabort = function (event) {
  3943. try {
  3944. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  3945. _this.hasReachedQuota = true;
  3946. }
  3947. }
  3948. catch (ex) { }
  3949. callback(-1);
  3950. };
  3951. transaction.oncomplete = function (event) {
  3952. callback(_this.manifestVersionFound);
  3953. };
  3954. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  3955. // Put the scene into the database
  3956. var addRequest = transaction.objectStore("versions").put(newVersion);
  3957. addRequest.onsuccess = function (event) {
  3958. };
  3959. addRequest.onerror = function (event) {
  3960. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  3961. };
  3962. }
  3963. catch (ex) {
  3964. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  3965. callback(-1);
  3966. }
  3967. }
  3968. else {
  3969. callback(-1);
  3970. }
  3971. };
  3972. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  3973. var _this = this;
  3974. var completeUrl = Database.ReturnFullUrlLocation(url);
  3975. var saveAndLoadFile = function (event) {
  3976. // the scene is not yet in the DB, let's try to save it
  3977. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  3978. };
  3979. this._checkVersionFromDB(completeUrl, function (version) {
  3980. if (version !== -1) {
  3981. if (!_this.mustUpdateRessources) {
  3982. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  3983. }
  3984. else {
  3985. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  3986. }
  3987. }
  3988. else {
  3989. errorCallback();
  3990. }
  3991. });
  3992. };
  3993. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  3994. if (this.isSupported) {
  3995. var targetStore;
  3996. if (url.indexOf(".babylon") !== -1) {
  3997. targetStore = "scenes";
  3998. }
  3999. else {
  4000. targetStore = "textures";
  4001. }
  4002. var file;
  4003. var transaction = this.db.transaction([targetStore]);
  4004. transaction.oncomplete = function (event) {
  4005. if (file) {
  4006. callback(file.data);
  4007. }
  4008. else {
  4009. notInDBCallback();
  4010. }
  4011. };
  4012. transaction.onabort = function (event) {
  4013. notInDBCallback();
  4014. };
  4015. var getRequest = transaction.objectStore(targetStore).get(url);
  4016. getRequest.onsuccess = function (event) {
  4017. file = (event.target).result;
  4018. };
  4019. getRequest.onerror = function (event) {
  4020. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  4021. notInDBCallback();
  4022. };
  4023. }
  4024. else {
  4025. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  4026. callback();
  4027. }
  4028. };
  4029. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  4030. var _this = this;
  4031. if (this.isSupported) {
  4032. var targetStore;
  4033. if (url.indexOf(".babylon") !== -1) {
  4034. targetStore = "scenes";
  4035. }
  4036. else {
  4037. targetStore = "textures";
  4038. }
  4039. // Create XHR
  4040. var xhr = new XMLHttpRequest(), fileData;
  4041. xhr.open("GET", url, true);
  4042. if (useArrayBuffer) {
  4043. xhr.responseType = "arraybuffer";
  4044. }
  4045. xhr.onprogress = progressCallback;
  4046. xhr.addEventListener("load", function () {
  4047. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  4048. // Blob as response (XHR2)
  4049. //fileData = xhr.responseText;
  4050. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  4051. if (!_this.hasReachedQuota) {
  4052. // Open a transaction to the database
  4053. var transaction = _this.db.transaction([targetStore], "readwrite");
  4054. // the transaction could abort because of a QuotaExceededError error
  4055. transaction.onabort = function (event) {
  4056. try {
  4057. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  4058. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  4059. _this.hasReachedQuota = true;
  4060. }
  4061. }
  4062. catch (ex) { }
  4063. callback(fileData);
  4064. };
  4065. transaction.oncomplete = function (event) {
  4066. callback(fileData);
  4067. };
  4068. var newFile;
  4069. if (targetStore === "scenes") {
  4070. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  4071. }
  4072. else {
  4073. newFile = { textureUrl: url, data: fileData };
  4074. }
  4075. try {
  4076. // Put the scene into the database
  4077. var addRequest = transaction.objectStore(targetStore).put(newFile);
  4078. addRequest.onsuccess = function (event) {
  4079. };
  4080. addRequest.onerror = function (event) {
  4081. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  4082. };
  4083. }
  4084. catch (ex) {
  4085. callback(fileData);
  4086. }
  4087. }
  4088. else {
  4089. callback(fileData);
  4090. }
  4091. }
  4092. else {
  4093. callback();
  4094. }
  4095. }, false);
  4096. xhr.addEventListener("error", function (event) {
  4097. BABYLON.Tools.Error("error on XHR request.");
  4098. callback();
  4099. }, false);
  4100. xhr.send();
  4101. }
  4102. else {
  4103. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  4104. callback();
  4105. }
  4106. };
  4107. return Database;
  4108. }());
  4109. Database.IsUASupportingBlobStorage = true;
  4110. Database.IDBStorageEnabled = true;
  4111. Database.parseURL = function (url) {
  4112. var a = document.createElement('a');
  4113. a.href = url;
  4114. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  4115. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  4116. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  4117. return absLocation;
  4118. };
  4119. Database.ReturnFullUrlLocation = function (url) {
  4120. if (url.indexOf("http:/") === -1) {
  4121. return (Database.parseURL(window.location.href) + url);
  4122. }
  4123. else {
  4124. return url;
  4125. }
  4126. };
  4127. BABYLON.Database = Database;
  4128. })(BABYLON || (BABYLON = {}));
  4129. //# sourceMappingURL=babylon.database.js.map
  4130. var BABYLON;
  4131. (function (BABYLON) {
  4132. var Internals;
  4133. (function (Internals) {
  4134. /*
  4135. * Based on jsTGALoader - Javascript loader for TGA file
  4136. * By Vincent Thibault
  4137. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  4138. */
  4139. var TGATools = (function () {
  4140. function TGATools() {
  4141. }
  4142. TGATools.GetTGAHeader = function (data) {
  4143. var offset = 0;
  4144. var header = {
  4145. id_length: data[offset++],
  4146. colormap_type: data[offset++],
  4147. image_type: data[offset++],
  4148. colormap_index: data[offset++] | data[offset++] << 8,
  4149. colormap_length: data[offset++] | data[offset++] << 8,
  4150. colormap_size: data[offset++],
  4151. origin: [
  4152. data[offset++] | data[offset++] << 8,
  4153. data[offset++] | data[offset++] << 8
  4154. ],
  4155. width: data[offset++] | data[offset++] << 8,
  4156. height: data[offset++] | data[offset++] << 8,
  4157. pixel_size: data[offset++],
  4158. flags: data[offset++]
  4159. };
  4160. return header;
  4161. };
  4162. TGATools.UploadContent = function (gl, data) {
  4163. // Not enough data to contain header ?
  4164. if (data.length < 19) {
  4165. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  4166. return;
  4167. }
  4168. // Read Header
  4169. var offset = 18;
  4170. var header = TGATools.GetTGAHeader(data);
  4171. // Assume it's a valid Targa file.
  4172. if (header.id_length + offset > data.length) {
  4173. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  4174. return;
  4175. }
  4176. // Skip not needed data
  4177. offset += header.id_length;
  4178. var use_rle = false;
  4179. var use_pal = false;
  4180. var use_rgb = false;
  4181. var use_grey = false;
  4182. // Get some informations.
  4183. switch (header.image_type) {
  4184. case TGATools._TYPE_RLE_INDEXED:
  4185. use_rle = true;
  4186. case TGATools._TYPE_INDEXED:
  4187. use_pal = true;
  4188. break;
  4189. case TGATools._TYPE_RLE_RGB:
  4190. use_rle = true;
  4191. case TGATools._TYPE_RGB:
  4192. use_rgb = true;
  4193. break;
  4194. case TGATools._TYPE_RLE_GREY:
  4195. use_rle = true;
  4196. case TGATools._TYPE_GREY:
  4197. use_grey = true;
  4198. break;
  4199. }
  4200. var pixel_data;
  4201. var numAlphaBits = header.flags & 0xf;
  4202. var pixel_size = header.pixel_size >> 3;
  4203. var pixel_total = header.width * header.height * pixel_size;
  4204. // Read palettes
  4205. var palettes;
  4206. if (use_pal) {
  4207. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  4208. }
  4209. // Read LRE
  4210. if (use_rle) {
  4211. pixel_data = new Uint8Array(pixel_total);
  4212. var c, count, i;
  4213. var localOffset = 0;
  4214. var pixels = new Uint8Array(pixel_size);
  4215. while (offset < pixel_total && localOffset < pixel_total) {
  4216. c = data[offset++];
  4217. count = (c & 0x7f) + 1;
  4218. // RLE pixels
  4219. if (c & 0x80) {
  4220. // Bind pixel tmp array
  4221. for (i = 0; i < pixel_size; ++i) {
  4222. pixels[i] = data[offset++];
  4223. }
  4224. // Copy pixel array
  4225. for (i = 0; i < count; ++i) {
  4226. pixel_data.set(pixels, localOffset + i * pixel_size);
  4227. }
  4228. localOffset += pixel_size * count;
  4229. }
  4230. else {
  4231. count *= pixel_size;
  4232. for (i = 0; i < count; ++i) {
  4233. pixel_data[localOffset + i] = data[offset++];
  4234. }
  4235. localOffset += count;
  4236. }
  4237. }
  4238. }
  4239. else {
  4240. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  4241. }
  4242. // Load to texture
  4243. var x_start, y_start, x_step, y_step, y_end, x_end;
  4244. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  4245. default:
  4246. case TGATools._ORIGIN_UL:
  4247. x_start = 0;
  4248. x_step = 1;
  4249. x_end = header.width;
  4250. y_start = 0;
  4251. y_step = 1;
  4252. y_end = header.height;
  4253. break;
  4254. case TGATools._ORIGIN_BL:
  4255. x_start = 0;
  4256. x_step = 1;
  4257. x_end = header.width;
  4258. y_start = header.height - 1;
  4259. y_step = -1;
  4260. y_end = -1;
  4261. break;
  4262. case TGATools._ORIGIN_UR:
  4263. x_start = header.width - 1;
  4264. x_step = -1;
  4265. x_end = -1;
  4266. y_start = 0;
  4267. y_step = 1;
  4268. y_end = header.height;
  4269. break;
  4270. case TGATools._ORIGIN_BR:
  4271. x_start = header.width - 1;
  4272. x_step = -1;
  4273. x_end = -1;
  4274. y_start = header.height - 1;
  4275. y_step = -1;
  4276. y_end = -1;
  4277. break;
  4278. }
  4279. // Load the specify method
  4280. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  4281. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  4282. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  4283. };
  4284. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  4285. var image = pixel_data, colormap = palettes;
  4286. var width = header.width, height = header.height;
  4287. var color, i = 0, x, y;
  4288. var imageData = new Uint8Array(width * height * 4);
  4289. for (y = y_start; y !== y_end; y += y_step) {
  4290. for (x = x_start; x !== x_end; x += x_step, i++) {
  4291. color = image[i];
  4292. imageData[(x + width * y) * 4 + 3] = 255;
  4293. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  4294. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  4295. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  4296. }
  4297. }
  4298. return imageData;
  4299. };
  4300. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  4301. var image = pixel_data;
  4302. var width = header.width, height = header.height;
  4303. var color, i = 0, x, y;
  4304. var imageData = new Uint8Array(width * height * 4);
  4305. for (y = y_start; y !== y_end; y += y_step) {
  4306. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  4307. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  4308. imageData[(x + width * y) * 4 + 0] = (color & 0x7C00) >> 7;
  4309. imageData[(x + width * y) * 4 + 1] = (color & 0x03E0) >> 2;
  4310. imageData[(x + width * y) * 4 + 2] = (color & 0x001F) >> 3;
  4311. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  4312. }
  4313. }
  4314. return imageData;
  4315. };
  4316. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  4317. var image = pixel_data;
  4318. var width = header.width, height = header.height;
  4319. var i = 0, x, y;
  4320. var imageData = new Uint8Array(width * height * 4);
  4321. for (y = y_start; y !== y_end; y += y_step) {
  4322. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  4323. imageData[(x + width * y) * 4 + 3] = 255;
  4324. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  4325. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  4326. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  4327. }
  4328. }
  4329. return imageData;
  4330. };
  4331. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  4332. var image = pixel_data;
  4333. var width = header.width, height = header.height;
  4334. var i = 0, x, y;
  4335. var imageData = new Uint8Array(width * height * 4);
  4336. for (y = y_start; y !== y_end; y += y_step) {
  4337. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  4338. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  4339. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  4340. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  4341. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  4342. }
  4343. }
  4344. return imageData;
  4345. };
  4346. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  4347. var image = pixel_data;
  4348. var width = header.width, height = header.height;
  4349. var color, i = 0, x, y;
  4350. var imageData = new Uint8Array(width * height * 4);
  4351. for (y = y_start; y !== y_end; y += y_step) {
  4352. for (x = x_start; x !== x_end; x += x_step, i++) {
  4353. color = image[i];
  4354. imageData[(x + width * y) * 4 + 0] = color;
  4355. imageData[(x + width * y) * 4 + 1] = color;
  4356. imageData[(x + width * y) * 4 + 2] = color;
  4357. imageData[(x + width * y) * 4 + 3] = 255;
  4358. }
  4359. }
  4360. return imageData;
  4361. };
  4362. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  4363. var image = pixel_data;
  4364. var width = header.width, height = header.height;
  4365. var i = 0, x, y;
  4366. var imageData = new Uint8Array(width * height * 4);
  4367. for (y = y_start; y !== y_end; y += y_step) {
  4368. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  4369. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  4370. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  4371. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  4372. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  4373. }
  4374. }
  4375. return imageData;
  4376. };
  4377. return TGATools;
  4378. }());
  4379. TGATools._TYPE_NO_DATA = 0;
  4380. TGATools._TYPE_INDEXED = 1;
  4381. TGATools._TYPE_RGB = 2;
  4382. TGATools._TYPE_GREY = 3;
  4383. TGATools._TYPE_RLE_INDEXED = 9;
  4384. TGATools._TYPE_RLE_RGB = 10;
  4385. TGATools._TYPE_RLE_GREY = 11;
  4386. TGATools._ORIGIN_MASK = 0x30;
  4387. TGATools._ORIGIN_SHIFT = 0x04;
  4388. TGATools._ORIGIN_BL = 0x00;
  4389. TGATools._ORIGIN_BR = 0x01;
  4390. TGATools._ORIGIN_UL = 0x02;
  4391. TGATools._ORIGIN_UR = 0x03;
  4392. Internals.TGATools = TGATools;
  4393. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  4394. })(BABYLON || (BABYLON = {}));
  4395. //# sourceMappingURL=babylon.tools.tga.js.map
  4396. var BABYLON;
  4397. (function (BABYLON) {
  4398. var SmartArray = (function () {
  4399. function SmartArray(capacity) {
  4400. this.length = 0;
  4401. this._duplicateId = 0;
  4402. this.data = new Array(capacity);
  4403. this._id = SmartArray._GlobalId++;
  4404. }
  4405. SmartArray.prototype.push = function (value) {
  4406. this.data[this.length++] = value;
  4407. if (this.length > this.data.length) {
  4408. this.data.length *= 2;
  4409. }
  4410. if (!value.__smartArrayFlags) {
  4411. value.__smartArrayFlags = {};
  4412. }
  4413. value.__smartArrayFlags[this._id] = this._duplicateId;
  4414. };
  4415. SmartArray.prototype.pushNoDuplicate = function (value) {
  4416. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  4417. return false;
  4418. }
  4419. this.push(value);
  4420. return true;
  4421. };
  4422. SmartArray.prototype.sort = function (compareFn) {
  4423. this.data.sort(compareFn);
  4424. };
  4425. SmartArray.prototype.reset = function () {
  4426. this.length = 0;
  4427. this._duplicateId++;
  4428. };
  4429. SmartArray.prototype.concat = function (array) {
  4430. if (array.length === 0) {
  4431. return;
  4432. }
  4433. if (this.length + array.length > this.data.length) {
  4434. this.data.length = (this.length + array.length) * 2;
  4435. }
  4436. for (var index = 0; index < array.length; index++) {
  4437. this.data[this.length++] = (array.data || array)[index];
  4438. }
  4439. };
  4440. SmartArray.prototype.concatWithNoDuplicate = function (array) {
  4441. if (array.length === 0) {
  4442. return;
  4443. }
  4444. if (this.length + array.length > this.data.length) {
  4445. this.data.length = (this.length + array.length) * 2;
  4446. }
  4447. for (var index = 0; index < array.length; index++) {
  4448. var item = (array.data || array)[index];
  4449. this.pushNoDuplicate(item);
  4450. }
  4451. };
  4452. SmartArray.prototype.indexOf = function (value) {
  4453. var position = this.data.indexOf(value);
  4454. if (position >= this.length) {
  4455. return -1;
  4456. }
  4457. return position;
  4458. };
  4459. return SmartArray;
  4460. }());
  4461. // Statics
  4462. SmartArray._GlobalId = 0;
  4463. BABYLON.SmartArray = SmartArray;
  4464. })(BABYLON || (BABYLON = {}));
  4465. //# sourceMappingURL=babylon.smartArray.js.map
  4466. var BABYLON;
  4467. (function (BABYLON) {
  4468. /**
  4469. * This class implement a typical dictionary using a string as key and the generic type T as value.
  4470. * The underlying implementation relies on an associative array to ensure the best performances.
  4471. * The value can be anything including 'null' but except 'undefined'
  4472. */
  4473. var StringDictionary = (function () {
  4474. function StringDictionary() {
  4475. this._count = 0;
  4476. this._data = {};
  4477. }
  4478. /**
  4479. * This will clear this dictionary and copy the content from the 'source' one.
  4480. * If the T value is a custom object, it won't be copied/cloned, the same object will be used
  4481. * @param source the dictionary to take the content from and copy to this dictionary
  4482. */
  4483. StringDictionary.prototype.copyFrom = function (source) {
  4484. var _this = this;
  4485. this.clear();
  4486. source.forEach(function (t, v) { return _this.add(t, v); });
  4487. };
  4488. /**
  4489. * Get a value based from its key
  4490. * @param key the given key to get the matching value from
  4491. * @return the value if found, otherwise undefined is returned
  4492. */
  4493. StringDictionary.prototype.get = function (key) {
  4494. var val = this._data[key];
  4495. if (val !== undefined) {
  4496. return val;
  4497. }
  4498. return undefined;
  4499. };
  4500. /**
  4501. * Get a value from its key or add it if it doesn't exist.
  4502. * This method will ensure you that a given key/data will be present in the dictionary.
  4503. * @param key the given key to get the matching value from
  4504. * @param factory the factory that will create the value if the key is not present in the dictionary.
  4505. * The factory will only be invoked if there's no data for the given key.
  4506. * @return the value corresponding to the key.
  4507. */
  4508. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  4509. var val = this.get(key);
  4510. if (val !== undefined) {
  4511. return val;
  4512. }
  4513. val = factory(key);
  4514. if (val) {
  4515. this.add(key, val);
  4516. }
  4517. return val;
  4518. };
  4519. /**
  4520. * Get a value from its key if present in the dictionary otherwise add it
  4521. * @param key the key to get the value from
  4522. * @param val if there's no such key/value pair in the dictionary add it with this value
  4523. * @return the value corresponding to the key
  4524. */
  4525. StringDictionary.prototype.getOrAdd = function (key, val) {
  4526. var curVal = this.get(key);
  4527. if (curVal !== undefined) {
  4528. return curVal;
  4529. }
  4530. this.add(key, val);
  4531. return val;
  4532. };
  4533. /**
  4534. * Check if there's a given key in the dictionary
  4535. * @param key the key to check for
  4536. * @return true if the key is present, false otherwise
  4537. */
  4538. StringDictionary.prototype.contains = function (key) {
  4539. return this._data[key] !== undefined;
  4540. };
  4541. /**
  4542. * Add a new key and its corresponding value
  4543. * @param key the key to add
  4544. * @param value the value corresponding to the key
  4545. * @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
  4546. */
  4547. StringDictionary.prototype.add = function (key, value) {
  4548. if (this._data[key] !== undefined) {
  4549. return false;
  4550. }
  4551. this._data[key] = value;
  4552. ++this._count;
  4553. return true;
  4554. };
  4555. StringDictionary.prototype.set = function (key, value) {
  4556. if (this._data[key] === undefined) {
  4557. return false;
  4558. }
  4559. this._data[key] = value;
  4560. return true;
  4561. };
  4562. /**
  4563. * Get the element of the given key and remove it from the dictionary
  4564. * @param key
  4565. */
  4566. StringDictionary.prototype.getAndRemove = function (key) {
  4567. var val = this.get(key);
  4568. if (val !== undefined) {
  4569. delete this._data[key];
  4570. --this._count;
  4571. return val;
  4572. }
  4573. return null;
  4574. };
  4575. /**
  4576. * Remove a key/value from the dictionary.
  4577. * @param key the key to remove
  4578. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  4579. */
  4580. StringDictionary.prototype.remove = function (key) {
  4581. if (this.contains(key)) {
  4582. delete this._data[key];
  4583. --this._count;
  4584. return true;
  4585. }
  4586. return false;
  4587. };
  4588. /**
  4589. * Clear the whole content of the dictionary
  4590. */
  4591. StringDictionary.prototype.clear = function () {
  4592. this._data = {};
  4593. this._count = 0;
  4594. };
  4595. Object.defineProperty(StringDictionary.prototype, "count", {
  4596. get: function () {
  4597. return this._count;
  4598. },
  4599. enumerable: true,
  4600. configurable: true
  4601. });
  4602. /**
  4603. * Execute a callback on each key/val of the dictionary.
  4604. * Note that you can remove any element in this dictionary in the callback implementation
  4605. * @param callback the callback to execute on a given key/value pair
  4606. */
  4607. StringDictionary.prototype.forEach = function (callback) {
  4608. for (var cur in this._data) {
  4609. var val = this._data[cur];
  4610. callback(cur, val);
  4611. }
  4612. };
  4613. /**
  4614. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  4615. * If the callback returns null or undefined the method will iterate to the next key/value pair
  4616. * Note that you can remove any element in this dictionary in the callback implementation
  4617. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  4618. */
  4619. StringDictionary.prototype.first = function (callback) {
  4620. for (var cur in this._data) {
  4621. var val = this._data[cur];
  4622. var res = callback(cur, val);
  4623. if (res) {
  4624. return res;
  4625. }
  4626. }
  4627. return null;
  4628. };
  4629. return StringDictionary;
  4630. }());
  4631. BABYLON.StringDictionary = StringDictionary;
  4632. })(BABYLON || (BABYLON = {}));
  4633. //# sourceMappingURL=babylon.stringDictionary.js.map
  4634. var BABYLON;
  4635. (function (BABYLON) {
  4636. // Screenshots
  4637. var screenshotCanvas;
  4638. var cloneValue = function (source, destinationObject) {
  4639. if (!source)
  4640. return null;
  4641. if (source instanceof BABYLON.Mesh) {
  4642. return null;
  4643. }
  4644. if (source instanceof BABYLON.SubMesh) {
  4645. return source.clone(destinationObject);
  4646. }
  4647. else if (source.clone) {
  4648. return source.clone();
  4649. }
  4650. return null;
  4651. };
  4652. var Tools = (function () {
  4653. function Tools() {
  4654. }
  4655. ;
  4656. Tools.Instantiate = function (className) {
  4657. var arr = className.split(".");
  4658. var fn = (window || this);
  4659. for (var i = 0, len = arr.length; i < len; i++) {
  4660. fn = fn[arr[i]];
  4661. }
  4662. if (typeof fn !== "function") {
  4663. return null;
  4664. }
  4665. return fn;
  4666. };
  4667. Tools.SetImmediate = function (action) {
  4668. if (window.setImmediate) {
  4669. window.setImmediate(action);
  4670. }
  4671. else {
  4672. setTimeout(action, 1);
  4673. }
  4674. };
  4675. Tools.IsExponentOfTwo = function (value) {
  4676. var count = 1;
  4677. do {
  4678. count *= 2;
  4679. } while (count < value);
  4680. return count === value;
  4681. };
  4682. Tools.GetExponentOfTwo = function (value, max) {
  4683. var count = 1;
  4684. do {
  4685. count *= 2;
  4686. } while (count < value);
  4687. if (count > max)
  4688. count = max;
  4689. return count;
  4690. };
  4691. Tools.GetFilename = function (path) {
  4692. var index = path.lastIndexOf("/");
  4693. if (index < 0)
  4694. return path;
  4695. return path.substring(index + 1);
  4696. };
  4697. Tools.GetDOMTextContent = function (element) {
  4698. var result = "";
  4699. var child = element.firstChild;
  4700. while (child) {
  4701. if (child.nodeType === 3) {
  4702. result += child.textContent;
  4703. }
  4704. child = child.nextSibling;
  4705. }
  4706. return result;
  4707. };
  4708. Tools.ToDegrees = function (angle) {
  4709. return angle * 180 / Math.PI;
  4710. };
  4711. Tools.ToRadians = function (angle) {
  4712. return angle * Math.PI / 180;
  4713. };
  4714. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  4715. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  4716. var output = "";
  4717. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  4718. var i = 0;
  4719. var bytes = new Uint8Array(buffer);
  4720. while (i < bytes.length) {
  4721. chr1 = bytes[i++];
  4722. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  4723. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  4724. enc1 = chr1 >> 2;
  4725. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  4726. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  4727. enc4 = chr3 & 63;
  4728. if (isNaN(chr2)) {
  4729. enc3 = enc4 = 64;
  4730. }
  4731. else if (isNaN(chr3)) {
  4732. enc4 = 64;
  4733. }
  4734. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  4735. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  4736. }
  4737. return "data:image/png;base64," + output;
  4738. };
  4739. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {
  4740. if (bias === void 0) { bias = null; }
  4741. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  4742. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  4743. for (var index = indexStart; index < indexStart + indexCount; index++) {
  4744. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  4745. minimum = BABYLON.Vector3.Minimize(current, minimum);
  4746. maximum = BABYLON.Vector3.Maximize(current, maximum);
  4747. }
  4748. if (bias) {
  4749. minimum.x -= minimum.x * bias.x + bias.y;
  4750. minimum.y -= minimum.y * bias.x + bias.y;
  4751. minimum.z -= minimum.z * bias.x + bias.y;
  4752. maximum.x += maximum.x * bias.x + bias.y;
  4753. maximum.y += maximum.y * bias.x + bias.y;
  4754. maximum.z += maximum.z * bias.x + bias.y;
  4755. }
  4756. return {
  4757. minimum: minimum,
  4758. maximum: maximum
  4759. };
  4760. };
  4761. Tools.ExtractMinAndMax = function (positions, start, count, bias, stride) {
  4762. if (bias === void 0) { bias = null; }
  4763. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  4764. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  4765. if (!stride) {
  4766. stride = 3;
  4767. }
  4768. for (var index = start; index < start + count; index++) {
  4769. var current = new BABYLON.Vector3(positions[index * stride], positions[index * stride + 1], positions[index * stride + 2]);
  4770. minimum = BABYLON.Vector3.Minimize(current, minimum);
  4771. maximum = BABYLON.Vector3.Maximize(current, maximum);
  4772. }
  4773. if (bias) {
  4774. minimum.x -= minimum.x * bias.x + bias.y;
  4775. minimum.y -= minimum.y * bias.x + bias.y;
  4776. minimum.z -= minimum.z * bias.x + bias.y;
  4777. maximum.x += maximum.x * bias.x + bias.y;
  4778. maximum.y += maximum.y * bias.x + bias.y;
  4779. maximum.z += maximum.z * bias.x + bias.y;
  4780. }
  4781. return {
  4782. minimum: minimum,
  4783. maximum: maximum
  4784. };
  4785. };
  4786. Tools.Vector2ArrayFeeder = function (array) {
  4787. return function (index) {
  4788. var isFloatArray = (array.BYTES_PER_ELEMENT !== undefined);
  4789. var length = isFloatArray ? array.length / 2 : array.length;
  4790. if (index >= length) {
  4791. return null;
  4792. }
  4793. if (isFloatArray) {
  4794. var fa = array;
  4795. return new BABYLON.Vector2(fa[index * 2 + 0], fa[index * 2 + 1]);
  4796. }
  4797. var a = array;
  4798. return a[index];
  4799. };
  4800. };
  4801. Tools.ExtractMinAndMaxVector2 = function (feeder, bias) {
  4802. if (bias === void 0) { bias = null; }
  4803. var minimum = new BABYLON.Vector2(Number.MAX_VALUE, Number.MAX_VALUE);
  4804. var maximum = new BABYLON.Vector2(-Number.MAX_VALUE, -Number.MAX_VALUE);
  4805. var i = 0;
  4806. var cur = feeder(i++);
  4807. while (cur) {
  4808. minimum = BABYLON.Vector2.Minimize(cur, minimum);
  4809. maximum = BABYLON.Vector2.Maximize(cur, maximum);
  4810. cur = feeder(i++);
  4811. }
  4812. if (bias) {
  4813. minimum.x -= minimum.x * bias.x + bias.y;
  4814. minimum.y -= minimum.y * bias.x + bias.y;
  4815. maximum.x += maximum.x * bias.x + bias.y;
  4816. maximum.y += maximum.y * bias.x + bias.y;
  4817. }
  4818. return {
  4819. minimum: minimum,
  4820. maximum: maximum
  4821. };
  4822. };
  4823. Tools.MakeArray = function (obj, allowsNullUndefined) {
  4824. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  4825. return undefined;
  4826. return Array.isArray(obj) ? obj : [obj];
  4827. };
  4828. // Misc.
  4829. Tools.GetPointerPrefix = function () {
  4830. var eventPrefix = "pointer";
  4831. // Check if pointer events are supported
  4832. if (!window.PointerEvent && !navigator.pointerEnabled) {
  4833. eventPrefix = "mouse";
  4834. }
  4835. return eventPrefix;
  4836. };
  4837. /**
  4838. * @param func - the function to be called
  4839. * @param requester - the object that will request the next frame. Falls back to window.
  4840. */
  4841. Tools.QueueNewFrame = function (func, requester) {
  4842. if (requester === void 0) { requester = window; }
  4843. //if WebVR is enabled AND presenting, requestAnimationFrame is triggered when enabled.
  4844. /*if(requester.isPresenting) {
  4845. return;
  4846. } else*/ if (requester.requestAnimationFrame)
  4847. requester.requestAnimationFrame(func);
  4848. else if (requester.msRequestAnimationFrame)
  4849. requester.msRequestAnimationFrame(func);
  4850. else if (requester.webkitRequestAnimationFrame)
  4851. requester.webkitRequestAnimationFrame(func);
  4852. else if (requester.mozRequestAnimationFrame)
  4853. requester.mozRequestAnimationFrame(func);
  4854. else if (requester.oRequestAnimationFrame)
  4855. requester.oRequestAnimationFrame(func);
  4856. else {
  4857. window.setTimeout(func, 16);
  4858. }
  4859. };
  4860. Tools.RequestFullscreen = function (element) {
  4861. var requestFunction = element.requestFullscreen || element.msRequestFullscreen || element.webkitRequestFullscreen || element.mozRequestFullScreen;
  4862. if (!requestFunction)
  4863. return;
  4864. requestFunction.call(element);
  4865. };
  4866. Tools.ExitFullscreen = function () {
  4867. if (document.exitFullscreen) {
  4868. document.exitFullscreen();
  4869. }
  4870. else if (document.mozCancelFullScreen) {
  4871. document.mozCancelFullScreen();
  4872. }
  4873. else if (document.webkitCancelFullScreen) {
  4874. document.webkitCancelFullScreen();
  4875. }
  4876. else if (document.msCancelFullScreen) {
  4877. document.msCancelFullScreen();
  4878. }
  4879. };
  4880. Tools.SetCorsBehavior = function (url, img) {
  4881. if (Tools.CorsBehavior) {
  4882. switch (typeof (Tools.CorsBehavior)) {
  4883. case "function":
  4884. var result = Tools.CorsBehavior(url);
  4885. if (result) {
  4886. return result;
  4887. }
  4888. break;
  4889. case "string":
  4890. default:
  4891. img.crossOrigin = Tools.CorsBehavior;
  4892. break;
  4893. }
  4894. }
  4895. };
  4896. // External files
  4897. Tools.CleanUrl = function (url) {
  4898. url = url.replace(/#/mg, "%23");
  4899. return url;
  4900. };
  4901. Tools.LoadImage = function (url, onload, onerror, database) {
  4902. if (url instanceof ArrayBuffer) {
  4903. url = Tools.EncodeArrayBufferTobase64(url);
  4904. }
  4905. url = Tools.CleanUrl(url);
  4906. var img = new Image();
  4907. if (url.substr(0, 5) !== "data:") {
  4908. Tools.SetCorsBehavior(url, img);
  4909. }
  4910. img.onload = function () {
  4911. onload(img);
  4912. };
  4913. img.onerror = function (err) {
  4914. Tools.Error("Error while trying to load image: " + url);
  4915. if (Tools.UseFallbackTexture) {
  4916. img.src = Tools.fallbackTexture;
  4917. onload(img);
  4918. }
  4919. else {
  4920. onerror();
  4921. }
  4922. };
  4923. var noIndexedDB = function () {
  4924. img.src = url;
  4925. };
  4926. var loadFromIndexedDB = function () {
  4927. database.loadImageFromDB(url, img);
  4928. };
  4929. //ANY database to do!
  4930. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  4931. database.openAsync(loadFromIndexedDB, noIndexedDB);
  4932. }
  4933. else {
  4934. if (url.indexOf("file:") === -1) {
  4935. noIndexedDB();
  4936. }
  4937. else {
  4938. var textureName = url.substring(5).toLowerCase();
  4939. if (BABYLON.FilesInput.FilesTextures[textureName]) {
  4940. try {
  4941. var blobURL;
  4942. try {
  4943. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName], { oneTimeOnly: true });
  4944. }
  4945. catch (ex) {
  4946. // Chrome doesn't support oneTimeOnly parameter
  4947. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName]);
  4948. }
  4949. img.src = blobURL;
  4950. }
  4951. catch (e) {
  4952. img.src = null;
  4953. }
  4954. }
  4955. else {
  4956. Tools.Error("Image: " + textureName + " not found. Did you forget to provide it?");
  4957. img.src = Tools.fallbackTexture;
  4958. }
  4959. }
  4960. }
  4961. return img;
  4962. };
  4963. //ANY
  4964. Tools.LoadFile = function (url, callback, progressCallBack, database, useArrayBuffer, onError) {
  4965. url = Tools.CleanUrl(url);
  4966. var noIndexedDB = function () {
  4967. var request = new XMLHttpRequest();
  4968. var loadUrl = Tools.BaseUrl + url;
  4969. request.open('GET', loadUrl, true);
  4970. if (useArrayBuffer) {
  4971. request.responseType = "arraybuffer";
  4972. }
  4973. request.onprogress = progressCallBack;
  4974. request.onreadystatechange = function () {
  4975. if (request.readyState === 4) {
  4976. request.onreadystatechange = null; //some browsers have issues where onreadystatechange can be called multiple times with the same value
  4977. if (request.status >= 200 && request.status < 300 || (navigator.isCocoonJS && (request.status === 0))) {
  4978. callback(!useArrayBuffer ? request.responseText : request.response);
  4979. }
  4980. else {
  4981. if (onError) {
  4982. onError();
  4983. }
  4984. else {
  4985. throw new Error("Error status: " + request.status + " - Unable to load " + loadUrl);
  4986. }
  4987. }
  4988. }
  4989. };
  4990. request.send(null);
  4991. };
  4992. var loadFromIndexedDB = function () {
  4993. database.loadFileFromDB(url, callback, progressCallBack, noIndexedDB, useArrayBuffer);
  4994. };
  4995. if (url.indexOf("file:") !== -1) {
  4996. var fileName = url.substring(5).toLowerCase();
  4997. if (BABYLON.FilesInput.FilesToLoad[fileName]) {
  4998. Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], callback, progressCallBack, useArrayBuffer);
  4999. }
  5000. else {
  5001. Tools.Error("File: " + fileName + " not found. Did you forget to provide it?");
  5002. }
  5003. }
  5004. else {
  5005. // Caching all files
  5006. if (database && database.enableSceneOffline) {
  5007. database.openAsync(loadFromIndexedDB, noIndexedDB);
  5008. }
  5009. else {
  5010. noIndexedDB();
  5011. }
  5012. }
  5013. };
  5014. /**
  5015. * Load a script (identified by an url). When the url returns, the
  5016. * content of this file is added into a new script element, attached to the DOM (body element)
  5017. */
  5018. Tools.LoadScript = function (scriptUrl, onSuccess, onError) {
  5019. var head = document.getElementsByTagName('head')[0];
  5020. var script = document.createElement('script');
  5021. script.type = 'text/javascript';
  5022. script.src = scriptUrl;
  5023. var self = this;
  5024. script.onload = function () {
  5025. if (onSuccess) {
  5026. onSuccess();
  5027. }
  5028. };
  5029. script.onerror = function () {
  5030. if (onError) {
  5031. onError();
  5032. }
  5033. };
  5034. head.appendChild(script);
  5035. };
  5036. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  5037. var reader = new FileReader();
  5038. reader.onload = function (e) {
  5039. //target doesn't have result from ts 1.3
  5040. callback(e.target['result']);
  5041. };
  5042. reader.onprogress = progressCallback;
  5043. reader.readAsDataURL(fileToLoad);
  5044. };
  5045. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  5046. var reader = new FileReader();
  5047. reader.onerror = function (e) {
  5048. Tools.Log("Error while reading file: " + fileToLoad.name);
  5049. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  5050. };
  5051. reader.onload = function (e) {
  5052. //target doesn't have result from ts 1.3
  5053. callback(e.target['result']);
  5054. };
  5055. reader.onprogress = progressCallBack;
  5056. if (!useArrayBuffer) {
  5057. // Asynchronous read
  5058. reader.readAsText(fileToLoad);
  5059. }
  5060. else {
  5061. reader.readAsArrayBuffer(fileToLoad);
  5062. }
  5063. };
  5064. //returns a downloadable url to a file content.
  5065. Tools.FileAsURL = function (content) {
  5066. var fileBlob = new Blob([content]);
  5067. var url = window.URL || window.webkitURL;
  5068. var link = url.createObjectURL(fileBlob);
  5069. return link;
  5070. };
  5071. // Misc.
  5072. Tools.Format = function (value, decimals) {
  5073. if (decimals === void 0) { decimals = 2; }
  5074. return value.toFixed(decimals);
  5075. };
  5076. Tools.CheckExtends = function (v, min, max) {
  5077. if (v.x < min.x)
  5078. min.x = v.x;
  5079. if (v.y < min.y)
  5080. min.y = v.y;
  5081. if (v.z < min.z)
  5082. min.z = v.z;
  5083. if (v.x > max.x)
  5084. max.x = v.x;
  5085. if (v.y > max.y)
  5086. max.y = v.y;
  5087. if (v.z > max.z)
  5088. max.z = v.z;
  5089. };
  5090. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  5091. for (var prop in source) {
  5092. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  5093. continue;
  5094. }
  5095. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  5096. continue;
  5097. }
  5098. var sourceValue = source[prop];
  5099. var typeOfSourceValue = typeof sourceValue;
  5100. if (typeOfSourceValue === "function") {
  5101. continue;
  5102. }
  5103. if (typeOfSourceValue === "object") {
  5104. if (sourceValue instanceof Array) {
  5105. destination[prop] = [];
  5106. if (sourceValue.length > 0) {
  5107. if (typeof sourceValue[0] == "object") {
  5108. for (var index = 0; index < sourceValue.length; index++) {
  5109. var clonedValue = cloneValue(sourceValue[index], destination);
  5110. if (destination[prop].indexOf(clonedValue) === -1) {
  5111. destination[prop].push(clonedValue);
  5112. }
  5113. }
  5114. }
  5115. else {
  5116. destination[prop] = sourceValue.slice(0);
  5117. }
  5118. }
  5119. }
  5120. else {
  5121. destination[prop] = cloneValue(sourceValue, destination);
  5122. }
  5123. }
  5124. else {
  5125. destination[prop] = sourceValue;
  5126. }
  5127. }
  5128. };
  5129. Tools.IsEmpty = function (obj) {
  5130. for (var i in obj) {
  5131. return false;
  5132. }
  5133. return true;
  5134. };
  5135. Tools.RegisterTopRootEvents = function (events) {
  5136. for (var index = 0; index < events.length; index++) {
  5137. var event = events[index];
  5138. window.addEventListener(event.name, event.handler, false);
  5139. try {
  5140. if (window.parent) {
  5141. window.parent.addEventListener(event.name, event.handler, false);
  5142. }
  5143. }
  5144. catch (e) {
  5145. }
  5146. }
  5147. };
  5148. Tools.UnregisterTopRootEvents = function (events) {
  5149. for (var index = 0; index < events.length; index++) {
  5150. var event = events[index];
  5151. window.removeEventListener(event.name, event.handler);
  5152. try {
  5153. if (window.parent) {
  5154. window.parent.removeEventListener(event.name, event.handler);
  5155. }
  5156. }
  5157. catch (e) {
  5158. }
  5159. }
  5160. };
  5161. Tools.DumpFramebuffer = function (width, height, engine, successCallback, mimeType) {
  5162. if (mimeType === void 0) { mimeType = "image/png"; }
  5163. // Read the contents of the framebuffer
  5164. var numberOfChannelsByLine = width * 4;
  5165. var halfHeight = height / 2;
  5166. //Reading datas from WebGL
  5167. var data = engine.readPixels(0, 0, width, height);
  5168. //To flip image on Y axis.
  5169. for (var i = 0; i < halfHeight; i++) {
  5170. for (var j = 0; j < numberOfChannelsByLine; j++) {
  5171. var currentCell = j + i * numberOfChannelsByLine;
  5172. var targetLine = height - i - 1;
  5173. var targetCell = j + targetLine * numberOfChannelsByLine;
  5174. var temp = data[currentCell];
  5175. data[currentCell] = data[targetCell];
  5176. data[targetCell] = temp;
  5177. }
  5178. }
  5179. // Create a 2D canvas to store the result
  5180. if (!screenshotCanvas) {
  5181. screenshotCanvas = document.createElement('canvas');
  5182. }
  5183. screenshotCanvas.width = width;
  5184. screenshotCanvas.height = height;
  5185. var context = screenshotCanvas.getContext('2d');
  5186. // Copy the pixels to a 2D canvas
  5187. var imageData = context.createImageData(width, height);
  5188. var castData = (imageData.data);
  5189. castData.set(data);
  5190. context.putImageData(imageData, 0, 0);
  5191. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  5192. };
  5193. Tools.EncodeScreenshotCanvasData = function (successCallback, mimeType) {
  5194. if (mimeType === void 0) { mimeType = "image/png"; }
  5195. var base64Image = screenshotCanvas.toDataURL(mimeType);
  5196. if (successCallback) {
  5197. successCallback(base64Image);
  5198. }
  5199. else {
  5200. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  5201. if (("download" in document.createElement("a"))) {
  5202. var a = window.document.createElement("a");
  5203. a.href = base64Image;
  5204. var date = new Date();
  5205. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(-2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  5206. a.setAttribute("download", "screenshot_" + stringDate + ".png");
  5207. window.document.body.appendChild(a);
  5208. a.addEventListener("click", function () {
  5209. a.parentElement.removeChild(a);
  5210. });
  5211. a.click();
  5212. }
  5213. else {
  5214. var newWindow = window.open("");
  5215. var img = newWindow.document.createElement("img");
  5216. img.src = base64Image;
  5217. newWindow.document.body.appendChild(img);
  5218. }
  5219. }
  5220. };
  5221. Tools.CreateScreenshot = function (engine, camera, size, successCallback, mimeType) {
  5222. if (mimeType === void 0) { mimeType = "image/png"; }
  5223. var width;
  5224. var height;
  5225. // If a precision value is specified
  5226. if (size.precision) {
  5227. width = Math.round(engine.getRenderWidth() * size.precision);
  5228. height = Math.round(width / engine.getAspectRatio(camera));
  5229. }
  5230. else if (size.width && size.height) {
  5231. width = size.width;
  5232. height = size.height;
  5233. }
  5234. else if (size.width && !size.height) {
  5235. width = size.width;
  5236. height = Math.round(width / engine.getAspectRatio(camera));
  5237. }
  5238. else if (size.height && !size.width) {
  5239. height = size.height;
  5240. width = Math.round(height * engine.getAspectRatio(camera));
  5241. }
  5242. else if (!isNaN(size)) {
  5243. height = size;
  5244. width = size;
  5245. }
  5246. else {
  5247. Tools.Error("Invalid 'size' parameter !");
  5248. return;
  5249. }
  5250. if (!screenshotCanvas) {
  5251. screenshotCanvas = document.createElement('canvas');
  5252. }
  5253. screenshotCanvas.width = width;
  5254. screenshotCanvas.height = height;
  5255. var renderContext = screenshotCanvas.getContext("2d");
  5256. var ratio = engine.getRenderWidth() / engine.getRenderHeight();
  5257. var newWidth = width;
  5258. var newHeight = newWidth / ratio;
  5259. if (newHeight > height) {
  5260. newHeight = height;
  5261. newWidth = newHeight * ratio;
  5262. }
  5263. var offsetX = Math.max(0, width - newWidth) / 2;
  5264. var offsetY = Math.max(0, height - newHeight) / 2;
  5265. renderContext.drawImage(engine.getRenderingCanvas(), offsetX, offsetY, newWidth, newHeight);
  5266. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  5267. };
  5268. Tools.CreateScreenshotUsingRenderTarget = function (engine, camera, size, successCallback, mimeType) {
  5269. if (mimeType === void 0) { mimeType = "image/png"; }
  5270. var width;
  5271. var height;
  5272. //If a precision value is specified
  5273. if (size.precision) {
  5274. width = Math.round(engine.getRenderWidth() * size.precision);
  5275. height = Math.round(width / engine.getAspectRatio(camera));
  5276. size = { width: width, height: height };
  5277. }
  5278. else if (size.width && size.height) {
  5279. width = size.width;
  5280. height = size.height;
  5281. }
  5282. else if (size.width && !size.height) {
  5283. width = size.width;
  5284. height = Math.round(width / engine.getAspectRatio(camera));
  5285. size = { width: width, height: height };
  5286. }
  5287. else if (size.height && !size.width) {
  5288. height = size.height;
  5289. width = Math.round(height * engine.getAspectRatio(camera));
  5290. size = { width: width, height: height };
  5291. }
  5292. else if (!isNaN(size)) {
  5293. height = size;
  5294. width = size;
  5295. }
  5296. else {
  5297. Tools.Error("Invalid 'size' parameter !");
  5298. return;
  5299. }
  5300. var scene = camera.getScene();
  5301. var previousCamera = null;
  5302. if (scene.activeCamera !== camera) {
  5303. previousCamera = scene.activeCamera;
  5304. scene.activeCamera = camera;
  5305. }
  5306. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  5307. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  5308. texture.renderList = scene.meshes;
  5309. texture.onAfterRenderObservable.add(function () {
  5310. Tools.DumpFramebuffer(width, height, engine, successCallback, mimeType);
  5311. });
  5312. scene.incrementRenderId();
  5313. scene.resetCachedMaterial();
  5314. texture.render(true);
  5315. texture.dispose();
  5316. if (previousCamera) {
  5317. scene.activeCamera = previousCamera;
  5318. }
  5319. camera.getProjectionMatrix(true); // Force cache refresh;
  5320. };
  5321. // XHR response validator for local file scenario
  5322. Tools.ValidateXHRData = function (xhr, dataType) {
  5323. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  5324. if (dataType === void 0) { dataType = 7; }
  5325. try {
  5326. if (dataType & 1) {
  5327. if (xhr.responseText && xhr.responseText.length > 0) {
  5328. return true;
  5329. }
  5330. else if (dataType === 1) {
  5331. return false;
  5332. }
  5333. }
  5334. if (dataType & 2) {
  5335. // Check header width and height since there is no "TGA" magic number
  5336. var tgaHeader = BABYLON.Internals.TGATools.GetTGAHeader(xhr.response);
  5337. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  5338. return true;
  5339. }
  5340. else if (dataType === 2) {
  5341. return false;
  5342. }
  5343. }
  5344. if (dataType & 4) {
  5345. // Check for the "DDS" magic number
  5346. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  5347. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  5348. return true;
  5349. }
  5350. else {
  5351. return false;
  5352. }
  5353. }
  5354. }
  5355. catch (e) {
  5356. }
  5357. return false;
  5358. };
  5359. /**
  5360. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  5361. * Be aware Math.random() could cause collisions, but:
  5362. * "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"
  5363. */
  5364. Tools.RandomId = function () {
  5365. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  5366. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  5367. return v.toString(16);
  5368. });
  5369. };
  5370. Object.defineProperty(Tools, "NoneLogLevel", {
  5371. get: function () {
  5372. return Tools._NoneLogLevel;
  5373. },
  5374. enumerable: true,
  5375. configurable: true
  5376. });
  5377. Object.defineProperty(Tools, "MessageLogLevel", {
  5378. get: function () {
  5379. return Tools._MessageLogLevel;
  5380. },
  5381. enumerable: true,
  5382. configurable: true
  5383. });
  5384. Object.defineProperty(Tools, "WarningLogLevel", {
  5385. get: function () {
  5386. return Tools._WarningLogLevel;
  5387. },
  5388. enumerable: true,
  5389. configurable: true
  5390. });
  5391. Object.defineProperty(Tools, "ErrorLogLevel", {
  5392. get: function () {
  5393. return Tools._ErrorLogLevel;
  5394. },
  5395. enumerable: true,
  5396. configurable: true
  5397. });
  5398. Object.defineProperty(Tools, "AllLogLevel", {
  5399. get: function () {
  5400. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  5401. },
  5402. enumerable: true,
  5403. configurable: true
  5404. });
  5405. Tools._AddLogEntry = function (entry) {
  5406. Tools._LogCache = entry + Tools._LogCache;
  5407. if (Tools.OnNewCacheEntry) {
  5408. Tools.OnNewCacheEntry(entry);
  5409. }
  5410. };
  5411. Tools._FormatMessage = function (message) {
  5412. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  5413. var date = new Date();
  5414. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  5415. };
  5416. Tools._LogDisabled = function (message) {
  5417. // nothing to do
  5418. };
  5419. Tools._LogEnabled = function (message) {
  5420. var formattedMessage = Tools._FormatMessage(message);
  5421. console.log("BJS - " + formattedMessage);
  5422. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  5423. Tools._AddLogEntry(entry);
  5424. };
  5425. Tools._WarnDisabled = function (message) {
  5426. // nothing to do
  5427. };
  5428. Tools._WarnEnabled = function (message) {
  5429. var formattedMessage = Tools._FormatMessage(message);
  5430. console.warn("BJS - " + formattedMessage);
  5431. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  5432. Tools._AddLogEntry(entry);
  5433. };
  5434. Tools._ErrorDisabled = function (message) {
  5435. // nothing to do
  5436. };
  5437. Tools._ErrorEnabled = function (message) {
  5438. Tools.errorsCount++;
  5439. var formattedMessage = Tools._FormatMessage(message);
  5440. console.error("BJS - " + formattedMessage);
  5441. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  5442. Tools._AddLogEntry(entry);
  5443. };
  5444. Object.defineProperty(Tools, "LogCache", {
  5445. get: function () {
  5446. return Tools._LogCache;
  5447. },
  5448. enumerable: true,
  5449. configurable: true
  5450. });
  5451. Tools.ClearLogCache = function () {
  5452. Tools._LogCache = "";
  5453. Tools.errorsCount = 0;
  5454. };
  5455. Object.defineProperty(Tools, "LogLevels", {
  5456. set: function (level) {
  5457. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  5458. Tools.Log = Tools._LogEnabled;
  5459. }
  5460. else {
  5461. Tools.Log = Tools._LogDisabled;
  5462. }
  5463. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  5464. Tools.Warn = Tools._WarnEnabled;
  5465. }
  5466. else {
  5467. Tools.Warn = Tools._WarnDisabled;
  5468. }
  5469. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  5470. Tools.Error = Tools._ErrorEnabled;
  5471. }
  5472. else {
  5473. Tools.Error = Tools._ErrorDisabled;
  5474. }
  5475. },
  5476. enumerable: true,
  5477. configurable: true
  5478. });
  5479. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  5480. get: function () {
  5481. return Tools._PerformanceNoneLogLevel;
  5482. },
  5483. enumerable: true,
  5484. configurable: true
  5485. });
  5486. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  5487. get: function () {
  5488. return Tools._PerformanceUserMarkLogLevel;
  5489. },
  5490. enumerable: true,
  5491. configurable: true
  5492. });
  5493. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  5494. get: function () {
  5495. return Tools._PerformanceConsoleLogLevel;
  5496. },
  5497. enumerable: true,
  5498. configurable: true
  5499. });
  5500. Object.defineProperty(Tools, "PerformanceLogLevel", {
  5501. set: function (level) {
  5502. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  5503. Tools.StartPerformanceCounter = Tools._StartUserMark;
  5504. Tools.EndPerformanceCounter = Tools._EndUserMark;
  5505. return;
  5506. }
  5507. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  5508. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  5509. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  5510. return;
  5511. }
  5512. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  5513. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  5514. },
  5515. enumerable: true,
  5516. configurable: true
  5517. });
  5518. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  5519. };
  5520. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  5521. };
  5522. Tools._StartUserMark = function (counterName, condition) {
  5523. if (condition === void 0) { condition = true; }
  5524. if (!condition || !Tools._performance.mark) {
  5525. return;
  5526. }
  5527. Tools._performance.mark(counterName + "-Begin");
  5528. };
  5529. Tools._EndUserMark = function (counterName, condition) {
  5530. if (condition === void 0) { condition = true; }
  5531. if (!condition || !Tools._performance.mark) {
  5532. return;
  5533. }
  5534. Tools._performance.mark(counterName + "-End");
  5535. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  5536. };
  5537. Tools._StartPerformanceConsole = function (counterName, condition) {
  5538. if (condition === void 0) { condition = true; }
  5539. if (!condition) {
  5540. return;
  5541. }
  5542. Tools._StartUserMark(counterName, condition);
  5543. if (console.time) {
  5544. console.time(counterName);
  5545. }
  5546. };
  5547. Tools._EndPerformanceConsole = function (counterName, condition) {
  5548. if (condition === void 0) { condition = true; }
  5549. if (!condition) {
  5550. return;
  5551. }
  5552. Tools._EndUserMark(counterName, condition);
  5553. if (console.time) {
  5554. console.timeEnd(counterName);
  5555. }
  5556. };
  5557. Object.defineProperty(Tools, "Now", {
  5558. get: function () {
  5559. if (window.performance && window.performance.now) {
  5560. return window.performance.now();
  5561. }
  5562. return new Date().getTime();
  5563. },
  5564. enumerable: true,
  5565. configurable: true
  5566. });
  5567. /**
  5568. * This method will return the name of the class used to create the instance of the given object.
  5569. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  5570. * @param object the object to get the class name from
  5571. * @return the name of the class, will be "object" for a custom data type not using the @className decorator
  5572. */
  5573. Tools.getClassName = function (object, isType) {
  5574. if (isType === void 0) { isType = false; }
  5575. var name = null;
  5576. if (!isType && object.getClassName) {
  5577. name = object.getClassName();
  5578. }
  5579. else {
  5580. if (object instanceof Object) {
  5581. var classObj = isType ? object : Object.getPrototypeOf(object);
  5582. name = classObj.constructor["__bjsclassName__"];
  5583. }
  5584. if (!name) {
  5585. name = typeof object;
  5586. }
  5587. }
  5588. return name;
  5589. };
  5590. Tools.first = function (array, predicate) {
  5591. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  5592. var el = array_1[_i];
  5593. if (predicate(el)) {
  5594. return el;
  5595. }
  5596. }
  5597. };
  5598. /**
  5599. * This method will return the name of the full name of the class, including its owning module (if any).
  5600. * 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).
  5601. * @param object the object to get the class name from
  5602. * @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.
  5603. */
  5604. Tools.getFullClassName = function (object, isType) {
  5605. if (isType === void 0) { isType = false; }
  5606. var className = null;
  5607. var moduleName = null;
  5608. if (!isType && object.getClassName) {
  5609. className = object.getClassName();
  5610. }
  5611. else {
  5612. if (object instanceof Object) {
  5613. var classObj = isType ? object : Object.getPrototypeOf(object);
  5614. className = classObj.constructor["__bjsclassName__"];
  5615. moduleName = classObj.constructor["__bjsmoduleName__"];
  5616. }
  5617. if (!className) {
  5618. className = typeof object;
  5619. }
  5620. }
  5621. if (!className) {
  5622. return null;
  5623. }
  5624. return ((moduleName != null) ? (moduleName + ".") : "") + className;
  5625. };
  5626. /**
  5627. * 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.
  5628. * @param array
  5629. */
  5630. Tools.arrayOrStringFeeder = function (array) {
  5631. return function (index) {
  5632. if (index >= array.length) {
  5633. return null;
  5634. }
  5635. var val = array.charCodeAt ? array.charCodeAt(index) : array[index];
  5636. if (val && val.getHashCode) {
  5637. val = val.getHashCode();
  5638. }
  5639. if (typeof val === "string") {
  5640. return Tools.hashCodeFromStream(Tools.arrayOrStringFeeder(val));
  5641. }
  5642. return val;
  5643. };
  5644. };
  5645. /**
  5646. * Compute the hashCode of a stream of number
  5647. * To compute the HashCode on a string or an Array of data types implementing the getHashCode() method, use the arrayOrStringFeeder method.
  5648. * @param feeder a callback that will be called until it returns null, each valid returned values will be used to compute the hash code.
  5649. * @return the hash code computed
  5650. */
  5651. Tools.hashCodeFromStream = function (feeder) {
  5652. // Based from here: http://stackoverflow.com/a/7616484/802124
  5653. var hash = 0;
  5654. var index = 0;
  5655. var chr = feeder(index++);
  5656. while (chr != null) {
  5657. hash = ((hash << 5) - hash) + chr;
  5658. hash |= 0; // Convert to 32bit integer
  5659. chr = feeder(index++);
  5660. }
  5661. return hash;
  5662. };
  5663. return Tools;
  5664. }());
  5665. Tools.BaseUrl = "";
  5666. Tools.CorsBehavior = "anonymous";
  5667. Tools.UseFallbackTexture = true;
  5668. // Used in case of a texture loading problem
  5669. 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";
  5670. // Logs
  5671. Tools._NoneLogLevel = 0;
  5672. Tools._MessageLogLevel = 1;
  5673. Tools._WarningLogLevel = 2;
  5674. Tools._ErrorLogLevel = 4;
  5675. Tools._LogCache = "";
  5676. Tools.errorsCount = 0;
  5677. Tools.Log = Tools._LogEnabled;
  5678. Tools.Warn = Tools._WarnEnabled;
  5679. Tools.Error = Tools._ErrorEnabled;
  5680. // Performances
  5681. Tools._PerformanceNoneLogLevel = 0;
  5682. Tools._PerformanceUserMarkLogLevel = 1;
  5683. Tools._PerformanceConsoleLogLevel = 2;
  5684. Tools._performance = window.performance;
  5685. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  5686. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  5687. BABYLON.Tools = Tools;
  5688. /**
  5689. * This class is used to track a performance counter which is number based.
  5690. * The user has access to many properties which give statistics of different nature
  5691. *
  5692. * The implementer can track two kinds of Performance Counter: time and count
  5693. * 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.
  5694. * 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.
  5695. */
  5696. var PerfCounter = (function () {
  5697. function PerfCounter() {
  5698. this._startMonitoringTime = 0;
  5699. this._min = 0;
  5700. this._max = 0;
  5701. this._average = 0;
  5702. this._lastSecAverage = 0;
  5703. this._current = 0;
  5704. this._totalValueCount = 0;
  5705. this._totalAccumulated = 0;
  5706. this._lastSecAccumulated = 0;
  5707. this._lastSecTime = 0;
  5708. this._lastSecValueCount = 0;
  5709. }
  5710. Object.defineProperty(PerfCounter.prototype, "min", {
  5711. /**
  5712. * Returns the smallest value ever
  5713. */
  5714. get: function () {
  5715. return this._min;
  5716. },
  5717. enumerable: true,
  5718. configurable: true
  5719. });
  5720. Object.defineProperty(PerfCounter.prototype, "max", {
  5721. /**
  5722. * Returns the biggest value ever
  5723. */
  5724. get: function () {
  5725. return this._max;
  5726. },
  5727. enumerable: true,
  5728. configurable: true
  5729. });
  5730. Object.defineProperty(PerfCounter.prototype, "average", {
  5731. /**
  5732. * Returns the average value since the performance counter is running
  5733. */
  5734. get: function () {
  5735. return this._average;
  5736. },
  5737. enumerable: true,
  5738. configurable: true
  5739. });
  5740. Object.defineProperty(PerfCounter.prototype, "lastSecAverage", {
  5741. /**
  5742. * Returns the average value of the last second the counter was monitored
  5743. */
  5744. get: function () {
  5745. return this._lastSecAverage;
  5746. },
  5747. enumerable: true,
  5748. configurable: true
  5749. });
  5750. Object.defineProperty(PerfCounter.prototype, "current", {
  5751. /**
  5752. * Returns the current value
  5753. */
  5754. get: function () {
  5755. return this._current;
  5756. },
  5757. enumerable: true,
  5758. configurable: true
  5759. });
  5760. Object.defineProperty(PerfCounter.prototype, "total", {
  5761. get: function () {
  5762. return this._totalAccumulated;
  5763. },
  5764. enumerable: true,
  5765. configurable: true
  5766. });
  5767. /**
  5768. * Call this method to start monitoring a new frame.
  5769. * 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.
  5770. */
  5771. PerfCounter.prototype.fetchNewFrame = function () {
  5772. this._totalValueCount++;
  5773. this._current = 0;
  5774. this._lastSecValueCount++;
  5775. };
  5776. /**
  5777. * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)
  5778. * @param newCount the count value to add to the monitored count
  5779. * @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.
  5780. */
  5781. PerfCounter.prototype.addCount = function (newCount, fetchResult) {
  5782. this._current += newCount;
  5783. if (fetchResult) {
  5784. this._fetchResult();
  5785. }
  5786. };
  5787. /**
  5788. * Start monitoring this performance counter
  5789. */
  5790. PerfCounter.prototype.beginMonitoring = function () {
  5791. this._startMonitoringTime = Tools.Now;
  5792. };
  5793. /**
  5794. * Compute the time lapsed since the previous beginMonitoring() call.
  5795. * @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
  5796. */
  5797. PerfCounter.prototype.endMonitoring = function (newFrame) {
  5798. if (newFrame === void 0) { newFrame = true; }
  5799. if (newFrame) {
  5800. this.fetchNewFrame();
  5801. }
  5802. var currentTime = Tools.Now;
  5803. this._current = currentTime - this._startMonitoringTime;
  5804. if (newFrame) {
  5805. this._fetchResult();
  5806. }
  5807. };
  5808. PerfCounter.prototype._fetchResult = function () {
  5809. this._totalAccumulated += this._current;
  5810. this._lastSecAccumulated += this._current;
  5811. // Min/Max update
  5812. this._min = Math.min(this._min, this._current);
  5813. this._max = Math.max(this._max, this._current);
  5814. this._average = this._totalAccumulated / this._totalValueCount;
  5815. // Reset last sec?
  5816. var now = Tools.Now;
  5817. if ((now - this._lastSecTime) > 1000) {
  5818. this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
  5819. this._lastSecTime = now;
  5820. this._lastSecAccumulated = 0;
  5821. this._lastSecValueCount = 0;
  5822. }
  5823. };
  5824. return PerfCounter;
  5825. }());
  5826. BABYLON.PerfCounter = PerfCounter;
  5827. /**
  5828. * Use this className as a decorator on a given class definition to add it a name and optionally its module.
  5829. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  5830. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  5831. * @param name The name of the class, case should be preserved
  5832. * @param module The name of the Module hosting the class, optional, but strongly recommended to specify if possible. Case should be preserved.
  5833. */
  5834. function className(name, module) {
  5835. return function (target) {
  5836. target["__bjsclassName__"] = name;
  5837. target["__bjsmoduleName__"] = (module != null) ? module : null;
  5838. };
  5839. }
  5840. BABYLON.className = className;
  5841. /**
  5842. * An implementation of a loop for asynchronous functions.
  5843. */
  5844. var AsyncLoop = (function () {
  5845. /**
  5846. * Constroctor.
  5847. * @param iterations the number of iterations.
  5848. * @param _fn the function to run each iteration
  5849. * @param _successCallback the callback that will be called upon succesful execution
  5850. * @param offset starting offset.
  5851. */
  5852. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  5853. if (offset === void 0) { offset = 0; }
  5854. this.iterations = iterations;
  5855. this._fn = _fn;
  5856. this._successCallback = _successCallback;
  5857. this.index = offset - 1;
  5858. this._done = false;
  5859. }
  5860. /**
  5861. * Execute the next iteration. Must be called after the last iteration was finished.
  5862. */
  5863. AsyncLoop.prototype.executeNext = function () {
  5864. if (!this._done) {
  5865. if (this.index + 1 < this.iterations) {
  5866. ++this.index;
  5867. this._fn(this);
  5868. }
  5869. else {
  5870. this.breakLoop();
  5871. }
  5872. }
  5873. };
  5874. /**
  5875. * Break the loop and run the success callback.
  5876. */
  5877. AsyncLoop.prototype.breakLoop = function () {
  5878. this._done = true;
  5879. this._successCallback();
  5880. };
  5881. /**
  5882. * Helper function
  5883. */
  5884. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  5885. if (offset === void 0) { offset = 0; }
  5886. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  5887. loop.executeNext();
  5888. return loop;
  5889. };
  5890. /**
  5891. * A for-loop that will run a given number of iterations synchronous and the rest async.
  5892. * @param iterations total number of iterations
  5893. * @param syncedIterations number of synchronous iterations in each async iteration.
  5894. * @param fn the function to call each iteration.
  5895. * @param callback a success call back that will be called when iterating stops.
  5896. * @param breakFunction a break condition (optional)
  5897. * @param timeout timeout settings for the setTimeout function. default - 0.
  5898. * @constructor
  5899. */
  5900. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  5901. if (timeout === void 0) { timeout = 0; }
  5902. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  5903. if (breakFunction && breakFunction())
  5904. loop.breakLoop();
  5905. else {
  5906. setTimeout(function () {
  5907. for (var i = 0; i < syncedIterations; ++i) {
  5908. var iteration = (loop.index * syncedIterations) + i;
  5909. if (iteration >= iterations)
  5910. break;
  5911. fn(iteration);
  5912. if (breakFunction && breakFunction()) {
  5913. loop.breakLoop();
  5914. break;
  5915. }
  5916. }
  5917. loop.executeNext();
  5918. }, timeout);
  5919. }
  5920. }, callback);
  5921. };
  5922. return AsyncLoop;
  5923. }());
  5924. BABYLON.AsyncLoop = AsyncLoop;
  5925. })(BABYLON || (BABYLON = {}));
  5926. //# sourceMappingURL=babylon.tools.js.map
  5927. var BABYLON;
  5928. (function (BABYLON) {
  5929. var Internals;
  5930. (function (Internals) {
  5931. var _AlphaState = (function () {
  5932. /**
  5933. * Initializes the state.
  5934. */
  5935. function _AlphaState() {
  5936. this._isAlphaBlendDirty = false;
  5937. this._isBlendFunctionParametersDirty = false;
  5938. this._alphaBlend = false;
  5939. this._blendFunctionParameters = new Array(4);
  5940. this.reset();
  5941. }
  5942. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  5943. get: function () {
  5944. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  5945. },
  5946. enumerable: true,
  5947. configurable: true
  5948. });
  5949. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  5950. get: function () {
  5951. return this._alphaBlend;
  5952. },
  5953. set: function (value) {
  5954. if (this._alphaBlend === value) {
  5955. return;
  5956. }
  5957. this._alphaBlend = value;
  5958. this._isAlphaBlendDirty = true;
  5959. },
  5960. enumerable: true,
  5961. configurable: true
  5962. });
  5963. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  5964. if (this._blendFunctionParameters[0] === value0 &&
  5965. this._blendFunctionParameters[1] === value1 &&
  5966. this._blendFunctionParameters[2] === value2 &&
  5967. this._blendFunctionParameters[3] === value3) {
  5968. return;
  5969. }
  5970. this._blendFunctionParameters[0] = value0;
  5971. this._blendFunctionParameters[1] = value1;
  5972. this._blendFunctionParameters[2] = value2;
  5973. this._blendFunctionParameters[3] = value3;
  5974. this._isBlendFunctionParametersDirty = true;
  5975. };
  5976. _AlphaState.prototype.reset = function () {
  5977. this._alphaBlend = false;
  5978. this._blendFunctionParameters[0] = null;
  5979. this._blendFunctionParameters[1] = null;
  5980. this._blendFunctionParameters[2] = null;
  5981. this._blendFunctionParameters[3] = null;
  5982. this._isAlphaBlendDirty = true;
  5983. this._isBlendFunctionParametersDirty = false;
  5984. };
  5985. _AlphaState.prototype.apply = function (gl) {
  5986. if (!this.isDirty) {
  5987. return;
  5988. }
  5989. // Alpha blend
  5990. if (this._isAlphaBlendDirty) {
  5991. if (this._alphaBlend) {
  5992. gl.enable(gl.BLEND);
  5993. }
  5994. else {
  5995. gl.disable(gl.BLEND);
  5996. }
  5997. this._isAlphaBlendDirty = false;
  5998. }
  5999. // Alpha function
  6000. if (this._isBlendFunctionParametersDirty) {
  6001. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  6002. this._isBlendFunctionParametersDirty = false;
  6003. }
  6004. };
  6005. return _AlphaState;
  6006. }());
  6007. Internals._AlphaState = _AlphaState;
  6008. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  6009. })(BABYLON || (BABYLON = {}));
  6010. //# sourceMappingURL=babylon.alphaCullingState.js.map
  6011. var BABYLON;
  6012. (function (BABYLON) {
  6013. var Internals;
  6014. (function (Internals) {
  6015. var _DepthCullingState = (function () {
  6016. /**
  6017. * Initializes the state.
  6018. */
  6019. function _DepthCullingState() {
  6020. this._isDepthTestDirty = false;
  6021. this._isDepthMaskDirty = false;
  6022. this._isDepthFuncDirty = false;
  6023. this._isCullFaceDirty = false;
  6024. this._isCullDirty = false;
  6025. this._isZOffsetDirty = false;
  6026. this.reset();
  6027. }
  6028. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  6029. get: function () {
  6030. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty;
  6031. },
  6032. enumerable: true,
  6033. configurable: true
  6034. });
  6035. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  6036. get: function () {
  6037. return this._zOffset;
  6038. },
  6039. set: function (value) {
  6040. if (this._zOffset === value) {
  6041. return;
  6042. }
  6043. this._zOffset = value;
  6044. this._isZOffsetDirty = true;
  6045. },
  6046. enumerable: true,
  6047. configurable: true
  6048. });
  6049. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  6050. get: function () {
  6051. return this._cullFace;
  6052. },
  6053. set: function (value) {
  6054. if (this._cullFace === value) {
  6055. return;
  6056. }
  6057. this._cullFace = value;
  6058. this._isCullFaceDirty = true;
  6059. },
  6060. enumerable: true,
  6061. configurable: true
  6062. });
  6063. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  6064. get: function () {
  6065. return this._cull;
  6066. },
  6067. set: function (value) {
  6068. if (this._cull === value) {
  6069. return;
  6070. }
  6071. this._cull = value;
  6072. this._isCullDirty = true;
  6073. },
  6074. enumerable: true,
  6075. configurable: true
  6076. });
  6077. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  6078. get: function () {
  6079. return this._depthFunc;
  6080. },
  6081. set: function (value) {
  6082. if (this._depthFunc === value) {
  6083. return;
  6084. }
  6085. this._depthFunc = value;
  6086. this._isDepthFuncDirty = true;
  6087. },
  6088. enumerable: true,
  6089. configurable: true
  6090. });
  6091. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  6092. get: function () {
  6093. return this._depthMask;
  6094. },
  6095. set: function (value) {
  6096. if (this._depthMask === value) {
  6097. return;
  6098. }
  6099. this._depthMask = value;
  6100. this._isDepthMaskDirty = true;
  6101. },
  6102. enumerable: true,
  6103. configurable: true
  6104. });
  6105. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  6106. get: function () {
  6107. return this._depthTest;
  6108. },
  6109. set: function (value) {
  6110. if (this._depthTest === value) {
  6111. return;
  6112. }
  6113. this._depthTest = value;
  6114. this._isDepthTestDirty = true;
  6115. },
  6116. enumerable: true,
  6117. configurable: true
  6118. });
  6119. _DepthCullingState.prototype.reset = function () {
  6120. this._depthMask = true;
  6121. this._depthTest = true;
  6122. this._depthFunc = null;
  6123. this._cullFace = null;
  6124. this._cull = null;
  6125. this._zOffset = 0;
  6126. this._isDepthTestDirty = true;
  6127. this._isDepthMaskDirty = true;
  6128. this._isDepthFuncDirty = false;
  6129. this._isCullFaceDirty = false;
  6130. this._isCullDirty = false;
  6131. this._isZOffsetDirty = false;
  6132. };
  6133. _DepthCullingState.prototype.apply = function (gl) {
  6134. if (!this.isDirty) {
  6135. return;
  6136. }
  6137. // Cull
  6138. if (this._isCullDirty) {
  6139. if (this.cull) {
  6140. gl.enable(gl.CULL_FACE);
  6141. }
  6142. else {
  6143. gl.disable(gl.CULL_FACE);
  6144. }
  6145. this._isCullDirty = false;
  6146. }
  6147. // Cull face
  6148. if (this._isCullFaceDirty) {
  6149. gl.cullFace(this.cullFace);
  6150. this._isCullFaceDirty = false;
  6151. }
  6152. // Depth mask
  6153. if (this._isDepthMaskDirty) {
  6154. gl.depthMask(this.depthMask);
  6155. this._isDepthMaskDirty = false;
  6156. }
  6157. // Depth test
  6158. if (this._isDepthTestDirty) {
  6159. if (this.depthTest) {
  6160. gl.enable(gl.DEPTH_TEST);
  6161. }
  6162. else {
  6163. gl.disable(gl.DEPTH_TEST);
  6164. }
  6165. this._isDepthTestDirty = false;
  6166. }
  6167. // Depth func
  6168. if (this._isDepthFuncDirty) {
  6169. gl.depthFunc(this.depthFunc);
  6170. this._isDepthFuncDirty = false;
  6171. }
  6172. // zOffset
  6173. if (this._isZOffsetDirty) {
  6174. if (this.zOffset) {
  6175. gl.enable(gl.POLYGON_OFFSET_FILL);
  6176. gl.polygonOffset(this.zOffset, 0);
  6177. }
  6178. else {
  6179. gl.disable(gl.POLYGON_OFFSET_FILL);
  6180. }
  6181. this._isZOffsetDirty = false;
  6182. }
  6183. };
  6184. return _DepthCullingState;
  6185. }());
  6186. Internals._DepthCullingState = _DepthCullingState;
  6187. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  6188. })(BABYLON || (BABYLON = {}));
  6189. //# sourceMappingURL=babylon.depthCullingState.js.map
  6190. var BABYLON;
  6191. (function (BABYLON) {
  6192. var Internals;
  6193. (function (Internals) {
  6194. var _StencilState = (function () {
  6195. function _StencilState() {
  6196. this._isStencilTestDirty = false;
  6197. this._isStencilMaskDirty = false;
  6198. this._isStencilFuncDirty = false;
  6199. this._isStencilOpDirty = false;
  6200. this.reset();
  6201. }
  6202. Object.defineProperty(_StencilState.prototype, "isDirty", {
  6203. get: function () {
  6204. return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty;
  6205. },
  6206. enumerable: true,
  6207. configurable: true
  6208. });
  6209. Object.defineProperty(_StencilState.prototype, "stencilFunc", {
  6210. get: function () {
  6211. return this._stencilFunc;
  6212. },
  6213. set: function (value) {
  6214. if (this._stencilFunc === value) {
  6215. return;
  6216. }
  6217. this._stencilFunc = value;
  6218. this._isStencilFuncDirty = true;
  6219. },
  6220. enumerable: true,
  6221. configurable: true
  6222. });
  6223. Object.defineProperty(_StencilState.prototype, "stencilFuncRef", {
  6224. get: function () {
  6225. return this._stencilFuncRef;
  6226. },
  6227. set: function (value) {
  6228. if (this._stencilFuncRef === value) {
  6229. return;
  6230. }
  6231. this._stencilFuncRef = value;
  6232. this._isStencilFuncDirty = true;
  6233. },
  6234. enumerable: true,
  6235. configurable: true
  6236. });
  6237. Object.defineProperty(_StencilState.prototype, "stencilFuncMask", {
  6238. get: function () {
  6239. return this._stencilFuncMask;
  6240. },
  6241. set: function (value) {
  6242. if (this._stencilFuncMask === value) {
  6243. return;
  6244. }
  6245. this._stencilFuncMask = value;
  6246. this._isStencilFuncDirty = true;
  6247. },
  6248. enumerable: true,
  6249. configurable: true
  6250. });
  6251. Object.defineProperty(_StencilState.prototype, "stencilOpStencilFail", {
  6252. get: function () {
  6253. return this._stencilOpStencilFail;
  6254. },
  6255. set: function (value) {
  6256. if (this._stencilOpStencilFail === value) {
  6257. return;
  6258. }
  6259. this._stencilOpStencilFail = value;
  6260. this._isStencilOpDirty = true;
  6261. },
  6262. enumerable: true,
  6263. configurable: true
  6264. });
  6265. Object.defineProperty(_StencilState.prototype, "stencilOpDepthFail", {
  6266. get: function () {
  6267. return this._stencilOpDepthFail;
  6268. },
  6269. set: function (value) {
  6270. if (this._stencilOpDepthFail === value) {
  6271. return;
  6272. }
  6273. this._stencilOpDepthFail = value;
  6274. this._isStencilOpDirty = true;
  6275. },
  6276. enumerable: true,
  6277. configurable: true
  6278. });
  6279. Object.defineProperty(_StencilState.prototype, "stencilOpStencilDepthPass", {
  6280. get: function () {
  6281. return this._stencilOpStencilDepthPass;
  6282. },
  6283. set: function (value) {
  6284. if (this._stencilOpStencilDepthPass === value) {
  6285. return;
  6286. }
  6287. this._stencilOpStencilDepthPass = value;
  6288. this._isStencilOpDirty = true;
  6289. },
  6290. enumerable: true,
  6291. configurable: true
  6292. });
  6293. Object.defineProperty(_StencilState.prototype, "stencilMask", {
  6294. get: function () {
  6295. return this._stencilMask;
  6296. },
  6297. set: function (value) {
  6298. if (this._stencilMask === value) {
  6299. return;
  6300. }
  6301. this._stencilMask = value;
  6302. this._isStencilMaskDirty = true;
  6303. },
  6304. enumerable: true,
  6305. configurable: true
  6306. });
  6307. Object.defineProperty(_StencilState.prototype, "stencilTest", {
  6308. get: function () {
  6309. return this._stencilTest;
  6310. },
  6311. set: function (value) {
  6312. if (this._stencilTest === value) {
  6313. return;
  6314. }
  6315. this._stencilTest = value;
  6316. this._isStencilTestDirty = true;
  6317. },
  6318. enumerable: true,
  6319. configurable: true
  6320. });
  6321. _StencilState.prototype.reset = function () {
  6322. this._stencilTest = false;
  6323. this._stencilMask = 0xFF;
  6324. this._stencilFunc = BABYLON.Engine.ALWAYS;
  6325. this._stencilFuncRef = 1;
  6326. this._stencilFuncMask = 0xFF;
  6327. this._stencilOpStencilFail = BABYLON.Engine.KEEP;
  6328. this._stencilOpDepthFail = BABYLON.Engine.KEEP;
  6329. this._stencilOpStencilDepthPass = BABYLON.Engine.REPLACE;
  6330. this._isStencilTestDirty = true;
  6331. this._isStencilMaskDirty = true;
  6332. this._isStencilFuncDirty = true;
  6333. this._isStencilOpDirty = true;
  6334. };
  6335. _StencilState.prototype.apply = function (gl) {
  6336. if (!this.isDirty) {
  6337. return;
  6338. }
  6339. // Stencil test
  6340. if (this._isStencilTestDirty) {
  6341. if (this.stencilTest) {
  6342. gl.enable(gl.STENCIL_TEST);
  6343. }
  6344. else {
  6345. gl.disable(gl.STENCIL_TEST);
  6346. }
  6347. this._isStencilTestDirty = false;
  6348. }
  6349. // Stencil mask
  6350. if (this._isStencilMaskDirty) {
  6351. gl.stencilMask(this.stencilMask);
  6352. this._isStencilMaskDirty = false;
  6353. }
  6354. // Stencil func
  6355. if (this._isStencilFuncDirty) {
  6356. gl.stencilFunc(this.stencilFunc, this.stencilFuncRef, this.stencilFuncMask);
  6357. this._isStencilFuncDirty = false;
  6358. }
  6359. // Stencil op
  6360. if (this._isStencilOpDirty) {
  6361. gl.stencilOp(this.stencilOpStencilFail, this.stencilOpDepthFail, this.stencilOpStencilDepthPass);
  6362. this._isStencilOpDirty = false;
  6363. }
  6364. };
  6365. return _StencilState;
  6366. }());
  6367. Internals._StencilState = _StencilState;
  6368. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  6369. })(BABYLON || (BABYLON = {}));
  6370. //# sourceMappingURL=babylon.stencilState.js.map
  6371. var BABYLON;
  6372. (function (BABYLON) {
  6373. var compileShader = function (gl, source, type, defines, shaderVersion) {
  6374. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  6375. gl.shaderSource(shader, shaderVersion + (defines ? defines + "\n" : "") + source);
  6376. gl.compileShader(shader);
  6377. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  6378. throw new Error(gl.getShaderInfoLog(shader));
  6379. }
  6380. return shader;
  6381. };
  6382. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  6383. var magFilter = gl.NEAREST;
  6384. var minFilter = gl.NEAREST;
  6385. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  6386. magFilter = gl.LINEAR;
  6387. if (generateMipMaps) {
  6388. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  6389. }
  6390. else {
  6391. minFilter = gl.LINEAR;
  6392. }
  6393. }
  6394. else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  6395. magFilter = gl.LINEAR;
  6396. if (generateMipMaps) {
  6397. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  6398. }
  6399. else {
  6400. minFilter = gl.LINEAR;
  6401. }
  6402. }
  6403. else if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  6404. magFilter = gl.NEAREST;
  6405. if (generateMipMaps) {
  6406. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  6407. }
  6408. else {
  6409. minFilter = gl.NEAREST;
  6410. }
  6411. }
  6412. return {
  6413. min: minFilter,
  6414. mag: magFilter
  6415. };
  6416. };
  6417. var prepareWebGLTexture = function (texture, gl, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  6418. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  6419. var engine = scene.getEngine();
  6420. var potWidth = BABYLON.Tools.GetExponentOfTwo(width, engine.getCaps().maxTextureSize);
  6421. var potHeight = BABYLON.Tools.GetExponentOfTwo(height, engine.getCaps().maxTextureSize);
  6422. engine._bindTextureDirectly(gl.TEXTURE_2D, texture);
  6423. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  6424. texture._baseWidth = width;
  6425. texture._baseHeight = height;
  6426. texture._width = potWidth;
  6427. texture._height = potHeight;
  6428. texture.isReady = true;
  6429. processFunction(potWidth, potHeight);
  6430. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  6431. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  6432. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  6433. if (!noMipmap && !isCompressed) {
  6434. gl.generateMipmap(gl.TEXTURE_2D);
  6435. }
  6436. engine._bindTextureDirectly(gl.TEXTURE_2D, null);
  6437. engine.resetTextureCache();
  6438. scene._removePendingData(texture);
  6439. texture.onLoadedCallbacks.forEach(function (callback) {
  6440. callback();
  6441. });
  6442. texture.onLoadedCallbacks = [];
  6443. };
  6444. var partialLoad = function (url, index, loadedImages, scene, onfinish, onErrorCallBack) {
  6445. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  6446. var img;
  6447. var onload = function () {
  6448. loadedImages[index] = img;
  6449. loadedImages._internalCount++;
  6450. scene._removePendingData(img);
  6451. if (loadedImages._internalCount === 6) {
  6452. onfinish(loadedImages);
  6453. }
  6454. };
  6455. var onerror = function () {
  6456. scene._removePendingData(img);
  6457. if (onErrorCallBack) {
  6458. onErrorCallBack();
  6459. }
  6460. };
  6461. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  6462. scene._addPendingData(img);
  6463. };
  6464. var cascadeLoad = function (rootUrl, scene, onfinish, files, onError) {
  6465. if (onError === void 0) { onError = null; }
  6466. var loadedImages = [];
  6467. loadedImages._internalCount = 0;
  6468. for (var index = 0; index < 6; index++) {
  6469. partialLoad(files[index], index, loadedImages, scene, onfinish, onError);
  6470. }
  6471. };
  6472. var InstancingAttributeInfo = (function () {
  6473. function InstancingAttributeInfo() {
  6474. }
  6475. return InstancingAttributeInfo;
  6476. }());
  6477. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  6478. var EngineCapabilities = (function () {
  6479. function EngineCapabilities() {
  6480. }
  6481. return EngineCapabilities;
  6482. }());
  6483. BABYLON.EngineCapabilities = EngineCapabilities;
  6484. /**
  6485. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
  6486. */
  6487. var Engine = (function () {
  6488. /**
  6489. * @constructor
  6490. * @param {HTMLCanvasElement} canvas - the canvas to be used for rendering
  6491. * @param {boolean} [antialias] - enable antialias
  6492. * @param options - further options to be sent to the getContext function
  6493. */
  6494. function Engine(canvas, antialias, options, adaptToDeviceRatio) {
  6495. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = false; }
  6496. var _this = this;
  6497. // Public members
  6498. this.isFullscreen = false;
  6499. this.isPointerLock = false;
  6500. this.cullBackFaces = true;
  6501. this.renderEvenInBackground = true;
  6502. // To enable/disable IDB support and avoid XHR on .manifest
  6503. this.enableOfflineSupport = true;
  6504. this.scenes = new Array();
  6505. this._windowIsBackground = false;
  6506. this._webGLVersion = 1.0;
  6507. this._badOS = false;
  6508. this._drawCalls = new BABYLON.PerfCounter();
  6509. this._renderingQueueLaunched = false;
  6510. this._activeRenderLoops = [];
  6511. // FPS
  6512. this.fpsRange = 60;
  6513. this.previousFramesDuration = [];
  6514. this.fps = 60;
  6515. this.deltaTime = 0;
  6516. // States
  6517. this._depthCullingState = new BABYLON.Internals._DepthCullingState();
  6518. this._stencilState = new BABYLON.Internals._StencilState();
  6519. this._alphaState = new BABYLON.Internals._AlphaState();
  6520. this._alphaMode = Engine.ALPHA_DISABLE;
  6521. // Cache
  6522. this._loadedTexturesCache = new Array();
  6523. this._maxTextureChannels = 16;
  6524. this._activeTexturesCache = new Array(this._maxTextureChannels);
  6525. this._compiledEffects = {};
  6526. this._vertexAttribArraysEnabled = [];
  6527. this._uintIndicesCurrentlySet = false;
  6528. this._currentBoundBuffer = new Array();
  6529. this._currentBufferPointers = [];
  6530. this._currentInstanceLocations = new Array();
  6531. this._currentInstanceBuffers = new Array();
  6532. this._vaoRecordInProgress = false;
  6533. this._mustWipeVertexAttributes = false;
  6534. // Hardware supported Compressed Textures
  6535. this._texturesSupported = new Array();
  6536. this._onVRFullScreenTriggered = function () {
  6537. if (_this._vrDisplayEnabled && _this._vrDisplayEnabled.isPresenting) {
  6538. //get the old size before we change
  6539. _this._oldSize = new BABYLON.Size(_this.getRenderWidth(), _this.getRenderHeight());
  6540. _this._oldHardwareScaleFactor = _this.getHardwareScalingLevel();
  6541. //according to the WebVR specs, requestAnimationFrame should be triggered only once.
  6542. //But actually, no browser follow the specs...
  6543. //this._vrAnimationFrameHandler = this._vrDisplayEnabled.requestAnimationFrame(this._bindedRenderFunction);
  6544. //get the width and height, change the render size
  6545. var leftEye = _this._vrDisplayEnabled.getEyeParameters('left');
  6546. var width, height;
  6547. _this.setHardwareScalingLevel(1);
  6548. _this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  6549. }
  6550. else {
  6551. //When the specs are implemented, need to uncomment this.
  6552. //this._vrDisplayEnabled.cancelAnimationFrame(this._vrAnimationFrameHandler);
  6553. _this.setHardwareScalingLevel(_this._oldHardwareScaleFactor);
  6554. _this.setSize(_this._oldSize.width, _this._oldSize.height);
  6555. _this._vrDisplayEnabled = undefined;
  6556. }
  6557. };
  6558. this._renderingCanvas = canvas;
  6559. this._externalData = new BABYLON.StringDictionary();
  6560. options = options || {};
  6561. if (antialias != null) {
  6562. options.antialias = antialias;
  6563. }
  6564. if (options.preserveDrawingBuffer === undefined) {
  6565. options.preserveDrawingBuffer = false;
  6566. }
  6567. // GL
  6568. if (!options.disableWebGL2Support) {
  6569. try {
  6570. this._gl = (canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  6571. if (this._gl) {
  6572. this._webGLVersion = 2.0;
  6573. }
  6574. }
  6575. catch (e) {
  6576. }
  6577. }
  6578. if (!this._gl) {
  6579. if (!canvas) {
  6580. throw new Error("The provided canvas is null or undefined.");
  6581. }
  6582. try {
  6583. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  6584. }
  6585. catch (e) {
  6586. throw new Error("WebGL not supported");
  6587. }
  6588. }
  6589. if (!this._gl) {
  6590. throw new Error("WebGL not supported");
  6591. }
  6592. this._onBlur = function () {
  6593. _this._windowIsBackground = true;
  6594. };
  6595. this._onFocus = function () {
  6596. _this._windowIsBackground = false;
  6597. };
  6598. window.addEventListener("blur", this._onBlur);
  6599. window.addEventListener("focus", this._onFocus);
  6600. // Viewport
  6601. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  6602. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  6603. this.resize();
  6604. // Caps
  6605. this._isStencilEnable = options.stencil;
  6606. this._caps = new EngineCapabilities();
  6607. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  6608. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  6609. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  6610. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  6611. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  6612. this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS);
  6613. this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  6614. this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS);
  6615. // Infos
  6616. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  6617. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  6618. if (rendererInfo != null) {
  6619. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  6620. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  6621. }
  6622. if (!this._glVendor) {
  6623. this._glVendor = "Unknown vendor";
  6624. }
  6625. if (!this._glRenderer) {
  6626. this._glRenderer = "Unknown renderer";
  6627. }
  6628. // Extensions
  6629. this._caps.standardDerivatives = this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null);
  6630. this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc');
  6631. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  6632. this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  6633. this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1');
  6634. this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc') ||
  6635. this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // also a requirement of OpenGL ES 3
  6636. this._caps.atc = this._gl.getExtension('WEBGL_compressed_texture_atc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_atc');
  6637. 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');
  6638. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  6639. this._caps.uintIndices = this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null;
  6640. this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null;
  6641. this._caps.highPrecisionShaderSupported = true;
  6642. this._caps.drawBuffersExtension = this._webGLVersion > 1 || this._gl.getExtension('WEBGL_draw_buffers');
  6643. // Checks if some of the format renders first to allow the use of webgl inspector.
  6644. this._caps.colorBufferFloat = this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float');
  6645. this._caps.textureFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float');
  6646. this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear');
  6647. this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer();
  6648. this._caps.textureHalfFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float');
  6649. this._caps.textureHalfFloatLinearFiltering = this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'));
  6650. this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
  6651. this._caps.textureLOD = this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod');
  6652. // Vertex array object
  6653. if (this._webGLVersion > 1) {
  6654. this._caps.vertexArrayObject = true;
  6655. }
  6656. else {
  6657. var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object');
  6658. if (vertexArrayObjectExtension != null) {
  6659. this._caps.vertexArrayObject = true;
  6660. this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
  6661. this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
  6662. this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
  6663. }
  6664. else {
  6665. this._caps.vertexArrayObject = false;
  6666. }
  6667. }
  6668. // Instances count
  6669. if (this._webGLVersion > 1) {
  6670. this._caps.instancedArrays = true;
  6671. }
  6672. else {
  6673. var instanceExtension = this._gl.getExtension('ANGLE_instanced_arrays');
  6674. if (instanceExtension != null) {
  6675. this._caps.instancedArrays = true;
  6676. this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
  6677. this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
  6678. this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
  6679. }
  6680. else {
  6681. this._caps.instancedArrays = false;
  6682. }
  6683. }
  6684. // Intelligently add supported compressed formats in order to check for.
  6685. // Check for ASTC support first as it is most powerful and to be very cross platform.
  6686. // Next PVRTC & DXT, which are probably superior to ETC1/2.
  6687. // Likely no hardware which supports both PVR & DXT, so order matters little.
  6688. // ETC2 is newer and handles ETC1 (no alpha capability), so check for first.
  6689. // ATC before ETC1, since both old (widely supported), but ATC supports alpha, but ETC1 does not
  6690. if (this._caps.astc)
  6691. this.texturesSupported.push('-astc.ktx');
  6692. if (this._caps.s3tc)
  6693. this.texturesSupported.push('-dxt.ktx');
  6694. if (this._caps.pvrtc)
  6695. this.texturesSupported.push('-pvrtc.ktx');
  6696. if (this._caps.etc2)
  6697. this.texturesSupported.push('-etc2.ktx');
  6698. if (this._caps.atc)
  6699. this.texturesSupported.push('-atc.ktx');
  6700. if (this._caps.etc1)
  6701. this.texturesSupported.push('-etc1.ktx');
  6702. if (this._gl.getShaderPrecisionFormat) {
  6703. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  6704. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  6705. }
  6706. // Depth buffer
  6707. this.setDepthBuffer(true);
  6708. this.setDepthFunctionToLessOrEqual();
  6709. this.setDepthWrite(true);
  6710. // Fullscreen
  6711. this._onFullscreenChange = function () {
  6712. if (document.fullscreen !== undefined) {
  6713. _this.isFullscreen = document.fullscreen;
  6714. }
  6715. else if (document.mozFullScreen !== undefined) {
  6716. _this.isFullscreen = document.mozFullScreen;
  6717. }
  6718. else if (document.webkitIsFullScreen !== undefined) {
  6719. _this.isFullscreen = document.webkitIsFullScreen;
  6720. }
  6721. else if (document.msIsFullScreen !== undefined) {
  6722. _this.isFullscreen = document.msIsFullScreen;
  6723. }
  6724. // Pointer lock
  6725. if (_this.isFullscreen && _this._pointerLockRequested) {
  6726. canvas.requestPointerLock = canvas.requestPointerLock ||
  6727. canvas.msRequestPointerLock ||
  6728. canvas.mozRequestPointerLock ||
  6729. canvas.webkitRequestPointerLock;
  6730. if (canvas.requestPointerLock) {
  6731. canvas.requestPointerLock();
  6732. }
  6733. }
  6734. };
  6735. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  6736. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  6737. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  6738. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  6739. // Pointer lock
  6740. this._onPointerLockChange = function () {
  6741. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  6742. document.webkitPointerLockElement === canvas ||
  6743. document.msPointerLockElement === canvas ||
  6744. document.pointerLockElement === canvas);
  6745. };
  6746. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  6747. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  6748. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  6749. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  6750. if (BABYLON.AudioEngine && !Engine.audioEngine) {
  6751. Engine.audioEngine = new BABYLON.AudioEngine();
  6752. }
  6753. //default loading screen
  6754. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  6755. //Load WebVR Devices
  6756. if (options.autoEnableWebVR) {
  6757. this.initWebVR();
  6758. }
  6759. //Detect if we are running on a faulty buggy OS.
  6760. var regexp = /AppleWebKit.*10.[\d] Mobile/;
  6761. //ua sniffing is the tool of the devil.
  6762. this._badOS = regexp.test(navigator.userAgent);
  6763. BABYLON.Tools.Log("Babylon.js engine (v" + Engine.Version + ") launched");
  6764. }
  6765. Object.defineProperty(Engine, "NEVER", {
  6766. get: function () {
  6767. return Engine._NEVER;
  6768. },
  6769. enumerable: true,
  6770. configurable: true
  6771. });
  6772. Object.defineProperty(Engine, "ALWAYS", {
  6773. get: function () {
  6774. return Engine._ALWAYS;
  6775. },
  6776. enumerable: true,
  6777. configurable: true
  6778. });
  6779. Object.defineProperty(Engine, "LESS", {
  6780. get: function () {
  6781. return Engine._LESS;
  6782. },
  6783. enumerable: true,
  6784. configurable: true
  6785. });
  6786. Object.defineProperty(Engine, "EQUAL", {
  6787. get: function () {
  6788. return Engine._EQUAL;
  6789. },
  6790. enumerable: true,
  6791. configurable: true
  6792. });
  6793. Object.defineProperty(Engine, "LEQUAL", {
  6794. get: function () {
  6795. return Engine._LEQUAL;
  6796. },
  6797. enumerable: true,
  6798. configurable: true
  6799. });
  6800. Object.defineProperty(Engine, "GREATER", {
  6801. get: function () {
  6802. return Engine._GREATER;
  6803. },
  6804. enumerable: true,
  6805. configurable: true
  6806. });
  6807. Object.defineProperty(Engine, "GEQUAL", {
  6808. get: function () {
  6809. return Engine._GEQUAL;
  6810. },
  6811. enumerable: true,
  6812. configurable: true
  6813. });
  6814. Object.defineProperty(Engine, "NOTEQUAL", {
  6815. get: function () {
  6816. return Engine._NOTEQUAL;
  6817. },
  6818. enumerable: true,
  6819. configurable: true
  6820. });
  6821. Object.defineProperty(Engine, "KEEP", {
  6822. get: function () {
  6823. return Engine._KEEP;
  6824. },
  6825. enumerable: true,
  6826. configurable: true
  6827. });
  6828. Object.defineProperty(Engine, "REPLACE", {
  6829. get: function () {
  6830. return Engine._REPLACE;
  6831. },
  6832. enumerable: true,
  6833. configurable: true
  6834. });
  6835. Object.defineProperty(Engine, "INCR", {
  6836. get: function () {
  6837. return Engine._INCR;
  6838. },
  6839. enumerable: true,
  6840. configurable: true
  6841. });
  6842. Object.defineProperty(Engine, "DECR", {
  6843. get: function () {
  6844. return Engine._DECR;
  6845. },
  6846. enumerable: true,
  6847. configurable: true
  6848. });
  6849. Object.defineProperty(Engine, "INVERT", {
  6850. get: function () {
  6851. return Engine._INVERT;
  6852. },
  6853. enumerable: true,
  6854. configurable: true
  6855. });
  6856. Object.defineProperty(Engine, "INCR_WRAP", {
  6857. get: function () {
  6858. return Engine._INCR_WRAP;
  6859. },
  6860. enumerable: true,
  6861. configurable: true
  6862. });
  6863. Object.defineProperty(Engine, "DECR_WRAP", {
  6864. get: function () {
  6865. return Engine._DECR_WRAP;
  6866. },
  6867. enumerable: true,
  6868. configurable: true
  6869. });
  6870. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  6871. get: function () {
  6872. return Engine._ALPHA_DISABLE;
  6873. },
  6874. enumerable: true,
  6875. configurable: true
  6876. });
  6877. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  6878. get: function () {
  6879. return Engine._ALPHA_ONEONE;
  6880. },
  6881. enumerable: true,
  6882. configurable: true
  6883. });
  6884. Object.defineProperty(Engine, "ALPHA_ADD", {
  6885. get: function () {
  6886. return Engine._ALPHA_ADD;
  6887. },
  6888. enumerable: true,
  6889. configurable: true
  6890. });
  6891. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  6892. get: function () {
  6893. return Engine._ALPHA_COMBINE;
  6894. },
  6895. enumerable: true,
  6896. configurable: true
  6897. });
  6898. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  6899. get: function () {
  6900. return Engine._ALPHA_SUBTRACT;
  6901. },
  6902. enumerable: true,
  6903. configurable: true
  6904. });
  6905. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  6906. get: function () {
  6907. return Engine._ALPHA_MULTIPLY;
  6908. },
  6909. enumerable: true,
  6910. configurable: true
  6911. });
  6912. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  6913. get: function () {
  6914. return Engine._ALPHA_MAXIMIZED;
  6915. },
  6916. enumerable: true,
  6917. configurable: true
  6918. });
  6919. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED", {
  6920. get: function () {
  6921. return Engine._ALPHA_PREMULTIPLIED;
  6922. },
  6923. enumerable: true,
  6924. configurable: true
  6925. });
  6926. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  6927. get: function () {
  6928. return Engine._DELAYLOADSTATE_NONE;
  6929. },
  6930. enumerable: true,
  6931. configurable: true
  6932. });
  6933. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  6934. get: function () {
  6935. return Engine._DELAYLOADSTATE_LOADED;
  6936. },
  6937. enumerable: true,
  6938. configurable: true
  6939. });
  6940. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  6941. get: function () {
  6942. return Engine._DELAYLOADSTATE_LOADING;
  6943. },
  6944. enumerable: true,
  6945. configurable: true
  6946. });
  6947. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  6948. get: function () {
  6949. return Engine._DELAYLOADSTATE_NOTLOADED;
  6950. },
  6951. enumerable: true,
  6952. configurable: true
  6953. });
  6954. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  6955. get: function () {
  6956. return Engine._TEXTUREFORMAT_ALPHA;
  6957. },
  6958. enumerable: true,
  6959. configurable: true
  6960. });
  6961. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  6962. get: function () {
  6963. return Engine._TEXTUREFORMAT_LUMINANCE;
  6964. },
  6965. enumerable: true,
  6966. configurable: true
  6967. });
  6968. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  6969. get: function () {
  6970. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  6971. },
  6972. enumerable: true,
  6973. configurable: true
  6974. });
  6975. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  6976. get: function () {
  6977. return Engine._TEXTUREFORMAT_RGB;
  6978. },
  6979. enumerable: true,
  6980. configurable: true
  6981. });
  6982. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  6983. get: function () {
  6984. return Engine._TEXTUREFORMAT_RGBA;
  6985. },
  6986. enumerable: true,
  6987. configurable: true
  6988. });
  6989. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  6990. get: function () {
  6991. return Engine._TEXTURETYPE_UNSIGNED_INT;
  6992. },
  6993. enumerable: true,
  6994. configurable: true
  6995. });
  6996. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  6997. get: function () {
  6998. return Engine._TEXTURETYPE_FLOAT;
  6999. },
  7000. enumerable: true,
  7001. configurable: true
  7002. });
  7003. Object.defineProperty(Engine, "TEXTURETYPE_HALF_FLOAT", {
  7004. get: function () {
  7005. return Engine._TEXTURETYPE_HALF_FLOAT;
  7006. },
  7007. enumerable: true,
  7008. configurable: true
  7009. });
  7010. Object.defineProperty(Engine, "Version", {
  7011. get: function () {
  7012. return "2.6-alpha";
  7013. },
  7014. enumerable: true,
  7015. configurable: true
  7016. });
  7017. Object.defineProperty(Engine.prototype, "texturesSupported", {
  7018. get: function () {
  7019. return this._texturesSupported;
  7020. },
  7021. enumerable: true,
  7022. configurable: true
  7023. });
  7024. Object.defineProperty(Engine.prototype, "textureFormatInUse", {
  7025. get: function () {
  7026. return this._textureFormatInUse;
  7027. },
  7028. enumerable: true,
  7029. configurable: true
  7030. });
  7031. Object.defineProperty(Engine.prototype, "webGLVersion", {
  7032. get: function () {
  7033. return this._webGLVersion;
  7034. },
  7035. enumerable: true,
  7036. configurable: true
  7037. });
  7038. Object.defineProperty(Engine.prototype, "isStencilEnable", {
  7039. /**
  7040. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  7041. */
  7042. get: function () {
  7043. return this._isStencilEnable;
  7044. },
  7045. enumerable: true,
  7046. configurable: true
  7047. });
  7048. Engine.prototype._prepareWorkingCanvas = function () {
  7049. if (this._workingCanvas) {
  7050. return;
  7051. }
  7052. this._workingCanvas = document.createElement("canvas");
  7053. this._workingContext = this._workingCanvas.getContext("2d");
  7054. };
  7055. Engine.prototype.resetTextureCache = function () {
  7056. for (var index = 0; index < this._maxTextureChannels; index++) {
  7057. this._activeTexturesCache[index] = null;
  7058. }
  7059. };
  7060. Engine.prototype.getGlInfo = function () {
  7061. return {
  7062. vendor: this._glVendor,
  7063. renderer: this._glRenderer,
  7064. version: this._glVersion
  7065. };
  7066. };
  7067. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  7068. if (useScreen === void 0) { useScreen = false; }
  7069. var viewport = camera.viewport;
  7070. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  7071. };
  7072. Engine.prototype.getRenderWidth = function (useScreen) {
  7073. if (useScreen === void 0) { useScreen = false; }
  7074. if (!useScreen && this._currentRenderTarget) {
  7075. return this._currentRenderTarget._width;
  7076. }
  7077. return this._renderingCanvas.width;
  7078. };
  7079. Engine.prototype.getRenderHeight = function (useScreen) {
  7080. if (useScreen === void 0) { useScreen = false; }
  7081. if (!useScreen && this._currentRenderTarget) {
  7082. return this._currentRenderTarget._height;
  7083. }
  7084. return this._renderingCanvas.height;
  7085. };
  7086. Engine.prototype.getRenderingCanvas = function () {
  7087. return this._renderingCanvas;
  7088. };
  7089. Engine.prototype.getRenderingCanvasClientRect = function () {
  7090. return this._renderingCanvas.getBoundingClientRect();
  7091. };
  7092. Engine.prototype.setHardwareScalingLevel = function (level) {
  7093. this._hardwareScalingLevel = level;
  7094. this.resize();
  7095. };
  7096. Engine.prototype.getHardwareScalingLevel = function () {
  7097. return this._hardwareScalingLevel;
  7098. };
  7099. Engine.prototype.getLoadedTexturesCache = function () {
  7100. return this._loadedTexturesCache;
  7101. };
  7102. Engine.prototype.getCaps = function () {
  7103. return this._caps;
  7104. };
  7105. Object.defineProperty(Engine.prototype, "drawCalls", {
  7106. get: function () {
  7107. return this._drawCalls.current;
  7108. },
  7109. enumerable: true,
  7110. configurable: true
  7111. });
  7112. Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
  7113. get: function () {
  7114. return this._drawCalls;
  7115. },
  7116. enumerable: true,
  7117. configurable: true
  7118. });
  7119. Engine.prototype.getDepthFunction = function () {
  7120. return this._depthCullingState.depthFunc;
  7121. };
  7122. Engine.prototype.setDepthFunction = function (depthFunc) {
  7123. this._depthCullingState.depthFunc = depthFunc;
  7124. };
  7125. Engine.prototype.setDepthFunctionToGreater = function () {
  7126. this._depthCullingState.depthFunc = this._gl.GREATER;
  7127. };
  7128. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  7129. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  7130. };
  7131. Engine.prototype.setDepthFunctionToLess = function () {
  7132. this._depthCullingState.depthFunc = this._gl.LESS;
  7133. };
  7134. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  7135. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  7136. };
  7137. Engine.prototype.getStencilBuffer = function () {
  7138. return this._stencilState.stencilTest;
  7139. };
  7140. Engine.prototype.setStencilBuffer = function (enable) {
  7141. this._stencilState.stencilTest = enable;
  7142. };
  7143. Engine.prototype.getStencilMask = function () {
  7144. return this._stencilState.stencilMask;
  7145. };
  7146. Engine.prototype.setStencilMask = function (mask) {
  7147. this._stencilState.stencilMask = mask;
  7148. };
  7149. Engine.prototype.getStencilFunction = function () {
  7150. return this._stencilState.stencilFunc;
  7151. };
  7152. Engine.prototype.getStencilFunctionReference = function () {
  7153. return this._stencilState.stencilFuncRef;
  7154. };
  7155. Engine.prototype.getStencilFunctionMask = function () {
  7156. return this._stencilState.stencilFuncMask;
  7157. };
  7158. Engine.prototype.setStencilFunction = function (stencilFunc) {
  7159. this._stencilState.stencilFunc = stencilFunc;
  7160. };
  7161. Engine.prototype.setStencilFunctionReference = function (reference) {
  7162. this._stencilState.stencilFuncRef = reference;
  7163. };
  7164. Engine.prototype.setStencilFunctionMask = function (mask) {
  7165. this._stencilState.stencilFuncMask = mask;
  7166. };
  7167. Engine.prototype.getStencilOperationFail = function () {
  7168. return this._stencilState.stencilOpStencilFail;
  7169. };
  7170. Engine.prototype.getStencilOperationDepthFail = function () {
  7171. return this._stencilState.stencilOpDepthFail;
  7172. };
  7173. Engine.prototype.getStencilOperationPass = function () {
  7174. return this._stencilState.stencilOpStencilDepthPass;
  7175. };
  7176. Engine.prototype.setStencilOperationFail = function (operation) {
  7177. this._stencilState.stencilOpStencilFail = operation;
  7178. };
  7179. Engine.prototype.setStencilOperationDepthFail = function (operation) {
  7180. this._stencilState.stencilOpDepthFail = operation;
  7181. };
  7182. Engine.prototype.setStencilOperationPass = function (operation) {
  7183. this._stencilState.stencilOpStencilDepthPass = operation;
  7184. };
  7185. /**
  7186. * stop executing a render loop function and remove it from the execution array
  7187. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  7188. */
  7189. Engine.prototype.stopRenderLoop = function (renderFunction) {
  7190. if (!renderFunction) {
  7191. this._activeRenderLoops = [];
  7192. return;
  7193. }
  7194. var index = this._activeRenderLoops.indexOf(renderFunction);
  7195. if (index >= 0) {
  7196. this._activeRenderLoops.splice(index, 1);
  7197. }
  7198. };
  7199. Engine.prototype._renderLoop = function () {
  7200. var shouldRender = true;
  7201. if (!this.renderEvenInBackground && this._windowIsBackground) {
  7202. shouldRender = false;
  7203. }
  7204. if (shouldRender) {
  7205. // Start new frame
  7206. this.beginFrame();
  7207. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  7208. var renderFunction = this._activeRenderLoops[index];
  7209. renderFunction();
  7210. }
  7211. // Present
  7212. this.endFrame();
  7213. }
  7214. if (this._activeRenderLoops.length > 0) {
  7215. // Register new frame
  7216. BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction, this._vrDisplayEnabled);
  7217. }
  7218. else {
  7219. this._renderingQueueLaunched = false;
  7220. }
  7221. };
  7222. /**
  7223. * Register and execute a render loop. The engine can have more than one render function.
  7224. * @param {Function} renderFunction - the function to continuously execute starting the next render loop.
  7225. * @example
  7226. * engine.runRenderLoop(function () {
  7227. * scene.render()
  7228. * })
  7229. */
  7230. Engine.prototype.runRenderLoop = function (renderFunction) {
  7231. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  7232. return;
  7233. }
  7234. this._activeRenderLoops.push(renderFunction);
  7235. if (!this._renderingQueueLaunched) {
  7236. this._renderingQueueLaunched = true;
  7237. this._bindedRenderFunction = this._renderLoop.bind(this);
  7238. BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  7239. }
  7240. };
  7241. /**
  7242. * Toggle full screen mode.
  7243. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  7244. * @param {any} options - an options object to be sent to the requestFullscreen function
  7245. */
  7246. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  7247. if (this.isFullscreen) {
  7248. BABYLON.Tools.ExitFullscreen();
  7249. }
  7250. else {
  7251. this._pointerLockRequested = requestPointerLock;
  7252. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  7253. }
  7254. };
  7255. Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
  7256. if (stencil === void 0) { stencil = false; }
  7257. this.applyStates();
  7258. var mode = 0;
  7259. if (backBuffer && color) {
  7260. this._gl.clearColor(color.r, color.g, color.b, color.a);
  7261. mode |= this._gl.COLOR_BUFFER_BIT;
  7262. }
  7263. if (depth) {
  7264. this._gl.clearDepth(1.0);
  7265. mode |= this._gl.DEPTH_BUFFER_BIT;
  7266. }
  7267. if (stencil) {
  7268. this._gl.clearStencil(0);
  7269. mode |= this._gl.STENCIL_BUFFER_BIT;
  7270. }
  7271. this._gl.clear(mode);
  7272. };
  7273. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  7274. var gl = this._gl;
  7275. // Save state
  7276. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  7277. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  7278. // Change state
  7279. gl.enable(gl.SCISSOR_TEST);
  7280. gl.scissor(x, y, width, height);
  7281. // Clear
  7282. this.clear(clearColor, true, true, true);
  7283. // Restore state
  7284. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  7285. if (curScissor === true) {
  7286. gl.enable(gl.SCISSOR_TEST);
  7287. }
  7288. else {
  7289. gl.disable(gl.SCISSOR_TEST);
  7290. }
  7291. };
  7292. /**
  7293. * Set the WebGL's viewport
  7294. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  7295. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  7296. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  7297. */
  7298. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  7299. var width = requiredWidth || (navigator.isCocoonJS ? window.innerWidth : this.getRenderWidth());
  7300. var height = requiredHeight || (navigator.isCocoonJS ? window.innerHeight : this.getRenderHeight());
  7301. var x = viewport.x || 0;
  7302. var y = viewport.y || 0;
  7303. this._cachedViewport = viewport;
  7304. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  7305. };
  7306. /**
  7307. * Directly set the WebGL Viewport
  7308. * The x, y, width & height are directly passed to the WebGL call
  7309. * @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.
  7310. */
  7311. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  7312. var currentViewport = this._cachedViewport;
  7313. this._cachedViewport = null;
  7314. this._gl.viewport(x, y, width, height);
  7315. return currentViewport;
  7316. };
  7317. Engine.prototype.beginFrame = function () {
  7318. this._measureFps();
  7319. };
  7320. Engine.prototype.endFrame = function () {
  7321. //force a flush in case we are using a bad OS.
  7322. if (this._badOS) {
  7323. this.flushFramebuffer();
  7324. }
  7325. //submit frame to the vr device, if enabled
  7326. if (this._vrDisplayEnabled && this._vrDisplayEnabled.isPresenting) {
  7327. this._vrDisplayEnabled.submitFrame();
  7328. }
  7329. };
  7330. /**
  7331. * resize the view according to the canvas' size.
  7332. * @example
  7333. * window.addEventListener("resize", function () {
  7334. * engine.resize();
  7335. * });
  7336. */
  7337. Engine.prototype.resize = function () {
  7338. var width = navigator.isCocoonJS ? window.innerWidth : this._renderingCanvas.clientWidth;
  7339. var height = navigator.isCocoonJS ? window.innerHeight : this._renderingCanvas.clientHeight;
  7340. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  7341. };
  7342. /**
  7343. * force a specific size of the canvas
  7344. * @param {number} width - the new canvas' width
  7345. * @param {number} height - the new canvas' height
  7346. */
  7347. Engine.prototype.setSize = function (width, height) {
  7348. this._renderingCanvas.width = width;
  7349. this._renderingCanvas.height = height;
  7350. for (var index = 0; index < this.scenes.length; index++) {
  7351. var scene = this.scenes[index];
  7352. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  7353. var cam = scene.cameras[camIndex];
  7354. cam._currentRenderId = 0;
  7355. }
  7356. }
  7357. };
  7358. //WebVR functions
  7359. Engine.prototype.initWebVR = function () {
  7360. if (!this.vrDisplaysPromise) {
  7361. this._getVRDisplays();
  7362. }
  7363. };
  7364. Engine.prototype.enableVR = function (vrDevice) {
  7365. this._vrDisplayEnabled = vrDevice;
  7366. this._vrDisplayEnabled.requestPresent([{ source: this.getRenderingCanvas() }]).then(this._onVRFullScreenTriggered);
  7367. };
  7368. Engine.prototype.disableVR = function () {
  7369. if (this._vrDisplayEnabled) {
  7370. this._vrDisplayEnabled.exitPresent().then(this._onVRFullScreenTriggered);
  7371. }
  7372. };
  7373. Engine.prototype._getVRDisplays = function () {
  7374. var _this = this;
  7375. var getWebVRDevices = function (devices) {
  7376. var size = devices.length;
  7377. var i = 0;
  7378. _this._vrDisplays = devices.filter(function (device) {
  7379. return devices[i] instanceof VRDisplay;
  7380. });
  7381. return _this._vrDisplays;
  7382. };
  7383. //using a key due to typescript
  7384. if (navigator.getVRDisplays) {
  7385. this.vrDisplaysPromise = navigator.getVRDisplays().then(getWebVRDevices);
  7386. }
  7387. };
  7388. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight) {
  7389. this._currentRenderTarget = texture;
  7390. this.bindUnboundFramebuffer(texture._framebuffer);
  7391. var gl = this._gl;
  7392. if (texture.isCube) {
  7393. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture, 0);
  7394. }
  7395. gl.viewport(0, 0, requiredWidth || texture._width, requiredHeight || texture._height);
  7396. this.wipeCaches();
  7397. };
  7398. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  7399. if (this._currentFramebuffer !== framebuffer) {
  7400. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  7401. this._currentFramebuffer = framebuffer;
  7402. }
  7403. };
  7404. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps) {
  7405. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  7406. this._currentRenderTarget = null;
  7407. if (texture.generateMipMaps && !disableGenerateMipMaps) {
  7408. var gl = this._gl;
  7409. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  7410. gl.generateMipmap(gl.TEXTURE_2D);
  7411. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  7412. }
  7413. this.bindUnboundFramebuffer(null);
  7414. };
  7415. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  7416. if (texture.generateMipMaps) {
  7417. var gl = this._gl;
  7418. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  7419. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  7420. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  7421. }
  7422. };
  7423. Engine.prototype.flushFramebuffer = function () {
  7424. this._gl.flush();
  7425. };
  7426. Engine.prototype.restoreDefaultFramebuffer = function () {
  7427. this._currentRenderTarget = null;
  7428. this.bindUnboundFramebuffer(null);
  7429. this.setViewport(this._cachedViewport);
  7430. this.wipeCaches();
  7431. };
  7432. // VBOs
  7433. Engine.prototype._resetVertexBufferBinding = function () {
  7434. this.bindArrayBuffer(null);
  7435. this._cachedVertexBuffers = null;
  7436. };
  7437. Engine.prototype.createVertexBuffer = function (vertices) {
  7438. var vbo = this._gl.createBuffer();
  7439. this.bindArrayBuffer(vbo);
  7440. if (vertices instanceof Float32Array) {
  7441. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.STATIC_DRAW);
  7442. }
  7443. else {
  7444. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  7445. }
  7446. this._resetVertexBufferBinding();
  7447. vbo.references = 1;
  7448. return vbo;
  7449. };
  7450. Engine.prototype.createDynamicVertexBuffer = function (vertices) {
  7451. var vbo = this._gl.createBuffer();
  7452. this.bindArrayBuffer(vbo);
  7453. if (vertices instanceof Float32Array) {
  7454. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.DYNAMIC_DRAW);
  7455. }
  7456. else {
  7457. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.DYNAMIC_DRAW);
  7458. }
  7459. this._resetVertexBufferBinding();
  7460. vbo.references = 1;
  7461. return vbo;
  7462. };
  7463. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset, count) {
  7464. this.bindArrayBuffer(vertexBuffer);
  7465. if (offset === undefined) {
  7466. offset = 0;
  7467. }
  7468. if (count === undefined) {
  7469. if (vertices instanceof Float32Array) {
  7470. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  7471. }
  7472. else {
  7473. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  7474. }
  7475. }
  7476. else {
  7477. if (vertices instanceof Float32Array) {
  7478. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, vertices.subarray(offset, offset + count));
  7479. }
  7480. else {
  7481. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(vertices).subarray(offset, offset + count));
  7482. }
  7483. }
  7484. this._resetVertexBufferBinding();
  7485. };
  7486. Engine.prototype._resetIndexBufferBinding = function () {
  7487. this.bindIndexBuffer(null);
  7488. this._cachedIndexBuffer = null;
  7489. };
  7490. Engine.prototype.createIndexBuffer = function (indices) {
  7491. var vbo = this._gl.createBuffer();
  7492. this.bindIndexBuffer(vbo);
  7493. // Check for 32 bits indices
  7494. var arrayBuffer;
  7495. var need32Bits = false;
  7496. if (indices instanceof Uint16Array) {
  7497. arrayBuffer = indices;
  7498. }
  7499. else {
  7500. //check 32 bit support
  7501. if (this._caps.uintIndices) {
  7502. if (indices instanceof Uint32Array) {
  7503. arrayBuffer = indices;
  7504. need32Bits = true;
  7505. }
  7506. else {
  7507. //number[] or Int32Array, check if 32 bit is necessary
  7508. for (var index = 0; index < indices.length; index++) {
  7509. if (indices[index] > 65535) {
  7510. need32Bits = true;
  7511. break;
  7512. }
  7513. }
  7514. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  7515. }
  7516. }
  7517. else {
  7518. //no 32 bit support, force conversion to 16 bit (values greater 16 bit are lost)
  7519. arrayBuffer = new Uint16Array(indices);
  7520. }
  7521. }
  7522. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.STATIC_DRAW);
  7523. this._resetIndexBufferBinding();
  7524. vbo.references = 1;
  7525. vbo.is32Bits = need32Bits;
  7526. return vbo;
  7527. };
  7528. Engine.prototype.bindArrayBuffer = function (buffer) {
  7529. if (!this._vaoRecordInProgress) {
  7530. this._unBindVertexArrayObject();
  7531. }
  7532. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  7533. };
  7534. Engine.prototype.bindIndexBuffer = function (buffer) {
  7535. if (!this._vaoRecordInProgress) {
  7536. this._unBindVertexArrayObject();
  7537. }
  7538. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  7539. };
  7540. Engine.prototype.bindBuffer = function (buffer, target) {
  7541. if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
  7542. this._gl.bindBuffer(target, buffer);
  7543. this._currentBoundBuffer[target] = buffer;
  7544. }
  7545. };
  7546. Engine.prototype.updateArrayBuffer = function (data) {
  7547. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  7548. };
  7549. Engine.prototype.vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  7550. var pointer = this._currentBufferPointers[indx];
  7551. var changed = false;
  7552. if (!pointer) {
  7553. changed = true;
  7554. this._currentBufferPointers[indx] = { indx: indx, size: size, type: type, normalized: normalized, stride: stride, offset: offset, buffer: buffer };
  7555. }
  7556. else {
  7557. if (pointer.buffer !== buffer) {
  7558. pointer.buffer = buffer;
  7559. changed = true;
  7560. }
  7561. if (pointer.size !== size) {
  7562. pointer.size = size;
  7563. changed = true;
  7564. }
  7565. if (pointer.type !== type) {
  7566. pointer.type = type;
  7567. changed = true;
  7568. }
  7569. if (pointer.normalized !== normalized) {
  7570. pointer.normalized = normalized;
  7571. changed = true;
  7572. }
  7573. if (pointer.stride !== stride) {
  7574. pointer.stride = stride;
  7575. changed = true;
  7576. }
  7577. if (pointer.offset !== offset) {
  7578. pointer.offset = offset;
  7579. changed = true;
  7580. }
  7581. }
  7582. if (changed || this._vaoRecordInProgress) {
  7583. this.bindArrayBuffer(buffer);
  7584. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  7585. }
  7586. };
  7587. Engine.prototype._bindIndexBufferWithCache = function (indexBuffer) {
  7588. if (indexBuffer == null) {
  7589. return;
  7590. }
  7591. if (this._cachedIndexBuffer !== indexBuffer) {
  7592. this._cachedIndexBuffer = indexBuffer;
  7593. this.bindIndexBuffer(indexBuffer);
  7594. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  7595. }
  7596. };
  7597. Engine.prototype._bindVertexBuffersAttributes = function (vertexBuffers, effect) {
  7598. var attributes = effect.getAttributesNames();
  7599. if (!this._vaoRecordInProgress) {
  7600. this._unBindVertexArrayObject();
  7601. }
  7602. this.unbindAllAttributes();
  7603. for (var index = 0; index < attributes.length; index++) {
  7604. var order = effect.getAttributeLocation(index);
  7605. if (order >= 0) {
  7606. var vertexBuffer = vertexBuffers[attributes[index]];
  7607. if (!vertexBuffer) {
  7608. continue;
  7609. }
  7610. this._gl.enableVertexAttribArray(order);
  7611. if (!this._vaoRecordInProgress) {
  7612. this._vertexAttribArraysEnabled[order] = true;
  7613. }
  7614. var buffer = vertexBuffer.getBuffer();
  7615. this.vertexAttribPointer(buffer, order, vertexBuffer.getSize(), this._gl.FLOAT, false, vertexBuffer.getStrideSize() * 4, vertexBuffer.getOffset() * 4);
  7616. if (vertexBuffer.getIsInstanced()) {
  7617. this._gl.vertexAttribDivisor(order, 1);
  7618. if (!this._vaoRecordInProgress) {
  7619. this._currentInstanceLocations.push(order);
  7620. this._currentInstanceBuffers.push(buffer);
  7621. }
  7622. }
  7623. }
  7624. }
  7625. };
  7626. Engine.prototype.recordVertexArrayObject = function (vertexBuffers, indexBuffer, effect) {
  7627. var vao = this._gl.createVertexArray();
  7628. this._vaoRecordInProgress = true;
  7629. this._gl.bindVertexArray(vao);
  7630. this._mustWipeVertexAttributes = true;
  7631. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  7632. this.bindIndexBuffer(indexBuffer);
  7633. this._vaoRecordInProgress = false;
  7634. this._gl.bindVertexArray(null);
  7635. return vao;
  7636. };
  7637. Engine.prototype.bindVertexArrayObject = function (vertexArrayObject, indexBuffer) {
  7638. if (this._cachedVertexArrayObject !== vertexArrayObject) {
  7639. this._cachedVertexArrayObject = vertexArrayObject;
  7640. this._gl.bindVertexArray(vertexArrayObject);
  7641. this._cachedVertexBuffers = null;
  7642. this._cachedIndexBuffer = null;
  7643. this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
  7644. this._mustWipeVertexAttributes = true;
  7645. }
  7646. };
  7647. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  7648. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  7649. this._cachedVertexBuffers = vertexBuffer;
  7650. this._cachedEffectForVertexBuffers = effect;
  7651. var attributesCount = effect.getAttributesCount();
  7652. this._unBindVertexArrayObject();
  7653. this.unbindAllAttributes();
  7654. var offset = 0;
  7655. for (var index = 0; index < attributesCount; index++) {
  7656. if (index < vertexDeclaration.length) {
  7657. var order = effect.getAttributeLocation(index);
  7658. if (order >= 0) {
  7659. this._gl.enableVertexAttribArray(order);
  7660. this._vertexAttribArraysEnabled[order] = true;
  7661. this.vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  7662. }
  7663. offset += vertexDeclaration[index] * 4;
  7664. }
  7665. }
  7666. }
  7667. this._bindIndexBufferWithCache(indexBuffer);
  7668. };
  7669. Engine.prototype._unBindVertexArrayObject = function () {
  7670. if (!this._cachedVertexArrayObject) {
  7671. return;
  7672. }
  7673. this._cachedVertexArrayObject = null;
  7674. this._gl.bindVertexArray(null);
  7675. };
  7676. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  7677. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  7678. this._cachedVertexBuffers = vertexBuffers;
  7679. this._cachedEffectForVertexBuffers = effect;
  7680. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  7681. }
  7682. this._bindIndexBufferWithCache(indexBuffer);
  7683. };
  7684. Engine.prototype.unbindInstanceAttributes = function () {
  7685. var boundBuffer;
  7686. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  7687. var instancesBuffer = this._currentInstanceBuffers[i];
  7688. if (boundBuffer != instancesBuffer) {
  7689. boundBuffer = instancesBuffer;
  7690. this.bindArrayBuffer(instancesBuffer);
  7691. }
  7692. var offsetLocation = this._currentInstanceLocations[i];
  7693. this._gl.vertexAttribDivisor(offsetLocation, 0);
  7694. }
  7695. this._currentInstanceBuffers.length = 0;
  7696. this._currentInstanceLocations.length = 0;
  7697. };
  7698. Engine.prototype.releaseVertexArrayObject = function (vao) {
  7699. this._gl.deleteVertexArray(vao);
  7700. };
  7701. Engine.prototype._releaseBuffer = function (buffer) {
  7702. buffer.references--;
  7703. if (buffer.references === 0) {
  7704. this._gl.deleteBuffer(buffer);
  7705. return true;
  7706. }
  7707. return false;
  7708. };
  7709. Engine.prototype.createInstancesBuffer = function (capacity) {
  7710. var buffer = this._gl.createBuffer();
  7711. buffer.capacity = capacity;
  7712. this.bindArrayBuffer(buffer);
  7713. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  7714. return buffer;
  7715. };
  7716. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  7717. this._gl.deleteBuffer(buffer);
  7718. };
  7719. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  7720. this.bindArrayBuffer(instancesBuffer);
  7721. if (data) {
  7722. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  7723. }
  7724. if (offsetLocations[0].index !== undefined) {
  7725. var stride = 0;
  7726. for (var i = 0; i < offsetLocations.length; i++) {
  7727. var ai = offsetLocations[i];
  7728. stride += ai.attributeSize * 4;
  7729. }
  7730. for (var i = 0; i < offsetLocations.length; i++) {
  7731. var ai = offsetLocations[i];
  7732. if (!this._vertexAttribArraysEnabled[ai.index]) {
  7733. this._gl.enableVertexAttribArray(ai.index);
  7734. this._vertexAttribArraysEnabled[ai.index] = true;
  7735. }
  7736. this.vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  7737. this._gl.vertexAttribDivisor(ai.index, 1);
  7738. this._currentInstanceLocations.push(ai.index);
  7739. this._currentInstanceBuffers.push(instancesBuffer);
  7740. }
  7741. }
  7742. else {
  7743. for (var index = 0; index < 4; index++) {
  7744. var offsetLocation = offsetLocations[index];
  7745. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  7746. this._gl.enableVertexAttribArray(offsetLocation);
  7747. this._vertexAttribArraysEnabled[offsetLocation] = true;
  7748. }
  7749. this.vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  7750. this._gl.vertexAttribDivisor(offsetLocation, 1);
  7751. this._currentInstanceLocations.push(offsetLocation);
  7752. this._currentInstanceBuffers.push(instancesBuffer);
  7753. }
  7754. }
  7755. };
  7756. Engine.prototype.applyStates = function () {
  7757. this._depthCullingState.apply(this._gl);
  7758. this._stencilState.apply(this._gl);
  7759. this._alphaState.apply(this._gl);
  7760. };
  7761. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  7762. // Apply states
  7763. this.applyStates();
  7764. this._drawCalls.addCount(1, false);
  7765. // Render
  7766. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  7767. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  7768. if (instancesCount) {
  7769. this._gl.drawElementsInstanced(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult, instancesCount);
  7770. return;
  7771. }
  7772. this._gl.drawElements(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult);
  7773. };
  7774. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  7775. // Apply states
  7776. this.applyStates();
  7777. this._drawCalls.addCount(1, false);
  7778. if (instancesCount) {
  7779. this._gl.drawArraysInstanced(this._gl.POINTS, verticesStart, verticesCount, instancesCount);
  7780. return;
  7781. }
  7782. this._gl.drawArrays(this._gl.POINTS, verticesStart, verticesCount);
  7783. };
  7784. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  7785. // Apply states
  7786. this.applyStates();
  7787. this._drawCalls.addCount(1, false);
  7788. if (instancesCount) {
  7789. this._gl.drawArraysInstanced(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount, instancesCount);
  7790. return;
  7791. }
  7792. this._gl.drawArrays(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount);
  7793. };
  7794. // Shaders
  7795. Engine.prototype._releaseEffect = function (effect) {
  7796. if (this._compiledEffects[effect._key]) {
  7797. delete this._compiledEffects[effect._key];
  7798. if (effect.getProgram()) {
  7799. this._gl.deleteProgram(effect.getProgram());
  7800. }
  7801. }
  7802. };
  7803. Engine.prototype.createEffect = function (baseName, attributesNames, uniformsNames, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  7804. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  7805. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  7806. var name = vertex + "+" + fragment + "@" + defines;
  7807. if (this._compiledEffects[name]) {
  7808. return this._compiledEffects[name];
  7809. }
  7810. var effect = new BABYLON.Effect(baseName, attributesNames, uniformsNames, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  7811. effect._key = name;
  7812. this._compiledEffects[name] = effect;
  7813. return effect;
  7814. };
  7815. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  7816. if (uniformsNames === void 0) { uniformsNames = []; }
  7817. if (samplers === void 0) { samplers = []; }
  7818. if (defines === void 0) { defines = ""; }
  7819. return this.createEffect({
  7820. vertex: "particles",
  7821. fragmentElement: fragmentName
  7822. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  7823. };
  7824. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context) {
  7825. context = context || this._gl;
  7826. var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n" : "";
  7827. var vertexShader = compileShader(context, vertexCode, "vertex", defines, shaderVersion);
  7828. var fragmentShader = compileShader(context, fragmentCode, "fragment", defines, shaderVersion);
  7829. var shaderProgram = context.createProgram();
  7830. context.attachShader(shaderProgram, vertexShader);
  7831. context.attachShader(shaderProgram, fragmentShader);
  7832. context.linkProgram(shaderProgram);
  7833. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  7834. if (!linked) {
  7835. var error = context.getProgramInfoLog(shaderProgram);
  7836. if (error) {
  7837. throw new Error(error);
  7838. }
  7839. }
  7840. context.deleteShader(vertexShader);
  7841. context.deleteShader(fragmentShader);
  7842. return shaderProgram;
  7843. };
  7844. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  7845. var results = [];
  7846. for (var index = 0; index < uniformsNames.length; index++) {
  7847. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  7848. }
  7849. return results;
  7850. };
  7851. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  7852. var results = [];
  7853. for (var index = 0; index < attributesNames.length; index++) {
  7854. try {
  7855. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  7856. }
  7857. catch (e) {
  7858. results.push(-1);
  7859. }
  7860. }
  7861. return results;
  7862. };
  7863. Engine.prototype.enableEffect = function (effect) {
  7864. // Use program
  7865. this.setProgram(effect.getProgram());
  7866. this._currentEffect = effect;
  7867. if (effect.onBind) {
  7868. effect.onBind(effect);
  7869. }
  7870. };
  7871. Engine.prototype.setIntArray = function (uniform, array) {
  7872. if (!uniform)
  7873. return;
  7874. this._gl.uniform1iv(uniform, array);
  7875. };
  7876. Engine.prototype.setIntArray2 = function (uniform, array) {
  7877. if (!uniform || array.length % 2 !== 0)
  7878. return;
  7879. this._gl.uniform2iv(uniform, array);
  7880. };
  7881. Engine.prototype.setIntArray3 = function (uniform, array) {
  7882. if (!uniform || array.length % 3 !== 0)
  7883. return;
  7884. this._gl.uniform3iv(uniform, array);
  7885. };
  7886. Engine.prototype.setIntArray4 = function (uniform, array) {
  7887. if (!uniform || array.length % 4 !== 0)
  7888. return;
  7889. this._gl.uniform4iv(uniform, array);
  7890. };
  7891. Engine.prototype.setFloatArray = function (uniform, array) {
  7892. if (!uniform)
  7893. return;
  7894. this._gl.uniform1fv(uniform, array);
  7895. };
  7896. Engine.prototype.setFloatArray2 = function (uniform, array) {
  7897. if (!uniform || array.length % 2 !== 0)
  7898. return;
  7899. this._gl.uniform2fv(uniform, array);
  7900. };
  7901. Engine.prototype.setFloatArray3 = function (uniform, array) {
  7902. if (!uniform || array.length % 3 !== 0)
  7903. return;
  7904. this._gl.uniform3fv(uniform, array);
  7905. };
  7906. Engine.prototype.setFloatArray4 = function (uniform, array) {
  7907. if (!uniform || array.length % 4 !== 0)
  7908. return;
  7909. this._gl.uniform4fv(uniform, array);
  7910. };
  7911. Engine.prototype.setArray = function (uniform, array) {
  7912. if (!uniform)
  7913. return;
  7914. this._gl.uniform1fv(uniform, array);
  7915. };
  7916. Engine.prototype.setArray2 = function (uniform, array) {
  7917. if (!uniform || array.length % 2 !== 0)
  7918. return;
  7919. this._gl.uniform2fv(uniform, array);
  7920. };
  7921. Engine.prototype.setArray3 = function (uniform, array) {
  7922. if (!uniform || array.length % 3 !== 0)
  7923. return;
  7924. this._gl.uniform3fv(uniform, array);
  7925. };
  7926. Engine.prototype.setArray4 = function (uniform, array) {
  7927. if (!uniform || array.length % 4 !== 0)
  7928. return;
  7929. this._gl.uniform4fv(uniform, array);
  7930. };
  7931. Engine.prototype.setMatrices = function (uniform, matrices) {
  7932. if (!uniform)
  7933. return;
  7934. this._gl.uniformMatrix4fv(uniform, false, matrices);
  7935. };
  7936. Engine.prototype.setMatrix = function (uniform, matrix) {
  7937. if (!uniform)
  7938. return;
  7939. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  7940. };
  7941. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  7942. if (!uniform)
  7943. return;
  7944. this._gl.uniformMatrix3fv(uniform, false, matrix);
  7945. };
  7946. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  7947. if (!uniform)
  7948. return;
  7949. this._gl.uniformMatrix2fv(uniform, false, matrix);
  7950. };
  7951. Engine.prototype.setFloat = function (uniform, value) {
  7952. if (!uniform)
  7953. return;
  7954. this._gl.uniform1f(uniform, value);
  7955. };
  7956. Engine.prototype.setFloat2 = function (uniform, x, y) {
  7957. if (!uniform)
  7958. return;
  7959. this._gl.uniform2f(uniform, x, y);
  7960. };
  7961. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  7962. if (!uniform)
  7963. return;
  7964. this._gl.uniform3f(uniform, x, y, z);
  7965. };
  7966. Engine.prototype.setBool = function (uniform, bool) {
  7967. if (!uniform)
  7968. return;
  7969. this._gl.uniform1i(uniform, bool);
  7970. };
  7971. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  7972. if (!uniform)
  7973. return;
  7974. this._gl.uniform4f(uniform, x, y, z, w);
  7975. };
  7976. Engine.prototype.setColor3 = function (uniform, color3) {
  7977. if (!uniform)
  7978. return;
  7979. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  7980. };
  7981. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  7982. if (!uniform)
  7983. return;
  7984. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  7985. };
  7986. // States
  7987. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  7988. if (zOffset === void 0) { zOffset = 0; }
  7989. if (reverseSide === void 0) { reverseSide = false; }
  7990. // Culling
  7991. var showSide = reverseSide ? this._gl.FRONT : this._gl.BACK;
  7992. var hideSide = reverseSide ? this._gl.BACK : this._gl.FRONT;
  7993. var cullFace = this.cullBackFaces ? showSide : hideSide;
  7994. if (this._depthCullingState.cull !== culling || force || this._depthCullingState.cullFace !== cullFace) {
  7995. if (culling) {
  7996. this._depthCullingState.cullFace = cullFace;
  7997. this._depthCullingState.cull = true;
  7998. }
  7999. else {
  8000. this._depthCullingState.cull = false;
  8001. }
  8002. }
  8003. // Z offset
  8004. this._depthCullingState.zOffset = zOffset;
  8005. };
  8006. Engine.prototype.setDepthBuffer = function (enable) {
  8007. this._depthCullingState.depthTest = enable;
  8008. };
  8009. Engine.prototype.getDepthWrite = function () {
  8010. return this._depthCullingState.depthMask;
  8011. };
  8012. Engine.prototype.setDepthWrite = function (enable) {
  8013. this._depthCullingState.depthMask = enable;
  8014. };
  8015. Engine.prototype.setColorWrite = function (enable) {
  8016. this._gl.colorMask(enable, enable, enable, enable);
  8017. };
  8018. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  8019. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  8020. if (this._alphaMode === mode) {
  8021. return;
  8022. }
  8023. switch (mode) {
  8024. case Engine.ALPHA_DISABLE:
  8025. this._alphaState.alphaBlend = false;
  8026. break;
  8027. case Engine.ALPHA_PREMULTIPLIED:
  8028. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  8029. this._alphaState.alphaBlend = true;
  8030. break;
  8031. case Engine.ALPHA_COMBINE:
  8032. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  8033. this._alphaState.alphaBlend = true;
  8034. break;
  8035. case Engine.ALPHA_ONEONE:
  8036. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  8037. this._alphaState.alphaBlend = true;
  8038. break;
  8039. case Engine.ALPHA_ADD:
  8040. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  8041. this._alphaState.alphaBlend = true;
  8042. break;
  8043. case Engine.ALPHA_SUBTRACT:
  8044. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  8045. this._alphaState.alphaBlend = true;
  8046. break;
  8047. case Engine.ALPHA_MULTIPLY:
  8048. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  8049. this._alphaState.alphaBlend = true;
  8050. break;
  8051. case Engine.ALPHA_MAXIMIZED:
  8052. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  8053. this._alphaState.alphaBlend = true;
  8054. break;
  8055. }
  8056. if (!noDepthWriteChange) {
  8057. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  8058. }
  8059. this._alphaMode = mode;
  8060. };
  8061. Engine.prototype.getAlphaMode = function () {
  8062. return this._alphaMode;
  8063. };
  8064. Engine.prototype.setAlphaTesting = function (enable) {
  8065. this._alphaTest = enable;
  8066. };
  8067. Engine.prototype.getAlphaTesting = function () {
  8068. return this._alphaTest;
  8069. };
  8070. // Textures
  8071. Engine.prototype.wipeCaches = function () {
  8072. this.resetTextureCache();
  8073. this._currentEffect = null;
  8074. this._stencilState.reset();
  8075. this._depthCullingState.reset();
  8076. this.setDepthFunctionToLessOrEqual();
  8077. this._alphaState.reset();
  8078. this._cachedVertexBuffers = null;
  8079. this._cachedIndexBuffer = null;
  8080. this._cachedEffectForVertexBuffers = null;
  8081. this._unBindVertexArrayObject();
  8082. this.bindIndexBuffer(null);
  8083. this.bindArrayBuffer(null);
  8084. };
  8085. /**
  8086. * Set the compressed texture format to use, based on the formats you have, and the formats
  8087. * supported by the hardware / browser.
  8088. *
  8089. * Khronos Texture Container (.ktx) files are used to support this. This format has the
  8090. * advantage of being specifically designed for OpenGL. Header elements directly correspond
  8091. * to API arguments needed to compressed textures. This puts the burden on the container
  8092. * generator to house the arcane code for determining these for current & future formats.
  8093. *
  8094. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  8095. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  8096. *
  8097. * Note: The result of this call is not taken into account when a texture is base64.
  8098. *
  8099. * @param {Array<string>} formatsAvailable- The list of those format families you have created
  8100. * on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.)
  8101. *
  8102. * Current families are astc, dxt, pvrtc, etc2, atc, & etc1.
  8103. * @returns The extension selected.
  8104. */
  8105. Engine.prototype.setTextureFormatToUse = function (formatsAvailable) {
  8106. for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
  8107. for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
  8108. if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
  8109. return this._textureFormatInUse = this._texturesSupported[i];
  8110. }
  8111. }
  8112. }
  8113. // actively set format to nothing, to allow this to be called more than once
  8114. // and possibly fail the 2nd time
  8115. return this._textureFormatInUse = null;
  8116. };
  8117. Engine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack) {
  8118. var _this = this;
  8119. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  8120. if (onLoad === void 0) { onLoad = null; }
  8121. if (onError === void 0) { onError = null; }
  8122. if (buffer === void 0) { buffer = null; }
  8123. var texture = fallBack ? fallBack : this._gl.createTexture();
  8124. var extension;
  8125. var isKTX = false;
  8126. var fromData = false;
  8127. var url = String(urlArg);
  8128. if (url.substr(0, 5) === "data:") {
  8129. fromData = true;
  8130. }
  8131. if (!fromData) {
  8132. var lastDot = url.lastIndexOf('.');
  8133. extension = url.substring(lastDot).toLowerCase();
  8134. if (this._textureFormatInUse && !fromData && !fallBack) {
  8135. extension = this._textureFormatInUse;
  8136. url = url.substring(0, lastDot) + this._textureFormatInUse;
  8137. isKTX = true;
  8138. }
  8139. }
  8140. else {
  8141. var oldUrl = url;
  8142. fromData = oldUrl.split(':');
  8143. url = oldUrl;
  8144. extension = fromData[1].substr(fromData[1].length - 4, 4).toLowerCase();
  8145. }
  8146. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  8147. var isTGA = (extension === ".tga");
  8148. scene._addPendingData(texture);
  8149. texture.url = url;
  8150. texture.noMipmap = noMipmap;
  8151. texture.references = 1;
  8152. texture.samplingMode = samplingMode;
  8153. texture.onLoadedCallbacks = [];
  8154. if (onLoad) {
  8155. texture.onLoadedCallbacks.push(onLoad);
  8156. }
  8157. if (!fallBack)
  8158. this._loadedTexturesCache.push(texture);
  8159. var onerror = function () {
  8160. scene._removePendingData(texture);
  8161. // fallback for when compressed file not found to try again. For instance, etc1 does not have an alpha capable type
  8162. if (isKTX) {
  8163. _this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, texture);
  8164. }
  8165. else if (onError) {
  8166. onError();
  8167. }
  8168. };
  8169. var callback;
  8170. if (isKTX || isTGA || isDDS) {
  8171. if (isKTX) {
  8172. callback = function (data) {
  8173. var ktx = new BABYLON.Internals.KhronosTextureContainer(data, 1);
  8174. prepareWebGLTexture(texture, _this._gl, scene, ktx.pixelWidth, ktx.pixelHeight, invertY, false, true, function () {
  8175. ktx.uploadLevels(_this._gl, !noMipmap);
  8176. }, samplingMode);
  8177. };
  8178. }
  8179. else if (isTGA) {
  8180. callback = function (arrayBuffer) {
  8181. var data = new Uint8Array(arrayBuffer);
  8182. var header = BABYLON.Internals.TGATools.GetTGAHeader(data);
  8183. prepareWebGLTexture(texture, _this._gl, scene, header.width, header.height, invertY, noMipmap, false, function () {
  8184. BABYLON.Internals.TGATools.UploadContent(_this._gl, data);
  8185. }, samplingMode);
  8186. };
  8187. }
  8188. else if (isDDS) {
  8189. callback = function (data) {
  8190. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  8191. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  8192. prepareWebGLTexture(texture, _this._gl, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  8193. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 1);
  8194. }, samplingMode);
  8195. };
  8196. }
  8197. if (!(fromData instanceof Array))
  8198. BABYLON.Tools.LoadFile(url, function (data) {
  8199. callback(data);
  8200. }, null, scene.database, true, onerror);
  8201. else
  8202. callback(buffer);
  8203. }
  8204. else {
  8205. var onload = function (img) {
  8206. prepareWebGLTexture(texture, _this._gl, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight) {
  8207. var isPot = (img.width === potWidth && img.height === potHeight);
  8208. if (!isPot) {
  8209. _this._prepareWorkingCanvas();
  8210. _this._workingCanvas.width = potWidth;
  8211. _this._workingCanvas.height = potHeight;
  8212. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  8213. _this._workingContext.imageSmoothingEnabled = false;
  8214. _this._workingContext.mozImageSmoothingEnabled = false;
  8215. _this._workingContext.oImageSmoothingEnabled = false;
  8216. _this._workingContext.webkitImageSmoothingEnabled = false;
  8217. _this._workingContext.msImageSmoothingEnabled = false;
  8218. }
  8219. _this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  8220. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  8221. _this._workingContext.imageSmoothingEnabled = true;
  8222. _this._workingContext.mozImageSmoothingEnabled = true;
  8223. _this._workingContext.oImageSmoothingEnabled = true;
  8224. _this._workingContext.webkitImageSmoothingEnabled = true;
  8225. _this._workingContext.msImageSmoothingEnabled = true;
  8226. }
  8227. }
  8228. _this._gl.texImage2D(_this._gl.TEXTURE_2D, 0, _this._gl.RGBA, _this._gl.RGBA, _this._gl.UNSIGNED_BYTE, isPot ? img : _this._workingCanvas);
  8229. }, samplingMode);
  8230. };
  8231. if (!(fromData instanceof Array))
  8232. BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  8233. else
  8234. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene.database);
  8235. }
  8236. return texture;
  8237. };
  8238. Engine.prototype._getInternalFormat = function (format) {
  8239. var internalFormat = this._gl.RGBA;
  8240. switch (format) {
  8241. case Engine.TEXTUREFORMAT_ALPHA:
  8242. internalFormat = this._gl.ALPHA;
  8243. break;
  8244. case Engine.TEXTUREFORMAT_LUMINANCE:
  8245. internalFormat = this._gl.LUMINANCE;
  8246. break;
  8247. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  8248. internalFormat = this._gl.LUMINANCE_ALPHA;
  8249. break;
  8250. case Engine.TEXTUREFORMAT_RGB:
  8251. internalFormat = this._gl.RGB;
  8252. break;
  8253. case Engine.TEXTUREFORMAT_RGBA:
  8254. internalFormat = this._gl.RGBA;
  8255. break;
  8256. }
  8257. return internalFormat;
  8258. };
  8259. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression) {
  8260. if (compression === void 0) { compression = null; }
  8261. var internalFormat = this._getInternalFormat(format);
  8262. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  8263. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  8264. if (texture._width % 4 !== 0) {
  8265. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  8266. }
  8267. if (compression) {
  8268. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture._width, texture._height, 0, data);
  8269. }
  8270. else {
  8271. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, texture._width, texture._height, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  8272. }
  8273. if (texture.generateMipMaps) {
  8274. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  8275. }
  8276. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  8277. this.resetTextureCache();
  8278. texture.isReady = true;
  8279. };
  8280. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression) {
  8281. if (compression === void 0) { compression = null; }
  8282. var texture = this._gl.createTexture();
  8283. texture._baseWidth = width;
  8284. texture._baseHeight = height;
  8285. texture._width = width;
  8286. texture._height = height;
  8287. texture.references = 1;
  8288. this.updateRawTexture(texture, data, format, invertY, compression);
  8289. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  8290. // Filters
  8291. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  8292. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  8293. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  8294. if (generateMipMaps) {
  8295. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  8296. }
  8297. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  8298. texture.samplingMode = samplingMode;
  8299. this._loadedTexturesCache.push(texture);
  8300. return texture;
  8301. };
  8302. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  8303. var texture = this._gl.createTexture();
  8304. texture._baseWidth = width;
  8305. texture._baseHeight = height;
  8306. if (generateMipMaps) {
  8307. width = BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize);
  8308. height = BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize);
  8309. }
  8310. this.resetTextureCache();
  8311. texture._width = width;
  8312. texture._height = height;
  8313. texture.isReady = false;
  8314. texture.generateMipMaps = generateMipMaps;
  8315. texture.references = 1;
  8316. texture.samplingMode = samplingMode;
  8317. this.updateTextureSamplingMode(samplingMode, texture);
  8318. this._loadedTexturesCache.push(texture);
  8319. return texture;
  8320. };
  8321. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  8322. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  8323. if (texture.isCube) {
  8324. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture);
  8325. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  8326. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  8327. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  8328. }
  8329. else {
  8330. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  8331. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  8332. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  8333. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  8334. }
  8335. texture.samplingMode = samplingMode;
  8336. };
  8337. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha) {
  8338. if (premulAlpha === void 0) { premulAlpha = false; }
  8339. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  8340. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  8341. if (premulAlpha) {
  8342. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  8343. }
  8344. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, canvas);
  8345. if (texture.generateMipMaps) {
  8346. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  8347. }
  8348. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  8349. if (premulAlpha) {
  8350. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  8351. }
  8352. this.resetTextureCache();
  8353. texture.isReady = true;
  8354. };
  8355. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  8356. if (texture._isDisabled) {
  8357. return;
  8358. }
  8359. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  8360. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  8361. try {
  8362. // Testing video texture support
  8363. if (this._videoTextureSupported === undefined) {
  8364. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  8365. if (this._gl.getError() !== 0) {
  8366. this._videoTextureSupported = false;
  8367. }
  8368. else {
  8369. this._videoTextureSupported = true;
  8370. }
  8371. }
  8372. // Copy video through the current working canvas if video texture is not supported
  8373. if (!this._videoTextureSupported) {
  8374. if (!texture._workingCanvas) {
  8375. texture._workingCanvas = document.createElement("canvas");
  8376. texture._workingContext = texture._workingCanvas.getContext("2d");
  8377. texture._workingCanvas.width = texture._width;
  8378. texture._workingCanvas.height = texture._height;
  8379. }
  8380. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture._width, texture._height);
  8381. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  8382. }
  8383. else {
  8384. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  8385. }
  8386. if (texture.generateMipMaps) {
  8387. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  8388. }
  8389. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  8390. this.resetTextureCache();
  8391. texture.isReady = true;
  8392. }
  8393. catch (ex) {
  8394. // Something unexpected
  8395. // Let's disable the texture
  8396. texture._isDisabled = true;
  8397. }
  8398. };
  8399. Engine.prototype.createRenderTargetTexture = function (size, options) {
  8400. // old version had a "generateMipMaps" arg instead of options.
  8401. // if options.generateMipMaps is undefined, consider that options itself if the generateMipmaps value
  8402. // in the same way, generateDepthBuffer is defaulted to true
  8403. var generateMipMaps = false;
  8404. var generateDepthBuffer = true;
  8405. var generateStencilBuffer = false;
  8406. var type = Engine.TEXTURETYPE_UNSIGNED_INT;
  8407. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  8408. if (options !== undefined) {
  8409. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipMaps;
  8410. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  8411. generateStencilBuffer = generateDepthBuffer && options.generateStencilBuffer;
  8412. type = options.type === undefined ? type : options.type;
  8413. if (options.samplingMode !== undefined) {
  8414. samplingMode = options.samplingMode;
  8415. }
  8416. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  8417. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  8418. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  8419. }
  8420. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  8421. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  8422. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  8423. }
  8424. }
  8425. var gl = this._gl;
  8426. var texture = gl.createTexture();
  8427. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  8428. var width = size.width || size;
  8429. var height = size.height || size;
  8430. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  8431. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  8432. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  8433. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  8434. }
  8435. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  8436. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  8437. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  8438. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  8439. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  8440. var depthStencilBuffer;
  8441. // Create the depth/stencil buffer
  8442. if (generateStencilBuffer) {
  8443. depthStencilBuffer = gl.createRenderbuffer();
  8444. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  8445. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  8446. }
  8447. else if (generateDepthBuffer) {
  8448. depthStencilBuffer = gl.createRenderbuffer();
  8449. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  8450. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  8451. }
  8452. // Create the framebuffer
  8453. var framebuffer = gl.createFramebuffer();
  8454. this.bindUnboundFramebuffer(framebuffer);
  8455. // Manage attachments
  8456. if (generateStencilBuffer) {
  8457. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  8458. }
  8459. else if (generateDepthBuffer) {
  8460. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  8461. }
  8462. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  8463. if (generateMipMaps) {
  8464. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  8465. }
  8466. // Unbind
  8467. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  8468. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  8469. this.bindUnboundFramebuffer(null);
  8470. texture._framebuffer = framebuffer;
  8471. if (generateDepthBuffer) {
  8472. texture._depthBuffer = depthStencilBuffer;
  8473. }
  8474. texture._baseWidth = width;
  8475. texture._baseHeight = height;
  8476. texture._width = width;
  8477. texture._height = height;
  8478. texture.isReady = true;
  8479. texture.generateMipMaps = generateMipMaps;
  8480. texture.references = 1;
  8481. texture.samplingMode = samplingMode;
  8482. texture.type = type;
  8483. this.resetTextureCache();
  8484. this._loadedTexturesCache.push(texture);
  8485. return texture;
  8486. };
  8487. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  8488. var gl = this._gl;
  8489. var texture = gl.createTexture();
  8490. var generateMipMaps = true;
  8491. var generateDepthBuffer = true;
  8492. var generateStencilBuffer = false;
  8493. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  8494. if (options !== undefined) {
  8495. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipMaps;
  8496. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  8497. generateStencilBuffer = generateDepthBuffer && options.generateStencilBuffer;
  8498. if (options.samplingMode !== undefined) {
  8499. samplingMode = options.samplingMode;
  8500. }
  8501. }
  8502. texture.isCube = true;
  8503. texture.references = 1;
  8504. texture.generateMipMaps = generateMipMaps;
  8505. texture.references = 1;
  8506. texture.samplingMode = samplingMode;
  8507. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  8508. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  8509. for (var face = 0; face < 6; face++) {
  8510. gl.texImage2D((gl.TEXTURE_CUBE_MAP_POSITIVE_X + face), 0, gl.RGBA, size, size, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
  8511. }
  8512. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  8513. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  8514. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  8515. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  8516. // Create the depth buffer
  8517. var depthStencilBuffer;
  8518. // Create the depth/stencil buffer
  8519. if (generateStencilBuffer) {
  8520. depthStencilBuffer = gl.createRenderbuffer();
  8521. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  8522. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, size, size);
  8523. }
  8524. else if (generateDepthBuffer) {
  8525. depthStencilBuffer = gl.createRenderbuffer();
  8526. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  8527. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, size, size);
  8528. }
  8529. // Create the framebuffer
  8530. var framebuffer = gl.createFramebuffer();
  8531. this.bindUnboundFramebuffer(framebuffer);
  8532. // Manage attachments
  8533. if (generateStencilBuffer) {
  8534. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  8535. }
  8536. else if (generateDepthBuffer) {
  8537. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  8538. }
  8539. // Mipmaps
  8540. if (texture.generateMipMaps) {
  8541. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  8542. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  8543. }
  8544. // Unbind
  8545. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  8546. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  8547. this.bindUnboundFramebuffer(null);
  8548. texture._framebuffer = framebuffer;
  8549. if (generateDepthBuffer) {
  8550. texture._depthBuffer = depthStencilBuffer;
  8551. }
  8552. texture._width = size;
  8553. texture._height = size;
  8554. texture.isReady = true;
  8555. this.resetTextureCache();
  8556. this._loadedTexturesCache.push(texture);
  8557. return texture;
  8558. };
  8559. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError) {
  8560. var _this = this;
  8561. if (onLoad === void 0) { onLoad = null; }
  8562. if (onError === void 0) { onError = null; }
  8563. var gl = this._gl;
  8564. var texture = gl.createTexture();
  8565. texture.isCube = true;
  8566. texture.url = rootUrl;
  8567. texture.references = 1;
  8568. texture.onLoadedCallbacks = [];
  8569. var isKTX = false;
  8570. var lastDot = rootUrl.lastIndexOf('.');
  8571. var extension = rootUrl.substring(lastDot).toLowerCase();
  8572. if (this._textureFormatInUse) {
  8573. extension = this._textureFormatInUse;
  8574. rootUrl = rootUrl.substring(0, lastDot) + this._textureFormatInUse;
  8575. isKTX = true;
  8576. }
  8577. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  8578. if (isKTX) {
  8579. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  8580. var ktx = new BABYLON.Internals.KhronosTextureContainer(data, 6);
  8581. var loadMipmap = ktx.numberOfMipmapLevels > 1 && !noMipmap;
  8582. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  8583. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  8584. ktx.uploadLevels(_this._gl, !noMipmap);
  8585. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  8586. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  8587. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  8588. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  8589. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  8590. _this.resetTextureCache();
  8591. texture._width = ktx.pixelWidth;
  8592. texture._height = ktx.pixelHeight;
  8593. texture.isReady = true;
  8594. }, null, null, true, onError);
  8595. }
  8596. else if (isDDS) {
  8597. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  8598. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  8599. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  8600. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  8601. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  8602. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 6);
  8603. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  8604. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  8605. }
  8606. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  8607. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  8608. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  8609. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  8610. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  8611. _this.resetTextureCache();
  8612. texture._width = info.width;
  8613. texture._height = info.height;
  8614. texture.isReady = true;
  8615. }, null, null, true, onError);
  8616. }
  8617. else {
  8618. cascadeLoad(rootUrl, scene, function (imgs) {
  8619. var width = BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize);
  8620. var height = width;
  8621. _this._prepareWorkingCanvas();
  8622. _this._workingCanvas.width = width;
  8623. _this._workingCanvas.height = height;
  8624. var faces = [
  8625. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  8626. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  8627. ];
  8628. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  8629. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  8630. for (var index = 0; index < faces.length; index++) {
  8631. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  8632. gl.texImage2D(faces[index], 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, _this._workingCanvas);
  8633. }
  8634. if (!noMipmap) {
  8635. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  8636. }
  8637. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  8638. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  8639. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  8640. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  8641. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  8642. _this.resetTextureCache();
  8643. texture._width = width;
  8644. texture._height = height;
  8645. texture.isReady = true;
  8646. texture.onLoadedCallbacks.forEach(function (callback) {
  8647. callback();
  8648. });
  8649. if (onLoad) {
  8650. onLoad();
  8651. }
  8652. }, files, onError);
  8653. }
  8654. this._loadedTexturesCache.push(texture);
  8655. return texture;
  8656. };
  8657. Engine.prototype.updateTextureSize = function (texture, width, height) {
  8658. texture._width = width;
  8659. texture._height = height;
  8660. texture._size = width * height;
  8661. texture._baseWidth = width;
  8662. texture._baseHeight = height;
  8663. };
  8664. Engine.prototype.createRawCubeTexture = function (url, scene, size, format, type, noMipmap, callback, mipmmapGenerator) {
  8665. var _this = this;
  8666. var gl = this._gl;
  8667. var texture = gl.createTexture();
  8668. scene._addPendingData(texture);
  8669. texture.isCube = true;
  8670. texture.references = 1;
  8671. texture.url = url;
  8672. var textureType = gl.UNSIGNED_BYTE;
  8673. if (type === Engine.TEXTURETYPE_FLOAT) {
  8674. textureType = gl.FLOAT;
  8675. }
  8676. var internalFormat = this._getInternalFormat(format);
  8677. var needConversion = false;
  8678. if (internalFormat === gl.RGB) {
  8679. internalFormat = gl.RGBA;
  8680. needConversion = true;
  8681. }
  8682. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  8683. var width = size;
  8684. var height = width;
  8685. var isPot = (BABYLON.Tools.IsExponentOfTwo(width) && BABYLON.Tools.IsExponentOfTwo(height));
  8686. texture._width = width;
  8687. texture._height = height;
  8688. var onerror = function () {
  8689. scene._removePendingData(texture);
  8690. };
  8691. var internalCallback = function (data) {
  8692. var rgbeDataArrays = callback(data);
  8693. var facesIndex = [
  8694. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  8695. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  8696. ];
  8697. width = texture._width;
  8698. height = texture._height;
  8699. isPot = (BABYLON.Tools.IsExponentOfTwo(width) && BABYLON.Tools.IsExponentOfTwo(height));
  8700. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  8701. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  8702. if (mipmmapGenerator) {
  8703. var arrayTemp = [];
  8704. // Data are known to be in +X +Y +Z -X -Y -Z
  8705. // mipmmapGenerator data is expected to be order in +X -X +Y -Y +Z -Z
  8706. arrayTemp.push(rgbeDataArrays[0]); // +X
  8707. arrayTemp.push(rgbeDataArrays[3]); // -X
  8708. arrayTemp.push(rgbeDataArrays[1]); // +Y
  8709. arrayTemp.push(rgbeDataArrays[4]); // -Y
  8710. arrayTemp.push(rgbeDataArrays[2]); // +Z
  8711. arrayTemp.push(rgbeDataArrays[5]); // -Z
  8712. var mipData = mipmmapGenerator(arrayTemp);
  8713. // mipData is order in +X -X +Y -Y +Z -Z
  8714. var mipFaces = [0, 2, 4, 1, 3, 5];
  8715. for (var level = 0; level < mipData.length; level++) {
  8716. var mipSize = width >> level;
  8717. for (var mipIndex in mipFaces) {
  8718. var mipFaceData = mipData[level][mipFaces[mipIndex]];
  8719. if (needConversion) {
  8720. mipFaceData = _this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
  8721. }
  8722. gl.texImage2D(facesIndex[mipIndex], level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);
  8723. }
  8724. }
  8725. }
  8726. else {
  8727. // Data are known to be in +X +Y +Z -X -Y -Z
  8728. for (var index = 0; index < facesIndex.length; index++) {
  8729. var faceData = rgbeDataArrays[index];
  8730. if (needConversion) {
  8731. faceData = _this._convertRGBtoRGBATextureData(faceData, width, height, type);
  8732. }
  8733. gl.texImage2D(facesIndex[index], 0, internalSizedFomat, width, height, 0, internalFormat, textureType, faceData);
  8734. }
  8735. if (!noMipmap && isPot) {
  8736. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  8737. }
  8738. else {
  8739. noMipmap = true;
  8740. }
  8741. }
  8742. if (textureType === gl.FLOAT && !_this._caps.textureFloatLinearFiltering) {
  8743. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  8744. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  8745. }
  8746. else if (textureType === Engine.HALF_FLOAT_OES && !_this._caps.textureHalfFloatLinearFiltering) {
  8747. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  8748. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  8749. }
  8750. else {
  8751. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  8752. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  8753. }
  8754. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  8755. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  8756. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  8757. texture.isReady = true;
  8758. _this.resetTextureCache();
  8759. scene._removePendingData(texture);
  8760. };
  8761. BABYLON.Tools.LoadFile(url, function (data) {
  8762. internalCallback(data);
  8763. }, onerror, scene.database, true);
  8764. return texture;
  8765. };
  8766. ;
  8767. Engine.prototype._convertRGBtoRGBATextureData = function (rgbData, width, height, textureType) {
  8768. // Create new RGBA data container.
  8769. var rgbaData;
  8770. if (textureType === Engine.TEXTURETYPE_FLOAT) {
  8771. rgbaData = new Float32Array(width * height * 4);
  8772. }
  8773. else {
  8774. rgbaData = new Uint32Array(width * height * 4);
  8775. }
  8776. // Convert each pixel.
  8777. for (var x = 0; x < width; x++) {
  8778. for (var y = 0; y < height; y++) {
  8779. var index = (y * width + x) * 3;
  8780. var newIndex = (y * width + x) * 4;
  8781. // Map Old Value to new value.
  8782. rgbaData[newIndex + 0] = rgbData[index + 0];
  8783. rgbaData[newIndex + 1] = rgbData[index + 1];
  8784. rgbaData[newIndex + 2] = rgbData[index + 2];
  8785. // Add fully opaque alpha channel.
  8786. rgbaData[newIndex + 3] = 1;
  8787. }
  8788. }
  8789. return rgbaData;
  8790. };
  8791. Engine.prototype._releaseTexture = function (texture) {
  8792. var gl = this._gl;
  8793. if (texture._framebuffer) {
  8794. gl.deleteFramebuffer(texture._framebuffer);
  8795. }
  8796. if (texture._depthBuffer) {
  8797. gl.deleteRenderbuffer(texture._depthBuffer);
  8798. }
  8799. gl.deleteTexture(texture);
  8800. // Unbind channels
  8801. this.unbindAllTextures();
  8802. var index = this._loadedTexturesCache.indexOf(texture);
  8803. if (index !== -1) {
  8804. this._loadedTexturesCache.splice(index, 1);
  8805. }
  8806. };
  8807. Engine.prototype.setProgram = function (program) {
  8808. if (this._currentProgram !== program) {
  8809. this._gl.useProgram(program);
  8810. this._currentProgram = program;
  8811. }
  8812. };
  8813. Engine.prototype.bindSamplers = function (effect) {
  8814. this.setProgram(effect.getProgram());
  8815. var samplers = effect.getSamplers();
  8816. for (var index = 0; index < samplers.length; index++) {
  8817. var uniform = effect.getUniform(samplers[index]);
  8818. this._gl.uniform1i(uniform, index);
  8819. }
  8820. this._currentEffect = null;
  8821. };
  8822. Engine.prototype.activateTexture = function (texture) {
  8823. if (this._activeTexture !== texture) {
  8824. this._gl.activeTexture(texture);
  8825. this._activeTexture = texture;
  8826. }
  8827. };
  8828. Engine.prototype._bindTextureDirectly = function (target, texture) {
  8829. if (this._activeTexturesCache[this._activeTexture] !== texture) {
  8830. this._gl.bindTexture(target, texture);
  8831. this._activeTexturesCache[this._activeTexture] = texture;
  8832. }
  8833. };
  8834. Engine.prototype._bindTexture = function (channel, texture) {
  8835. if (channel < 0) {
  8836. return;
  8837. }
  8838. this.activateTexture(this._gl.TEXTURE0 + channel);
  8839. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  8840. };
  8841. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  8842. this._bindTexture(channel, postProcess._textures.data[postProcess._currentRenderTextureInd]);
  8843. };
  8844. Engine.prototype.unbindAllTextures = function () {
  8845. for (var channel = 0; channel < this._caps.maxTexturesImageUnits; channel++) {
  8846. this.activateTexture(this._gl["TEXTURE" + channel]);
  8847. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  8848. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  8849. }
  8850. };
  8851. Engine.prototype.setTexture = function (channel, uniform, texture) {
  8852. if (channel < 0) {
  8853. return;
  8854. }
  8855. this._gl.uniform1i(uniform, channel);
  8856. this._setTexture(channel, texture);
  8857. };
  8858. Engine.prototype._setTexture = function (channel, texture) {
  8859. // Not ready?
  8860. if (!texture || !texture.isReady()) {
  8861. if (this._activeTexturesCache[channel] != null) {
  8862. this.activateTexture(this._gl["TEXTURE" + channel]);
  8863. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  8864. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  8865. }
  8866. return;
  8867. }
  8868. // Video
  8869. var alreadyActivated = false;
  8870. if (texture instanceof BABYLON.VideoTexture) {
  8871. this.activateTexture(this._gl["TEXTURE" + channel]);
  8872. alreadyActivated = true;
  8873. texture.update();
  8874. }
  8875. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  8876. texture.delayLoad();
  8877. return;
  8878. }
  8879. var internalTexture = texture.getInternalTexture();
  8880. if (this._activeTexturesCache[channel] === internalTexture) {
  8881. return;
  8882. }
  8883. if (!alreadyActivated) {
  8884. this.activateTexture(this._gl["TEXTURE" + channel]);
  8885. }
  8886. if (internalTexture.isCube) {
  8887. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture);
  8888. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  8889. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  8890. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  8891. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  8892. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  8893. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  8894. }
  8895. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  8896. }
  8897. else {
  8898. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture);
  8899. if (internalTexture._cachedWrapU !== texture.wrapU) {
  8900. internalTexture._cachedWrapU = texture.wrapU;
  8901. switch (texture.wrapU) {
  8902. case BABYLON.Texture.WRAP_ADDRESSMODE:
  8903. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  8904. break;
  8905. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  8906. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  8907. break;
  8908. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  8909. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  8910. break;
  8911. }
  8912. }
  8913. if (internalTexture._cachedWrapV !== texture.wrapV) {
  8914. internalTexture._cachedWrapV = texture.wrapV;
  8915. switch (texture.wrapV) {
  8916. case BABYLON.Texture.WRAP_ADDRESSMODE:
  8917. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  8918. break;
  8919. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  8920. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  8921. break;
  8922. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  8923. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  8924. break;
  8925. }
  8926. }
  8927. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  8928. }
  8929. };
  8930. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  8931. if (channel < 0) {
  8932. return;
  8933. }
  8934. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  8935. this._textureUnits = new Int32Array(textures.length);
  8936. }
  8937. for (var i = 0; i < textures.length; i++) {
  8938. this._textureUnits[i] = channel + i;
  8939. }
  8940. this._gl.uniform1iv(uniform, this._textureUnits);
  8941. for (var index = 0; index < textures.length; index++) {
  8942. this._setTexture(channel + index, textures[index]);
  8943. }
  8944. };
  8945. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  8946. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  8947. var value = texture.anisotropicFilteringLevel;
  8948. if (texture.getInternalTexture().samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  8949. value = 1;
  8950. }
  8951. if (anisotropicFilterExtension && texture._cachedAnisotropicFilteringLevel !== value) {
  8952. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
  8953. texture._cachedAnisotropicFilteringLevel = value;
  8954. }
  8955. };
  8956. Engine.prototype.readPixels = function (x, y, width, height) {
  8957. var data = new Uint8Array(height * width * 4);
  8958. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  8959. return data;
  8960. };
  8961. /**
  8962. * Add an externaly attached data from its key.
  8963. * This method call will fail and return false, if such key already exists.
  8964. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  8965. * @param key the unique key that identifies the data
  8966. * @param data the data object to associate to the key for this Engine instance
  8967. * @return true if no such key were already present and the data was added successfully, false otherwise
  8968. */
  8969. Engine.prototype.addExternalData = function (key, data) {
  8970. return this._externalData.add(key, data);
  8971. };
  8972. /**
  8973. * Get an externaly attached data from its key
  8974. * @param key the unique key that identifies the data
  8975. * @return the associated data, if present (can be null), or undefined if not present
  8976. */
  8977. Engine.prototype.getExternalData = function (key) {
  8978. return this._externalData.get(key);
  8979. };
  8980. /**
  8981. * Get an externaly attached data from its key, create it using a factory if it's not already present
  8982. * @param key the unique key that identifies the data
  8983. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  8984. * @return the associated data, can be null if the factory returned null.
  8985. */
  8986. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  8987. return this._externalData.getOrAddWithFactory(key, factory);
  8988. };
  8989. /**
  8990. * Remove an externaly attached data from the Engine instance
  8991. * @param key the unique key that identifies the data
  8992. * @return true if the data was successfully removed, false if it doesn't exist
  8993. */
  8994. Engine.prototype.removeExternalData = function (key) {
  8995. return this._externalData.remove(key);
  8996. };
  8997. Engine.prototype.releaseInternalTexture = function (texture) {
  8998. if (!texture) {
  8999. return;
  9000. }
  9001. texture.references--;
  9002. // Final reference ?
  9003. if (texture.references === 0) {
  9004. var texturesCache = this.getLoadedTexturesCache();
  9005. var index = texturesCache.indexOf(texture);
  9006. if (index > -1) {
  9007. texturesCache.splice(index, 1);
  9008. }
  9009. this._releaseTexture(texture);
  9010. }
  9011. };
  9012. Engine.prototype.unbindAllAttributes = function () {
  9013. if (this._mustWipeVertexAttributes) {
  9014. this._mustWipeVertexAttributes = false;
  9015. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  9016. this._gl.disableVertexAttribArray(i);
  9017. this._vertexAttribArraysEnabled[i] = false;
  9018. this._currentBufferPointers[i] = null;
  9019. }
  9020. return;
  9021. }
  9022. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  9023. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  9024. continue;
  9025. }
  9026. this._gl.disableVertexAttribArray(i);
  9027. this._vertexAttribArraysEnabled[i] = false;
  9028. this._currentBufferPointers[i] = null;
  9029. }
  9030. };
  9031. // Dispose
  9032. Engine.prototype.dispose = function () {
  9033. this.hideLoadingUI();
  9034. this.stopRenderLoop();
  9035. // Release scenes
  9036. while (this.scenes.length) {
  9037. this.scenes[0].dispose();
  9038. }
  9039. // Release audio engine
  9040. Engine.audioEngine.dispose();
  9041. // Release effects
  9042. for (var name in this._compiledEffects) {
  9043. this._gl.deleteProgram(this._compiledEffects[name]._program);
  9044. }
  9045. // Unbind
  9046. this.unbindAllAttributes();
  9047. this._gl = null;
  9048. //WebVR
  9049. this.disableVR();
  9050. // Events
  9051. window.removeEventListener("blur", this._onBlur);
  9052. window.removeEventListener("focus", this._onFocus);
  9053. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  9054. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  9055. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  9056. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  9057. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  9058. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  9059. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  9060. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  9061. };
  9062. // Loading screen
  9063. Engine.prototype.displayLoadingUI = function () {
  9064. this._loadingScreen.displayLoadingUI();
  9065. };
  9066. Engine.prototype.hideLoadingUI = function () {
  9067. this._loadingScreen.hideLoadingUI();
  9068. };
  9069. Object.defineProperty(Engine.prototype, "loadingScreen", {
  9070. get: function () {
  9071. return this._loadingScreen;
  9072. },
  9073. set: function (loadingScreen) {
  9074. this._loadingScreen = loadingScreen;
  9075. },
  9076. enumerable: true,
  9077. configurable: true
  9078. });
  9079. Object.defineProperty(Engine.prototype, "loadingUIText", {
  9080. set: function (text) {
  9081. this._loadingScreen.loadingUIText = text;
  9082. },
  9083. enumerable: true,
  9084. configurable: true
  9085. });
  9086. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  9087. set: function (color) {
  9088. this._loadingScreen.loadingUIBackgroundColor = color;
  9089. },
  9090. enumerable: true,
  9091. configurable: true
  9092. });
  9093. Engine.prototype.attachContextLostEvent = function (callback) {
  9094. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  9095. };
  9096. Engine.prototype.attachContextRestoredEvent = function (callback) {
  9097. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  9098. };
  9099. Engine.prototype.getVertexShaderSource = function (program) {
  9100. var shaders = this._gl.getAttachedShaders(program);
  9101. return this._gl.getShaderSource(shaders[0]);
  9102. };
  9103. Engine.prototype.getFragmentShaderSource = function (program) {
  9104. var shaders = this._gl.getAttachedShaders(program);
  9105. return this._gl.getShaderSource(shaders[1]);
  9106. };
  9107. // FPS
  9108. Engine.prototype.getFps = function () {
  9109. return this.fps;
  9110. };
  9111. Engine.prototype.getDeltaTime = function () {
  9112. return this.deltaTime;
  9113. };
  9114. Engine.prototype._measureFps = function () {
  9115. this.previousFramesDuration.push(BABYLON.Tools.Now);
  9116. var length = this.previousFramesDuration.length;
  9117. if (length >= 2) {
  9118. this.deltaTime = this.previousFramesDuration[length - 1] - this.previousFramesDuration[length - 2];
  9119. }
  9120. if (length >= this.fpsRange) {
  9121. if (length > this.fpsRange) {
  9122. this.previousFramesDuration.splice(0, 1);
  9123. length = this.previousFramesDuration.length;
  9124. }
  9125. var sum = 0;
  9126. for (var id = 0; id < length - 1; id++) {
  9127. sum += this.previousFramesDuration[id + 1] - this.previousFramesDuration[id];
  9128. }
  9129. this.fps = 1000.0 / (sum / (length - 1));
  9130. }
  9131. };
  9132. Engine.prototype._canRenderToFloatFramebuffer = function () {
  9133. if (this._webGLVersion > 1) {
  9134. return this._caps.colorBufferFloat;
  9135. }
  9136. return this._canRenderToFramebuffer(BABYLON.Engine.TEXTURETYPE_FLOAT);
  9137. };
  9138. Engine.prototype._canRenderToHalfFloatFramebuffer = function () {
  9139. if (this._webGLVersion > 1) {
  9140. return this._caps.colorBufferFloat;
  9141. }
  9142. return this._canRenderToFramebuffer(BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  9143. };
  9144. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  9145. Engine.prototype._canRenderToFramebuffer = function (type) {
  9146. var gl = this._gl;
  9147. //clear existing errors
  9148. while (gl.getError() !== gl.NO_ERROR) { }
  9149. var successful = true;
  9150. var texture = gl.createTexture();
  9151. gl.bindTexture(gl.TEXTURE_2D, texture);
  9152. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  9153. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  9154. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  9155. var fb = gl.createFramebuffer();
  9156. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  9157. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  9158. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  9159. successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
  9160. successful = successful && (gl.getError() === gl.NO_ERROR);
  9161. //try render by clearing frame buffer's color buffer
  9162. if (successful) {
  9163. gl.clear(gl.COLOR_BUFFER_BIT);
  9164. successful = successful && (gl.getError() === gl.NO_ERROR);
  9165. }
  9166. //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
  9167. if (successful) {
  9168. //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
  9169. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  9170. var readFormat = gl.RGBA;
  9171. var readType = gl.UNSIGNED_BYTE;
  9172. var buffer = new Uint8Array(4);
  9173. gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
  9174. successful = successful && (gl.getError() === gl.NO_ERROR);
  9175. }
  9176. //clean up
  9177. gl.deleteTexture(texture);
  9178. gl.deleteFramebuffer(fb);
  9179. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  9180. //clear accumulated errors
  9181. while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
  9182. return successful;
  9183. };
  9184. Engine.prototype._getWebGLTextureType = function (type) {
  9185. if (type === Engine.TEXTURETYPE_FLOAT) {
  9186. return this._gl.FLOAT;
  9187. }
  9188. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  9189. // Add Half Float Constant.
  9190. return Engine.HALF_FLOAT_OES;
  9191. }
  9192. return this._gl.UNSIGNED_BYTE;
  9193. };
  9194. ;
  9195. Engine.prototype._getRGBABufferInternalSizedFormat = function (type) {
  9196. if (this._webGLVersion === 1) {
  9197. return this._gl.RGBA;
  9198. }
  9199. if (type === Engine.TEXTURETYPE_FLOAT) {
  9200. return Engine.RGBA32F;
  9201. }
  9202. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  9203. return Engine.RGBA16F;
  9204. }
  9205. return this._gl.RGBA;
  9206. };
  9207. ;
  9208. // Statics
  9209. Engine.isSupported = function () {
  9210. try {
  9211. // Avoid creating an unsized context for CocoonJS, since size determined on first creation. Is not resizable
  9212. if (navigator.isCocoonJS) {
  9213. return true;
  9214. }
  9215. var tempcanvas = document.createElement("canvas");
  9216. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  9217. return gl != null && !!window.WebGLRenderingContext;
  9218. }
  9219. catch (e) {
  9220. return false;
  9221. }
  9222. };
  9223. return Engine;
  9224. }());
  9225. // Const statics
  9226. Engine._ALPHA_DISABLE = 0;
  9227. Engine._ALPHA_ADD = 1;
  9228. Engine._ALPHA_COMBINE = 2;
  9229. Engine._ALPHA_SUBTRACT = 3;
  9230. Engine._ALPHA_MULTIPLY = 4;
  9231. Engine._ALPHA_MAXIMIZED = 5;
  9232. Engine._ALPHA_ONEONE = 6;
  9233. Engine._ALPHA_PREMULTIPLIED = 7;
  9234. Engine._DELAYLOADSTATE_NONE = 0;
  9235. Engine._DELAYLOADSTATE_LOADED = 1;
  9236. Engine._DELAYLOADSTATE_LOADING = 2;
  9237. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  9238. Engine._TEXTUREFORMAT_ALPHA = 0;
  9239. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  9240. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  9241. Engine._TEXTUREFORMAT_RGB = 4;
  9242. Engine._TEXTUREFORMAT_RGBA = 5;
  9243. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  9244. Engine._TEXTURETYPE_FLOAT = 1;
  9245. Engine._TEXTURETYPE_HALF_FLOAT = 2;
  9246. // Depht or Stencil test Constants.
  9247. Engine._NEVER = 0x0200; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn.
  9248. 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.
  9249. 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.
  9250. 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.
  9251. 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.
  9252. 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.
  9253. 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.
  9254. 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.
  9255. Engine.HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).
  9256. Engine.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.
  9257. Engine.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
  9258. // Stencil Actions Constants.
  9259. Engine._KEEP = 0x1E00;
  9260. Engine._REPLACE = 0x1E01;
  9261. Engine._INCR = 0x1E02;
  9262. Engine._DECR = 0x1E03;
  9263. Engine._INVERT = 0x150A;
  9264. Engine._INCR_WRAP = 0x8507;
  9265. Engine._DECR_WRAP = 0x8508;
  9266. // Updatable statics so stick with vars here
  9267. Engine.CollisionsEpsilon = 0.001;
  9268. Engine.CodeRepository = "src/";
  9269. Engine.ShadersRepository = "src/Shaders/";
  9270. BABYLON.Engine = Engine;
  9271. })(BABYLON || (BABYLON = {}));
  9272. //# sourceMappingURL=babylon.engine.js.map
  9273. var BABYLON;
  9274. (function (BABYLON) {
  9275. /**
  9276. * Node is the basic class for all scene objects (Mesh, Light Camera).
  9277. */
  9278. var Node = (function () {
  9279. /**
  9280. * @constructor
  9281. * @param {string} name - the name and id to be given to this node
  9282. * @param {BABYLON.Scene} the scene this node will be added to
  9283. */
  9284. function Node(name, scene) {
  9285. this.state = "";
  9286. this.metadata = null;
  9287. this.doNotSerialize = false;
  9288. this.animations = new Array();
  9289. this._ranges = {};
  9290. this._childrenFlag = -1;
  9291. this._isEnabled = true;
  9292. this._isReady = true;
  9293. this._currentRenderId = -1;
  9294. this._parentRenderId = -1;
  9295. /**
  9296. * An event triggered when the mesh is disposed.
  9297. * @type {BABYLON.Observable}
  9298. */
  9299. this.onDisposeObservable = new BABYLON.Observable();
  9300. this.name = name;
  9301. this.id = name;
  9302. this._scene = scene;
  9303. this._initCache();
  9304. }
  9305. Object.defineProperty(Node.prototype, "parent", {
  9306. get: function () {
  9307. return this._parentNode;
  9308. },
  9309. set: function (parent) {
  9310. if (this._parentNode === parent) {
  9311. return;
  9312. }
  9313. if (this._parentNode) {
  9314. var index = this._parentNode._children.indexOf(this);
  9315. if (index !== -1) {
  9316. this._parentNode._children.splice(index, 1);
  9317. }
  9318. }
  9319. this._parentNode = parent;
  9320. if (this._parentNode) {
  9321. if (!this._parentNode._children) {
  9322. this._parentNode._children = new Array();
  9323. }
  9324. this._parentNode._children.push(this);
  9325. }
  9326. },
  9327. enumerable: true,
  9328. configurable: true
  9329. });
  9330. Node.prototype.getClassName = function () {
  9331. return "Node";
  9332. };
  9333. Object.defineProperty(Node.prototype, "onDispose", {
  9334. set: function (callback) {
  9335. if (this._onDisposeObserver) {
  9336. this.onDisposeObservable.remove(this._onDisposeObserver);
  9337. }
  9338. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  9339. },
  9340. enumerable: true,
  9341. configurable: true
  9342. });
  9343. Node.prototype.getScene = function () {
  9344. return this._scene;
  9345. };
  9346. Node.prototype.getEngine = function () {
  9347. return this._scene.getEngine();
  9348. };
  9349. // override it in derived class
  9350. Node.prototype.getWorldMatrix = function () {
  9351. return BABYLON.Matrix.Identity();
  9352. };
  9353. // override it in derived class if you add new variables to the cache
  9354. // and call the parent class method
  9355. Node.prototype._initCache = function () {
  9356. this._cache = {};
  9357. this._cache.parent = undefined;
  9358. };
  9359. Node.prototype.updateCache = function (force) {
  9360. if (!force && this.isSynchronized())
  9361. return;
  9362. this._cache.parent = this.parent;
  9363. this._updateCache();
  9364. };
  9365. // override it in derived class if you add new variables to the cache
  9366. // and call the parent class method if !ignoreParentClass
  9367. Node.prototype._updateCache = function (ignoreParentClass) {
  9368. };
  9369. // override it in derived class if you add new variables to the cache
  9370. Node.prototype._isSynchronized = function () {
  9371. return true;
  9372. };
  9373. Node.prototype._markSyncedWithParent = function () {
  9374. this._parentRenderId = this.parent._currentRenderId;
  9375. };
  9376. Node.prototype.isSynchronizedWithParent = function () {
  9377. if (!this.parent) {
  9378. return true;
  9379. }
  9380. if (this._parentRenderId !== this.parent._currentRenderId) {
  9381. return false;
  9382. }
  9383. return this.parent.isSynchronized();
  9384. };
  9385. Node.prototype.isSynchronized = function (updateCache) {
  9386. var check = this.hasNewParent();
  9387. check = check || !this.isSynchronizedWithParent();
  9388. check = check || !this._isSynchronized();
  9389. if (updateCache)
  9390. this.updateCache(true);
  9391. return !check;
  9392. };
  9393. Node.prototype.hasNewParent = function (update) {
  9394. if (this._cache.parent === this.parent)
  9395. return false;
  9396. if (update)
  9397. this._cache.parent = this.parent;
  9398. return true;
  9399. };
  9400. /**
  9401. * Is this node ready to be used/rendered
  9402. * @return {boolean} is it ready
  9403. */
  9404. Node.prototype.isReady = function () {
  9405. return this._isReady;
  9406. };
  9407. /**
  9408. * Is this node enabled.
  9409. * If the node has a parent and is enabled, the parent will be inspected as well.
  9410. * @return {boolean} whether this node (and its parent) is enabled.
  9411. * @see setEnabled
  9412. */
  9413. Node.prototype.isEnabled = function () {
  9414. if (!this._isEnabled) {
  9415. return false;
  9416. }
  9417. if (this.parent) {
  9418. return this.parent.isEnabled();
  9419. }
  9420. return true;
  9421. };
  9422. /**
  9423. * Set the enabled state of this node.
  9424. * @param {boolean} value - the new enabled state
  9425. * @see isEnabled
  9426. */
  9427. Node.prototype.setEnabled = function (value) {
  9428. this._isEnabled = value;
  9429. };
  9430. /**
  9431. * Is this node a descendant of the given node.
  9432. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined.
  9433. * @param {BABYLON.Node} ancestor - The parent node to inspect
  9434. * @see parent
  9435. */
  9436. Node.prototype.isDescendantOf = function (ancestor) {
  9437. if (this.parent) {
  9438. if (this.parent === ancestor) {
  9439. return true;
  9440. }
  9441. return this.parent.isDescendantOf(ancestor);
  9442. }
  9443. return false;
  9444. };
  9445. /**
  9446. * Evaluate the list of children and determine if they should be considered as descendants considering the given criterias
  9447. * @param {BABYLON.Node[]} results the result array containing the nodes matching the given criterias
  9448. * @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.
  9449. * @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.
  9450. */
  9451. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  9452. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  9453. if (!this._children) {
  9454. return;
  9455. }
  9456. for (var index = 0; index < this._children.length; index++) {
  9457. var item = this._children[index];
  9458. if (!predicate || predicate(item)) {
  9459. results.push(item);
  9460. }
  9461. if (!directDescendantsOnly) {
  9462. item._getDescendants(results, false, predicate);
  9463. }
  9464. }
  9465. };
  9466. /**
  9467. * Will return all nodes that have this node as ascendant.
  9468. * @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.
  9469. * @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.
  9470. * @return {BABYLON.Node[]} all children nodes of all types.
  9471. */
  9472. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  9473. var results = [];
  9474. this._getDescendants(results, directDescendantsOnly, predicate);
  9475. return results;
  9476. };
  9477. /**
  9478. * @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.
  9479. * @Deprecated, legacy support.
  9480. * use getDecendants instead.
  9481. */
  9482. Node.prototype.getChildren = function (predicate) {
  9483. return this.getDescendants(true, predicate);
  9484. };
  9485. /**
  9486. * Get all child-meshes of this node.
  9487. */
  9488. Node.prototype.getChildMeshes = function (directDecendantsOnly, predicate) {
  9489. var results = [];
  9490. this._getDescendants(results, directDecendantsOnly, function (node) {
  9491. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  9492. });
  9493. return results;
  9494. };
  9495. Node.prototype._setReady = function (state) {
  9496. if (state === this._isReady) {
  9497. return;
  9498. }
  9499. if (!state) {
  9500. this._isReady = false;
  9501. return;
  9502. }
  9503. this._isReady = true;
  9504. if (this.onReady) {
  9505. this.onReady(this);
  9506. }
  9507. };
  9508. Node.prototype.getAnimationByName = function (name) {
  9509. for (var i = 0; i < this.animations.length; i++) {
  9510. var animation = this.animations[i];
  9511. if (animation.name === name) {
  9512. return animation;
  9513. }
  9514. }
  9515. return null;
  9516. };
  9517. Node.prototype.createAnimationRange = function (name, from, to) {
  9518. // check name not already in use
  9519. if (!this._ranges[name]) {
  9520. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  9521. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  9522. if (this.animations[i]) {
  9523. this.animations[i].createRange(name, from, to);
  9524. }
  9525. }
  9526. }
  9527. };
  9528. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  9529. if (deleteFrames === void 0) { deleteFrames = true; }
  9530. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  9531. if (this.animations[i]) {
  9532. this.animations[i].deleteRange(name, deleteFrames);
  9533. }
  9534. }
  9535. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  9536. };
  9537. Node.prototype.getAnimationRange = function (name) {
  9538. return this._ranges[name];
  9539. };
  9540. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  9541. var range = this.getAnimationRange(name);
  9542. if (!range) {
  9543. return null;
  9544. }
  9545. this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  9546. };
  9547. Node.prototype.serializeAnimationRanges = function () {
  9548. var serializationRanges = [];
  9549. for (var name in this._ranges) {
  9550. var range = {};
  9551. range.name = name;
  9552. range.from = this._ranges[name].from;
  9553. range.to = this._ranges[name].to;
  9554. serializationRanges.push(range);
  9555. }
  9556. return serializationRanges;
  9557. };
  9558. Node.prototype.dispose = function () {
  9559. this.parent = null;
  9560. // Callback
  9561. this.onDisposeObservable.notifyObservers(this);
  9562. this.onDisposeObservable.clear();
  9563. };
  9564. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  9565. if (parsedNode.ranges) {
  9566. for (var index = 0; index < parsedNode.ranges.length; index++) {
  9567. var data = parsedNode.ranges[index];
  9568. node.createAnimationRange(data.name, data.from, data.to);
  9569. }
  9570. }
  9571. };
  9572. return Node;
  9573. }());
  9574. __decorate([
  9575. BABYLON.serialize()
  9576. ], Node.prototype, "name", void 0);
  9577. __decorate([
  9578. BABYLON.serialize()
  9579. ], Node.prototype, "id", void 0);
  9580. __decorate([
  9581. BABYLON.serialize()
  9582. ], Node.prototype, "uniqueId", void 0);
  9583. __decorate([
  9584. BABYLON.serialize()
  9585. ], Node.prototype, "state", void 0);
  9586. __decorate([
  9587. BABYLON.serialize()
  9588. ], Node.prototype, "metadata", void 0);
  9589. BABYLON.Node = Node;
  9590. })(BABYLON || (BABYLON = {}));
  9591. //# sourceMappingURL=babylon.node.js.map
  9592. var BABYLON;
  9593. (function (BABYLON) {
  9594. var FilesInput = (function () {
  9595. /// Register to core BabylonJS object: engine, scene, rendering canvas, callback function when the scene will be loaded,
  9596. /// loading progress callback and optionnal addionnal logic to call in the rendering loop
  9597. function FilesInput(p_engine, p_scene, p_canvas, p_sceneLoadedCallback, p_progressCallback, p_additionnalRenderLoopLogicCallback, p_textureLoadingCallback, p_startingProcessingFilesCallback) {
  9598. this._engine = p_engine;
  9599. this._canvas = p_canvas;
  9600. this._currentScene = p_scene;
  9601. this._sceneLoadedCallback = p_sceneLoadedCallback;
  9602. this._progressCallback = p_progressCallback;
  9603. this._additionnalRenderLoopLogicCallback = p_additionnalRenderLoopLogicCallback;
  9604. this._textureLoadingCallback = p_textureLoadingCallback;
  9605. this._startingProcessingFilesCallback = p_startingProcessingFilesCallback;
  9606. }
  9607. FilesInput.prototype.monitorElementForDragNDrop = function (p_elementToMonitor) {
  9608. var _this = this;
  9609. if (p_elementToMonitor) {
  9610. this._elementToMonitor = p_elementToMonitor;
  9611. this._elementToMonitor.addEventListener("dragenter", function (e) { _this.drag(e); }, false);
  9612. this._elementToMonitor.addEventListener("dragover", function (e) { _this.drag(e); }, false);
  9613. this._elementToMonitor.addEventListener("drop", function (e) { _this.drop(e); }, false);
  9614. }
  9615. };
  9616. FilesInput.prototype.renderFunction = function () {
  9617. if (this._additionnalRenderLoopLogicCallback) {
  9618. this._additionnalRenderLoopLogicCallback();
  9619. }
  9620. if (this._currentScene) {
  9621. if (this._textureLoadingCallback) {
  9622. var remaining = this._currentScene.getWaitingItemsCount();
  9623. if (remaining > 0) {
  9624. this._textureLoadingCallback(remaining);
  9625. }
  9626. }
  9627. this._currentScene.render();
  9628. }
  9629. };
  9630. FilesInput.prototype.drag = function (e) {
  9631. e.stopPropagation();
  9632. e.preventDefault();
  9633. };
  9634. FilesInput.prototype.drop = function (eventDrop) {
  9635. eventDrop.stopPropagation();
  9636. eventDrop.preventDefault();
  9637. this.loadFiles(eventDrop);
  9638. };
  9639. FilesInput.prototype.loadFiles = function (event) {
  9640. if (this._startingProcessingFilesCallback)
  9641. this._startingProcessingFilesCallback();
  9642. // Handling data transfer via drag'n'drop
  9643. if (event && event.dataTransfer && event.dataTransfer.files) {
  9644. this._filesToLoad = event.dataTransfer.files;
  9645. }
  9646. // Handling files from input files
  9647. if (event && event.target && event.target.files) {
  9648. this._filesToLoad = event.target.files;
  9649. }
  9650. if (this._filesToLoad && this._filesToLoad.length > 0) {
  9651. for (var i = 0; i < this._filesToLoad.length; i++) {
  9652. var name_1 = this._filesToLoad[i].name.toLowerCase();
  9653. var extension = name_1.split('.').pop();
  9654. var type = this._filesToLoad[i].type;
  9655. if (extension === "jpg" || extension === "png" || extension === "bmp" || extension === "jpeg" ||
  9656. type === "image/jpeg" || type === "image/png" || type === "image/bmp") {
  9657. FilesInput.FilesTextures[name_1] = this._filesToLoad[i];
  9658. }
  9659. else {
  9660. if ((extension === "babylon" || extension === "stl" || extension === "obj")
  9661. && name_1.indexOf(".binary.babylon") === -1 && name_1.indexOf(".incremental.babylon") === -1) {
  9662. this._sceneFileToLoad = this._filesToLoad[i];
  9663. }
  9664. else {
  9665. FilesInput.FilesToLoad[name_1] = this._filesToLoad[i];
  9666. }
  9667. }
  9668. }
  9669. this.reload();
  9670. }
  9671. };
  9672. FilesInput.prototype.reload = function () {
  9673. var _this = this;
  9674. var that = this;
  9675. // If a ".babylon" file has been provided
  9676. if (this._sceneFileToLoad) {
  9677. if (this._currentScene) {
  9678. if (BABYLON.Tools.errorsCount > 0) {
  9679. BABYLON.Tools.ClearLogCache();
  9680. BABYLON.Tools.Log("Babylon.js engine (v" + BABYLON.Engine.Version + ") launched");
  9681. }
  9682. this._engine.stopRenderLoop();
  9683. this._currentScene.dispose();
  9684. }
  9685. BABYLON.SceneLoader.Load("file:", this._sceneFileToLoad, this._engine, function (newScene) {
  9686. that._currentScene = newScene;
  9687. // Wait for textures and shaders to be ready
  9688. that._currentScene.executeWhenReady(function () {
  9689. // Attach camera to canvas inputs
  9690. if (!that._currentScene.activeCamera || that._currentScene.lights.length === 0) {
  9691. that._currentScene.createDefaultCameraOrLight();
  9692. }
  9693. that._currentScene.activeCamera.attachControl(that._canvas);
  9694. if (that._sceneLoadedCallback) {
  9695. that._sceneLoadedCallback(_this._sceneFileToLoad, that._currentScene);
  9696. }
  9697. that._engine.runRenderLoop(function () { that.renderFunction(); });
  9698. });
  9699. }, function (progress) {
  9700. if (_this._progressCallback) {
  9701. _this._progressCallback(progress);
  9702. }
  9703. });
  9704. }
  9705. else {
  9706. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  9707. }
  9708. };
  9709. return FilesInput;
  9710. }());
  9711. FilesInput.FilesTextures = new Array();
  9712. FilesInput.FilesToLoad = new Array();
  9713. BABYLON.FilesInput = FilesInput;
  9714. })(BABYLON || (BABYLON = {}));
  9715. //# sourceMappingURL=babylon.filesInput.js.map
  9716. var BABYLON;
  9717. (function (BABYLON) {
  9718. var IntersectionInfo = (function () {
  9719. function IntersectionInfo(bu, bv, distance) {
  9720. this.bu = bu;
  9721. this.bv = bv;
  9722. this.distance = distance;
  9723. this.faceId = 0;
  9724. this.subMeshId = 0;
  9725. }
  9726. return IntersectionInfo;
  9727. }());
  9728. BABYLON.IntersectionInfo = IntersectionInfo;
  9729. var PickingInfo = (function () {
  9730. function PickingInfo() {
  9731. this.hit = false;
  9732. this.distance = 0;
  9733. this.pickedPoint = null;
  9734. this.pickedMesh = null;
  9735. this.bu = 0;
  9736. this.bv = 0;
  9737. this.faceId = -1;
  9738. this.subMeshId = 0;
  9739. this.pickedSprite = null;
  9740. }
  9741. // Methods
  9742. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  9743. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  9744. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  9745. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  9746. return null;
  9747. }
  9748. var indices = this.pickedMesh.getIndices();
  9749. var result;
  9750. if (useVerticesNormals) {
  9751. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  9752. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  9753. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  9754. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  9755. normal0 = normal0.scale(this.bu);
  9756. normal1 = normal1.scale(this.bv);
  9757. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  9758. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  9759. }
  9760. else {
  9761. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  9762. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  9763. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  9764. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  9765. var p1p2 = vertex1.subtract(vertex2);
  9766. var p3p2 = vertex3.subtract(vertex2);
  9767. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  9768. }
  9769. if (useWorldCoordinates) {
  9770. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  9771. }
  9772. return BABYLON.Vector3.Normalize(result);
  9773. };
  9774. PickingInfo.prototype.getTextureCoordinates = function () {
  9775. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  9776. return null;
  9777. }
  9778. var indices = this.pickedMesh.getIndices();
  9779. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  9780. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  9781. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  9782. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  9783. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  9784. uv1 = uv1.scale(this.bu);
  9785. uv2 = uv2.scale(this.bv);
  9786. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  9787. };
  9788. return PickingInfo;
  9789. }());
  9790. BABYLON.PickingInfo = PickingInfo;
  9791. })(BABYLON || (BABYLON = {}));
  9792. //# sourceMappingURL=babylon.pickingInfo.js.map
  9793. var BABYLON;
  9794. (function (BABYLON) {
  9795. var BoundingSphere = (function () {
  9796. function BoundingSphere(minimum, maximum) {
  9797. this.minimum = minimum;
  9798. this.maximum = maximum;
  9799. this._tempRadiusVector = BABYLON.Vector3.Zero();
  9800. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  9801. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  9802. this.radius = distance * 0.5;
  9803. this.centerWorld = BABYLON.Vector3.Zero();
  9804. this._update(BABYLON.Matrix.Identity());
  9805. }
  9806. // Methods
  9807. BoundingSphere.prototype._update = function (world) {
  9808. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  9809. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  9810. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  9811. };
  9812. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  9813. for (var i = 0; i < 6; i++) {
  9814. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  9815. return false;
  9816. }
  9817. return true;
  9818. };
  9819. BoundingSphere.prototype.intersectsPoint = function (point) {
  9820. var x = this.centerWorld.x - point.x;
  9821. var y = this.centerWorld.y - point.y;
  9822. var z = this.centerWorld.z - point.z;
  9823. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  9824. if (Math.abs(this.radiusWorld - distance) < BABYLON.Epsilon)
  9825. return false;
  9826. return true;
  9827. };
  9828. // Statics
  9829. BoundingSphere.Intersects = function (sphere0, sphere1) {
  9830. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  9831. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  9832. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  9833. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  9834. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  9835. return false;
  9836. return true;
  9837. };
  9838. return BoundingSphere;
  9839. }());
  9840. BABYLON.BoundingSphere = BoundingSphere;
  9841. })(BABYLON || (BABYLON = {}));
  9842. //# sourceMappingURL=babylon.boundingSphere.js.map
  9843. var BABYLON;
  9844. (function (BABYLON) {
  9845. var BoundingBox = (function () {
  9846. function BoundingBox(minimum, maximum) {
  9847. this.minimum = minimum;
  9848. this.maximum = maximum;
  9849. this.vectors = new Array();
  9850. this.vectorsWorld = new Array();
  9851. // Bounding vectors
  9852. this.vectors.push(this.minimum.clone());
  9853. this.vectors.push(this.maximum.clone());
  9854. this.vectors.push(this.minimum.clone());
  9855. this.vectors[2].x = this.maximum.x;
  9856. this.vectors.push(this.minimum.clone());
  9857. this.vectors[3].y = this.maximum.y;
  9858. this.vectors.push(this.minimum.clone());
  9859. this.vectors[4].z = this.maximum.z;
  9860. this.vectors.push(this.maximum.clone());
  9861. this.vectors[5].z = this.minimum.z;
  9862. this.vectors.push(this.maximum.clone());
  9863. this.vectors[6].x = this.minimum.x;
  9864. this.vectors.push(this.maximum.clone());
  9865. this.vectors[7].y = this.minimum.y;
  9866. // OBB
  9867. this.center = this.maximum.add(this.minimum).scale(0.5);
  9868. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  9869. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  9870. // World
  9871. for (var index = 0; index < this.vectors.length; index++) {
  9872. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  9873. }
  9874. this.minimumWorld = BABYLON.Vector3.Zero();
  9875. this.maximumWorld = BABYLON.Vector3.Zero();
  9876. this._update(BABYLON.Matrix.Identity());
  9877. }
  9878. // Methods
  9879. BoundingBox.prototype.getWorldMatrix = function () {
  9880. return this._worldMatrix;
  9881. };
  9882. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  9883. this._worldMatrix.copyFrom(matrix);
  9884. return this;
  9885. };
  9886. BoundingBox.prototype._update = function (world) {
  9887. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  9888. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  9889. for (var index = 0; index < this.vectors.length; index++) {
  9890. var v = this.vectorsWorld[index];
  9891. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  9892. if (v.x < this.minimumWorld.x)
  9893. this.minimumWorld.x = v.x;
  9894. if (v.y < this.minimumWorld.y)
  9895. this.minimumWorld.y = v.y;
  9896. if (v.z < this.minimumWorld.z)
  9897. this.minimumWorld.z = v.z;
  9898. if (v.x > this.maximumWorld.x)
  9899. this.maximumWorld.x = v.x;
  9900. if (v.y > this.maximumWorld.y)
  9901. this.maximumWorld.y = v.y;
  9902. if (v.z > this.maximumWorld.z)
  9903. this.maximumWorld.z = v.z;
  9904. }
  9905. // OBB
  9906. this.maximumWorld.addToRef(this.minimumWorld, this.center);
  9907. this.center.scaleInPlace(0.5);
  9908. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  9909. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  9910. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  9911. this._worldMatrix = world;
  9912. };
  9913. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  9914. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  9915. };
  9916. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  9917. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  9918. };
  9919. BoundingBox.prototype.intersectsPoint = function (point) {
  9920. var delta = -BABYLON.Epsilon;
  9921. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  9922. return false;
  9923. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  9924. return false;
  9925. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  9926. return false;
  9927. return true;
  9928. };
  9929. BoundingBox.prototype.intersectsSphere = function (sphere) {
  9930. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  9931. };
  9932. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  9933. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  9934. return false;
  9935. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  9936. return false;
  9937. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  9938. return false;
  9939. return true;
  9940. };
  9941. // Statics
  9942. BoundingBox.Intersects = function (box0, box1) {
  9943. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  9944. return false;
  9945. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  9946. return false;
  9947. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  9948. return false;
  9949. return true;
  9950. };
  9951. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  9952. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  9953. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  9954. return (num <= (sphereRadius * sphereRadius));
  9955. };
  9956. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  9957. for (var p = 0; p < 6; p++) {
  9958. for (var i = 0; i < 8; i++) {
  9959. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  9960. return false;
  9961. }
  9962. }
  9963. }
  9964. return true;
  9965. };
  9966. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  9967. for (var p = 0; p < 6; p++) {
  9968. var inCount = 8;
  9969. for (var i = 0; i < 8; i++) {
  9970. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  9971. --inCount;
  9972. }
  9973. else {
  9974. break;
  9975. }
  9976. }
  9977. if (inCount === 0)
  9978. return false;
  9979. }
  9980. return true;
  9981. };
  9982. return BoundingBox;
  9983. }());
  9984. BABYLON.BoundingBox = BoundingBox;
  9985. })(BABYLON || (BABYLON = {}));
  9986. //# sourceMappingURL=babylon.boundingBox.js.map
  9987. var BABYLON;
  9988. (function (BABYLON) {
  9989. var computeBoxExtents = function (axis, box) {
  9990. var p = BABYLON.Vector3.Dot(box.center, axis);
  9991. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  9992. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  9993. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  9994. var r = r0 + r1 + r2;
  9995. return {
  9996. min: p - r,
  9997. max: p + r
  9998. };
  9999. };
  10000. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  10001. var axisOverlap = function (axis, box0, box1) {
  10002. var result0 = computeBoxExtents(axis, box0);
  10003. var result1 = computeBoxExtents(axis, box1);
  10004. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  10005. };
  10006. var BoundingInfo = (function () {
  10007. function BoundingInfo(minimum, maximum) {
  10008. this.minimum = minimum;
  10009. this.maximum = maximum;
  10010. this._isLocked = false;
  10011. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  10012. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  10013. }
  10014. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  10015. get: function () {
  10016. return this._isLocked;
  10017. },
  10018. set: function (value) {
  10019. this._isLocked = value;
  10020. },
  10021. enumerable: true,
  10022. configurable: true
  10023. });
  10024. // Methods
  10025. BoundingInfo.prototype.update = function (world) {
  10026. if (this._isLocked) {
  10027. return;
  10028. }
  10029. this.boundingBox._update(world);
  10030. this.boundingSphere._update(world);
  10031. };
  10032. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  10033. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  10034. return false;
  10035. return this.boundingBox.isInFrustum(frustumPlanes);
  10036. };
  10037. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  10038. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  10039. };
  10040. BoundingInfo.prototype._checkCollision = function (collider) {
  10041. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  10042. };
  10043. BoundingInfo.prototype.intersectsPoint = function (point) {
  10044. if (!this.boundingSphere.centerWorld) {
  10045. return false;
  10046. }
  10047. if (!this.boundingSphere.intersectsPoint(point)) {
  10048. return false;
  10049. }
  10050. if (!this.boundingBox.intersectsPoint(point)) {
  10051. return false;
  10052. }
  10053. return true;
  10054. };
  10055. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  10056. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  10057. return false;
  10058. }
  10059. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  10060. return false;
  10061. }
  10062. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  10063. return false;
  10064. }
  10065. if (!precise) {
  10066. return true;
  10067. }
  10068. var box0 = this.boundingBox;
  10069. var box1 = boundingInfo.boundingBox;
  10070. if (!axisOverlap(box0.directions[0], box0, box1))
  10071. return false;
  10072. if (!axisOverlap(box0.directions[1], box0, box1))
  10073. return false;
  10074. if (!axisOverlap(box0.directions[2], box0, box1))
  10075. return false;
  10076. if (!axisOverlap(box1.directions[0], box0, box1))
  10077. return false;
  10078. if (!axisOverlap(box1.directions[1], box0, box1))
  10079. return false;
  10080. if (!axisOverlap(box1.directions[2], box0, box1))
  10081. return false;
  10082. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  10083. return false;
  10084. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  10085. return false;
  10086. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  10087. return false;
  10088. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  10089. return false;
  10090. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  10091. return false;
  10092. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  10093. return false;
  10094. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  10095. return false;
  10096. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  10097. return false;
  10098. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  10099. return false;
  10100. return true;
  10101. };
  10102. return BoundingInfo;
  10103. }());
  10104. BABYLON.BoundingInfo = BoundingInfo;
  10105. })(BABYLON || (BABYLON = {}));
  10106. //# sourceMappingURL=babylon.boundingInfo.js.map
  10107. var BABYLON;
  10108. (function (BABYLON) {
  10109. var Ray = (function () {
  10110. function Ray(origin, direction, length) {
  10111. if (length === void 0) { length = Number.MAX_VALUE; }
  10112. this.origin = origin;
  10113. this.direction = direction;
  10114. this.length = length;
  10115. }
  10116. // Methods
  10117. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  10118. var d = 0.0;
  10119. var maxValue = Number.MAX_VALUE;
  10120. var inv;
  10121. var min;
  10122. var max;
  10123. var temp;
  10124. if (Math.abs(this.direction.x) < 0.0000001) {
  10125. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  10126. return false;
  10127. }
  10128. }
  10129. else {
  10130. inv = 1.0 / this.direction.x;
  10131. min = (minimum.x - this.origin.x) * inv;
  10132. max = (maximum.x - this.origin.x) * inv;
  10133. if (max === -Infinity) {
  10134. max = Infinity;
  10135. }
  10136. if (min > max) {
  10137. temp = min;
  10138. min = max;
  10139. max = temp;
  10140. }
  10141. d = Math.max(min, d);
  10142. maxValue = Math.min(max, maxValue);
  10143. if (d > maxValue) {
  10144. return false;
  10145. }
  10146. }
  10147. if (Math.abs(this.direction.y) < 0.0000001) {
  10148. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  10149. return false;
  10150. }
  10151. }
  10152. else {
  10153. inv = 1.0 / this.direction.y;
  10154. min = (minimum.y - this.origin.y) * inv;
  10155. max = (maximum.y - this.origin.y) * inv;
  10156. if (max === -Infinity) {
  10157. max = Infinity;
  10158. }
  10159. if (min > max) {
  10160. temp = min;
  10161. min = max;
  10162. max = temp;
  10163. }
  10164. d = Math.max(min, d);
  10165. maxValue = Math.min(max, maxValue);
  10166. if (d > maxValue) {
  10167. return false;
  10168. }
  10169. }
  10170. if (Math.abs(this.direction.z) < 0.0000001) {
  10171. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  10172. return false;
  10173. }
  10174. }
  10175. else {
  10176. inv = 1.0 / this.direction.z;
  10177. min = (minimum.z - this.origin.z) * inv;
  10178. max = (maximum.z - this.origin.z) * inv;
  10179. if (max === -Infinity) {
  10180. max = Infinity;
  10181. }
  10182. if (min > max) {
  10183. temp = min;
  10184. min = max;
  10185. max = temp;
  10186. }
  10187. d = Math.max(min, d);
  10188. maxValue = Math.min(max, maxValue);
  10189. if (d > maxValue) {
  10190. return false;
  10191. }
  10192. }
  10193. return true;
  10194. };
  10195. Ray.prototype.intersectsBox = function (box) {
  10196. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  10197. };
  10198. Ray.prototype.intersectsSphere = function (sphere) {
  10199. var x = sphere.center.x - this.origin.x;
  10200. var y = sphere.center.y - this.origin.y;
  10201. var z = sphere.center.z - this.origin.z;
  10202. var pyth = (x * x) + (y * y) + (z * z);
  10203. var rr = sphere.radius * sphere.radius;
  10204. if (pyth <= rr) {
  10205. return true;
  10206. }
  10207. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  10208. if (dot < 0.0) {
  10209. return false;
  10210. }
  10211. var temp = pyth - (dot * dot);
  10212. return temp <= rr;
  10213. };
  10214. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  10215. if (!this._edge1) {
  10216. this._edge1 = BABYLON.Vector3.Zero();
  10217. this._edge2 = BABYLON.Vector3.Zero();
  10218. this._pvec = BABYLON.Vector3.Zero();
  10219. this._tvec = BABYLON.Vector3.Zero();
  10220. this._qvec = BABYLON.Vector3.Zero();
  10221. }
  10222. vertex1.subtractToRef(vertex0, this._edge1);
  10223. vertex2.subtractToRef(vertex0, this._edge2);
  10224. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  10225. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  10226. if (det === 0) {
  10227. return null;
  10228. }
  10229. var invdet = 1 / det;
  10230. this.origin.subtractToRef(vertex0, this._tvec);
  10231. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  10232. if (bu < 0 || bu > 1.0) {
  10233. return null;
  10234. }
  10235. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  10236. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  10237. if (bv < 0 || bu + bv > 1.0) {
  10238. return null;
  10239. }
  10240. //check if the distance is longer than the predefined length.
  10241. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  10242. if (distance > this.length) {
  10243. return null;
  10244. }
  10245. return new BABYLON.IntersectionInfo(bu, bv, distance);
  10246. };
  10247. Ray.prototype.intersectsPlane = function (plane) {
  10248. var distance;
  10249. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  10250. if (Math.abs(result1) < 9.99999997475243E-07) {
  10251. return null;
  10252. }
  10253. else {
  10254. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  10255. distance = (-plane.d - result2) / result1;
  10256. if (distance < 0.0) {
  10257. if (distance < -9.99999997475243E-07) {
  10258. return null;
  10259. }
  10260. else {
  10261. return 0;
  10262. }
  10263. }
  10264. return distance;
  10265. }
  10266. };
  10267. Ray.prototype.intersectsMesh = function (mesh, fastCheck) {
  10268. var tm = BABYLON.Tmp.Matrix[0];
  10269. mesh.getWorldMatrix().invertToRef(tm);
  10270. if (this._tmpRay) {
  10271. Ray.TransformToRef(this, tm, this._tmpRay);
  10272. }
  10273. else {
  10274. this._tmpRay = Ray.Transform(this, tm);
  10275. }
  10276. return mesh.intersects(this._tmpRay, fastCheck);
  10277. };
  10278. Ray.prototype.intersectsMeshes = function (meshes, fastCheck, results) {
  10279. if (results) {
  10280. results.length = 0;
  10281. }
  10282. else {
  10283. results = [];
  10284. }
  10285. for (var i = 0; i < meshes.length; i++) {
  10286. var pickInfo = this.intersectsMesh(meshes[i], fastCheck);
  10287. if (pickInfo.hit) {
  10288. results.push(pickInfo);
  10289. }
  10290. }
  10291. results.sort(this._comparePickingInfo);
  10292. return results;
  10293. };
  10294. Ray.prototype._comparePickingInfo = function (pickingInfoA, pickingInfoB) {
  10295. if (pickingInfoA.distance < pickingInfoB.distance) {
  10296. return -1;
  10297. }
  10298. else if (pickingInfoA.distance > pickingInfoB.distance) {
  10299. return 1;
  10300. }
  10301. else {
  10302. return 0;
  10303. }
  10304. };
  10305. /**
  10306. * @Deprecated. Use new RayHelper.show() instead.
  10307. * */
  10308. Ray.prototype.show = function (scene, color) {
  10309. console.warn('Ray.show() has been deprecated. Use new RayHelper.show() instead.');
  10310. if (!this._rayHelper) {
  10311. this._rayHelper = new BABYLON.RayHelper(this);
  10312. }
  10313. this._rayHelper.show(scene, color);
  10314. };
  10315. /**
  10316. * @Deprecated. Use new RayHelper.hide() instead.
  10317. * */
  10318. Ray.prototype.hide = function () {
  10319. console.warn('Ray.hide() has been deprecated. Use new RayHelper.hide() instead.');
  10320. if (this._rayHelper) {
  10321. this._rayHelper.hide();
  10322. this._rayHelper = null;
  10323. }
  10324. };
  10325. /**
  10326. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  10327. * @param sega the first point of the segment to test the intersection against
  10328. * @param segb the second point of the segment to test the intersection against
  10329. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  10330. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  10331. */
  10332. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  10333. var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
  10334. var u = segb.subtract(sega);
  10335. var v = rsegb.subtract(this.origin);
  10336. var w = sega.subtract(this.origin);
  10337. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  10338. var b = BABYLON.Vector3.Dot(u, v);
  10339. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  10340. var d = BABYLON.Vector3.Dot(u, w);
  10341. var e = BABYLON.Vector3.Dot(v, w);
  10342. var D = a * c - b * b; // always >= 0
  10343. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  10344. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  10345. // compute the line parameters of the two closest points
  10346. if (D < Ray.smallnum) {
  10347. sN = 0.0; // force using point P0 on segment S1
  10348. sD = 1.0; // to prevent possible division by 0.0 later
  10349. tN = e;
  10350. tD = c;
  10351. }
  10352. else {
  10353. sN = (b * e - c * d);
  10354. tN = (a * e - b * d);
  10355. if (sN < 0.0) {
  10356. sN = 0.0;
  10357. tN = e;
  10358. tD = c;
  10359. }
  10360. else if (sN > sD) {
  10361. sN = sD;
  10362. tN = e + b;
  10363. tD = c;
  10364. }
  10365. }
  10366. if (tN < 0.0) {
  10367. tN = 0.0;
  10368. // recompute sc for this edge
  10369. if (-d < 0.0) {
  10370. sN = 0.0;
  10371. }
  10372. else if (-d > a)
  10373. sN = sD;
  10374. else {
  10375. sN = -d;
  10376. sD = a;
  10377. }
  10378. }
  10379. else if (tN > tD) {
  10380. tN = tD;
  10381. // recompute sc for this edge
  10382. if ((-d + b) < 0.0) {
  10383. sN = 0;
  10384. }
  10385. else if ((-d + b) > a) {
  10386. sN = sD;
  10387. }
  10388. else {
  10389. sN = (-d + b);
  10390. sD = a;
  10391. }
  10392. }
  10393. // finally do the division to get sc and tc
  10394. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  10395. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  10396. // get the difference of the two closest points
  10397. var qtc = v.multiplyByFloats(tc, tc, tc);
  10398. var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)
  10399. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  10400. if (isIntersected) {
  10401. return qtc.length();
  10402. }
  10403. return -1;
  10404. };
  10405. // Statics
  10406. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  10407. var start = BABYLON.Vector3.Unproject(new BABYLON.Vector3(x, y, 0), viewportWidth, viewportHeight, world, view, projection);
  10408. var end = BABYLON.Vector3.Unproject(new BABYLON.Vector3(x, y, 1), viewportWidth, viewportHeight, world, view, projection);
  10409. var direction = end.subtract(start);
  10410. direction.normalize();
  10411. return new Ray(start, direction);
  10412. };
  10413. /**
  10414. * 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
  10415. * transformed to the given world matrix.
  10416. * @param origin The origin point
  10417. * @param end The end point
  10418. * @param world a matrix to transform the ray to. Default is the identity matrix.
  10419. */
  10420. Ray.CreateNewFromTo = function (origin, end, world) {
  10421. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  10422. var direction = end.subtract(origin);
  10423. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  10424. direction.normalize();
  10425. return Ray.Transform(new Ray(origin, direction, length), world);
  10426. };
  10427. Ray.Transform = function (ray, matrix) {
  10428. var newOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, matrix);
  10429. var newDirection = BABYLON.Vector3.TransformNormal(ray.direction, matrix);
  10430. newDirection.normalize();
  10431. return new Ray(newOrigin, newDirection, ray.length);
  10432. };
  10433. Ray.TransformToRef = function (ray, matrix, result) {
  10434. BABYLON.Vector3.TransformCoordinatesToRef(ray.origin, matrix, result.origin);
  10435. BABYLON.Vector3.TransformNormalToRef(ray.direction, matrix, result.direction);
  10436. ray.direction.normalize();
  10437. };
  10438. return Ray;
  10439. }());
  10440. Ray.smallnum = 0.00000001;
  10441. Ray.rayl = 10e8;
  10442. BABYLON.Ray = Ray;
  10443. })(BABYLON || (BABYLON = {}));
  10444. //# sourceMappingURL=babylon.ray.js.map
  10445. var BABYLON;
  10446. (function (BABYLON) {
  10447. var RayHelper = (function () {
  10448. function RayHelper(ray) {
  10449. this.ray = ray;
  10450. }
  10451. RayHelper.prototype.show = function (scene, color) {
  10452. if (!this._renderFunction) {
  10453. var ray = this.ray;
  10454. this._renderFunction = this._render.bind(this);
  10455. this._scene = scene;
  10456. this._renderPoints = [ray.origin, ray.origin.add(ray.direction.scale(ray.length))];
  10457. this._renderLine = BABYLON.Mesh.CreateLines("ray", this._renderPoints, scene, true);
  10458. this._scene.registerBeforeRender(this._renderFunction);
  10459. }
  10460. if (color) {
  10461. this._renderLine.color.copyFrom(color);
  10462. }
  10463. };
  10464. RayHelper.prototype.hide = function () {
  10465. if (this._renderFunction) {
  10466. this._scene.unregisterBeforeRender(this._renderFunction);
  10467. this._scene = null;
  10468. this._renderFunction = null;
  10469. this._renderLine.dispose();
  10470. this._renderLine = null;
  10471. this._renderPoints = null;
  10472. }
  10473. };
  10474. RayHelper.prototype._render = function () {
  10475. var ray = this.ray;
  10476. var point = this._renderPoints[1];
  10477. var len = Math.min(ray.length, 1000000);
  10478. point.copyFrom(ray.direction);
  10479. point.scaleInPlace(len);
  10480. point.addInPlace(ray.origin);
  10481. BABYLON.Mesh.CreateLines("ray", this._renderPoints, this._scene, true, this._renderLine);
  10482. };
  10483. RayHelper.prototype.attachToMesh = function (mesh, meshSpaceDirection, meshSpaceOrigin, length) {
  10484. this._attachedToMesh = mesh;
  10485. var ray = this.ray;
  10486. if (!ray.direction) {
  10487. ray.direction = BABYLON.Vector3.Zero();
  10488. }
  10489. if (!ray.origin) {
  10490. ray.origin = BABYLON.Vector3.Zero();
  10491. }
  10492. if (length) {
  10493. ray.length = length;
  10494. }
  10495. if (!meshSpaceOrigin) {
  10496. meshSpaceOrigin = BABYLON.Vector3.Zero();
  10497. }
  10498. if (!meshSpaceDirection) {
  10499. // -1 so that this will work with Mesh.lookAt
  10500. meshSpaceDirection = new BABYLON.Vector3(0, 0, -1);
  10501. }
  10502. if (!this._meshSpaceDirection) {
  10503. this._meshSpaceDirection = meshSpaceDirection.clone();
  10504. this._meshSpaceOrigin = meshSpaceOrigin.clone();
  10505. }
  10506. else {
  10507. this._meshSpaceDirection.copyFrom(meshSpaceDirection);
  10508. this._meshSpaceOrigin.copyFrom(meshSpaceOrigin);
  10509. }
  10510. if (!this._updateToMeshFunction) {
  10511. this._updateToMeshFunction = this._updateToMesh.bind(this);
  10512. this._attachedToMesh.getScene().registerBeforeRender(this._updateToMeshFunction);
  10513. }
  10514. this._updateToMesh();
  10515. };
  10516. RayHelper.prototype.detachFromMesh = function () {
  10517. if (this._attachedToMesh) {
  10518. this._attachedToMesh.getScene().unregisterBeforeRender(this._updateToMeshFunction);
  10519. this._attachedToMesh = null;
  10520. this._updateToMeshFunction = null;
  10521. }
  10522. };
  10523. RayHelper.prototype._updateToMesh = function () {
  10524. var ray = this.ray;
  10525. if (this._attachedToMesh._isDisposed) {
  10526. this.detachFromMesh();
  10527. return;
  10528. }
  10529. this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection, ray.direction);
  10530. BABYLON.Vector3.TransformCoordinatesToRef(this._meshSpaceOrigin, this._attachedToMesh.getWorldMatrix(), ray.origin);
  10531. };
  10532. RayHelper.prototype.dispose = function () {
  10533. this.hide();
  10534. this.detachFromMesh();
  10535. this.ray = null;
  10536. };
  10537. return RayHelper;
  10538. }());
  10539. BABYLON.RayHelper = RayHelper;
  10540. })(BABYLON || (BABYLON = {}));
  10541. //# sourceMappingURL=babylon.rayHelper.js.map
  10542. var BABYLON;
  10543. (function (BABYLON) {
  10544. var AbstractMesh = (function (_super) {
  10545. __extends(AbstractMesh, _super);
  10546. // Constructor
  10547. function AbstractMesh(name, scene) {
  10548. var _this = _super.call(this, name, scene) || this;
  10549. _this._facetNb = 0; // facet number
  10550. _this._partitioningSubdivisions = 10; // number of subdivisions per axis in the partioning space
  10551. _this._partitioningBBoxRatio = 1.01; // the partioning array space is by default 1% bigger than the bounding box
  10552. _this._facetDataEnabled = false; // is the facet data feature enabled on this mesh ?
  10553. _this._facetParameters = {}; // keep a reference to the object parameters to avoid memory re-allocation
  10554. _this._bbSize = BABYLON.Vector3.Zero(); // bbox size approximated for facet data
  10555. _this._subDiv = {
  10556. max: 1,
  10557. X: 1,
  10558. Y: 1,
  10559. Z: 1
  10560. };
  10561. // Events
  10562. /**
  10563. * An event triggered when this mesh collides with another one
  10564. * @type {BABYLON.Observable}
  10565. */
  10566. _this.onCollideObservable = new BABYLON.Observable();
  10567. /**
  10568. * An event triggered when the collision's position changes
  10569. * @type {BABYLON.Observable}
  10570. */
  10571. _this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  10572. /**
  10573. * An event triggered after the world matrix is updated
  10574. * @type {BABYLON.Observable}
  10575. */
  10576. _this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  10577. // Properties
  10578. _this.definedFacingForward = true; // orientation for POV movement & rotation
  10579. _this.position = new BABYLON.Vector3(0, 0, 0);
  10580. _this._rotation = new BABYLON.Vector3(0, 0, 0);
  10581. _this._scaling = new BABYLON.Vector3(1, 1, 1);
  10582. _this.billboardMode = AbstractMesh.BILLBOARDMODE_NONE;
  10583. _this.visibility = 1.0;
  10584. _this.alphaIndex = Number.MAX_VALUE;
  10585. _this.infiniteDistance = false;
  10586. _this.isVisible = true;
  10587. _this.isPickable = true;
  10588. _this.showBoundingBox = false;
  10589. _this.showSubMeshesBoundingBox = false;
  10590. _this.isBlocker = false;
  10591. _this.renderingGroupId = 0;
  10592. _this.receiveShadows = false;
  10593. _this.renderOutline = false;
  10594. _this.outlineColor = BABYLON.Color3.Red();
  10595. _this.outlineWidth = 0.02;
  10596. _this.renderOverlay = false;
  10597. _this.overlayColor = BABYLON.Color3.Red();
  10598. _this.overlayAlpha = 0.5;
  10599. _this.hasVertexAlpha = false;
  10600. _this.useVertexColors = true;
  10601. _this.applyFog = true;
  10602. _this.computeBonesUsingShaders = true;
  10603. _this.scalingDeterminant = 1;
  10604. _this.numBoneInfluencers = 4;
  10605. _this.useOctreeForRenderingSelection = true;
  10606. _this.useOctreeForPicking = true;
  10607. _this.useOctreeForCollisions = true;
  10608. _this.layerMask = 0x0FFFFFFF;
  10609. _this.alwaysSelectAsActiveMesh = false;
  10610. // Collisions
  10611. _this._checkCollisions = false;
  10612. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  10613. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  10614. _this._collider = new BABYLON.Collider();
  10615. _this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  10616. _this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  10617. _this._newPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  10618. // Edges
  10619. _this.edgesWidth = 1;
  10620. _this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  10621. // Cache
  10622. _this._localWorld = BABYLON.Matrix.Zero();
  10623. _this._worldMatrix = BABYLON.Matrix.Zero();
  10624. _this._rotateYByPI = BABYLON.Matrix.RotationY(Math.PI);
  10625. _this._absolutePosition = BABYLON.Vector3.Zero();
  10626. _this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  10627. _this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  10628. _this._isDirty = false;
  10629. _this._pivotMatrix = BABYLON.Matrix.Identity();
  10630. _this._isDisposed = false;
  10631. _this._renderId = 0;
  10632. _this._intersectionsInProgress = new Array();
  10633. _this._isWorldMatrixFrozen = false;
  10634. _this._unIndexed = false;
  10635. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  10636. if (collidedMesh === void 0) { collidedMesh = null; }
  10637. //TODO move this to the collision coordinator!
  10638. if (_this.getScene().workerCollisions)
  10639. newPosition.multiplyInPlace(_this._collider.radius);
  10640. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  10641. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  10642. _this.position.addInPlace(_this._diffPositionForCollisions);
  10643. }
  10644. if (collidedMesh) {
  10645. _this.onCollideObservable.notifyObservers(collidedMesh);
  10646. }
  10647. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  10648. };
  10649. scene.addMesh(_this);
  10650. return _this;
  10651. }
  10652. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  10653. get: function () {
  10654. return AbstractMesh._BILLBOARDMODE_NONE;
  10655. },
  10656. enumerable: true,
  10657. configurable: true
  10658. });
  10659. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  10660. get: function () {
  10661. return AbstractMesh._BILLBOARDMODE_X;
  10662. },
  10663. enumerable: true,
  10664. configurable: true
  10665. });
  10666. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  10667. get: function () {
  10668. return AbstractMesh._BILLBOARDMODE_Y;
  10669. },
  10670. enumerable: true,
  10671. configurable: true
  10672. });
  10673. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  10674. get: function () {
  10675. return AbstractMesh._BILLBOARDMODE_Z;
  10676. },
  10677. enumerable: true,
  10678. configurable: true
  10679. });
  10680. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  10681. get: function () {
  10682. return AbstractMesh._BILLBOARDMODE_ALL;
  10683. },
  10684. enumerable: true,
  10685. configurable: true
  10686. });
  10687. Object.defineProperty(AbstractMesh.prototype, "facetNb", {
  10688. /**
  10689. * Read-only : the number of facets in the mesh
  10690. */
  10691. get: function () {
  10692. return this._facetNb;
  10693. },
  10694. enumerable: true,
  10695. configurable: true
  10696. });
  10697. Object.defineProperty(AbstractMesh.prototype, "partitioningSubdivisions", {
  10698. /**
  10699. * The number of subdivisions per axis in the partioning space
  10700. */
  10701. get: function () {
  10702. return this._partitioningSubdivisions;
  10703. },
  10704. set: function (nb) {
  10705. this._partitioningSubdivisions = nb;
  10706. },
  10707. enumerable: true,
  10708. configurable: true
  10709. });
  10710. Object.defineProperty(AbstractMesh.prototype, "partitioningBBoxRatio", {
  10711. /**
  10712. * The ratio to apply to the bouding box size to set to the partioning space.
  10713. * Ex : 1.01 (default) the partioning space is 1% bigger than the bounding box.
  10714. */
  10715. get: function () {
  10716. return this._partitioningBBoxRatio;
  10717. },
  10718. set: function (ratio) {
  10719. this._partitioningBBoxRatio = ratio;
  10720. },
  10721. enumerable: true,
  10722. configurable: true
  10723. });
  10724. Object.defineProperty(AbstractMesh.prototype, "isFacetDataEnabled", {
  10725. /**
  10726. * Read-only : is the feature facetData enabled ?
  10727. */
  10728. get: function () {
  10729. return this._facetDataEnabled;
  10730. },
  10731. enumerable: true,
  10732. configurable: true
  10733. });
  10734. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  10735. set: function (callback) {
  10736. if (this._onCollideObserver) {
  10737. this.onCollideObservable.remove(this._onCollideObserver);
  10738. }
  10739. this._onCollideObserver = this.onCollideObservable.add(callback);
  10740. },
  10741. enumerable: true,
  10742. configurable: true
  10743. });
  10744. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  10745. set: function (callback) {
  10746. if (this._onCollisionPositionChangeObserver) {
  10747. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  10748. }
  10749. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  10750. },
  10751. enumerable: true,
  10752. configurable: true
  10753. });
  10754. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  10755. get: function () {
  10756. return this._skeleton;
  10757. },
  10758. set: function (value) {
  10759. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  10760. this._skeleton._unregisterMeshWithPoseMatrix(this);
  10761. }
  10762. if (value && value.needInitialSkinMatrix) {
  10763. value._registerMeshWithPoseMatrix(this);
  10764. }
  10765. this._skeleton = value;
  10766. if (!this._skeleton) {
  10767. this._bonesTransformMatrices = null;
  10768. }
  10769. },
  10770. enumerable: true,
  10771. configurable: true
  10772. });
  10773. AbstractMesh.prototype.getClassName = function () {
  10774. return "AbstractMesh";
  10775. };
  10776. /**
  10777. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  10778. */
  10779. AbstractMesh.prototype.toString = function (fullDetails) {
  10780. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  10781. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  10782. if (this._skeleton) {
  10783. ret += ", skeleton: " + this._skeleton.name;
  10784. }
  10785. if (fullDetails) {
  10786. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  10787. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  10788. }
  10789. return ret;
  10790. };
  10791. Object.defineProperty(AbstractMesh.prototype, "rotation", {
  10792. /**
  10793. * Getting the rotation object.
  10794. * If rotation quaternion is set, this vector will (almost always) be the Zero vector!
  10795. */
  10796. get: function () {
  10797. return this._rotation;
  10798. },
  10799. set: function (newRotation) {
  10800. this._rotation = newRotation;
  10801. },
  10802. enumerable: true,
  10803. configurable: true
  10804. });
  10805. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  10806. get: function () {
  10807. return this._scaling;
  10808. },
  10809. set: function (newScaling) {
  10810. this._scaling = newScaling;
  10811. if (this.physicsImpostor) {
  10812. this.physicsImpostor.forceUpdate();
  10813. }
  10814. },
  10815. enumerable: true,
  10816. configurable: true
  10817. });
  10818. Object.defineProperty(AbstractMesh.prototype, "rotationQuaternion", {
  10819. get: function () {
  10820. return this._rotationQuaternion;
  10821. },
  10822. set: function (quaternion) {
  10823. this._rotationQuaternion = quaternion;
  10824. //reset the rotation vector.
  10825. if (quaternion && this.rotation.length()) {
  10826. this.rotation.copyFromFloats(0, 0, 0);
  10827. }
  10828. },
  10829. enumerable: true,
  10830. configurable: true
  10831. });
  10832. // Methods
  10833. AbstractMesh.prototype.updatePoseMatrix = function (matrix) {
  10834. this._poseMatrix.copyFrom(matrix);
  10835. };
  10836. AbstractMesh.prototype.getPoseMatrix = function () {
  10837. return this._poseMatrix;
  10838. };
  10839. AbstractMesh.prototype.disableEdgesRendering = function () {
  10840. if (this._edgesRenderer !== undefined) {
  10841. this._edgesRenderer.dispose();
  10842. this._edgesRenderer = undefined;
  10843. }
  10844. };
  10845. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  10846. if (epsilon === void 0) { epsilon = 0.95; }
  10847. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  10848. this.disableEdgesRendering();
  10849. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  10850. };
  10851. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  10852. get: function () {
  10853. return false;
  10854. },
  10855. enumerable: true,
  10856. configurable: true
  10857. });
  10858. AbstractMesh.prototype.getLOD = function (camera) {
  10859. return this;
  10860. };
  10861. AbstractMesh.prototype.getTotalVertices = function () {
  10862. return 0;
  10863. };
  10864. AbstractMesh.prototype.getIndices = function () {
  10865. return null;
  10866. };
  10867. AbstractMesh.prototype.getVerticesData = function (kind) {
  10868. return null;
  10869. };
  10870. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  10871. return false;
  10872. };
  10873. AbstractMesh.prototype.getBoundingInfo = function () {
  10874. if (this._masterMesh) {
  10875. return this._masterMesh.getBoundingInfo();
  10876. }
  10877. if (!this._boundingInfo) {
  10878. this._updateBoundingInfo();
  10879. }
  10880. return this._boundingInfo;
  10881. };
  10882. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  10883. this._boundingInfo = boundingInfo;
  10884. };
  10885. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  10886. get: function () {
  10887. return this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind);
  10888. },
  10889. enumerable: true,
  10890. configurable: true
  10891. });
  10892. AbstractMesh.prototype._preActivate = function () {
  10893. };
  10894. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  10895. };
  10896. AbstractMesh.prototype._activate = function (renderId) {
  10897. this._renderId = renderId;
  10898. };
  10899. AbstractMesh.prototype.getWorldMatrix = function () {
  10900. if (this._masterMesh) {
  10901. return this._masterMesh.getWorldMatrix();
  10902. }
  10903. if (this._currentRenderId !== this.getScene().getRenderId()) {
  10904. this.computeWorldMatrix();
  10905. }
  10906. return this._worldMatrix;
  10907. };
  10908. Object.defineProperty(AbstractMesh.prototype, "worldMatrixFromCache", {
  10909. get: function () {
  10910. return this._worldMatrix;
  10911. },
  10912. enumerable: true,
  10913. configurable: true
  10914. });
  10915. Object.defineProperty(AbstractMesh.prototype, "absolutePosition", {
  10916. get: function () {
  10917. return this._absolutePosition;
  10918. },
  10919. enumerable: true,
  10920. configurable: true
  10921. });
  10922. AbstractMesh.prototype.freezeWorldMatrix = function () {
  10923. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  10924. this.computeWorldMatrix(true);
  10925. this._isWorldMatrixFrozen = true;
  10926. };
  10927. AbstractMesh.prototype.unfreezeWorldMatrix = function () {
  10928. this._isWorldMatrixFrozen = false;
  10929. this.computeWorldMatrix(true);
  10930. };
  10931. Object.defineProperty(AbstractMesh.prototype, "isWorldMatrixFrozen", {
  10932. get: function () {
  10933. return this._isWorldMatrixFrozen;
  10934. },
  10935. enumerable: true,
  10936. configurable: true
  10937. });
  10938. AbstractMesh.prototype.rotate = function (axis, amount, space) {
  10939. axis.normalize();
  10940. if (!this.rotationQuaternion) {
  10941. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  10942. this.rotation = BABYLON.Vector3.Zero();
  10943. }
  10944. var rotationQuaternion;
  10945. if (!space || space === BABYLON.Space.LOCAL) {
  10946. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, AbstractMesh._rotationAxisCache);
  10947. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  10948. }
  10949. else {
  10950. if (this.parent) {
  10951. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  10952. invertParentWorldMatrix.invert();
  10953. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  10954. }
  10955. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, AbstractMesh._rotationAxisCache);
  10956. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  10957. }
  10958. };
  10959. AbstractMesh.prototype.translate = function (axis, distance, space) {
  10960. var displacementVector = axis.scale(distance);
  10961. if (!space || space === BABYLON.Space.LOCAL) {
  10962. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  10963. this.setPositionWithLocalVector(tempV3);
  10964. }
  10965. else {
  10966. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  10967. }
  10968. };
  10969. AbstractMesh.prototype.getAbsolutePosition = function () {
  10970. this.computeWorldMatrix();
  10971. return this._absolutePosition;
  10972. };
  10973. AbstractMesh.prototype.setAbsolutePosition = function (absolutePosition) {
  10974. if (!absolutePosition) {
  10975. return;
  10976. }
  10977. var absolutePositionX;
  10978. var absolutePositionY;
  10979. var absolutePositionZ;
  10980. if (absolutePosition.x === undefined) {
  10981. if (arguments.length < 3) {
  10982. return;
  10983. }
  10984. absolutePositionX = arguments[0];
  10985. absolutePositionY = arguments[1];
  10986. absolutePositionZ = arguments[2];
  10987. }
  10988. else {
  10989. absolutePositionX = absolutePosition.x;
  10990. absolutePositionY = absolutePosition.y;
  10991. absolutePositionZ = absolutePosition.z;
  10992. }
  10993. if (this.parent) {
  10994. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  10995. invertParentWorldMatrix.invert();
  10996. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  10997. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  10998. }
  10999. else {
  11000. this.position.x = absolutePositionX;
  11001. this.position.y = absolutePositionY;
  11002. this.position.z = absolutePositionZ;
  11003. }
  11004. };
  11005. // ================================== Point of View Movement =================================
  11006. /**
  11007. * Perform relative position change from the point of view of behind the front of the mesh.
  11008. * This is performed taking into account the meshes current rotation, so you do not have to care.
  11009. * Supports definition of mesh facing forward or backward.
  11010. * @param {number} amountRight
  11011. * @param {number} amountUp
  11012. * @param {number} amountForward
  11013. */
  11014. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  11015. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  11016. };
  11017. /**
  11018. * Calculate relative position change from the point of view of behind the front of the mesh.
  11019. * This is performed taking into account the meshes current rotation, so you do not have to care.
  11020. * Supports definition of mesh facing forward or backward.
  11021. * @param {number} amountRight
  11022. * @param {number} amountUp
  11023. * @param {number} amountForward
  11024. */
  11025. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  11026. var rotMatrix = new BABYLON.Matrix();
  11027. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  11028. rotQuaternion.toRotationMatrix(rotMatrix);
  11029. var translationDelta = BABYLON.Vector3.Zero();
  11030. var defForwardMult = this.definedFacingForward ? -1 : 1;
  11031. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  11032. return translationDelta;
  11033. };
  11034. // ================================== Point of View Rotation =================================
  11035. /**
  11036. * Perform relative rotation change from the point of view of behind the front of the mesh.
  11037. * Supports definition of mesh facing forward or backward.
  11038. * @param {number} flipBack
  11039. * @param {number} twirlClockwise
  11040. * @param {number} tiltRight
  11041. */
  11042. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  11043. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  11044. };
  11045. /**
  11046. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  11047. * Supports definition of mesh facing forward or backward.
  11048. * @param {number} flipBack
  11049. * @param {number} twirlClockwise
  11050. * @param {number} tiltRight
  11051. */
  11052. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  11053. var defForwardMult = this.definedFacingForward ? 1 : -1;
  11054. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  11055. };
  11056. AbstractMesh.prototype.setPivotMatrix = function (matrix) {
  11057. this._pivotMatrix = matrix;
  11058. this._cache.pivotMatrixUpdated = true;
  11059. };
  11060. AbstractMesh.prototype.getPivotMatrix = function () {
  11061. return this._pivotMatrix;
  11062. };
  11063. AbstractMesh.prototype._isSynchronized = function () {
  11064. if (this._isDirty) {
  11065. return false;
  11066. }
  11067. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE)
  11068. return false;
  11069. if (this._cache.pivotMatrixUpdated) {
  11070. return false;
  11071. }
  11072. if (this.infiniteDistance) {
  11073. return false;
  11074. }
  11075. if (!this._cache.position.equals(this.position))
  11076. return false;
  11077. if (this.rotationQuaternion) {
  11078. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  11079. return false;
  11080. }
  11081. if (!this._cache.rotation.equals(this.rotation))
  11082. return false;
  11083. if (!this._cache.scaling.equals(this.scaling))
  11084. return false;
  11085. return true;
  11086. };
  11087. AbstractMesh.prototype._initCache = function () {
  11088. _super.prototype._initCache.call(this);
  11089. this._cache.localMatrixUpdated = false;
  11090. this._cache.position = BABYLON.Vector3.Zero();
  11091. this._cache.scaling = BABYLON.Vector3.Zero();
  11092. this._cache.rotation = BABYLON.Vector3.Zero();
  11093. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  11094. this._cache.billboardMode = -1;
  11095. };
  11096. AbstractMesh.prototype.markAsDirty = function (property) {
  11097. if (property === "rotation") {
  11098. this.rotationQuaternion = null;
  11099. }
  11100. this._currentRenderId = Number.MAX_VALUE;
  11101. this._isDirty = true;
  11102. };
  11103. AbstractMesh.prototype._updateBoundingInfo = function () {
  11104. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  11105. this._boundingInfo.update(this.worldMatrixFromCache);
  11106. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  11107. };
  11108. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  11109. if (!this.subMeshes) {
  11110. return;
  11111. }
  11112. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  11113. var subMesh = this.subMeshes[subIndex];
  11114. if (!subMesh.IsGlobal) {
  11115. subMesh.updateBoundingInfo(matrix);
  11116. }
  11117. }
  11118. };
  11119. AbstractMesh.prototype.computeWorldMatrix = function (force) {
  11120. if (this._isWorldMatrixFrozen) {
  11121. return this._worldMatrix;
  11122. }
  11123. if (!force && (this._currentRenderId === this.getScene().getRenderId() || this.isSynchronized(true))) {
  11124. this._currentRenderId = this.getScene().getRenderId();
  11125. return this._worldMatrix;
  11126. }
  11127. this._cache.position.copyFrom(this.position);
  11128. this._cache.scaling.copyFrom(this.scaling);
  11129. this._cache.pivotMatrixUpdated = false;
  11130. this._cache.billboardMode = this.billboardMode;
  11131. this._currentRenderId = this.getScene().getRenderId();
  11132. this._isDirty = false;
  11133. // Scaling
  11134. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  11135. // Rotation
  11136. //rotate, if quaternion is set and rotation was used
  11137. if (this.rotationQuaternion) {
  11138. var len = this.rotation.length();
  11139. if (len) {
  11140. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  11141. this.rotation.copyFromFloats(0, 0, 0);
  11142. }
  11143. }
  11144. if (this.rotationQuaternion) {
  11145. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  11146. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  11147. }
  11148. else {
  11149. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  11150. this._cache.rotation.copyFrom(this.rotation);
  11151. }
  11152. // Translation
  11153. if (this.infiniteDistance && !this.parent) {
  11154. var camera = this.getScene().activeCamera;
  11155. if (camera) {
  11156. var cameraWorldMatrix = camera.getWorldMatrix();
  11157. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  11158. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  11159. }
  11160. }
  11161. else {
  11162. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  11163. }
  11164. // Composing transformations
  11165. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  11166. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  11167. // Billboarding
  11168. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE && this.getScene().activeCamera) {
  11169. BABYLON.Tmp.Vector3[0].copyFrom(this.position);
  11170. var localPosition = BABYLON.Tmp.Vector3[0];
  11171. if (this.parent && this.parent.getWorldMatrix) {
  11172. this._markSyncedWithParent();
  11173. var parentMatrix;
  11174. if (this._meshToBoneReferal) {
  11175. this.parent.getWorldMatrix().multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  11176. parentMatrix = BABYLON.Tmp.Matrix[6];
  11177. }
  11178. else {
  11179. parentMatrix = this.parent.getWorldMatrix();
  11180. }
  11181. BABYLON.Vector3.TransformNormalToRef(localPosition, parentMatrix, BABYLON.Tmp.Vector3[1]);
  11182. localPosition = BABYLON.Tmp.Vector3[1];
  11183. }
  11184. var zero = this.getScene().activeCamera.globalPosition.clone();
  11185. if (this.parent && this.parent.position) {
  11186. localPosition.addInPlace(this.parent.position);
  11187. BABYLON.Matrix.TranslationToRef(localPosition.x, localPosition.y, localPosition.z, BABYLON.Tmp.Matrix[2]);
  11188. }
  11189. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_ALL) !== AbstractMesh.BILLBOARDMODE_ALL) {
  11190. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_X)
  11191. zero.x = localPosition.x + BABYLON.Epsilon;
  11192. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_Y)
  11193. zero.y = localPosition.y + BABYLON.Epsilon;
  11194. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_Z)
  11195. zero.z = localPosition.z + BABYLON.Epsilon;
  11196. }
  11197. BABYLON.Matrix.LookAtLHToRef(localPosition, zero, BABYLON.Vector3.Up(), BABYLON.Tmp.Matrix[3]);
  11198. BABYLON.Tmp.Matrix[3].m[12] = BABYLON.Tmp.Matrix[3].m[13] = BABYLON.Tmp.Matrix[3].m[14] = 0;
  11199. BABYLON.Tmp.Matrix[3].invert();
  11200. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[3], this._localWorld);
  11201. this._rotateYByPI.multiplyToRef(this._localWorld, BABYLON.Tmp.Matrix[5]);
  11202. }
  11203. // Local world
  11204. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  11205. // Parent
  11206. if (this.parent && this.parent.getWorldMatrix && this.billboardMode === AbstractMesh.BILLBOARDMODE_NONE) {
  11207. this._markSyncedWithParent();
  11208. if (this._meshToBoneReferal) {
  11209. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  11210. BABYLON.Tmp.Matrix[6].multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), this._worldMatrix);
  11211. }
  11212. else {
  11213. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  11214. }
  11215. }
  11216. else {
  11217. this._worldMatrix.copyFrom(this._localWorld);
  11218. }
  11219. // Bounding info
  11220. this._updateBoundingInfo();
  11221. // Absolute position
  11222. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  11223. // Callbacks
  11224. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  11225. if (!this._poseMatrix) {
  11226. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  11227. }
  11228. return this._worldMatrix;
  11229. };
  11230. /**
  11231. * If you'd like to be callbacked after the mesh position, rotation or scaling has been updated
  11232. * @param func: callback function to add
  11233. */
  11234. AbstractMesh.prototype.registerAfterWorldMatrixUpdate = function (func) {
  11235. this.onAfterWorldMatrixUpdateObservable.add(func);
  11236. };
  11237. AbstractMesh.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  11238. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  11239. };
  11240. AbstractMesh.prototype.setPositionWithLocalVector = function (vector3) {
  11241. this.computeWorldMatrix();
  11242. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  11243. };
  11244. AbstractMesh.prototype.getPositionExpressedInLocalSpace = function () {
  11245. this.computeWorldMatrix();
  11246. var invLocalWorldMatrix = this._localWorld.clone();
  11247. invLocalWorldMatrix.invert();
  11248. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  11249. };
  11250. AbstractMesh.prototype.locallyTranslate = function (vector3) {
  11251. this.computeWorldMatrix(true);
  11252. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  11253. };
  11254. AbstractMesh.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  11255. /// <summary>Orients a mesh towards a target point. Mesh must be drawn facing user.</summary>
  11256. /// <param name="targetPoint" type="Vector3">The position (must be in same space as current mesh) to look at</param>
  11257. /// <param name="yawCor" type="Number">optional yaw (y-axis) correction in radians</param>
  11258. /// <param name="pitchCor" type="Number">optional pitch (x-axis) correction in radians</param>
  11259. /// <param name="rollCor" type="Number">optional roll (z-axis) correction in radians</param>
  11260. /// <returns>Mesh oriented towards targetMesh</returns>
  11261. if (yawCor === void 0) { yawCor = 0; }
  11262. if (pitchCor === void 0) { pitchCor = 0; }
  11263. if (rollCor === void 0) { rollCor = 0; }
  11264. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  11265. var dv = AbstractMesh._lookAtVectorCache;
  11266. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  11267. targetPoint.subtractToRef(pos, dv);
  11268. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  11269. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  11270. var pitch = Math.atan2(dv.y, len);
  11271. this.rotationQuaternion = this.rotationQuaternion || new BABYLON.Quaternion();
  11272. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  11273. };
  11274. AbstractMesh.prototype.attachToBone = function (bone, affectedMesh) {
  11275. this._meshToBoneReferal = affectedMesh;
  11276. this.parent = bone;
  11277. if (bone.getWorldMatrix().determinant() < 0) {
  11278. this.scalingDeterminant *= -1;
  11279. }
  11280. };
  11281. AbstractMesh.prototype.detachFromBone = function () {
  11282. if (this.parent.getWorldMatrix().determinant() < 0) {
  11283. this.scalingDeterminant *= -1;
  11284. }
  11285. this._meshToBoneReferal = null;
  11286. this.parent = null;
  11287. };
  11288. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  11289. return this._boundingInfo.isInFrustum(frustumPlanes);
  11290. };
  11291. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  11292. return this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  11293. ;
  11294. };
  11295. AbstractMesh.prototype.intersectsMesh = function (mesh, precise) {
  11296. if (!this._boundingInfo || !mesh._boundingInfo) {
  11297. return false;
  11298. }
  11299. return this._boundingInfo.intersects(mesh._boundingInfo, precise);
  11300. };
  11301. AbstractMesh.prototype.intersectsPoint = function (point) {
  11302. if (!this._boundingInfo) {
  11303. return false;
  11304. }
  11305. return this._boundingInfo.intersectsPoint(point);
  11306. };
  11307. // Physics
  11308. /**
  11309. * @Deprecated. Use new PhysicsImpostor instead.
  11310. * */
  11311. AbstractMesh.prototype.setPhysicsState = function (impostor, options) {
  11312. //legacy support
  11313. if (impostor.impostor) {
  11314. options = impostor;
  11315. impostor = impostor.impostor;
  11316. }
  11317. this.physicsImpostor = new BABYLON.PhysicsImpostor(this, impostor, options, this.getScene());
  11318. return this.physicsImpostor.physicsBody;
  11319. };
  11320. AbstractMesh.prototype.getPhysicsImpostor = function () {
  11321. return this.physicsImpostor;
  11322. };
  11323. /**
  11324. * @Deprecated. Use getPhysicsImpostor().getParam("mass");
  11325. */
  11326. AbstractMesh.prototype.getPhysicsMass = function () {
  11327. return this.physicsImpostor.getParam("mass");
  11328. };
  11329. /**
  11330. * @Deprecated. Use getPhysicsImpostor().getParam("friction");
  11331. */
  11332. AbstractMesh.prototype.getPhysicsFriction = function () {
  11333. return this.physicsImpostor.getParam("friction");
  11334. };
  11335. /**
  11336. * @Deprecated. Use getPhysicsImpostor().getParam("restitution");
  11337. */
  11338. AbstractMesh.prototype.getPhysicsRestitution = function () {
  11339. return this.physicsImpostor.getParam("restitution");
  11340. };
  11341. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  11342. if (!camera) {
  11343. camera = this.getScene().activeCamera;
  11344. }
  11345. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  11346. };
  11347. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  11348. if (!camera) {
  11349. camera = this.getScene().activeCamera;
  11350. }
  11351. return this.absolutePosition.subtract(camera.position).length();
  11352. };
  11353. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  11354. if (!this.physicsImpostor) {
  11355. return;
  11356. }
  11357. this.physicsImpostor.applyImpulse(force, contactPoint);
  11358. };
  11359. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  11360. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  11361. return;
  11362. }
  11363. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  11364. mainPivot: pivot1,
  11365. connectedPivot: pivot2,
  11366. nativeParams: options
  11367. });
  11368. };
  11369. /**
  11370. * @Deprecated
  11371. */
  11372. AbstractMesh.prototype.updatePhysicsBodyPosition = function () {
  11373. BABYLON.Tools.Warn("updatePhysicsBodyPosition() is deprecated, please use updatePhysicsBody()");
  11374. this.updatePhysicsBody();
  11375. };
  11376. /**
  11377. * @Deprecated
  11378. * Calling this function is not needed anymore.
  11379. * The physics engine takes care of transofmration automatically.
  11380. */
  11381. AbstractMesh.prototype.updatePhysicsBody = function () {
  11382. //Unneeded
  11383. };
  11384. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  11385. // Collisions
  11386. get: function () {
  11387. return this._checkCollisions;
  11388. },
  11389. set: function (collisionEnabled) {
  11390. this._checkCollisions = collisionEnabled;
  11391. if (this.getScene().workerCollisions) {
  11392. this.getScene().collisionCoordinator.onMeshUpdated(this);
  11393. }
  11394. },
  11395. enumerable: true,
  11396. configurable: true
  11397. });
  11398. AbstractMesh.prototype.moveWithCollisions = function (velocity) {
  11399. var globalPosition = this.getAbsolutePosition();
  11400. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPositionForCollisions);
  11401. this._oldPositionForCollisions.addInPlace(this.ellipsoidOffset);
  11402. this._collider.radius = this.ellipsoid;
  11403. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, velocity, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  11404. };
  11405. // Submeshes octree
  11406. /**
  11407. * This function will create an octree to help select the right submeshes for rendering, picking and collisions
  11408. * Please note that you must have a decent number of submeshes to get performance improvements when using octree
  11409. */
  11410. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  11411. if (maxCapacity === void 0) { maxCapacity = 64; }
  11412. if (maxDepth === void 0) { maxDepth = 2; }
  11413. if (!this._submeshesOctree) {
  11414. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  11415. }
  11416. this.computeWorldMatrix(true);
  11417. // Update octree
  11418. var bbox = this.getBoundingInfo().boundingBox;
  11419. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  11420. return this._submeshesOctree;
  11421. };
  11422. // Collisions
  11423. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  11424. this._generatePointsArray();
  11425. // Transformation
  11426. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  11427. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  11428. subMesh._lastColliderWorldVertices = [];
  11429. subMesh._trianglePlanes = [];
  11430. var start = subMesh.verticesStart;
  11431. var end = (subMesh.verticesStart + subMesh.verticesCount);
  11432. for (var i = start; i < end; i++) {
  11433. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  11434. }
  11435. }
  11436. // Collide
  11437. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  11438. if (collider.collisionFound) {
  11439. collider.collidedMesh = this;
  11440. }
  11441. };
  11442. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  11443. var subMeshes;
  11444. var len;
  11445. // Octrees
  11446. if (this._submeshesOctree && this.useOctreeForCollisions) {
  11447. var radius = collider.velocityWorldLength + Math.max(collider.radius.x, collider.radius.y, collider.radius.z);
  11448. var intersections = this._submeshesOctree.intersects(collider.basePointWorld, radius);
  11449. len = intersections.length;
  11450. subMeshes = intersections.data;
  11451. }
  11452. else {
  11453. subMeshes = this.subMeshes;
  11454. len = subMeshes.length;
  11455. }
  11456. for (var index = 0; index < len; index++) {
  11457. var subMesh = subMeshes[index];
  11458. // Bounding test
  11459. if (len > 1 && !subMesh._checkCollision(collider))
  11460. continue;
  11461. this._collideForSubMesh(subMesh, transformMatrix, collider);
  11462. }
  11463. };
  11464. AbstractMesh.prototype._checkCollision = function (collider) {
  11465. // Bounding box test
  11466. if (!this._boundingInfo._checkCollision(collider))
  11467. return;
  11468. // Transformation matrix
  11469. BABYLON.Matrix.ScalingToRef(1.0 / collider.radius.x, 1.0 / collider.radius.y, 1.0 / collider.radius.z, this._collisionsScalingMatrix);
  11470. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  11471. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  11472. };
  11473. // Picking
  11474. AbstractMesh.prototype._generatePointsArray = function () {
  11475. return false;
  11476. };
  11477. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  11478. var pickingInfo = new BABYLON.PickingInfo();
  11479. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  11480. return pickingInfo;
  11481. }
  11482. if (!this._generatePointsArray()) {
  11483. return pickingInfo;
  11484. }
  11485. var intersectInfo = null;
  11486. // Octrees
  11487. var subMeshes;
  11488. var len;
  11489. if (this._submeshesOctree && this.useOctreeForPicking) {
  11490. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  11491. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  11492. len = intersections.length;
  11493. subMeshes = intersections.data;
  11494. }
  11495. else {
  11496. subMeshes = this.subMeshes;
  11497. len = subMeshes.length;
  11498. }
  11499. for (var index = 0; index < len; index++) {
  11500. var subMesh = subMeshes[index];
  11501. // Bounding test
  11502. if (len > 1 && !subMesh.canIntersects(ray))
  11503. continue;
  11504. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  11505. if (currentIntersectInfo) {
  11506. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  11507. intersectInfo = currentIntersectInfo;
  11508. intersectInfo.subMeshId = index;
  11509. if (fastCheck) {
  11510. break;
  11511. }
  11512. }
  11513. }
  11514. }
  11515. if (intersectInfo) {
  11516. // Get picked point
  11517. var world = this.getWorldMatrix();
  11518. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  11519. var direction = ray.direction.clone();
  11520. direction = direction.scale(intersectInfo.distance);
  11521. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  11522. var pickedPoint = worldOrigin.add(worldDirection);
  11523. // Return result
  11524. pickingInfo.hit = true;
  11525. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  11526. pickingInfo.pickedPoint = pickedPoint;
  11527. pickingInfo.pickedMesh = this;
  11528. pickingInfo.bu = intersectInfo.bu;
  11529. pickingInfo.bv = intersectInfo.bv;
  11530. pickingInfo.faceId = intersectInfo.faceId;
  11531. pickingInfo.subMeshId = intersectInfo.subMeshId;
  11532. return pickingInfo;
  11533. }
  11534. return pickingInfo;
  11535. };
  11536. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  11537. return null;
  11538. };
  11539. AbstractMesh.prototype.releaseSubMeshes = function () {
  11540. if (this.subMeshes) {
  11541. while (this.subMeshes.length) {
  11542. this.subMeshes[0].dispose();
  11543. }
  11544. }
  11545. else {
  11546. this.subMeshes = new Array();
  11547. }
  11548. };
  11549. AbstractMesh.prototype.dispose = function (doNotRecurse) {
  11550. var _this = this;
  11551. var index;
  11552. // Action manager
  11553. if (this.actionManager) {
  11554. this.actionManager.dispose();
  11555. this.actionManager = null;
  11556. }
  11557. // Skeleton
  11558. this.skeleton = null;
  11559. // Animations
  11560. this.getScene().stopAnimation(this);
  11561. // Physics
  11562. if (this.physicsImpostor) {
  11563. this.physicsImpostor.dispose();
  11564. }
  11565. // Intersections in progress
  11566. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  11567. var other = this._intersectionsInProgress[index];
  11568. var pos = other._intersectionsInProgress.indexOf(this);
  11569. other._intersectionsInProgress.splice(pos, 1);
  11570. }
  11571. this._intersectionsInProgress = [];
  11572. // Lights
  11573. var lights = this.getScene().lights;
  11574. lights.forEach(function (light) {
  11575. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  11576. if (meshIndex !== -1) {
  11577. light.includedOnlyMeshes.splice(meshIndex, 1);
  11578. }
  11579. meshIndex = light.excludedMeshes.indexOf(_this);
  11580. if (meshIndex !== -1) {
  11581. light.excludedMeshes.splice(meshIndex, 1);
  11582. }
  11583. // Shadow generators
  11584. var generator = light.getShadowGenerator();
  11585. if (generator) {
  11586. meshIndex = generator.getShadowMap().renderList.indexOf(_this);
  11587. if (meshIndex !== -1) {
  11588. generator.getShadowMap().renderList.splice(meshIndex, 1);
  11589. }
  11590. }
  11591. });
  11592. // Edges
  11593. if (this._edgesRenderer) {
  11594. this._edgesRenderer.dispose();
  11595. this._edgesRenderer = null;
  11596. }
  11597. // SubMeshes
  11598. if (this.getClassName() !== "InstancedMesh") {
  11599. this.releaseSubMeshes();
  11600. }
  11601. // Engine
  11602. this.getScene().getEngine().wipeCaches();
  11603. // Remove from scene
  11604. this.getScene().removeMesh(this);
  11605. if (!doNotRecurse) {
  11606. // Particles
  11607. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  11608. if (this.getScene().particleSystems[index].emitter === this) {
  11609. this.getScene().particleSystems[index].dispose();
  11610. index--;
  11611. }
  11612. }
  11613. // Children
  11614. var objects = this.getDescendants(true);
  11615. for (index = 0; index < objects.length; index++) {
  11616. objects[index].dispose();
  11617. }
  11618. }
  11619. else {
  11620. var childMeshes = this.getChildMeshes(true);
  11621. for (index = 0; index < childMeshes.length; index++) {
  11622. var child = childMeshes[index];
  11623. child.parent = null;
  11624. child.computeWorldMatrix(true);
  11625. }
  11626. }
  11627. // facet data
  11628. if (this._facetDataEnabled) {
  11629. this.disableFacetData();
  11630. }
  11631. this.onAfterWorldMatrixUpdateObservable.clear();
  11632. this.onCollideObservable.clear();
  11633. this.onCollisionPositionChangeObservable.clear();
  11634. this._isDisposed = true;
  11635. _super.prototype.dispose.call(this);
  11636. };
  11637. AbstractMesh.prototype.getDirection = function (localAxis) {
  11638. var result = BABYLON.Vector3.Zero();
  11639. this.getDirectionToRef(localAxis, result);
  11640. return result;
  11641. };
  11642. AbstractMesh.prototype.getDirectionToRef = function (localAxis, result) {
  11643. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  11644. };
  11645. AbstractMesh.prototype.setPivotPoint = function (point, space) {
  11646. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  11647. if (this.getScene().getRenderId() == 0) {
  11648. this.computeWorldMatrix(true);
  11649. }
  11650. var wm = this.getWorldMatrix();
  11651. if (space == BABYLON.Space.WORLD) {
  11652. var tmat = BABYLON.Tmp.Matrix[0];
  11653. wm.invertToRef(tmat);
  11654. point = BABYLON.Vector3.TransformCoordinates(point, tmat);
  11655. }
  11656. BABYLON.Vector3.TransformCoordinatesToRef(point, wm, this.position);
  11657. this._pivotMatrix.m[12] = -point.x;
  11658. this._pivotMatrix.m[13] = -point.y;
  11659. this._pivotMatrix.m[14] = -point.z;
  11660. this._cache.pivotMatrixUpdated = true;
  11661. };
  11662. AbstractMesh.prototype.getPivotPoint = function () {
  11663. var point = BABYLON.Vector3.Zero();
  11664. this.getPivotPointToRef(point);
  11665. return point;
  11666. };
  11667. AbstractMesh.prototype.getPivotPointToRef = function (result) {
  11668. result.x = -this._pivotMatrix.m[12];
  11669. result.y = -this._pivotMatrix.m[13];
  11670. result.z = -this._pivotMatrix.m[14];
  11671. };
  11672. AbstractMesh.prototype.getAbsolutePivotPoint = function () {
  11673. var point = BABYLON.Vector3.Zero();
  11674. this.getAbsolutePivotPointToRef(point);
  11675. return point;
  11676. };
  11677. AbstractMesh.prototype.setParent = function (mesh, keepWorldPositionRotation) {
  11678. if (keepWorldPositionRotation === void 0) { keepWorldPositionRotation = false; }
  11679. var child = this;
  11680. var parent = mesh;
  11681. if (mesh == null) {
  11682. if (child.parent && keepWorldPositionRotation) {
  11683. var rotation = BABYLON.Tmp.Quaternion[0];
  11684. var position = BABYLON.Tmp.Vector3[0];
  11685. var scale = BABYLON.Tmp.Vector3[1];
  11686. child.getWorldMatrix().decompose(scale, rotation, position);
  11687. if (child.rotationQuaternion) {
  11688. child.rotationQuaternion.copyFrom(rotation);
  11689. }
  11690. else {
  11691. rotation.toEulerAnglesToRef(child.rotation);
  11692. }
  11693. child.position.x = position.x;
  11694. child.position.y = position.y;
  11695. child.position.z = position.z;
  11696. }
  11697. }
  11698. else {
  11699. if (keepWorldPositionRotation) {
  11700. var rotation = BABYLON.Tmp.Quaternion[0];
  11701. var position = BABYLON.Tmp.Vector3[0];
  11702. var scale = BABYLON.Tmp.Vector3[1];
  11703. var m1 = BABYLON.Tmp.Matrix[0];
  11704. var m2 = BABYLON.Tmp.Matrix[1];
  11705. parent.getWorldMatrix().decompose(scale, rotation, position);
  11706. rotation.toRotationMatrix(m1);
  11707. m2.setTranslation(position);
  11708. m2.multiplyToRef(m1, m1);
  11709. var invParentMatrix = BABYLON.Matrix.Invert(m1);
  11710. var m = child.getWorldMatrix().multiply(invParentMatrix);
  11711. m.decompose(scale, rotation, position);
  11712. if (child.rotationQuaternion) {
  11713. child.rotationQuaternion.copyFrom(rotation);
  11714. }
  11715. else {
  11716. rotation.toEulerAnglesToRef(child.rotation);
  11717. }
  11718. invParentMatrix = BABYLON.Matrix.Invert(parent.getWorldMatrix());
  11719. var m = child.getWorldMatrix().multiply(invParentMatrix);
  11720. m.decompose(scale, rotation, position);
  11721. child.position.x = position.x;
  11722. child.position.y = position.y;
  11723. child.position.z = position.z;
  11724. }
  11725. }
  11726. child.parent = parent;
  11727. };
  11728. AbstractMesh.prototype.addChild = function (mesh, keepWorldPositionRotation) {
  11729. if (keepWorldPositionRotation === void 0) { keepWorldPositionRotation = false; }
  11730. mesh.setParent(this, keepWorldPositionRotation);
  11731. };
  11732. AbstractMesh.prototype.removeChild = function (mesh, keepWorldPositionRotation) {
  11733. if (keepWorldPositionRotation === void 0) { keepWorldPositionRotation = false; }
  11734. mesh.setParent(null, keepWorldPositionRotation);
  11735. };
  11736. AbstractMesh.prototype.getAbsolutePivotPointToRef = function (result) {
  11737. result.x = this._pivotMatrix.m[12];
  11738. result.y = this._pivotMatrix.m[13];
  11739. result.z = this._pivotMatrix.m[14];
  11740. this.getPivotPointToRef(result);
  11741. BABYLON.Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
  11742. };
  11743. // Facet data
  11744. /**
  11745. * Initialize the facet data arrays : facetNormals, facetPositions and facetPartitioning
  11746. */
  11747. AbstractMesh.prototype._initFacetData = function () {
  11748. if (!this._facetNormals) {
  11749. this._facetNormals = new Array();
  11750. }
  11751. if (!this._facetPositions) {
  11752. this._facetPositions = new Array();
  11753. }
  11754. if (!this._facetPartitioning) {
  11755. this._facetPartitioning = new Array();
  11756. }
  11757. this._facetNb = this.getIndices().length / 3;
  11758. this._partitioningSubdivisions = (this._partitioningSubdivisions) ? this._partitioningSubdivisions : 10; // default nb of partitioning subdivisions = 10
  11759. this._partitioningBBoxRatio = (this._partitioningBBoxRatio) ? this._partitioningBBoxRatio : 1.01; // default ratio 1.01 = the partitioning is 1% bigger than the bounding box
  11760. for (var f = 0; f < this._facetNb; f++) {
  11761. this._facetNormals[f] = BABYLON.Vector3.Zero();
  11762. this._facetPositions[f] = BABYLON.Vector3.Zero();
  11763. }
  11764. this._facetDataEnabled = true;
  11765. return this;
  11766. };
  11767. /**
  11768. * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated.
  11769. * This method can be called within the render loop.
  11770. * 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.
  11771. */
  11772. AbstractMesh.prototype.updateFacetData = function () {
  11773. if (!this._facetDataEnabled) {
  11774. this._initFacetData();
  11775. }
  11776. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  11777. var indices = this.getIndices();
  11778. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  11779. var bInfo = this.getBoundingInfo();
  11780. this._bbSize.x = (bInfo.maximum.x - bInfo.minimum.x > BABYLON.Epsilon) ? bInfo.maximum.x - bInfo.minimum.x : BABYLON.Epsilon;
  11781. this._bbSize.y = (bInfo.maximum.y - bInfo.minimum.y > BABYLON.Epsilon) ? bInfo.maximum.y - bInfo.minimum.y : BABYLON.Epsilon;
  11782. this._bbSize.z = (bInfo.maximum.z - bInfo.minimum.z > BABYLON.Epsilon) ? bInfo.maximum.z - bInfo.minimum.z : BABYLON.Epsilon;
  11783. var bbSizeMax = (this._bbSize.x > this._bbSize.y) ? this._bbSize.x : this._bbSize.y;
  11784. bbSizeMax = (bbSizeMax > this._bbSize.z) ? bbSizeMax : this._bbSize.z;
  11785. this._subDiv.max = this._partitioningSubdivisions;
  11786. this._subDiv.X = Math.floor(this._subDiv.max * this._bbSize.x / bbSizeMax); // adjust the number of subdivisions per axis
  11787. this._subDiv.Y = Math.floor(this._subDiv.max * this._bbSize.y / bbSizeMax); // according to each bbox size per axis
  11788. this._subDiv.Z = Math.floor(this._subDiv.max * this._bbSize.z / bbSizeMax);
  11789. this._subDiv.X = this._subDiv.X < 1 ? 1 : this._subDiv.X; // at least one subdivision
  11790. this._subDiv.Y = this._subDiv.Y < 1 ? 1 : this._subDiv.Y;
  11791. this._subDiv.Z = this._subDiv.Z < 1 ? 1 : this._subDiv.Z;
  11792. // set the parameters for ComputeNormals()
  11793. this._facetParameters.facetNormals = this.getFacetLocalNormals();
  11794. this._facetParameters.facetPositions = this.getFacetLocalPositions();
  11795. this._facetParameters.facetPartitioning = this.getFacetLocalPartitioning();
  11796. this._facetParameters.bInfo = bInfo;
  11797. this._facetParameters.bbSize = this._bbSize;
  11798. this._facetParameters.subDiv = this._subDiv;
  11799. this._facetParameters.ratio = this.partitioningBBoxRatio;
  11800. BABYLON.VertexData.ComputeNormals(positions, indices, normals, this._facetParameters);
  11801. return this;
  11802. };
  11803. /**
  11804. * Returns the facetLocalNormals array.
  11805. * The normals are expressed in the mesh local space.
  11806. */
  11807. AbstractMesh.prototype.getFacetLocalNormals = function () {
  11808. if (!this._facetNormals) {
  11809. this.updateFacetData();
  11810. }
  11811. return this._facetNormals;
  11812. };
  11813. /**
  11814. * Returns the facetLocalPositions array.
  11815. * The facet positions are expressed in the mesh local space.
  11816. */
  11817. AbstractMesh.prototype.getFacetLocalPositions = function () {
  11818. if (!this._facetPositions) {
  11819. this.updateFacetData();
  11820. }
  11821. return this._facetPositions;
  11822. };
  11823. /**
  11824. * Returns the facetLocalPartioning array
  11825. */
  11826. AbstractMesh.prototype.getFacetLocalPartitioning = function () {
  11827. if (!this._facetPartitioning) {
  11828. this.updateFacetData();
  11829. }
  11830. return this._facetPartitioning;
  11831. };
  11832. /**
  11833. * Returns the i-th facet position in the world system.
  11834. * This method allocates a new Vector3 per call.
  11835. */
  11836. AbstractMesh.prototype.getFacetPosition = function (i) {
  11837. var pos = BABYLON.Vector3.Zero();
  11838. this.getFacetPositionToRef(i, pos);
  11839. return pos;
  11840. };
  11841. /**
  11842. * Sets the reference Vector3 with the i-th facet position in the world system.
  11843. * Returns the mesh.
  11844. */
  11845. AbstractMesh.prototype.getFacetPositionToRef = function (i, ref) {
  11846. var localPos = (this.getFacetLocalPositions())[i];
  11847. var world = this.getWorldMatrix();
  11848. BABYLON.Vector3.TransformCoordinatesToRef(localPos, world, ref);
  11849. return this;
  11850. };
  11851. /**
  11852. * Returns the i-th facet normal in the world system.
  11853. * This method allocates a new Vector3 per call.
  11854. */
  11855. AbstractMesh.prototype.getFacetNormal = function (i) {
  11856. var norm = BABYLON.Vector3.Zero();
  11857. this.getFacetNormalToRef(i, norm);
  11858. return norm;
  11859. };
  11860. /**
  11861. * Sets the reference Vector3 with the i-th facet normal in the world system.
  11862. * Returns the mesh.
  11863. */
  11864. AbstractMesh.prototype.getFacetNormalToRef = function (i, ref) {
  11865. var localNorm = (this.getFacetLocalNormals())[i];
  11866. BABYLON.Vector3.TransformNormalToRef(localNorm, this.getWorldMatrix(), ref);
  11867. return this;
  11868. };
  11869. /**
  11870. * 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).
  11871. */
  11872. AbstractMesh.prototype.getFacetsAtLocalCoordinates = function (x, y, z) {
  11873. var bInfo = this.getBoundingInfo();
  11874. var ox = Math.floor((x - bInfo.minimum.x * this._partitioningBBoxRatio) * this._subDiv.X * this._partitioningBBoxRatio / this._bbSize.x);
  11875. var oy = Math.floor((y - bInfo.minimum.y * this._partitioningBBoxRatio) * this._subDiv.Y * this._partitioningBBoxRatio / this._bbSize.y);
  11876. var oz = Math.floor((z - bInfo.minimum.z * this._partitioningBBoxRatio) * this._subDiv.Z * this._partitioningBBoxRatio / this._bbSize.z);
  11877. if (ox < 0 || ox > this._subDiv.max || oy < 0 || oy > this._subDiv.max || oz < 0 || oz > this._subDiv.max) {
  11878. return null;
  11879. }
  11880. return this._facetPartitioning[ox + this._subDiv.max * oy + this._subDiv.max * this._subDiv.max * oz];
  11881. };
  11882. /**
  11883. * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found.
  11884. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) World projection on the facet.
  11885. * 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.
  11886. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  11887. * 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.
  11888. */
  11889. AbstractMesh.prototype.getClosestFacetAtCoordinates = function (x, y, z, projected, checkFace, facing) {
  11890. if (checkFace === void 0) { checkFace = false; }
  11891. if (facing === void 0) { facing = true; }
  11892. var world = this.getWorldMatrix();
  11893. var invMat = BABYLON.Tmp.Matrix[5];
  11894. world.invertToRef(invMat);
  11895. var invVect = BABYLON.Tmp.Vector3[8];
  11896. var closest = null;
  11897. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, invMat, invVect); // transform (x,y,z) to coordinates in the mesh local space
  11898. closest = this.getClosestFacetAtLocalCoordinates(invVect.x, invVect.y, invVect.z, projected, checkFace, facing);
  11899. if (projected) {
  11900. // tranform the local computed projected vector to world coordinates
  11901. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(projected.x, projected.y, projected.z, world, projected);
  11902. }
  11903. return closest;
  11904. };
  11905. /**
  11906. * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found.
  11907. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) local projection on the facet.
  11908. * 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.
  11909. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  11910. * 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.
  11911. */
  11912. AbstractMesh.prototype.getClosestFacetAtLocalCoordinates = function (x, y, z, projected, checkFace, facing) {
  11913. if (checkFace === void 0) { checkFace = false; }
  11914. if (facing === void 0) { facing = true; }
  11915. var closest = null;
  11916. var tmpx = 0.0;
  11917. var tmpy = 0.0;
  11918. var tmpz = 0.0;
  11919. var d = 0.0; // tmp dot facet normal * facet position
  11920. var t0 = 0.0;
  11921. var projx = 0.0;
  11922. var projy = 0.0;
  11923. var projz = 0.0;
  11924. // Get all the facets in the same partitioning block than (x, y, z)
  11925. var facetPositions = this.getFacetLocalPositions();
  11926. var facetNormals = this.getFacetLocalNormals();
  11927. var facetsInBlock = this.getFacetsAtLocalCoordinates(x, y, z);
  11928. if (!facetsInBlock) {
  11929. return null;
  11930. }
  11931. // Get the closest facet to (x, y, z)
  11932. var shortest = Number.MAX_VALUE; // init distance vars
  11933. var tmpDistance = shortest;
  11934. var fib; // current facet in the block
  11935. var norm; // current facet normal
  11936. var p0; // current facet barycenter position
  11937. // loop on all the facets in the current partitioning block
  11938. for (var idx = 0; idx < facetsInBlock.length; idx++) {
  11939. fib = facetsInBlock[idx];
  11940. norm = facetNormals[fib];
  11941. p0 = facetPositions[fib];
  11942. d = (x - p0.x) * norm.x + (y - p0.y) * norm.y + (z - p0.z) * norm.z;
  11943. if (!checkFace || (checkFace && facing && d >= 0.0) || (checkFace && !facing && d <= 0.0)) {
  11944. // compute (x,y,z) projection on the facet = (projx, projy, projz)
  11945. d = norm.x * p0.x + norm.y * p0.y + norm.z * p0.z;
  11946. t0 = -(norm.x * x + norm.y * y + norm.z * z - d) / (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);
  11947. projx = x + norm.x * t0;
  11948. projy = y + norm.y * t0;
  11949. projz = z + norm.z * t0;
  11950. tmpx = projx - x;
  11951. tmpy = projy - y;
  11952. tmpz = projz - z;
  11953. tmpDistance = tmpx * tmpx + tmpy * tmpy + tmpz * tmpz; // compute length between (x, y, z) and its projection on the facet
  11954. if (tmpDistance < shortest) {
  11955. shortest = tmpDistance;
  11956. closest = fib;
  11957. if (projected) {
  11958. projected.x = projx;
  11959. projected.y = projy;
  11960. projected.z = projz;
  11961. }
  11962. }
  11963. }
  11964. }
  11965. return closest;
  11966. };
  11967. /**
  11968. * Returns the object "parameter" set with all the expected parameters for facetData computation by ComputeNormals()
  11969. */
  11970. AbstractMesh.prototype.getFacetDataParameters = function () {
  11971. return this._facetParameters;
  11972. };
  11973. /**
  11974. * Disables the feature FacetData and frees the related memory.
  11975. * Returns the mesh.
  11976. */
  11977. AbstractMesh.prototype.disableFacetData = function () {
  11978. if (this._facetDataEnabled) {
  11979. this._facetDataEnabled = false;
  11980. this._facetPositions = null;
  11981. this._facetNormals = null;
  11982. this._facetPartitioning = null;
  11983. this._facetParameters = null;
  11984. }
  11985. return this;
  11986. };
  11987. return AbstractMesh;
  11988. }(BABYLON.Node));
  11989. // Statics
  11990. AbstractMesh._BILLBOARDMODE_NONE = 0;
  11991. AbstractMesh._BILLBOARDMODE_X = 1;
  11992. AbstractMesh._BILLBOARDMODE_Y = 2;
  11993. AbstractMesh._BILLBOARDMODE_Z = 4;
  11994. AbstractMesh._BILLBOARDMODE_ALL = 7;
  11995. AbstractMesh._rotationAxisCache = new BABYLON.Quaternion();
  11996. AbstractMesh._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  11997. BABYLON.AbstractMesh = AbstractMesh;
  11998. })(BABYLON || (BABYLON = {}));
  11999. //# sourceMappingURL=babylon.abstractMesh.js.map
  12000. var BABYLON;
  12001. (function (BABYLON) {
  12002. var Light = (function (_super) {
  12003. __extends(Light, _super);
  12004. function Light(name, scene) {
  12005. var _this = _super.call(this, name, scene) || this;
  12006. _this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  12007. _this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  12008. _this.intensity = 1.0;
  12009. _this.range = Number.MAX_VALUE;
  12010. _this.includeOnlyWithLayerMask = 0;
  12011. _this.includedOnlyMeshes = new Array();
  12012. _this.excludedMeshes = new Array();
  12013. _this.excludeWithLayerMask = 0;
  12014. _this.lightmapMode = 0;
  12015. // PBR Properties.
  12016. _this.radius = 0.00001;
  12017. _this._excludedMeshesIds = new Array();
  12018. _this._includedOnlyMeshesIds = new Array();
  12019. scene.addLight(_this);
  12020. return _this;
  12021. }
  12022. Object.defineProperty(Light, "LIGHTMAP_DEFAULT", {
  12023. /**
  12024. * If every light affecting the material is in this lightmapMode,
  12025. * material.lightmapTexture adds or multiplies
  12026. * (depends on material.useLightmapAsShadowmap)
  12027. * after every other light calculations.
  12028. */
  12029. get: function () {
  12030. return Light._LIGHTMAP_DEFAULT;
  12031. },
  12032. enumerable: true,
  12033. configurable: true
  12034. });
  12035. Object.defineProperty(Light, "LIGHTMAP_SPECULAR", {
  12036. /**
  12037. * material.lightmapTexture as only diffuse lighting from this light
  12038. * adds pnly specular lighting from this light
  12039. * adds dynamic shadows
  12040. */
  12041. get: function () {
  12042. return Light._LIGHTMAP_SPECULAR;
  12043. },
  12044. enumerable: true,
  12045. configurable: true
  12046. });
  12047. Object.defineProperty(Light, "LIGHTMAP_SHADOWSONLY", {
  12048. /**
  12049. * material.lightmapTexture as only lighting
  12050. * no light calculation from this light
  12051. * only adds dynamic shadows from this light
  12052. */
  12053. get: function () {
  12054. return Light._LIGHTMAP_SHADOWSONLY;
  12055. },
  12056. enumerable: true,
  12057. configurable: true
  12058. });
  12059. Light.prototype.getClassName = function () {
  12060. return "Light";
  12061. };
  12062. /**
  12063. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  12064. */
  12065. Light.prototype.toString = function (fullDetails) {
  12066. var ret = "Name: " + this.name;
  12067. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  12068. if (this.animations) {
  12069. for (var i = 0; i < this.animations.length; i++) {
  12070. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  12071. }
  12072. }
  12073. if (fullDetails) {
  12074. }
  12075. return ret;
  12076. };
  12077. Light.prototype.getShadowGenerator = function () {
  12078. return this._shadowGenerator;
  12079. };
  12080. Light.prototype.getAbsolutePosition = function () {
  12081. return BABYLON.Vector3.Zero();
  12082. };
  12083. Light.prototype.transferToEffect = function (effect, uniformName0, uniformName1) {
  12084. };
  12085. Light.prototype._getWorldMatrix = function () {
  12086. return BABYLON.Matrix.Identity();
  12087. };
  12088. Light.prototype.canAffectMesh = function (mesh) {
  12089. if (!mesh) {
  12090. return true;
  12091. }
  12092. if (this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  12093. return false;
  12094. }
  12095. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  12096. return false;
  12097. }
  12098. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  12099. return false;
  12100. }
  12101. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  12102. return false;
  12103. }
  12104. return true;
  12105. };
  12106. Light.prototype.getWorldMatrix = function () {
  12107. this._currentRenderId = this.getScene().getRenderId();
  12108. var worldMatrix = this._getWorldMatrix();
  12109. if (this.parent && this.parent.getWorldMatrix) {
  12110. if (!this._parentedWorldMatrix) {
  12111. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  12112. }
  12113. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  12114. this._markSyncedWithParent();
  12115. return this._parentedWorldMatrix;
  12116. }
  12117. return worldMatrix;
  12118. };
  12119. Light.prototype.dispose = function () {
  12120. if (this._shadowGenerator) {
  12121. this._shadowGenerator.dispose();
  12122. this._shadowGenerator = null;
  12123. }
  12124. // Animations
  12125. this.getScene().stopAnimation(this);
  12126. // Remove from scene
  12127. this.getScene().removeLight(this);
  12128. _super.prototype.dispose.call(this);
  12129. };
  12130. Light.prototype.getTypeID = function () {
  12131. return 0;
  12132. };
  12133. Light.prototype.clone = function (name) {
  12134. return BABYLON.SerializationHelper.Clone(Light.GetConstructorFromName(this.getTypeID(), name, this.getScene()), this);
  12135. };
  12136. Light.prototype.serialize = function () {
  12137. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  12138. // Type
  12139. serializationObject.type = this.getTypeID();
  12140. // Parent
  12141. if (this.parent) {
  12142. serializationObject.parentId = this.parent.id;
  12143. }
  12144. // Inclusion / exclusions
  12145. if (this.excludedMeshes.length > 0) {
  12146. serializationObject.excludedMeshesIds = [];
  12147. this.excludedMeshes.forEach(function (mesh) {
  12148. serializationObject.excludedMeshesIds.push(mesh.id);
  12149. });
  12150. }
  12151. if (this.includedOnlyMeshes.length > 0) {
  12152. serializationObject.includedOnlyMeshesIds = [];
  12153. this.includedOnlyMeshes.forEach(function (mesh) {
  12154. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  12155. });
  12156. }
  12157. // Animations
  12158. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  12159. serializationObject.ranges = this.serializeAnimationRanges();
  12160. return serializationObject;
  12161. };
  12162. Light.GetConstructorFromName = function (type, name, scene) {
  12163. switch (type) {
  12164. case 0:
  12165. return function () { return new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), scene); };
  12166. case 1:
  12167. return function () { return new BABYLON.DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  12168. case 2:
  12169. return function () { return new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  12170. case 3:
  12171. return function () { return new BABYLON.HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  12172. }
  12173. };
  12174. Light.Parse = function (parsedLight, scene) {
  12175. var light = BABYLON.SerializationHelper.Parse(Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene), parsedLight, scene);
  12176. // Inclusion / exclusions
  12177. if (parsedLight.excludedMeshesIds) {
  12178. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  12179. }
  12180. if (parsedLight.includedOnlyMeshesIds) {
  12181. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  12182. }
  12183. // Parent
  12184. if (parsedLight.parentId) {
  12185. light._waitingParentId = parsedLight.parentId;
  12186. }
  12187. // Animations
  12188. if (parsedLight.animations) {
  12189. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  12190. var parsedAnimation = parsedLight.animations[animationIndex];
  12191. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  12192. }
  12193. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  12194. }
  12195. if (parsedLight.autoAnimate) {
  12196. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  12197. }
  12198. return light;
  12199. };
  12200. return Light;
  12201. }(BABYLON.Node));
  12202. //lightmapMode Consts
  12203. Light._LIGHTMAP_DEFAULT = 0;
  12204. Light._LIGHTMAP_SPECULAR = 1;
  12205. Light._LIGHTMAP_SHADOWSONLY = 2;
  12206. __decorate([
  12207. BABYLON.serializeAsColor3()
  12208. ], Light.prototype, "diffuse", void 0);
  12209. __decorate([
  12210. BABYLON.serializeAsColor3()
  12211. ], Light.prototype, "specular", void 0);
  12212. __decorate([
  12213. BABYLON.serialize()
  12214. ], Light.prototype, "intensity", void 0);
  12215. __decorate([
  12216. BABYLON.serialize()
  12217. ], Light.prototype, "range", void 0);
  12218. __decorate([
  12219. BABYLON.serialize()
  12220. ], Light.prototype, "includeOnlyWithLayerMask", void 0);
  12221. __decorate([
  12222. BABYLON.serialize()
  12223. ], Light.prototype, "excludeWithLayerMask", void 0);
  12224. __decorate([
  12225. BABYLON.serialize()
  12226. ], Light.prototype, "lightmapMode", void 0);
  12227. __decorate([
  12228. BABYLON.serialize()
  12229. ], Light.prototype, "radius", void 0);
  12230. BABYLON.Light = Light;
  12231. })(BABYLON || (BABYLON = {}));
  12232. //# sourceMappingURL=babylon.light.js.map
  12233. var BABYLON;
  12234. (function (BABYLON) {
  12235. var PointLight = (function (_super) {
  12236. __extends(PointLight, _super);
  12237. function PointLight(name, position, scene) {
  12238. var _this = _super.call(this, name, scene) || this;
  12239. _this.position = position;
  12240. return _this;
  12241. }
  12242. PointLight.prototype.getClassName = function () {
  12243. return "PointLight";
  12244. };
  12245. PointLight.prototype.getAbsolutePosition = function () {
  12246. return this.transformedPosition ? this.transformedPosition : this.position;
  12247. };
  12248. PointLight.prototype.computeTransformedPosition = function () {
  12249. if (this.parent && this.parent.getWorldMatrix) {
  12250. if (!this.transformedPosition) {
  12251. this.transformedPosition = BABYLON.Vector3.Zero();
  12252. }
  12253. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  12254. return true;
  12255. }
  12256. return false;
  12257. };
  12258. PointLight.prototype.transferToEffect = function (effect, positionUniformName) {
  12259. if (this.parent && this.parent.getWorldMatrix) {
  12260. this.computeTransformedPosition();
  12261. effect.setFloat4(positionUniformName, this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0);
  12262. return;
  12263. }
  12264. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, 0);
  12265. };
  12266. PointLight.prototype.needCube = function () {
  12267. return true;
  12268. };
  12269. PointLight.prototype.supportsVSM = function () {
  12270. return false;
  12271. };
  12272. PointLight.prototype.needRefreshPerFrame = function () {
  12273. return false;
  12274. };
  12275. PointLight.prototype.getShadowDirection = function (faceIndex) {
  12276. switch (faceIndex) {
  12277. case 0:
  12278. return new BABYLON.Vector3(1, 0, 0);
  12279. case 1:
  12280. return new BABYLON.Vector3(-1, 0, 0);
  12281. case 2:
  12282. return new BABYLON.Vector3(0, -1, 0);
  12283. case 3:
  12284. return new BABYLON.Vector3(0, 1, 0);
  12285. case 4:
  12286. return new BABYLON.Vector3(0, 0, 1);
  12287. case 5:
  12288. return new BABYLON.Vector3(0, 0, -1);
  12289. }
  12290. return BABYLON.Vector3.Zero();
  12291. };
  12292. PointLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  12293. var activeCamera = this.getScene().activeCamera;
  12294. BABYLON.Matrix.PerspectiveFovLHToRef(Math.PI / 2, 1.0, activeCamera.minZ, activeCamera.maxZ, matrix);
  12295. };
  12296. PointLight.prototype._getWorldMatrix = function () {
  12297. if (!this._worldMatrix) {
  12298. this._worldMatrix = BABYLON.Matrix.Identity();
  12299. }
  12300. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  12301. return this._worldMatrix;
  12302. };
  12303. PointLight.prototype.getTypeID = function () {
  12304. return 0;
  12305. };
  12306. return PointLight;
  12307. }(BABYLON.Light));
  12308. __decorate([
  12309. BABYLON.serializeAsVector3()
  12310. ], PointLight.prototype, "position", void 0);
  12311. BABYLON.PointLight = PointLight;
  12312. })(BABYLON || (BABYLON = {}));
  12313. //# sourceMappingURL=babylon.pointLight.js.map
  12314. var BABYLON;
  12315. (function (BABYLON) {
  12316. var SpotLight = (function (_super) {
  12317. __extends(SpotLight, _super);
  12318. function SpotLight(name, position, direction, angle, exponent, scene) {
  12319. var _this = _super.call(this, name, scene) || this;
  12320. _this.position = position;
  12321. _this.direction = direction;
  12322. _this.angle = angle;
  12323. _this.exponent = exponent;
  12324. return _this;
  12325. }
  12326. SpotLight.prototype.getClassName = function () {
  12327. return "SpotLight";
  12328. };
  12329. SpotLight.prototype.getAbsolutePosition = function () {
  12330. return this.transformedPosition ? this.transformedPosition : this.position;
  12331. };
  12332. SpotLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  12333. var activeCamera = this.getScene().activeCamera;
  12334. BABYLON.Matrix.PerspectiveFovLHToRef(this.angle, 1.0, activeCamera.minZ, activeCamera.maxZ, matrix);
  12335. };
  12336. SpotLight.prototype.needCube = function () {
  12337. return false;
  12338. };
  12339. SpotLight.prototype.supportsVSM = function () {
  12340. return true;
  12341. };
  12342. SpotLight.prototype.needRefreshPerFrame = function () {
  12343. return false;
  12344. };
  12345. SpotLight.prototype.getShadowDirection = function (faceIndex) {
  12346. return this.direction;
  12347. };
  12348. SpotLight.prototype.setDirectionToTarget = function (target) {
  12349. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  12350. return this.direction;
  12351. };
  12352. SpotLight.prototype.computeTransformedPosition = function () {
  12353. if (this.parent && this.parent.getWorldMatrix) {
  12354. if (!this.transformedPosition) {
  12355. this.transformedPosition = BABYLON.Vector3.Zero();
  12356. }
  12357. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  12358. return true;
  12359. }
  12360. return false;
  12361. };
  12362. SpotLight.prototype.transferToEffect = function (effect, positionUniformName, directionUniformName) {
  12363. var normalizeDirection;
  12364. if (this.parent && this.parent.getWorldMatrix) {
  12365. if (!this._transformedDirection) {
  12366. this._transformedDirection = BABYLON.Vector3.Zero();
  12367. }
  12368. this.computeTransformedPosition();
  12369. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  12370. effect.setFloat4(positionUniformName, this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent);
  12371. normalizeDirection = BABYLON.Vector3.Normalize(this._transformedDirection);
  12372. }
  12373. else {
  12374. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, this.exponent);
  12375. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  12376. }
  12377. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5));
  12378. };
  12379. SpotLight.prototype._getWorldMatrix = function () {
  12380. if (!this._worldMatrix) {
  12381. this._worldMatrix = BABYLON.Matrix.Identity();
  12382. }
  12383. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  12384. return this._worldMatrix;
  12385. };
  12386. SpotLight.prototype.getTypeID = function () {
  12387. return 2;
  12388. };
  12389. SpotLight.prototype.getRotation = function () {
  12390. this.direction.normalize();
  12391. var xaxis = BABYLON.Vector3.Cross(this.direction, BABYLON.Axis.Y);
  12392. var yaxis = BABYLON.Vector3.Cross(xaxis, this.direction);
  12393. return BABYLON.Vector3.RotationFromAxis(xaxis, yaxis, this.direction);
  12394. };
  12395. return SpotLight;
  12396. }(BABYLON.Light));
  12397. __decorate([
  12398. BABYLON.serializeAsVector3()
  12399. ], SpotLight.prototype, "position", void 0);
  12400. __decorate([
  12401. BABYLON.serializeAsVector3()
  12402. ], SpotLight.prototype, "direction", void 0);
  12403. __decorate([
  12404. BABYLON.serialize()
  12405. ], SpotLight.prototype, "angle", void 0);
  12406. __decorate([
  12407. BABYLON.serialize()
  12408. ], SpotLight.prototype, "exponent", void 0);
  12409. BABYLON.SpotLight = SpotLight;
  12410. })(BABYLON || (BABYLON = {}));
  12411. //# sourceMappingURL=babylon.spotLight.js.map
  12412. var BABYLON;
  12413. (function (BABYLON) {
  12414. var HemisphericLight = (function (_super) {
  12415. __extends(HemisphericLight, _super);
  12416. function HemisphericLight(name, direction, scene) {
  12417. var _this = _super.call(this, name, scene) || this;
  12418. _this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  12419. _this.direction = direction;
  12420. return _this;
  12421. }
  12422. HemisphericLight.prototype.getClassName = function () {
  12423. return "HemisphericLight";
  12424. };
  12425. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  12426. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  12427. return this.direction;
  12428. };
  12429. HemisphericLight.prototype.getShadowGenerator = function () {
  12430. return null;
  12431. };
  12432. HemisphericLight.prototype.transferToEffect = function (effect, directionUniformName, groundColorUniformName) {
  12433. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  12434. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0);
  12435. effect.setColor3(groundColorUniformName, this.groundColor.scale(this.intensity));
  12436. };
  12437. HemisphericLight.prototype._getWorldMatrix = function () {
  12438. if (!this._worldMatrix) {
  12439. this._worldMatrix = BABYLON.Matrix.Identity();
  12440. }
  12441. return this._worldMatrix;
  12442. };
  12443. HemisphericLight.prototype.getTypeID = function () {
  12444. return 3;
  12445. };
  12446. return HemisphericLight;
  12447. }(BABYLON.Light));
  12448. __decorate([
  12449. BABYLON.serializeAsColor3()
  12450. ], HemisphericLight.prototype, "groundColor", void 0);
  12451. __decorate([
  12452. BABYLON.serializeAsVector3()
  12453. ], HemisphericLight.prototype, "direction", void 0);
  12454. BABYLON.HemisphericLight = HemisphericLight;
  12455. })(BABYLON || (BABYLON = {}));
  12456. //# sourceMappingURL=babylon.hemisphericLight.js.map
  12457. var BABYLON;
  12458. (function (BABYLON) {
  12459. var DirectionalLight = (function (_super) {
  12460. __extends(DirectionalLight, _super);
  12461. function DirectionalLight(name, direction, scene) {
  12462. var _this = _super.call(this, name, scene) || this;
  12463. _this.shadowOrthoScale = 0.5;
  12464. _this.autoUpdateExtends = true;
  12465. // Cache
  12466. _this._orthoLeft = Number.MAX_VALUE;
  12467. _this._orthoRight = Number.MIN_VALUE;
  12468. _this._orthoTop = Number.MIN_VALUE;
  12469. _this._orthoBottom = Number.MAX_VALUE;
  12470. _this.position = direction.scale(-1);
  12471. _this.direction = direction;
  12472. return _this;
  12473. }
  12474. DirectionalLight.prototype.getClassName = function () {
  12475. return "DirectionalLight";
  12476. };
  12477. DirectionalLight.prototype.getAbsolutePosition = function () {
  12478. return this.transformedPosition ? this.transformedPosition : this.position;
  12479. };
  12480. DirectionalLight.prototype.setDirectionToTarget = function (target) {
  12481. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  12482. return this.direction;
  12483. };
  12484. DirectionalLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  12485. var activeCamera = this.getScene().activeCamera;
  12486. // Check extends
  12487. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  12488. var tempVector3 = BABYLON.Vector3.Zero();
  12489. this._orthoLeft = Number.MAX_VALUE;
  12490. this._orthoRight = Number.MIN_VALUE;
  12491. this._orthoTop = Number.MIN_VALUE;
  12492. this._orthoBottom = Number.MAX_VALUE;
  12493. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  12494. var mesh = renderList[meshIndex];
  12495. if (!mesh) {
  12496. continue;
  12497. }
  12498. var boundingInfo = mesh.getBoundingInfo();
  12499. if (!boundingInfo) {
  12500. continue;
  12501. }
  12502. var boundingBox = boundingInfo.boundingBox;
  12503. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  12504. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  12505. if (tempVector3.x < this._orthoLeft)
  12506. this._orthoLeft = tempVector3.x;
  12507. if (tempVector3.y < this._orthoBottom)
  12508. this._orthoBottom = tempVector3.y;
  12509. if (tempVector3.x > this._orthoRight)
  12510. this._orthoRight = tempVector3.x;
  12511. if (tempVector3.y > this._orthoTop)
  12512. this._orthoTop = tempVector3.y;
  12513. }
  12514. }
  12515. }
  12516. var xOffset = this._orthoRight - this._orthoLeft;
  12517. var yOffset = this._orthoTop - this._orthoBottom;
  12518. BABYLON.Matrix.OrthoOffCenterLHToRef(this._orthoLeft - xOffset * this.shadowOrthoScale, this._orthoRight + xOffset * this.shadowOrthoScale, this._orthoBottom - yOffset * this.shadowOrthoScale, this._orthoTop + yOffset * this.shadowOrthoScale, -activeCamera.maxZ, activeCamera.maxZ, matrix);
  12519. };
  12520. DirectionalLight.prototype.supportsVSM = function () {
  12521. return true;
  12522. };
  12523. DirectionalLight.prototype.needRefreshPerFrame = function () {
  12524. return true;
  12525. };
  12526. DirectionalLight.prototype.needCube = function () {
  12527. return false;
  12528. };
  12529. DirectionalLight.prototype.getShadowDirection = function (faceIndex) {
  12530. return this.direction;
  12531. };
  12532. DirectionalLight.prototype.computeTransformedPosition = function () {
  12533. if (this.parent && this.parent.getWorldMatrix) {
  12534. if (!this.transformedPosition) {
  12535. this.transformedPosition = BABYLON.Vector3.Zero();
  12536. }
  12537. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  12538. return true;
  12539. }
  12540. return false;
  12541. };
  12542. DirectionalLight.prototype.transferToEffect = function (effect, directionUniformName) {
  12543. if (this.parent && this.parent.getWorldMatrix) {
  12544. if (!this._transformedDirection) {
  12545. this._transformedDirection = BABYLON.Vector3.Zero();
  12546. }
  12547. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  12548. effect.setFloat4(directionUniformName, this._transformedDirection.x, this._transformedDirection.y, this._transformedDirection.z, 1);
  12549. return;
  12550. }
  12551. effect.setFloat4(directionUniformName, this.direction.x, this.direction.y, this.direction.z, 1);
  12552. };
  12553. DirectionalLight.prototype._getWorldMatrix = function () {
  12554. if (!this._worldMatrix) {
  12555. this._worldMatrix = BABYLON.Matrix.Identity();
  12556. }
  12557. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  12558. return this._worldMatrix;
  12559. };
  12560. DirectionalLight.prototype.getTypeID = function () {
  12561. return 1;
  12562. };
  12563. return DirectionalLight;
  12564. }(BABYLON.Light));
  12565. __decorate([
  12566. BABYLON.serializeAsVector3()
  12567. ], DirectionalLight.prototype, "position", void 0);
  12568. __decorate([
  12569. BABYLON.serializeAsVector3()
  12570. ], DirectionalLight.prototype, "direction", void 0);
  12571. __decorate([
  12572. BABYLON.serialize()
  12573. ], DirectionalLight.prototype, "shadowOrthoScale", void 0);
  12574. __decorate([
  12575. BABYLON.serialize()
  12576. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  12577. BABYLON.DirectionalLight = DirectionalLight;
  12578. })(BABYLON || (BABYLON = {}));
  12579. //# sourceMappingURL=babylon.directionalLight.js.map
  12580. var BABYLON;
  12581. (function (BABYLON) {
  12582. var ShadowGenerator = (function () {
  12583. function ShadowGenerator(mapSize, light) {
  12584. var _this = this;
  12585. // Members
  12586. this._filter = ShadowGenerator.FILTER_NONE;
  12587. this.blurScale = 2;
  12588. this._blurBoxOffset = 0;
  12589. this._bias = 0.00005;
  12590. this._lightDirection = BABYLON.Vector3.Zero();
  12591. this.forceBackFacesOnly = false;
  12592. this._darkness = 0;
  12593. this._transparencyShadow = false;
  12594. this._viewMatrix = BABYLON.Matrix.Zero();
  12595. this._projectionMatrix = BABYLON.Matrix.Zero();
  12596. this._transformMatrix = BABYLON.Matrix.Zero();
  12597. this._worldViewProjection = BABYLON.Matrix.Zero();
  12598. this._currentFaceIndex = 0;
  12599. this._currentFaceIndexCache = 0;
  12600. this._useFullFloat = true;
  12601. this._light = light;
  12602. this._scene = light.getScene();
  12603. this._mapSize = mapSize;
  12604. light._shadowGenerator = this;
  12605. // Texture type fallback from float to int if not supported.
  12606. var textureType;
  12607. var caps = this._scene.getEngine().getCaps();
  12608. if (caps.textureFloat && caps.textureFloatLinearFiltering && caps.textureFloatRender) {
  12609. this._useFullFloat = true;
  12610. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  12611. }
  12612. else {
  12613. this._useFullFloat = false;
  12614. textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  12615. }
  12616. // Render target
  12617. this._shadowMap = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, this._scene, false, true, textureType, light.needCube());
  12618. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  12619. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  12620. this._shadowMap.anisotropicFilteringLevel = 1;
  12621. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  12622. this._shadowMap.renderParticles = false;
  12623. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  12624. _this._currentFaceIndex = faceIndex;
  12625. });
  12626. this._shadowMap.onAfterUnbindObservable.add(function () {
  12627. if (!_this.useBlurVarianceShadowMap) {
  12628. return;
  12629. }
  12630. if (!_this._shadowMap2) {
  12631. _this._shadowMap2 = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, _this._scene, false, true, textureType);
  12632. _this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  12633. _this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  12634. _this._shadowMap2.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  12635. _this._downSamplePostprocess = new BABYLON.PassPostProcess("downScale", 1.0 / _this.blurScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, _this._scene.getEngine());
  12636. _this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  12637. effect.setTexture("textureSampler", _this._shadowMap);
  12638. });
  12639. _this.blurBoxOffset = 1;
  12640. }
  12641. _this._scene.postProcessManager.directRender([_this._downSamplePostprocess, _this._boxBlurPostprocess], _this._shadowMap2.getInternalTexture());
  12642. });
  12643. // Custom render function
  12644. var renderSubMesh = function (subMesh) {
  12645. var mesh = subMesh.getRenderingMesh();
  12646. var scene = _this._scene;
  12647. var engine = scene.getEngine();
  12648. // Culling
  12649. engine.setState(subMesh.getMaterial().backFaceCulling);
  12650. // Managing instances
  12651. var batch = mesh._getInstancesRenderList(subMesh._id);
  12652. if (batch.mustReturn) {
  12653. return;
  12654. }
  12655. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  12656. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  12657. engine.enableEffect(_this._effect);
  12658. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  12659. var material = subMesh.getMaterial();
  12660. _this._effect.setMatrix("viewProjection", _this.getTransformMatrix());
  12661. _this._effect.setVector3("lightPosition", _this.getLight().position);
  12662. if (_this.getLight().needCube()) {
  12663. _this._effect.setFloat2("depthValues", scene.activeCamera.minZ, scene.activeCamera.maxZ);
  12664. }
  12665. // Alpha test
  12666. if (material && material.needAlphaTesting()) {
  12667. var alphaTexture = material.getAlphaTestTexture();
  12668. _this._effect.setTexture("diffuseSampler", alphaTexture);
  12669. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  12670. }
  12671. // Bones
  12672. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  12673. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  12674. }
  12675. if (_this.forceBackFacesOnly) {
  12676. engine.setState(true, 0, false, true);
  12677. }
  12678. // Draw
  12679. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  12680. if (_this.forceBackFacesOnly) {
  12681. engine.setState(true, 0, false, false);
  12682. }
  12683. }
  12684. else {
  12685. // Need to reset refresh rate of the shadowMap
  12686. _this._shadowMap.resetRefreshCounter();
  12687. }
  12688. };
  12689. this._shadowMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  12690. var index;
  12691. for (index = 0; index < opaqueSubMeshes.length; index++) {
  12692. renderSubMesh(opaqueSubMeshes.data[index]);
  12693. }
  12694. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  12695. renderSubMesh(alphaTestSubMeshes.data[index]);
  12696. }
  12697. if (_this._transparencyShadow) {
  12698. for (index = 0; index < transparentSubMeshes.length; index++) {
  12699. renderSubMesh(transparentSubMeshes.data[index]);
  12700. }
  12701. }
  12702. };
  12703. this._shadowMap.onClearObservable.add(function (engine) {
  12704. if (_this.useBlurVarianceShadowMap || _this.useVarianceShadowMap) {
  12705. engine.clear(new BABYLON.Color4(0, 0, 0, 0), true, true, true);
  12706. }
  12707. else {
  12708. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  12709. }
  12710. });
  12711. }
  12712. Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
  12713. // Static
  12714. get: function () {
  12715. return ShadowGenerator._FILTER_NONE;
  12716. },
  12717. enumerable: true,
  12718. configurable: true
  12719. });
  12720. Object.defineProperty(ShadowGenerator, "FILTER_VARIANCESHADOWMAP", {
  12721. get: function () {
  12722. return ShadowGenerator._FILTER_VARIANCESHADOWMAP;
  12723. },
  12724. enumerable: true,
  12725. configurable: true
  12726. });
  12727. Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
  12728. get: function () {
  12729. return ShadowGenerator._FILTER_POISSONSAMPLING;
  12730. },
  12731. enumerable: true,
  12732. configurable: true
  12733. });
  12734. Object.defineProperty(ShadowGenerator, "FILTER_BLURVARIANCESHADOWMAP", {
  12735. get: function () {
  12736. return ShadowGenerator._FILTER_BLURVARIANCESHADOWMAP;
  12737. },
  12738. enumerable: true,
  12739. configurable: true
  12740. });
  12741. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  12742. get: function () {
  12743. return this._bias;
  12744. },
  12745. set: function (bias) {
  12746. this._bias = bias;
  12747. },
  12748. enumerable: true,
  12749. configurable: true
  12750. });
  12751. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  12752. get: function () {
  12753. return this._blurBoxOffset;
  12754. },
  12755. set: function (value) {
  12756. var _this = this;
  12757. if (this._blurBoxOffset === value) {
  12758. return;
  12759. }
  12760. this._blurBoxOffset = value;
  12761. if (this._boxBlurPostprocess) {
  12762. this._boxBlurPostprocess.dispose();
  12763. }
  12764. 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);
  12765. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  12766. effect.setFloat2("screenSize", _this._mapSize / _this.blurScale, _this._mapSize / _this.blurScale);
  12767. });
  12768. },
  12769. enumerable: true,
  12770. configurable: true
  12771. });
  12772. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  12773. get: function () {
  12774. return this._filter;
  12775. },
  12776. set: function (value) {
  12777. if (this._filter === value) {
  12778. return;
  12779. }
  12780. this._filter = value;
  12781. if (this.useVarianceShadowMap || this.useBlurVarianceShadowMap || this.usePoissonSampling) {
  12782. this._shadowMap.anisotropicFilteringLevel = 16;
  12783. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  12784. }
  12785. else {
  12786. this._shadowMap.anisotropicFilteringLevel = 1;
  12787. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  12788. }
  12789. },
  12790. enumerable: true,
  12791. configurable: true
  12792. });
  12793. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  12794. get: function () {
  12795. return this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP && this._light.supportsVSM();
  12796. },
  12797. set: function (value) {
  12798. this.filter = (value ? ShadowGenerator.FILTER_VARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  12799. },
  12800. enumerable: true,
  12801. configurable: true
  12802. });
  12803. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  12804. get: function () {
  12805. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING ||
  12806. (!this._light.supportsVSM() && (this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP ||
  12807. this.filter === ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP));
  12808. },
  12809. set: function (value) {
  12810. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  12811. },
  12812. enumerable: true,
  12813. configurable: true
  12814. });
  12815. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  12816. get: function () {
  12817. return this.filter === ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP && this._light.supportsVSM();
  12818. },
  12819. set: function (value) {
  12820. this.filter = (value ? ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  12821. },
  12822. enumerable: true,
  12823. configurable: true
  12824. });
  12825. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  12826. var defines = [];
  12827. if (this._useFullFloat) {
  12828. defines.push("#define FULLFLOAT");
  12829. }
  12830. if (this.useVarianceShadowMap || this.useBlurVarianceShadowMap) {
  12831. defines.push("#define VSM");
  12832. }
  12833. if (this.getLight().needCube()) {
  12834. defines.push("#define CUBEMAP");
  12835. }
  12836. var attribs = [BABYLON.VertexBuffer.PositionKind];
  12837. var mesh = subMesh.getMesh();
  12838. var material = subMesh.getMaterial();
  12839. // Alpha test
  12840. if (material && material.needAlphaTesting()) {
  12841. defines.push("#define ALPHATEST");
  12842. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  12843. attribs.push(BABYLON.VertexBuffer.UVKind);
  12844. defines.push("#define UV1");
  12845. }
  12846. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  12847. var alphaTexture = material.getAlphaTestTexture();
  12848. if (alphaTexture.coordinatesIndex === 1) {
  12849. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  12850. defines.push("#define UV2");
  12851. }
  12852. }
  12853. }
  12854. // Bones
  12855. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  12856. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  12857. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  12858. if (mesh.numBoneInfluencers > 4) {
  12859. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  12860. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  12861. }
  12862. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  12863. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  12864. }
  12865. else {
  12866. defines.push("#define NUM_BONE_INFLUENCERS 0");
  12867. }
  12868. // Instances
  12869. if (useInstances) {
  12870. defines.push("#define INSTANCES");
  12871. attribs.push("world0");
  12872. attribs.push("world1");
  12873. attribs.push("world2");
  12874. attribs.push("world3");
  12875. }
  12876. // Get correct effect
  12877. var join = defines.join("\n");
  12878. if (this._cachedDefines !== join) {
  12879. this._cachedDefines = join;
  12880. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightPosition", "depthValues"], ["diffuseSampler"], join);
  12881. }
  12882. return this._effect.isReady();
  12883. };
  12884. ShadowGenerator.prototype.getShadowMap = function () {
  12885. return this._shadowMap;
  12886. };
  12887. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  12888. if (this._shadowMap2) {
  12889. return this._shadowMap2;
  12890. }
  12891. return this._shadowMap;
  12892. };
  12893. ShadowGenerator.prototype.getLight = function () {
  12894. return this._light;
  12895. };
  12896. // Methods
  12897. ShadowGenerator.prototype.getTransformMatrix = function () {
  12898. var scene = this._scene;
  12899. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  12900. return this._transformMatrix;
  12901. }
  12902. this._currentRenderID = scene.getRenderId();
  12903. this._currentFaceIndexCache = this._currentFaceIndex;
  12904. var lightPosition = this._light.position;
  12905. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  12906. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  12907. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  12908. }
  12909. if (this._light.computeTransformedPosition()) {
  12910. lightPosition = this._light.transformedPosition;
  12911. }
  12912. if (this._light.needRefreshPerFrame() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  12913. this._cachedPosition = lightPosition.clone();
  12914. this._cachedDirection = this._lightDirection.clone();
  12915. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  12916. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, this.getShadowMap().renderList);
  12917. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  12918. }
  12919. return this._transformMatrix;
  12920. };
  12921. ShadowGenerator.prototype.getDarkness = function () {
  12922. return this._darkness;
  12923. };
  12924. ShadowGenerator.prototype.setDarkness = function (darkness) {
  12925. if (darkness >= 1.0)
  12926. this._darkness = 1.0;
  12927. else if (darkness <= 0.0)
  12928. this._darkness = 0.0;
  12929. else
  12930. this._darkness = darkness;
  12931. };
  12932. ShadowGenerator.prototype.setTransparencyShadow = function (hasShadow) {
  12933. this._transparencyShadow = hasShadow;
  12934. };
  12935. ShadowGenerator.prototype._packHalf = function (depth) {
  12936. var scale = depth * 255.0;
  12937. var fract = scale - Math.floor(scale);
  12938. return new BABYLON.Vector2(depth - fract / 255.0, fract);
  12939. };
  12940. ShadowGenerator.prototype.dispose = function () {
  12941. this._shadowMap.dispose();
  12942. if (this._shadowMap2) {
  12943. this._shadowMap2.dispose();
  12944. }
  12945. if (this._downSamplePostprocess) {
  12946. this._downSamplePostprocess.dispose();
  12947. }
  12948. if (this._boxBlurPostprocess) {
  12949. this._boxBlurPostprocess.dispose();
  12950. }
  12951. this._light._shadowGenerator = null;
  12952. };
  12953. ShadowGenerator.prototype.serialize = function () {
  12954. var serializationObject = {};
  12955. serializationObject.lightId = this._light.id;
  12956. serializationObject.mapSize = this.getShadowMap().getRenderSize();
  12957. serializationObject.useVarianceShadowMap = this.useVarianceShadowMap;
  12958. serializationObject.usePoissonSampling = this.usePoissonSampling;
  12959. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  12960. serializationObject.renderList = [];
  12961. for (var meshIndex = 0; meshIndex < this.getShadowMap().renderList.length; meshIndex++) {
  12962. var mesh = this.getShadowMap().renderList[meshIndex];
  12963. serializationObject.renderList.push(mesh.id);
  12964. }
  12965. return serializationObject;
  12966. };
  12967. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  12968. //casting to point light, as light is missing the position attr and typescript complains.
  12969. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  12970. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  12971. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  12972. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  12973. meshes.forEach(function (mesh) {
  12974. shadowGenerator.getShadowMap().renderList.push(mesh);
  12975. });
  12976. }
  12977. if (parsedShadowGenerator.usePoissonSampling) {
  12978. shadowGenerator.usePoissonSampling = true;
  12979. }
  12980. else if (parsedShadowGenerator.useVarianceShadowMap) {
  12981. shadowGenerator.useVarianceShadowMap = true;
  12982. }
  12983. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  12984. shadowGenerator.useBlurVarianceShadowMap = true;
  12985. if (parsedShadowGenerator.blurScale) {
  12986. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  12987. }
  12988. if (parsedShadowGenerator.blurBoxOffset) {
  12989. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  12990. }
  12991. }
  12992. if (parsedShadowGenerator.bias !== undefined) {
  12993. shadowGenerator.bias = parsedShadowGenerator.bias;
  12994. }
  12995. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  12996. return shadowGenerator;
  12997. };
  12998. return ShadowGenerator;
  12999. }());
  13000. ShadowGenerator._FILTER_NONE = 0;
  13001. ShadowGenerator._FILTER_VARIANCESHADOWMAP = 1;
  13002. ShadowGenerator._FILTER_POISSONSAMPLING = 2;
  13003. ShadowGenerator._FILTER_BLURVARIANCESHADOWMAP = 3;
  13004. BABYLON.ShadowGenerator = ShadowGenerator;
  13005. })(BABYLON || (BABYLON = {}));
  13006. //# sourceMappingURL=babylon.shadowGenerator.js.map
  13007. var BABYLON;
  13008. (function (BABYLON) {
  13009. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  13010. if (boxMin.x > sphereCenter.x + sphereRadius)
  13011. return false;
  13012. if (sphereCenter.x - sphereRadius > boxMax.x)
  13013. return false;
  13014. if (boxMin.y > sphereCenter.y + sphereRadius)
  13015. return false;
  13016. if (sphereCenter.y - sphereRadius > boxMax.y)
  13017. return false;
  13018. if (boxMin.z > sphereCenter.z + sphereRadius)
  13019. return false;
  13020. if (sphereCenter.z - sphereRadius > boxMax.z)
  13021. return false;
  13022. return true;
  13023. };
  13024. var getLowestRoot = (function () {
  13025. var result = { root: 0, found: false };
  13026. return function (a, b, c, maxR) {
  13027. result.root = 0;
  13028. result.found = false;
  13029. var determinant = b * b - 4.0 * a * c;
  13030. if (determinant < 0)
  13031. return result;
  13032. var sqrtD = Math.sqrt(determinant);
  13033. var r1 = (-b - sqrtD) / (2.0 * a);
  13034. var r2 = (-b + sqrtD) / (2.0 * a);
  13035. if (r1 > r2) {
  13036. var temp = r2;
  13037. r2 = r1;
  13038. r1 = temp;
  13039. }
  13040. if (r1 > 0 && r1 < maxR) {
  13041. result.root = r1;
  13042. result.found = true;
  13043. return result;
  13044. }
  13045. if (r2 > 0 && r2 < maxR) {
  13046. result.root = r2;
  13047. result.found = true;
  13048. return result;
  13049. }
  13050. return result;
  13051. };
  13052. })();
  13053. var Collider = (function () {
  13054. function Collider() {
  13055. this.radius = new BABYLON.Vector3(1, 1, 1);
  13056. this.retry = 0;
  13057. this.basePointWorld = BABYLON.Vector3.Zero();
  13058. this.velocityWorld = BABYLON.Vector3.Zero();
  13059. this.normalizedVelocity = BABYLON.Vector3.Zero();
  13060. this._collisionPoint = BABYLON.Vector3.Zero();
  13061. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  13062. this._tempVector = BABYLON.Vector3.Zero();
  13063. this._tempVector2 = BABYLON.Vector3.Zero();
  13064. this._tempVector3 = BABYLON.Vector3.Zero();
  13065. this._tempVector4 = BABYLON.Vector3.Zero();
  13066. this._edge = BABYLON.Vector3.Zero();
  13067. this._baseToVertex = BABYLON.Vector3.Zero();
  13068. this._destinationPoint = BABYLON.Vector3.Zero();
  13069. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  13070. this._displacementVector = BABYLON.Vector3.Zero();
  13071. }
  13072. // Methods
  13073. Collider.prototype._initialize = function (source, dir, e) {
  13074. this.velocity = dir;
  13075. BABYLON.Vector3.NormalizeToRef(dir, this.normalizedVelocity);
  13076. this.basePoint = source;
  13077. source.multiplyToRef(this.radius, this.basePointWorld);
  13078. dir.multiplyToRef(this.radius, this.velocityWorld);
  13079. this.velocityWorldLength = this.velocityWorld.length();
  13080. this.epsilon = e;
  13081. this.collisionFound = false;
  13082. };
  13083. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  13084. pa.subtractToRef(point, this._tempVector);
  13085. pb.subtractToRef(point, this._tempVector2);
  13086. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  13087. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  13088. if (d < 0)
  13089. return false;
  13090. pc.subtractToRef(point, this._tempVector3);
  13091. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  13092. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  13093. if (d < 0)
  13094. return false;
  13095. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  13096. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  13097. return d >= 0;
  13098. };
  13099. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  13100. var distance = BABYLON.Vector3.Distance(this.basePointWorld, sphereCenter);
  13101. var max = Math.max(this.radius.x, this.radius.y, this.radius.z);
  13102. if (distance > this.velocityWorldLength + max + sphereRadius) {
  13103. return false;
  13104. }
  13105. if (!intersectBoxAASphere(vecMin, vecMax, this.basePointWorld, this.velocityWorldLength + max))
  13106. return false;
  13107. return true;
  13108. };
  13109. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  13110. var t0;
  13111. var embeddedInPlane = false;
  13112. //defensive programming, actually not needed.
  13113. if (!trianglePlaneArray) {
  13114. trianglePlaneArray = [];
  13115. }
  13116. if (!trianglePlaneArray[faceIndex]) {
  13117. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  13118. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  13119. }
  13120. var trianglePlane = trianglePlaneArray[faceIndex];
  13121. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this.normalizedVelocity, 0))
  13122. return;
  13123. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this.basePoint);
  13124. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this.velocity);
  13125. if (normalDotVelocity == 0) {
  13126. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  13127. return;
  13128. embeddedInPlane = true;
  13129. t0 = 0;
  13130. }
  13131. else {
  13132. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  13133. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  13134. if (t0 > t1) {
  13135. var temp = t1;
  13136. t1 = t0;
  13137. t0 = temp;
  13138. }
  13139. if (t0 > 1.0 || t1 < 0.0)
  13140. return;
  13141. if (t0 < 0)
  13142. t0 = 0;
  13143. if (t0 > 1.0)
  13144. t0 = 1.0;
  13145. }
  13146. this._collisionPoint.copyFromFloats(0, 0, 0);
  13147. var found = false;
  13148. var t = 1.0;
  13149. if (!embeddedInPlane) {
  13150. this.basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  13151. this.velocity.scaleToRef(t0, this._tempVector);
  13152. this._planeIntersectionPoint.addInPlace(this._tempVector);
  13153. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  13154. found = true;
  13155. t = t0;
  13156. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  13157. }
  13158. }
  13159. if (!found) {
  13160. var velocitySquaredLength = this.velocity.lengthSquared();
  13161. var a = velocitySquaredLength;
  13162. this.basePoint.subtractToRef(p1, this._tempVector);
  13163. var b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  13164. var c = this._tempVector.lengthSquared() - 1.0;
  13165. var lowestRoot = getLowestRoot(a, b, c, t);
  13166. if (lowestRoot.found) {
  13167. t = lowestRoot.root;
  13168. found = true;
  13169. this._collisionPoint.copyFrom(p1);
  13170. }
  13171. this.basePoint.subtractToRef(p2, this._tempVector);
  13172. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  13173. c = this._tempVector.lengthSquared() - 1.0;
  13174. lowestRoot = getLowestRoot(a, b, c, t);
  13175. if (lowestRoot.found) {
  13176. t = lowestRoot.root;
  13177. found = true;
  13178. this._collisionPoint.copyFrom(p2);
  13179. }
  13180. this.basePoint.subtractToRef(p3, this._tempVector);
  13181. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  13182. c = this._tempVector.lengthSquared() - 1.0;
  13183. lowestRoot = getLowestRoot(a, b, c, t);
  13184. if (lowestRoot.found) {
  13185. t = lowestRoot.root;
  13186. found = true;
  13187. this._collisionPoint.copyFrom(p3);
  13188. }
  13189. p2.subtractToRef(p1, this._edge);
  13190. p1.subtractToRef(this.basePoint, this._baseToVertex);
  13191. var edgeSquaredLength = this._edge.lengthSquared();
  13192. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  13193. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  13194. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  13195. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  13196. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  13197. lowestRoot = getLowestRoot(a, b, c, t);
  13198. if (lowestRoot.found) {
  13199. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  13200. if (f >= 0.0 && f <= 1.0) {
  13201. t = lowestRoot.root;
  13202. found = true;
  13203. this._edge.scaleInPlace(f);
  13204. p1.addToRef(this._edge, this._collisionPoint);
  13205. }
  13206. }
  13207. p3.subtractToRef(p2, this._edge);
  13208. p2.subtractToRef(this.basePoint, this._baseToVertex);
  13209. edgeSquaredLength = this._edge.lengthSquared();
  13210. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  13211. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  13212. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  13213. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  13214. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  13215. lowestRoot = getLowestRoot(a, b, c, t);
  13216. if (lowestRoot.found) {
  13217. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  13218. if (f >= 0.0 && f <= 1.0) {
  13219. t = lowestRoot.root;
  13220. found = true;
  13221. this._edge.scaleInPlace(f);
  13222. p2.addToRef(this._edge, this._collisionPoint);
  13223. }
  13224. }
  13225. p1.subtractToRef(p3, this._edge);
  13226. p3.subtractToRef(this.basePoint, this._baseToVertex);
  13227. edgeSquaredLength = this._edge.lengthSquared();
  13228. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  13229. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  13230. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  13231. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  13232. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  13233. lowestRoot = getLowestRoot(a, b, c, t);
  13234. if (lowestRoot.found) {
  13235. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  13236. if (f >= 0.0 && f <= 1.0) {
  13237. t = lowestRoot.root;
  13238. found = true;
  13239. this._edge.scaleInPlace(f);
  13240. p3.addToRef(this._edge, this._collisionPoint);
  13241. }
  13242. }
  13243. }
  13244. if (found) {
  13245. var distToCollision = t * this.velocity.length();
  13246. if (!this.collisionFound || distToCollision < this.nearestDistance) {
  13247. if (!this.intersectionPoint) {
  13248. this.intersectionPoint = this._collisionPoint.clone();
  13249. }
  13250. else {
  13251. this.intersectionPoint.copyFrom(this._collisionPoint);
  13252. }
  13253. this.nearestDistance = distToCollision;
  13254. this.collisionFound = true;
  13255. }
  13256. }
  13257. };
  13258. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  13259. for (var i = indexStart; i < indexEnd; i += 3) {
  13260. var p1 = pts[indices[i] - decal];
  13261. var p2 = pts[indices[i + 1] - decal];
  13262. var p3 = pts[indices[i + 2] - decal];
  13263. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  13264. }
  13265. };
  13266. Collider.prototype._getResponse = function (pos, vel) {
  13267. pos.addToRef(vel, this._destinationPoint);
  13268. vel.scaleInPlace((this.nearestDistance / vel.length()));
  13269. this.basePoint.addToRef(vel, pos);
  13270. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  13271. this._slidePlaneNormal.normalize();
  13272. this._slidePlaneNormal.scaleToRef(this.epsilon, this._displacementVector);
  13273. pos.addInPlace(this._displacementVector);
  13274. this.intersectionPoint.addInPlace(this._displacementVector);
  13275. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  13276. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  13277. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  13278. };
  13279. return Collider;
  13280. }());
  13281. BABYLON.Collider = Collider;
  13282. })(BABYLON || (BABYLON = {}));
  13283. //# sourceMappingURL=babylon.collider.js.map
  13284. var BABYLON;
  13285. (function (BABYLON) {
  13286. //WebWorker code will be inserted to this variable.
  13287. BABYLON.CollisionWorker = "";
  13288. var WorkerTaskType;
  13289. (function (WorkerTaskType) {
  13290. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  13291. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  13292. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  13293. })(WorkerTaskType = BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  13294. var WorkerReplyType;
  13295. (function (WorkerReplyType) {
  13296. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  13297. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  13298. })(WorkerReplyType = BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  13299. var CollisionCoordinatorWorker = (function () {
  13300. function CollisionCoordinatorWorker() {
  13301. var _this = this;
  13302. this._scaledPosition = BABYLON.Vector3.Zero();
  13303. this._scaledVelocity = BABYLON.Vector3.Zero();
  13304. this.onMeshUpdated = function (mesh) {
  13305. _this._addUpdateMeshesList[mesh.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(mesh);
  13306. };
  13307. this.onGeometryUpdated = function (geometry) {
  13308. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  13309. };
  13310. this._afterRender = function () {
  13311. if (!_this._init)
  13312. return;
  13313. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  13314. return;
  13315. }
  13316. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  13317. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  13318. if (_this._runningUpdated > 4) {
  13319. return;
  13320. }
  13321. ++_this._runningUpdated;
  13322. var payload = {
  13323. updatedMeshes: _this._addUpdateMeshesList,
  13324. updatedGeometries: _this._addUpdateGeometriesList,
  13325. removedGeometries: _this._toRemoveGeometryArray,
  13326. removedMeshes: _this._toRemoveMeshesArray
  13327. };
  13328. var message = {
  13329. payload: payload,
  13330. taskType: WorkerTaskType.UPDATE
  13331. };
  13332. var serializable = [];
  13333. for (var id in payload.updatedGeometries) {
  13334. if (payload.updatedGeometries.hasOwnProperty(id)) {
  13335. //prepare transferables
  13336. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  13337. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  13338. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  13339. }
  13340. }
  13341. _this._worker.postMessage(message, serializable);
  13342. _this._addUpdateMeshesList = {};
  13343. _this._addUpdateGeometriesList = {};
  13344. _this._toRemoveGeometryArray = [];
  13345. _this._toRemoveMeshesArray = [];
  13346. };
  13347. this._onMessageFromWorker = function (e) {
  13348. var returnData = e.data;
  13349. if (returnData.error != WorkerReplyType.SUCCESS) {
  13350. //TODO what errors can be returned from the worker?
  13351. BABYLON.Tools.Warn("error returned from worker!");
  13352. return;
  13353. }
  13354. switch (returnData.taskType) {
  13355. case WorkerTaskType.INIT:
  13356. _this._init = true;
  13357. //Update the worked with ALL of the scene's current state
  13358. _this._scene.meshes.forEach(function (mesh) {
  13359. _this.onMeshAdded(mesh);
  13360. });
  13361. _this._scene.getGeometries().forEach(function (geometry) {
  13362. _this.onGeometryAdded(geometry);
  13363. });
  13364. break;
  13365. case WorkerTaskType.UPDATE:
  13366. _this._runningUpdated--;
  13367. break;
  13368. case WorkerTaskType.COLLIDE:
  13369. _this._runningCollisionTask = false;
  13370. var returnPayload = returnData.payload;
  13371. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  13372. return;
  13373. _this._collisionsCallbackArray[returnPayload.collisionId](returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId));
  13374. //cleanup
  13375. _this._collisionsCallbackArray[returnPayload.collisionId] = undefined;
  13376. break;
  13377. }
  13378. };
  13379. this._collisionsCallbackArray = [];
  13380. this._init = false;
  13381. this._runningUpdated = 0;
  13382. this._runningCollisionTask = false;
  13383. this._addUpdateMeshesList = {};
  13384. this._addUpdateGeometriesList = {};
  13385. this._toRemoveGeometryArray = [];
  13386. this._toRemoveMeshesArray = [];
  13387. }
  13388. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, velocity, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  13389. if (!this._init)
  13390. return;
  13391. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  13392. return;
  13393. position.divideToRef(collider.radius, this._scaledPosition);
  13394. velocity.divideToRef(collider.radius, this._scaledVelocity);
  13395. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  13396. var payload = {
  13397. collider: {
  13398. position: this._scaledPosition.asArray(),
  13399. velocity: this._scaledVelocity.asArray(),
  13400. radius: collider.radius.asArray()
  13401. },
  13402. collisionId: collisionIndex,
  13403. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  13404. maximumRetry: maximumRetry
  13405. };
  13406. var message = {
  13407. payload: payload,
  13408. taskType: WorkerTaskType.COLLIDE
  13409. };
  13410. this._worker.postMessage(message);
  13411. };
  13412. CollisionCoordinatorWorker.prototype.init = function (scene) {
  13413. this._scene = scene;
  13414. this._scene.registerAfterRender(this._afterRender);
  13415. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  13416. this._worker = new Worker(workerUrl);
  13417. this._worker.onmessage = this._onMessageFromWorker;
  13418. var message = {
  13419. payload: {},
  13420. taskType: WorkerTaskType.INIT
  13421. };
  13422. this._worker.postMessage(message);
  13423. };
  13424. CollisionCoordinatorWorker.prototype.destroy = function () {
  13425. this._scene.unregisterAfterRender(this._afterRender);
  13426. this._worker.terminate();
  13427. };
  13428. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  13429. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  13430. this.onMeshUpdated(mesh);
  13431. };
  13432. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  13433. this._toRemoveMeshesArray.push(mesh.uniqueId);
  13434. };
  13435. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  13436. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  13437. geometry.onGeometryUpdated = this.onGeometryUpdated;
  13438. this.onGeometryUpdated(geometry);
  13439. };
  13440. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  13441. this._toRemoveGeometryArray.push(geometry.id);
  13442. };
  13443. return CollisionCoordinatorWorker;
  13444. }());
  13445. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  13446. var submeshes = [];
  13447. if (mesh.subMeshes) {
  13448. submeshes = mesh.subMeshes.map(function (sm, idx) {
  13449. return {
  13450. position: idx,
  13451. verticesStart: sm.verticesStart,
  13452. verticesCount: sm.verticesCount,
  13453. indexStart: sm.indexStart,
  13454. indexCount: sm.indexCount,
  13455. hasMaterial: !!sm.getMaterial(),
  13456. sphereCenter: sm.getBoundingInfo().boundingSphere.centerWorld.asArray(),
  13457. sphereRadius: sm.getBoundingInfo().boundingSphere.radiusWorld,
  13458. boxMinimum: sm.getBoundingInfo().boundingBox.minimumWorld.asArray(),
  13459. boxMaximum: sm.getBoundingInfo().boundingBox.maximumWorld.asArray()
  13460. };
  13461. });
  13462. }
  13463. var geometryId = null;
  13464. if (mesh instanceof BABYLON.Mesh) {
  13465. geometryId = mesh.geometry ? mesh.geometry.id : null;
  13466. }
  13467. else if (mesh instanceof BABYLON.InstancedMesh) {
  13468. geometryId = (mesh.sourceMesh && mesh.sourceMesh.geometry) ? mesh.sourceMesh.geometry.id : null;
  13469. }
  13470. return {
  13471. uniqueId: mesh.uniqueId,
  13472. id: mesh.id,
  13473. name: mesh.name,
  13474. geometryId: geometryId,
  13475. sphereCenter: mesh.getBoundingInfo().boundingSphere.centerWorld.asArray(),
  13476. sphereRadius: mesh.getBoundingInfo().boundingSphere.radiusWorld,
  13477. boxMinimum: mesh.getBoundingInfo().boundingBox.minimumWorld.asArray(),
  13478. boxMaximum: mesh.getBoundingInfo().boundingBox.maximumWorld.asArray(),
  13479. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  13480. subMeshes: submeshes,
  13481. checkCollisions: mesh.checkCollisions
  13482. };
  13483. };
  13484. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  13485. return {
  13486. id: geometry.id,
  13487. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  13488. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  13489. indices: new Uint32Array(geometry.getIndices() || []),
  13490. };
  13491. };
  13492. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  13493. var CollisionCoordinatorLegacy = (function () {
  13494. function CollisionCoordinatorLegacy() {
  13495. this._scaledPosition = BABYLON.Vector3.Zero();
  13496. this._scaledVelocity = BABYLON.Vector3.Zero();
  13497. this._finalPosition = BABYLON.Vector3.Zero();
  13498. }
  13499. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, velocity, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  13500. position.divideToRef(collider.radius, this._scaledPosition);
  13501. velocity.divideToRef(collider.radius, this._scaledVelocity);
  13502. collider.collidedMesh = null;
  13503. collider.retry = 0;
  13504. collider.initialVelocity = this._scaledVelocity;
  13505. collider.initialPosition = this._scaledPosition;
  13506. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  13507. this._finalPosition.multiplyInPlace(collider.radius);
  13508. //run the callback
  13509. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  13510. };
  13511. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  13512. this._scene = scene;
  13513. };
  13514. CollisionCoordinatorLegacy.prototype.destroy = function () {
  13515. //Legacy need no destruction method.
  13516. };
  13517. //No update in legacy mode
  13518. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  13519. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  13520. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  13521. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  13522. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  13523. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  13524. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  13525. if (excludedMesh === void 0) { excludedMesh = null; }
  13526. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  13527. if (collider.retry >= maximumRetry) {
  13528. finalPosition.copyFrom(position);
  13529. return;
  13530. }
  13531. collider._initialize(position, velocity, closeDistance);
  13532. // Check all meshes
  13533. for (var index = 0; index < this._scene.meshes.length; index++) {
  13534. var mesh = this._scene.meshes[index];
  13535. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh) {
  13536. mesh._checkCollision(collider);
  13537. }
  13538. }
  13539. if (!collider.collisionFound) {
  13540. position.addToRef(velocity, finalPosition);
  13541. return;
  13542. }
  13543. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  13544. collider._getResponse(position, velocity);
  13545. }
  13546. if (velocity.length() <= closeDistance) {
  13547. finalPosition.copyFrom(position);
  13548. return;
  13549. }
  13550. collider.retry++;
  13551. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  13552. };
  13553. return CollisionCoordinatorLegacy;
  13554. }());
  13555. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  13556. })(BABYLON || (BABYLON = {}));
  13557. //# sourceMappingURL=babylon.collisionCoordinator.js.map
  13558. var BABYLON;
  13559. (function (BABYLON) {
  13560. var Camera = (function (_super) {
  13561. __extends(Camera, _super);
  13562. function Camera(name, position, scene) {
  13563. var _this = _super.call(this, name, scene) || this;
  13564. _this.upVector = BABYLON.Vector3.Up();
  13565. _this.orthoLeft = null;
  13566. _this.orthoRight = null;
  13567. _this.orthoBottom = null;
  13568. _this.orthoTop = null;
  13569. _this.fov = 0.8;
  13570. _this.minZ = 1.0;
  13571. _this.maxZ = 10000.0;
  13572. _this.inertia = 0.9;
  13573. _this.mode = Camera.PERSPECTIVE_CAMERA;
  13574. _this.isIntermediate = false;
  13575. _this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  13576. _this.layerMask = 0x0FFFFFFF;
  13577. _this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  13578. // Camera rig members
  13579. _this.cameraRigMode = Camera.RIG_MODE_NONE;
  13580. _this._rigCameras = new Array();
  13581. // Cache
  13582. _this._computedViewMatrix = BABYLON.Matrix.Identity();
  13583. _this._projectionMatrix = new BABYLON.Matrix();
  13584. _this._doNotComputeProjectionMatrix = false;
  13585. _this._postProcesses = new Array();
  13586. _this._transformMatrix = BABYLON.Matrix.Zero();
  13587. _this._webvrViewMatrix = BABYLON.Matrix.Identity();
  13588. _this._activeMeshes = new BABYLON.SmartArray(256);
  13589. _this._globalPosition = BABYLON.Vector3.Zero();
  13590. _this._refreshFrustumPlanes = true;
  13591. scene.addCamera(_this);
  13592. if (!scene.activeCamera) {
  13593. scene.activeCamera = _this;
  13594. }
  13595. _this.position = position;
  13596. return _this;
  13597. }
  13598. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  13599. get: function () {
  13600. return Camera._PERSPECTIVE_CAMERA;
  13601. },
  13602. enumerable: true,
  13603. configurable: true
  13604. });
  13605. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  13606. get: function () {
  13607. return Camera._ORTHOGRAPHIC_CAMERA;
  13608. },
  13609. enumerable: true,
  13610. configurable: true
  13611. });
  13612. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  13613. get: function () {
  13614. return Camera._FOVMODE_VERTICAL_FIXED;
  13615. },
  13616. enumerable: true,
  13617. configurable: true
  13618. });
  13619. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  13620. get: function () {
  13621. return Camera._FOVMODE_HORIZONTAL_FIXED;
  13622. },
  13623. enumerable: true,
  13624. configurable: true
  13625. });
  13626. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  13627. get: function () {
  13628. return Camera._RIG_MODE_NONE;
  13629. },
  13630. enumerable: true,
  13631. configurable: true
  13632. });
  13633. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  13634. get: function () {
  13635. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  13636. },
  13637. enumerable: true,
  13638. configurable: true
  13639. });
  13640. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  13641. get: function () {
  13642. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  13643. },
  13644. enumerable: true,
  13645. configurable: true
  13646. });
  13647. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  13648. get: function () {
  13649. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  13650. },
  13651. enumerable: true,
  13652. configurable: true
  13653. });
  13654. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  13655. get: function () {
  13656. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  13657. },
  13658. enumerable: true,
  13659. configurable: true
  13660. });
  13661. Object.defineProperty(Camera, "RIG_MODE_VR", {
  13662. get: function () {
  13663. return Camera._RIG_MODE_VR;
  13664. },
  13665. enumerable: true,
  13666. configurable: true
  13667. });
  13668. Object.defineProperty(Camera, "RIG_MODE_WEBVR", {
  13669. get: function () {
  13670. return Camera._RIG_MODE_WEBVR;
  13671. },
  13672. enumerable: true,
  13673. configurable: true
  13674. });
  13675. Camera.prototype.getClassName = function () {
  13676. return "Camera";
  13677. };
  13678. /**
  13679. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  13680. */
  13681. Camera.prototype.toString = function (fullDetails) {
  13682. var ret = "Name: " + this.name;
  13683. ret += ", type: " + this.getClassName();
  13684. if (this.animations) {
  13685. for (var i = 0; i < this.animations.length; i++) {
  13686. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  13687. }
  13688. }
  13689. if (fullDetails) {
  13690. }
  13691. return ret;
  13692. };
  13693. Object.defineProperty(Camera.prototype, "globalPosition", {
  13694. get: function () {
  13695. return this._globalPosition;
  13696. },
  13697. enumerable: true,
  13698. configurable: true
  13699. });
  13700. Camera.prototype.getActiveMeshes = function () {
  13701. return this._activeMeshes;
  13702. };
  13703. Camera.prototype.isActiveMesh = function (mesh) {
  13704. return (this._activeMeshes.indexOf(mesh) !== -1);
  13705. };
  13706. //Cache
  13707. Camera.prototype._initCache = function () {
  13708. _super.prototype._initCache.call(this);
  13709. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  13710. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  13711. this._cache.mode = undefined;
  13712. this._cache.minZ = undefined;
  13713. this._cache.maxZ = undefined;
  13714. this._cache.fov = undefined;
  13715. this._cache.fovMode = undefined;
  13716. this._cache.aspectRatio = undefined;
  13717. this._cache.orthoLeft = undefined;
  13718. this._cache.orthoRight = undefined;
  13719. this._cache.orthoBottom = undefined;
  13720. this._cache.orthoTop = undefined;
  13721. this._cache.renderWidth = undefined;
  13722. this._cache.renderHeight = undefined;
  13723. };
  13724. Camera.prototype._updateCache = function (ignoreParentClass) {
  13725. if (!ignoreParentClass) {
  13726. _super.prototype._updateCache.call(this);
  13727. }
  13728. var engine = this.getEngine();
  13729. this._cache.position.copyFrom(this.position);
  13730. this._cache.upVector.copyFrom(this.upVector);
  13731. this._cache.mode = this.mode;
  13732. this._cache.minZ = this.minZ;
  13733. this._cache.maxZ = this.maxZ;
  13734. this._cache.fov = this.fov;
  13735. this._cache.fovMode = this.fovMode;
  13736. this._cache.aspectRatio = engine.getAspectRatio(this);
  13737. this._cache.orthoLeft = this.orthoLeft;
  13738. this._cache.orthoRight = this.orthoRight;
  13739. this._cache.orthoBottom = this.orthoBottom;
  13740. this._cache.orthoTop = this.orthoTop;
  13741. this._cache.renderWidth = engine.getRenderWidth();
  13742. this._cache.renderHeight = engine.getRenderHeight();
  13743. };
  13744. Camera.prototype._updateFromScene = function () {
  13745. this.updateCache();
  13746. this.update();
  13747. };
  13748. // Synchronized
  13749. Camera.prototype._isSynchronized = function () {
  13750. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  13751. };
  13752. Camera.prototype._isSynchronizedViewMatrix = function () {
  13753. if (!_super.prototype._isSynchronized.call(this))
  13754. return false;
  13755. return this._cache.position.equals(this.position)
  13756. && this._cache.upVector.equals(this.upVector)
  13757. && this.isSynchronizedWithParent();
  13758. };
  13759. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  13760. var check = this._cache.mode === this.mode
  13761. && this._cache.minZ === this.minZ
  13762. && this._cache.maxZ === this.maxZ;
  13763. if (!check) {
  13764. return false;
  13765. }
  13766. var engine = this.getEngine();
  13767. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  13768. check = this._cache.fov === this.fov
  13769. && this._cache.fovMode === this.fovMode
  13770. && this._cache.aspectRatio === engine.getAspectRatio(this);
  13771. }
  13772. else {
  13773. check = this._cache.orthoLeft === this.orthoLeft
  13774. && this._cache.orthoRight === this.orthoRight
  13775. && this._cache.orthoBottom === this.orthoBottom
  13776. && this._cache.orthoTop === this.orthoTop
  13777. && this._cache.renderWidth === engine.getRenderWidth()
  13778. && this._cache.renderHeight === engine.getRenderHeight();
  13779. }
  13780. return check;
  13781. };
  13782. // Controls
  13783. Camera.prototype.attachControl = function (element, noPreventDefault) {
  13784. };
  13785. Camera.prototype.detachControl = function (element) {
  13786. };
  13787. Camera.prototype.update = function () {
  13788. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  13789. this._updateRigCameras();
  13790. }
  13791. this._checkInputs();
  13792. };
  13793. Camera.prototype._checkInputs = function () {
  13794. };
  13795. Camera.prototype._cascadePostProcessesToRigCams = function () {
  13796. // invalidate framebuffer
  13797. if (this._postProcesses.length > 0) {
  13798. this._postProcesses[0].markTextureDirty();
  13799. }
  13800. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  13801. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  13802. var cam = this._rigCameras[i];
  13803. var rigPostProcess = cam._rigPostProcess;
  13804. // for VR rig, there does not have to be a post process
  13805. if (rigPostProcess) {
  13806. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  13807. if (isPass) {
  13808. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  13809. cam.isIntermediate = this._postProcesses.length === 0;
  13810. }
  13811. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  13812. rigPostProcess.markTextureDirty();
  13813. }
  13814. else {
  13815. cam._postProcesses = this._postProcesses.slice(0);
  13816. }
  13817. }
  13818. };
  13819. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  13820. if (insertAt === void 0) { insertAt = null; }
  13821. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  13822. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  13823. return 0;
  13824. }
  13825. if (insertAt == null || insertAt < 0) {
  13826. this._postProcesses.push(postProcess);
  13827. }
  13828. else {
  13829. this._postProcesses.splice(insertAt, 0, postProcess);
  13830. }
  13831. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  13832. return this._postProcesses.indexOf(postProcess);
  13833. };
  13834. Camera.prototype.detachPostProcess = function (postProcess, atIndices) {
  13835. if (atIndices === void 0) { atIndices = null; }
  13836. var result = [];
  13837. var i;
  13838. var index;
  13839. if (!atIndices) {
  13840. var idx = this._postProcesses.indexOf(postProcess);
  13841. if (idx !== -1) {
  13842. this._postProcesses.splice(idx, 1);
  13843. }
  13844. }
  13845. else {
  13846. atIndices = (atIndices instanceof Array) ? atIndices : [atIndices];
  13847. // iterate descending, so can just splice as we go
  13848. for (i = atIndices.length - 1; i >= 0; i--) {
  13849. if (this._postProcesses[atIndices[i]] !== postProcess) {
  13850. result.push(i);
  13851. continue;
  13852. }
  13853. index = atIndices[i];
  13854. this._postProcesses.splice(index, 1);
  13855. }
  13856. }
  13857. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  13858. return result;
  13859. };
  13860. Camera.prototype.getWorldMatrix = function () {
  13861. if (!this._worldMatrix) {
  13862. this._worldMatrix = BABYLON.Matrix.Identity();
  13863. }
  13864. var viewMatrix = this.getViewMatrix();
  13865. viewMatrix.invertToRef(this._worldMatrix);
  13866. return this._worldMatrix;
  13867. };
  13868. Camera.prototype._getViewMatrix = function () {
  13869. return BABYLON.Matrix.Identity();
  13870. };
  13871. Camera.prototype.getViewMatrix = function (force) {
  13872. this._computedViewMatrix = this._computeViewMatrix(force);
  13873. if (!force && this._isSynchronizedViewMatrix()) {
  13874. return this._computedViewMatrix;
  13875. }
  13876. this._refreshFrustumPlanes = true;
  13877. if (!this.parent || !this.parent.getWorldMatrix) {
  13878. this._globalPosition.copyFrom(this.position);
  13879. }
  13880. else {
  13881. if (!this._worldMatrix) {
  13882. this._worldMatrix = BABYLON.Matrix.Identity();
  13883. }
  13884. this._computedViewMatrix.invertToRef(this._worldMatrix);
  13885. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  13886. this._globalPosition.copyFromFloats(this._computedViewMatrix.m[12], this._computedViewMatrix.m[13], this._computedViewMatrix.m[14]);
  13887. this._computedViewMatrix.invert();
  13888. this._markSyncedWithParent();
  13889. }
  13890. if (this._cameraRigParams && this._cameraRigParams.vrPreViewMatrix) {
  13891. this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._computedViewMatrix);
  13892. }
  13893. this._currentRenderId = this.getScene().getRenderId();
  13894. return this._computedViewMatrix;
  13895. };
  13896. Camera.prototype._computeViewMatrix = function (force) {
  13897. if (!force && this._isSynchronizedViewMatrix()) {
  13898. return this._computedViewMatrix;
  13899. }
  13900. this._computedViewMatrix = this._getViewMatrix();
  13901. this._currentRenderId = this.getScene().getRenderId();
  13902. return this._computedViewMatrix;
  13903. };
  13904. Camera.prototype.freezeProjectionMatrix = function (projection) {
  13905. this._doNotComputeProjectionMatrix = true;
  13906. if (projection !== undefined) {
  13907. this._projectionMatrix = projection;
  13908. }
  13909. };
  13910. ;
  13911. Camera.prototype.unfreezeProjectionMatrix = function () {
  13912. this._doNotComputeProjectionMatrix = false;
  13913. };
  13914. ;
  13915. Camera.prototype.getProjectionMatrix = function (force) {
  13916. if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {
  13917. return this._projectionMatrix;
  13918. }
  13919. this._refreshFrustumPlanes = true;
  13920. var engine = this.getEngine();
  13921. var scene = this.getScene();
  13922. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  13923. if (this.minZ <= 0) {
  13924. this.minZ = 0.1;
  13925. }
  13926. if (scene.useRightHandedSystem) {
  13927. BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  13928. }
  13929. else {
  13930. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  13931. }
  13932. return this._projectionMatrix;
  13933. }
  13934. var halfWidth = engine.getRenderWidth() / 2.0;
  13935. var halfHeight = engine.getRenderHeight() / 2.0;
  13936. if (scene.useRightHandedSystem) {
  13937. BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  13938. }
  13939. else {
  13940. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  13941. }
  13942. return this._projectionMatrix;
  13943. };
  13944. Camera.prototype.getTranformationMatrix = function () {
  13945. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  13946. return this._transformMatrix;
  13947. };
  13948. Camera.prototype.updateFrustumPlanes = function () {
  13949. if (!this._refreshFrustumPlanes) {
  13950. return;
  13951. }
  13952. this.getTranformationMatrix();
  13953. if (!this._frustumPlanes) {
  13954. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  13955. }
  13956. else {
  13957. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  13958. }
  13959. this._refreshFrustumPlanes = false;
  13960. };
  13961. Camera.prototype.isInFrustum = function (target) {
  13962. this.updateFrustumPlanes();
  13963. return target.isInFrustum(this._frustumPlanes);
  13964. };
  13965. Camera.prototype.isCompletelyInFrustum = function (target) {
  13966. this.updateFrustumPlanes();
  13967. return target.isCompletelyInFrustum(this._frustumPlanes);
  13968. };
  13969. Camera.prototype.dispose = function () {
  13970. // Animations
  13971. this.getScene().stopAnimation(this);
  13972. // Remove from scene
  13973. this.getScene().removeCamera(this);
  13974. while (this._rigCameras.length > 0) {
  13975. this._rigCameras.pop().dispose();
  13976. }
  13977. // Postprocesses
  13978. var i = this._postProcesses.length;
  13979. while (--i >= 0) {
  13980. this._postProcesses[i].dispose(this);
  13981. }
  13982. _super.prototype.dispose.call(this);
  13983. };
  13984. // ---- Camera rigs section ----
  13985. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  13986. while (this._rigCameras.length > 0) {
  13987. this._rigCameras.pop().dispose();
  13988. }
  13989. this.cameraRigMode = mode;
  13990. this._cameraRigParams = {};
  13991. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  13992. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  13993. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  13994. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  13995. // create the rig cameras, unless none
  13996. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  13997. this._rigCameras.push(this.createRigCamera(this.name + "_L", 0));
  13998. this._rigCameras.push(this.createRigCamera(this.name + "_R", 1));
  13999. }
  14000. switch (this.cameraRigMode) {
  14001. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  14002. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  14003. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  14004. break;
  14005. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  14006. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  14007. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  14008. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  14009. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  14010. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  14011. break;
  14012. case Camera.RIG_MODE_VR:
  14013. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  14014. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  14015. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  14016. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  14017. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  14018. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  14019. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  14020. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  14021. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  14022. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  14023. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  14024. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  14025. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  14026. if (metrics.compensateDistortion) {
  14027. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  14028. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  14029. }
  14030. break;
  14031. case Camera.RIG_MODE_WEBVR:
  14032. if (rigParams.vrDisplay) {
  14033. //var leftEye = rigParams.vrDisplay.getEyeParameters('left');
  14034. //var rightEye = rigParams.vrDisplay.getEyeParameters('right');
  14035. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  14036. this._rigCameras[0].setCameraRigParameter("left", true);
  14037. this._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData);
  14038. //this._rigCameras[0].setCameraRigParameter("vrOffsetMatrix", Matrix.Translation(-leftEye.offset[0], leftEye.offset[1], -leftEye.offset[2]));
  14039. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  14040. this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
  14041. //this._rigCameras[0]._getViewMatrix = this._getWebVRViewMatrix;
  14042. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  14043. this._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData);
  14044. //this._rigCameras[1].setCameraRigParameter("vrOffsetMatrix", Matrix.Translation(-rightEye.offset[0], rightEye.offset[1], -rightEye.offset[2]));
  14045. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  14046. this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
  14047. }
  14048. break;
  14049. }
  14050. this._cascadePostProcessesToRigCams();
  14051. this.
  14052. update();
  14053. };
  14054. Camera.prototype._getVRProjectionMatrix = function () {
  14055. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  14056. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  14057. return this._projectionMatrix;
  14058. };
  14059. Camera.prototype._getWebVRProjectionMatrix = function () {
  14060. var projectionArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftProjectionMatrix : this._cameraRigParams["frameData"].rightProjectionMatrix;
  14061. //babylon compatible matrix
  14062. [8, 9, 10, 11].forEach(function (num) {
  14063. projectionArray[num] *= -1;
  14064. });
  14065. BABYLON.Matrix.FromArrayToRef(projectionArray, 0, this._projectionMatrix);
  14066. return this._projectionMatrix;
  14067. };
  14068. //Can be used, but we'll use the free camera's view matrix calculation
  14069. Camera.prototype._getWebVRViewMatrix = function () {
  14070. var projectionArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftViewMatrix : this._cameraRigParams["frameData"].rightViewMatrix;
  14071. //babylon compatible matrix
  14072. [8, 9, 10, 11].forEach(function (num) {
  14073. projectionArray[num] *= -1;
  14074. });
  14075. BABYLON.Matrix.FromArrayToRef(projectionArray, 0, this._webvrViewMatrix);
  14076. return this._webvrViewMatrix;
  14077. };
  14078. Camera.prototype.setCameraRigParameter = function (name, value) {
  14079. if (!this._cameraRigParams) {
  14080. this._cameraRigParams = {};
  14081. }
  14082. this._cameraRigParams[name] = value;
  14083. //provisionnally:
  14084. if (name === "interaxialDistance") {
  14085. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  14086. }
  14087. };
  14088. /**
  14089. * needs to be overridden by children so sub has required properties to be copied
  14090. */
  14091. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  14092. return null;
  14093. };
  14094. /**
  14095. * May need to be overridden by children
  14096. */
  14097. Camera.prototype._updateRigCameras = function () {
  14098. for (var i = 0; i < this._rigCameras.length; i++) {
  14099. this._rigCameras[i].minZ = this.minZ;
  14100. this._rigCameras[i].maxZ = this.maxZ;
  14101. this._rigCameras[i].fov = this.fov;
  14102. }
  14103. // only update viewport when ANAGLYPH
  14104. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  14105. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  14106. }
  14107. };
  14108. Camera.prototype._setupInputs = function () {
  14109. };
  14110. Camera.prototype.serialize = function () {
  14111. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  14112. // Type
  14113. serializationObject.type = this.getClassName();
  14114. // Parent
  14115. if (this.parent) {
  14116. serializationObject.parentId = this.parent.id;
  14117. }
  14118. if (this.inputs) {
  14119. this.inputs.serialize(serializationObject);
  14120. }
  14121. // Animations
  14122. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  14123. serializationObject.ranges = this.serializeAnimationRanges();
  14124. return serializationObject;
  14125. };
  14126. Camera.prototype.clone = function (name) {
  14127. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  14128. };
  14129. Camera.prototype.getDirection = function (localAxis) {
  14130. var result = BABYLON.Vector3.Zero();
  14131. this.getDirectionToRef(localAxis, result);
  14132. return result;
  14133. };
  14134. Camera.prototype.getDirectionToRef = function (localAxis, result) {
  14135. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  14136. };
  14137. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  14138. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  14139. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  14140. switch (type) {
  14141. case "ArcRotateCamera":
  14142. return function () { return new BABYLON.ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  14143. case "DeviceOrientationCamera":
  14144. return function () { return new BABYLON.DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  14145. case "FollowCamera":
  14146. return function () { return new BABYLON.FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  14147. case "ArcFollowCamera":
  14148. return function () { return new BABYLON.ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  14149. case "GamepadCamera":
  14150. return function () { return new BABYLON.GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  14151. case "TouchCamera":
  14152. return function () { return new BABYLON.TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  14153. case "VirtualJoysticksCamera":
  14154. return function () { return new BABYLON.VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  14155. case "HolographicCamera":
  14156. return function () { return new BABYLON.HolographicCamera(name, scene); };
  14157. case "WebVRFreeCamera":
  14158. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  14159. case "VRDeviceOrientationFreeCamera":
  14160. return function () { return new BABYLON.VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  14161. case "VRDeviceOrientationGamepadCamera":
  14162. return function () { return new BABYLON.VRDeviceOrientationGamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  14163. case "AnaglyphArcRotateCamera":
  14164. return function () { return new BABYLON.AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  14165. case "AnaglyphFreeCamera":
  14166. return function () { return new BABYLON.AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  14167. case "AnaglyphGamepadCamera":
  14168. return function () { return new BABYLON.AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  14169. case "AnaglyphUniversalCamera":
  14170. return function () { return new BABYLON.AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  14171. case "StereoscopicArcRotateCamera":
  14172. return function () { return new BABYLON.StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  14173. case "StereoscopicFreeCamera":
  14174. return function () { return new BABYLON.StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  14175. case "StereoscopicGamepadCamera":
  14176. return function () { return new BABYLON.StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  14177. case "StereoscopicUniversalCamera":
  14178. return function () { return new BABYLON.StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  14179. case "FreeCamera":
  14180. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  14181. default:
  14182. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  14183. }
  14184. };
  14185. Camera.Parse = function (parsedCamera, scene) {
  14186. var type = parsedCamera.type;
  14187. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  14188. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  14189. // Parent
  14190. if (parsedCamera.parentId) {
  14191. camera._waitingParentId = parsedCamera.parentId;
  14192. }
  14193. //If camera has an input manager, let it parse inputs settings
  14194. if (camera.inputs) {
  14195. camera.inputs.parse(parsedCamera);
  14196. camera._setupInputs();
  14197. }
  14198. // Target
  14199. if (parsedCamera.target) {
  14200. if (camera.setTarget) {
  14201. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  14202. }
  14203. }
  14204. // Apply 3d rig, when found
  14205. if (parsedCamera.cameraRigMode) {
  14206. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  14207. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  14208. }
  14209. // Animations
  14210. if (parsedCamera.animations) {
  14211. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  14212. var parsedAnimation = parsedCamera.animations[animationIndex];
  14213. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  14214. }
  14215. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  14216. }
  14217. if (parsedCamera.autoAnimate) {
  14218. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  14219. }
  14220. return camera;
  14221. };
  14222. return Camera;
  14223. }(BABYLON.Node));
  14224. // Statics
  14225. Camera._PERSPECTIVE_CAMERA = 0;
  14226. Camera._ORTHOGRAPHIC_CAMERA = 1;
  14227. Camera._FOVMODE_VERTICAL_FIXED = 0;
  14228. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  14229. Camera._RIG_MODE_NONE = 0;
  14230. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  14231. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  14232. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  14233. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  14234. Camera._RIG_MODE_VR = 20;
  14235. Camera._RIG_MODE_WEBVR = 21;
  14236. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  14237. __decorate([
  14238. BABYLON.serializeAsVector3()
  14239. ], Camera.prototype, "position", void 0);
  14240. __decorate([
  14241. BABYLON.serializeAsVector3()
  14242. ], Camera.prototype, "upVector", void 0);
  14243. __decorate([
  14244. BABYLON.serialize()
  14245. ], Camera.prototype, "orthoLeft", void 0);
  14246. __decorate([
  14247. BABYLON.serialize()
  14248. ], Camera.prototype, "orthoRight", void 0);
  14249. __decorate([
  14250. BABYLON.serialize()
  14251. ], Camera.prototype, "orthoBottom", void 0);
  14252. __decorate([
  14253. BABYLON.serialize()
  14254. ], Camera.prototype, "orthoTop", void 0);
  14255. __decorate([
  14256. BABYLON.serialize()
  14257. ], Camera.prototype, "fov", void 0);
  14258. __decorate([
  14259. BABYLON.serialize()
  14260. ], Camera.prototype, "minZ", void 0);
  14261. __decorate([
  14262. BABYLON.serialize()
  14263. ], Camera.prototype, "maxZ", void 0);
  14264. __decorate([
  14265. BABYLON.serialize()
  14266. ], Camera.prototype, "inertia", void 0);
  14267. __decorate([
  14268. BABYLON.serialize()
  14269. ], Camera.prototype, "mode", void 0);
  14270. __decorate([
  14271. BABYLON.serialize()
  14272. ], Camera.prototype, "layerMask", void 0);
  14273. __decorate([
  14274. BABYLON.serialize()
  14275. ], Camera.prototype, "fovMode", void 0);
  14276. __decorate([
  14277. BABYLON.serialize()
  14278. ], Camera.prototype, "cameraRigMode", void 0);
  14279. __decorate([
  14280. BABYLON.serialize()
  14281. ], Camera.prototype, "interaxialDistance", void 0);
  14282. __decorate([
  14283. BABYLON.serialize()
  14284. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  14285. BABYLON.Camera = Camera;
  14286. })(BABYLON || (BABYLON = {}));
  14287. //# sourceMappingURL=babylon.camera.js.map
  14288. var BABYLON;
  14289. (function (BABYLON) {
  14290. BABYLON.CameraInputTypes = {};
  14291. var CameraInputsManager = (function () {
  14292. function CameraInputsManager(camera) {
  14293. this.attached = {};
  14294. this.camera = camera;
  14295. this.checkInputs = function () { };
  14296. }
  14297. CameraInputsManager.prototype.add = function (input) {
  14298. var type = input.getSimpleName();
  14299. if (this.attached[type]) {
  14300. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  14301. return;
  14302. }
  14303. this.attached[type] = input;
  14304. input.camera = this.camera;
  14305. //for checkInputs, we are dynamically creating a function
  14306. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  14307. if (input.checkInputs) {
  14308. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  14309. }
  14310. if (this.attachedElement) {
  14311. input.attachControl(this.attachedElement);
  14312. }
  14313. };
  14314. CameraInputsManager.prototype.remove = function (inputToRemove) {
  14315. for (var cam in this.attached) {
  14316. var input = this.attached[cam];
  14317. if (input === inputToRemove) {
  14318. input.detachControl(this.attachedElement);
  14319. delete this.attached[cam];
  14320. this.rebuildInputCheck();
  14321. }
  14322. }
  14323. };
  14324. CameraInputsManager.prototype.removeByType = function (inputType) {
  14325. for (var cam in this.attached) {
  14326. var input = this.attached[cam];
  14327. if (input.getTypeName() === inputType) {
  14328. input.detachControl(this.attachedElement);
  14329. delete this.attached[cam];
  14330. this.rebuildInputCheck();
  14331. }
  14332. }
  14333. };
  14334. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  14335. var current = this.checkInputs;
  14336. return function () {
  14337. current();
  14338. fn();
  14339. };
  14340. };
  14341. CameraInputsManager.prototype.attachInput = function (input) {
  14342. input.attachControl(this.attachedElement, this.noPreventDefault);
  14343. };
  14344. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  14345. if (this.attachedElement) {
  14346. return;
  14347. }
  14348. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  14349. this.attachedElement = element;
  14350. this.noPreventDefault = noPreventDefault;
  14351. for (var cam in this.attached) {
  14352. var input = this.attached[cam];
  14353. this.attached[cam].attachControl(element, noPreventDefault);
  14354. }
  14355. };
  14356. CameraInputsManager.prototype.detachElement = function (element) {
  14357. if (this.attachedElement !== element) {
  14358. return;
  14359. }
  14360. for (var cam in this.attached) {
  14361. var input = this.attached[cam];
  14362. this.attached[cam].detachControl(element);
  14363. }
  14364. this.attachedElement = null;
  14365. };
  14366. CameraInputsManager.prototype.rebuildInputCheck = function () {
  14367. this.checkInputs = function () { };
  14368. for (var cam in this.attached) {
  14369. var input = this.attached[cam];
  14370. if (input.checkInputs) {
  14371. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  14372. }
  14373. }
  14374. };
  14375. CameraInputsManager.prototype.clear = function () {
  14376. if (this.attachedElement) {
  14377. this.detachElement(this.attachedElement);
  14378. }
  14379. this.attached = {};
  14380. this.attachedElement = null;
  14381. this.checkInputs = function () { };
  14382. };
  14383. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  14384. var inputs = {};
  14385. for (var cam in this.attached) {
  14386. var input = this.attached[cam];
  14387. var res = BABYLON.SerializationHelper.Serialize(input);
  14388. inputs[input.getTypeName()] = res;
  14389. }
  14390. serializedCamera.inputsmgr = inputs;
  14391. };
  14392. CameraInputsManager.prototype.parse = function (parsedCamera) {
  14393. var parsedInputs = parsedCamera.inputsmgr;
  14394. if (parsedInputs) {
  14395. this.clear();
  14396. for (var n in parsedInputs) {
  14397. var construct = BABYLON.CameraInputTypes[n];
  14398. if (construct) {
  14399. var parsedinput = parsedInputs[n];
  14400. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  14401. this.add(input);
  14402. }
  14403. }
  14404. }
  14405. else {
  14406. //2016-03-08 this part is for managing backward compatibility
  14407. for (var n in this.attached) {
  14408. var construct = BABYLON.CameraInputTypes[this.attached[n].getTypeName()];
  14409. if (construct) {
  14410. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  14411. this.remove(this.attached[n]);
  14412. this.add(input);
  14413. }
  14414. }
  14415. }
  14416. };
  14417. return CameraInputsManager;
  14418. }());
  14419. BABYLON.CameraInputsManager = CameraInputsManager;
  14420. })(BABYLON || (BABYLON = {}));
  14421. //# sourceMappingURL=babylon.cameraInputsManager.js.map
  14422. var BABYLON;
  14423. (function (BABYLON) {
  14424. var FreeCameraMouseInput = (function () {
  14425. function FreeCameraMouseInput(touchEnabled) {
  14426. if (touchEnabled === void 0) { touchEnabled = true; }
  14427. this.touchEnabled = touchEnabled;
  14428. this.buttons = [0, 1, 2];
  14429. this.angularSensibility = 2000.0;
  14430. }
  14431. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  14432. var _this = this;
  14433. var engine = this.camera.getEngine();
  14434. if (!this._pointerInput) {
  14435. this._pointerInput = function (p, s) {
  14436. var evt = p.event;
  14437. if (!_this.touchEnabled && evt.pointerType === "touch") {
  14438. return;
  14439. }
  14440. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  14441. return;
  14442. }
  14443. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  14444. try {
  14445. evt.srcElement.setPointerCapture(evt.pointerId);
  14446. }
  14447. catch (e) {
  14448. }
  14449. _this.previousPosition = {
  14450. x: evt.clientX,
  14451. y: evt.clientY
  14452. };
  14453. if (!noPreventDefault) {
  14454. evt.preventDefault();
  14455. element.focus();
  14456. }
  14457. }
  14458. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  14459. try {
  14460. evt.srcElement.releasePointerCapture(evt.pointerId);
  14461. }
  14462. catch (e) {
  14463. }
  14464. _this.previousPosition = null;
  14465. if (!noPreventDefault) {
  14466. evt.preventDefault();
  14467. }
  14468. }
  14469. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  14470. if (!_this.previousPosition || engine.isPointerLock) {
  14471. return;
  14472. }
  14473. var offsetX = evt.clientX - _this.previousPosition.x;
  14474. var offsetY = evt.clientY - _this.previousPosition.y;
  14475. if (_this.camera.getScene().useRightHandedSystem) {
  14476. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  14477. }
  14478. else {
  14479. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  14480. }
  14481. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  14482. _this.previousPosition = {
  14483. x: evt.clientX,
  14484. y: evt.clientY
  14485. };
  14486. if (!noPreventDefault) {
  14487. evt.preventDefault();
  14488. }
  14489. }
  14490. };
  14491. }
  14492. this._onMouseMove = function (evt) {
  14493. if (!engine.isPointerLock) {
  14494. return;
  14495. }
  14496. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  14497. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  14498. if (_this.camera.getScene().useRightHandedSystem) {
  14499. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  14500. }
  14501. else {
  14502. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  14503. }
  14504. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  14505. _this.previousPosition = null;
  14506. if (!noPreventDefault) {
  14507. evt.preventDefault();
  14508. }
  14509. };
  14510. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  14511. element.addEventListener("mousemove", this._onMouseMove, false);
  14512. };
  14513. FreeCameraMouseInput.prototype.detachControl = function (element) {
  14514. if (this._observer && element) {
  14515. this.camera.getScene().onPointerObservable.remove(this._observer);
  14516. element.removeEventListener("mousemove", this._onMouseMove);
  14517. this._observer = null;
  14518. this._onMouseMove = null;
  14519. this.previousPosition = null;
  14520. }
  14521. };
  14522. FreeCameraMouseInput.prototype.getTypeName = function () {
  14523. return "FreeCameraMouseInput";
  14524. };
  14525. FreeCameraMouseInput.prototype.getSimpleName = function () {
  14526. return "mouse";
  14527. };
  14528. return FreeCameraMouseInput;
  14529. }());
  14530. __decorate([
  14531. BABYLON.serialize()
  14532. ], FreeCameraMouseInput.prototype, "buttons", void 0);
  14533. __decorate([
  14534. BABYLON.serialize()
  14535. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  14536. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  14537. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  14538. })(BABYLON || (BABYLON = {}));
  14539. //# sourceMappingURL=babylon.freecamera.input.mouse.js.map
  14540. var BABYLON;
  14541. (function (BABYLON) {
  14542. var FreeCameraKeyboardMoveInput = (function () {
  14543. function FreeCameraKeyboardMoveInput() {
  14544. this._keys = [];
  14545. this.keysUp = [38];
  14546. this.keysDown = [40];
  14547. this.keysLeft = [37];
  14548. this.keysRight = [39];
  14549. }
  14550. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  14551. var _this = this;
  14552. if (!this._onKeyDown) {
  14553. element.tabIndex = 1;
  14554. this._onKeyDown = function (evt) {
  14555. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  14556. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  14557. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  14558. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  14559. var index = _this._keys.indexOf(evt.keyCode);
  14560. if (index === -1) {
  14561. _this._keys.push(evt.keyCode);
  14562. }
  14563. if (!noPreventDefault) {
  14564. evt.preventDefault();
  14565. }
  14566. }
  14567. };
  14568. this._onKeyUp = function (evt) {
  14569. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  14570. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  14571. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  14572. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  14573. var index = _this._keys.indexOf(evt.keyCode);
  14574. if (index >= 0) {
  14575. _this._keys.splice(index, 1);
  14576. }
  14577. if (!noPreventDefault) {
  14578. evt.preventDefault();
  14579. }
  14580. }
  14581. };
  14582. element.addEventListener("keydown", this._onKeyDown, false);
  14583. element.addEventListener("keyup", this._onKeyUp, false);
  14584. BABYLON.Tools.RegisterTopRootEvents([
  14585. { name: "blur", handler: this._onLostFocus }
  14586. ]);
  14587. }
  14588. };
  14589. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  14590. if (this._onKeyDown) {
  14591. element.removeEventListener("keydown", this._onKeyDown);
  14592. element.removeEventListener("keyup", this._onKeyUp);
  14593. BABYLON.Tools.UnregisterTopRootEvents([
  14594. { name: "blur", handler: this._onLostFocus }
  14595. ]);
  14596. this._keys = [];
  14597. this._onKeyDown = null;
  14598. this._onKeyUp = null;
  14599. }
  14600. };
  14601. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  14602. if (this._onKeyDown) {
  14603. var camera = this.camera;
  14604. // Keyboard
  14605. for (var index = 0; index < this._keys.length; index++) {
  14606. var keyCode = this._keys[index];
  14607. var speed = camera._computeLocalCameraSpeed();
  14608. if (this.keysLeft.indexOf(keyCode) !== -1) {
  14609. camera._localDirection.copyFromFloats(-speed, 0, 0);
  14610. }
  14611. else if (this.keysUp.indexOf(keyCode) !== -1) {
  14612. camera._localDirection.copyFromFloats(0, 0, speed);
  14613. }
  14614. else if (this.keysRight.indexOf(keyCode) !== -1) {
  14615. camera._localDirection.copyFromFloats(speed, 0, 0);
  14616. }
  14617. else if (this.keysDown.indexOf(keyCode) !== -1) {
  14618. camera._localDirection.copyFromFloats(0, 0, -speed);
  14619. }
  14620. if (camera.getScene().useRightHandedSystem) {
  14621. camera._localDirection.z *= -1;
  14622. }
  14623. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  14624. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  14625. camera.cameraDirection.addInPlace(camera._transformedDirection);
  14626. }
  14627. }
  14628. };
  14629. FreeCameraKeyboardMoveInput.prototype.getTypeName = function () {
  14630. return "FreeCameraKeyboardMoveInput";
  14631. };
  14632. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  14633. this._keys = [];
  14634. };
  14635. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  14636. return "keyboard";
  14637. };
  14638. return FreeCameraKeyboardMoveInput;
  14639. }());
  14640. __decorate([
  14641. BABYLON.serialize()
  14642. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  14643. __decorate([
  14644. BABYLON.serialize()
  14645. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  14646. __decorate([
  14647. BABYLON.serialize()
  14648. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  14649. __decorate([
  14650. BABYLON.serialize()
  14651. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  14652. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  14653. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  14654. })(BABYLON || (BABYLON = {}));
  14655. //# sourceMappingURL=babylon.freecamera.input.keyboard.js.map
  14656. var BABYLON;
  14657. (function (BABYLON) {
  14658. var FreeCameraTouchInput = (function () {
  14659. function FreeCameraTouchInput() {
  14660. this._offsetX = null;
  14661. this._offsetY = null;
  14662. this._pointerCount = 0;
  14663. this._pointerPressed = [];
  14664. this.touchAngularSensibility = 200000.0;
  14665. this.touchMoveSensibility = 250.0;
  14666. }
  14667. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  14668. var _this = this;
  14669. var previousPosition;
  14670. if (this._pointerInput === undefined) {
  14671. this._onLostFocus = function (evt) {
  14672. _this._offsetX = null;
  14673. _this._offsetY = null;
  14674. };
  14675. this._pointerInput = function (p, s) {
  14676. var evt = p.event;
  14677. if (evt.pointerType === "mouse") {
  14678. return;
  14679. }
  14680. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  14681. if (!noPreventDefault) {
  14682. evt.preventDefault();
  14683. }
  14684. _this._pointerPressed.push(evt.pointerId);
  14685. if (_this._pointerPressed.length !== 1) {
  14686. return;
  14687. }
  14688. previousPosition = {
  14689. x: evt.clientX,
  14690. y: evt.clientY
  14691. };
  14692. }
  14693. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  14694. if (!noPreventDefault) {
  14695. evt.preventDefault();
  14696. }
  14697. var index = _this._pointerPressed.indexOf(evt.pointerId);
  14698. if (index === -1) {
  14699. return;
  14700. }
  14701. _this._pointerPressed.splice(index, 1);
  14702. if (index != 0) {
  14703. return;
  14704. }
  14705. previousPosition = null;
  14706. _this._offsetX = null;
  14707. _this._offsetY = null;
  14708. }
  14709. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  14710. if (!noPreventDefault) {
  14711. evt.preventDefault();
  14712. }
  14713. if (!previousPosition) {
  14714. return;
  14715. }
  14716. var index = _this._pointerPressed.indexOf(evt.pointerId);
  14717. if (index != 0) {
  14718. return;
  14719. }
  14720. _this._offsetX = evt.clientX - previousPosition.x;
  14721. _this._offsetY = -(evt.clientY - previousPosition.y);
  14722. }
  14723. };
  14724. }
  14725. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  14726. element.addEventListener("blur", this._onLostFocus);
  14727. };
  14728. FreeCameraTouchInput.prototype.detachControl = function (element) {
  14729. if (this._pointerInput && element) {
  14730. this.camera.getScene().onPointerObservable.remove(this._observer);
  14731. this._observer = null;
  14732. element.removeEventListener("blur", this._onLostFocus);
  14733. this._onLostFocus = null;
  14734. this._pointerPressed = [];
  14735. this._offsetX = null;
  14736. this._offsetY = null;
  14737. this._pointerCount = 0;
  14738. }
  14739. };
  14740. FreeCameraTouchInput.prototype.checkInputs = function () {
  14741. if (this._offsetX) {
  14742. var camera = this.camera;
  14743. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  14744. if (this._pointerPressed.length > 1) {
  14745. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  14746. }
  14747. else {
  14748. var speed = camera._computeLocalCameraSpeed();
  14749. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  14750. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  14751. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  14752. }
  14753. }
  14754. };
  14755. FreeCameraTouchInput.prototype.getTypeName = function () {
  14756. return "FreeCameraTouchInput";
  14757. };
  14758. FreeCameraTouchInput.prototype.getSimpleName = function () {
  14759. return "touch";
  14760. };
  14761. return FreeCameraTouchInput;
  14762. }());
  14763. __decorate([
  14764. BABYLON.serialize()
  14765. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  14766. __decorate([
  14767. BABYLON.serialize()
  14768. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  14769. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  14770. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  14771. })(BABYLON || (BABYLON = {}));
  14772. //# sourceMappingURL=babylon.freecamera.input.touch.js.map
  14773. var BABYLON;
  14774. (function (BABYLON) {
  14775. var FreeCameraDeviceOrientationInput = (function () {
  14776. function FreeCameraDeviceOrientationInput() {
  14777. var _this = this;
  14778. this._screenOrientationAngle = 0;
  14779. this._screenQuaternion = new BABYLON.Quaternion();
  14780. this._alpha = 0;
  14781. this._beta = 0;
  14782. this._gamma = 0;
  14783. this._orientationChanged = function () {
  14784. _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && window.screen.orientation['angle'] ? window.screen.orientation.angle : 0));
  14785. _this._screenOrientationAngle = -BABYLON.Tools.ToRadians(_this._screenOrientationAngle / 2);
  14786. _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle));
  14787. };
  14788. this._deviceOrientation = function (evt) {
  14789. _this._alpha = evt.alpha;
  14790. _this._beta = evt.beta;
  14791. _this._gamma = evt.gamma;
  14792. };
  14793. this._constantTranform = new BABYLON.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));
  14794. this._orientationChanged();
  14795. }
  14796. Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", {
  14797. get: function () {
  14798. return this._camera;
  14799. },
  14800. set: function (camera) {
  14801. this._camera = camera;
  14802. if (!this._camera.rotationQuaternion)
  14803. this._camera.rotationQuaternion = new BABYLON.Quaternion();
  14804. },
  14805. enumerable: true,
  14806. configurable: true
  14807. });
  14808. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  14809. window.addEventListener("orientationchange", this._orientationChanged);
  14810. window.addEventListener("deviceorientation", this._deviceOrientation);
  14811. //In certain cases, the attach control is called AFTER orientation was changed,
  14812. //So this is needed.
  14813. this._orientationChanged();
  14814. };
  14815. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  14816. window.removeEventListener("orientationchange", this._orientationChanged);
  14817. window.removeEventListener("deviceorientation", this._deviceOrientation);
  14818. };
  14819. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  14820. //if no device orientation provided, don't update the rotation.
  14821. //Only testing against alpha under the assumption thatnorientation will never be so exact when set.
  14822. if (!this._alpha)
  14823. return;
  14824. BABYLON.Quaternion.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(this._alpha), BABYLON.Tools.ToRadians(this._beta), -BABYLON.Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);
  14825. this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);
  14826. this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);
  14827. //Mirror on XY Plane
  14828. this._camera.rotationQuaternion.z *= -1;
  14829. this._camera.rotationQuaternion.w *= -1;
  14830. };
  14831. FreeCameraDeviceOrientationInput.prototype.getTypeName = function () {
  14832. return "FreeCameraDeviceOrientationInput";
  14833. };
  14834. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  14835. return "deviceOrientation";
  14836. };
  14837. return FreeCameraDeviceOrientationInput;
  14838. }());
  14839. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  14840. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  14841. })(BABYLON || (BABYLON = {}));
  14842. //# sourceMappingURL=babylon.freecamera.input.deviceorientation.js.map
  14843. var BABYLON;
  14844. (function (BABYLON) {
  14845. var FreeCameraGamepadInput = (function () {
  14846. function FreeCameraGamepadInput() {
  14847. this.gamepadAngularSensibility = 200;
  14848. this.gamepadMoveSensibility = 40;
  14849. }
  14850. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  14851. var _this = this;
  14852. this._gamepads = new BABYLON.Gamepads(function (gamepad) { _this._onNewGameConnected(gamepad); });
  14853. };
  14854. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  14855. if (this._gamepads) {
  14856. this._gamepads.dispose();
  14857. }
  14858. this.gamepad = null;
  14859. };
  14860. FreeCameraGamepadInput.prototype.checkInputs = function () {
  14861. if (this.gamepad) {
  14862. var camera = this.camera;
  14863. var LSValues = this.gamepad.leftStick;
  14864. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  14865. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  14866. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  14867. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  14868. var RSValues = this.gamepad.rightStick;
  14869. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  14870. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  14871. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  14872. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  14873. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  14874. var speed = camera._computeLocalCameraSpeed() * 50.0;
  14875. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(LSValues.x * speed, 0, -LSValues.y * speed), cameraTransform);
  14876. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  14877. camera.cameraRotation = camera.cameraRotation.add(new BABYLON.Vector2(RSValues.y, RSValues.x));
  14878. }
  14879. };
  14880. FreeCameraGamepadInput.prototype._onNewGameConnected = function (gamepad) {
  14881. // Only the first gamepad can control the camera
  14882. if (gamepad.index === 0) {
  14883. this.gamepad = gamepad;
  14884. }
  14885. };
  14886. FreeCameraGamepadInput.prototype.getTypeName = function () {
  14887. return "FreeCameraGamepadInput";
  14888. };
  14889. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  14890. return "gamepad";
  14891. };
  14892. return FreeCameraGamepadInput;
  14893. }());
  14894. __decorate([
  14895. BABYLON.serialize()
  14896. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  14897. __decorate([
  14898. BABYLON.serialize()
  14899. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  14900. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  14901. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  14902. })(BABYLON || (BABYLON = {}));
  14903. //# sourceMappingURL=babylon.freecamera.input.gamepad.js.map
  14904. var BABYLON;
  14905. (function (BABYLON) {
  14906. var ArcRotateCameraKeyboardMoveInput = (function () {
  14907. function ArcRotateCameraKeyboardMoveInput() {
  14908. this._keys = [];
  14909. this.keysUp = [38];
  14910. this.keysDown = [40];
  14911. this.keysLeft = [37];
  14912. this.keysRight = [39];
  14913. }
  14914. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  14915. var _this = this;
  14916. element.tabIndex = 1;
  14917. this._onKeyDown = function (evt) {
  14918. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  14919. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  14920. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  14921. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  14922. var index = _this._keys.indexOf(evt.keyCode);
  14923. if (index === -1) {
  14924. _this._keys.push(evt.keyCode);
  14925. }
  14926. if (evt.preventDefault) {
  14927. if (!noPreventDefault) {
  14928. evt.preventDefault();
  14929. }
  14930. }
  14931. }
  14932. };
  14933. this._onKeyUp = function (evt) {
  14934. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  14935. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  14936. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  14937. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  14938. var index = _this._keys.indexOf(evt.keyCode);
  14939. if (index >= 0) {
  14940. _this._keys.splice(index, 1);
  14941. }
  14942. if (evt.preventDefault) {
  14943. if (!noPreventDefault) {
  14944. evt.preventDefault();
  14945. }
  14946. }
  14947. }
  14948. };
  14949. this._onLostFocus = function () {
  14950. _this._keys = [];
  14951. };
  14952. element.addEventListener("keydown", this._onKeyDown, false);
  14953. element.addEventListener("keyup", this._onKeyUp, false);
  14954. BABYLON.Tools.RegisterTopRootEvents([
  14955. { name: "blur", handler: this._onLostFocus }
  14956. ]);
  14957. };
  14958. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  14959. if (element) {
  14960. element.removeEventListener("keydown", this._onKeyDown);
  14961. element.removeEventListener("keyup", this._onKeyUp);
  14962. }
  14963. BABYLON.Tools.UnregisterTopRootEvents([
  14964. { name: "blur", handler: this._onLostFocus }
  14965. ]);
  14966. this._keys = [];
  14967. this._onKeyDown = null;
  14968. this._onKeyUp = null;
  14969. this._onLostFocus = null;
  14970. };
  14971. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  14972. if (this._onKeyDown) {
  14973. var camera = this.camera;
  14974. for (var index = 0; index < this._keys.length; index++) {
  14975. var keyCode = this._keys[index];
  14976. if (this.keysLeft.indexOf(keyCode) !== -1) {
  14977. camera.inertialAlphaOffset -= 0.01;
  14978. }
  14979. else if (this.keysUp.indexOf(keyCode) !== -1) {
  14980. camera.inertialBetaOffset -= 0.01;
  14981. }
  14982. else if (this.keysRight.indexOf(keyCode) !== -1) {
  14983. camera.inertialAlphaOffset += 0.01;
  14984. }
  14985. else if (this.keysDown.indexOf(keyCode) !== -1) {
  14986. camera.inertialBetaOffset += 0.01;
  14987. }
  14988. }
  14989. }
  14990. };
  14991. ArcRotateCameraKeyboardMoveInput.prototype.getTypeName = function () {
  14992. return "ArcRotateCameraKeyboardMoveInput";
  14993. };
  14994. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  14995. return "keyboard";
  14996. };
  14997. return ArcRotateCameraKeyboardMoveInput;
  14998. }());
  14999. __decorate([
  15000. BABYLON.serialize()
  15001. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  15002. __decorate([
  15003. BABYLON.serialize()
  15004. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  15005. __decorate([
  15006. BABYLON.serialize()
  15007. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  15008. __decorate([
  15009. BABYLON.serialize()
  15010. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  15011. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  15012. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  15013. })(BABYLON || (BABYLON = {}));
  15014. //# sourceMappingURL=babylon.arcrotatecamera.input.keyboard.js.map
  15015. var BABYLON;
  15016. (function (BABYLON) {
  15017. var ArcRotateCameraMouseWheelInput = (function () {
  15018. function ArcRotateCameraMouseWheelInput() {
  15019. this.wheelPrecision = 3.0;
  15020. }
  15021. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  15022. var _this = this;
  15023. this._wheel = function (p, s) {
  15024. //sanity check - this should be a PointerWheel event.
  15025. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  15026. return;
  15027. var event = p.event;
  15028. var delta = 0;
  15029. if (event.wheelDelta) {
  15030. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  15031. }
  15032. else if (event.detail) {
  15033. delta = -event.detail / _this.wheelPrecision;
  15034. }
  15035. if (delta)
  15036. _this.camera.inertialRadiusOffset += delta;
  15037. if (event.preventDefault) {
  15038. if (!noPreventDefault) {
  15039. event.preventDefault();
  15040. }
  15041. }
  15042. };
  15043. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  15044. };
  15045. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  15046. if (this._observer && element) {
  15047. this.camera.getScene().onPointerObservable.remove(this._observer);
  15048. this._observer = null;
  15049. this._wheel = null;
  15050. }
  15051. };
  15052. ArcRotateCameraMouseWheelInput.prototype.getTypeName = function () {
  15053. return "ArcRotateCameraMouseWheelInput";
  15054. };
  15055. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  15056. return "mousewheel";
  15057. };
  15058. return ArcRotateCameraMouseWheelInput;
  15059. }());
  15060. __decorate([
  15061. BABYLON.serialize()
  15062. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  15063. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  15064. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  15065. })(BABYLON || (BABYLON = {}));
  15066. //# sourceMappingURL=babylon.arcrotatecamera.input.mousewheel.js.map
  15067. var BABYLON;
  15068. (function (BABYLON) {
  15069. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  15070. var ArcRotateCameraPointersInput = (function () {
  15071. function ArcRotateCameraPointersInput() {
  15072. this.buttons = [0, 1, 2];
  15073. this.angularSensibilityX = 1000.0;
  15074. this.angularSensibilityY = 1000.0;
  15075. this.pinchPrecision = 6.0;
  15076. this.panningSensibility = 50.0;
  15077. this._isPanClick = false;
  15078. this.pinchInwards = true;
  15079. }
  15080. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  15081. var _this = this;
  15082. var engine = this.camera.getEngine();
  15083. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  15084. var pointA, pointB;
  15085. var previousPinchDistance = 0;
  15086. this._pointerInput = function (p, s) {
  15087. var evt = p.event;
  15088. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  15089. return;
  15090. }
  15091. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  15092. try {
  15093. evt.srcElement.setPointerCapture(evt.pointerId);
  15094. }
  15095. catch (e) {
  15096. }
  15097. // Manage panning with pan button click
  15098. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  15099. // manage pointers
  15100. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  15101. if (pointA === undefined) {
  15102. pointA = cacheSoloPointer;
  15103. }
  15104. else if (pointB === undefined) {
  15105. pointB = cacheSoloPointer;
  15106. }
  15107. if (!noPreventDefault) {
  15108. evt.preventDefault();
  15109. element.focus();
  15110. }
  15111. }
  15112. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  15113. try {
  15114. evt.srcElement.releasePointerCapture(evt.pointerId);
  15115. }
  15116. catch (e) {
  15117. }
  15118. cacheSoloPointer = null;
  15119. previousPinchDistance = 0;
  15120. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  15121. //but emptying completly pointers collection is required to fix a bug on iPhone :
  15122. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  15123. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  15124. pointA = pointB = undefined;
  15125. if (!noPreventDefault) {
  15126. evt.preventDefault();
  15127. }
  15128. }
  15129. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  15130. if (!noPreventDefault) {
  15131. evt.preventDefault();
  15132. }
  15133. // One button down
  15134. if (pointA && pointB === undefined) {
  15135. if (_this.panningSensibility !== 0 &&
  15136. ((evt.ctrlKey && _this.camera._useCtrlForPanning) ||
  15137. (!_this.camera._useCtrlForPanning && _this._isPanClick))) {
  15138. _this.camera
  15139. .inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  15140. _this.camera
  15141. .inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  15142. }
  15143. else {
  15144. var offsetX = evt.clientX - cacheSoloPointer.x;
  15145. var offsetY = evt.clientY - cacheSoloPointer.y;
  15146. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  15147. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  15148. }
  15149. cacheSoloPointer.x = evt.clientX;
  15150. cacheSoloPointer.y = evt.clientY;
  15151. }
  15152. else if (pointA && pointB) {
  15153. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  15154. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  15155. ed.x = evt.clientX;
  15156. ed.y = evt.clientY;
  15157. var direction = _this.pinchInwards ? 1 : -1;
  15158. var distX = pointA.x - pointB.x;
  15159. var distY = pointA.y - pointB.y;
  15160. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  15161. if (previousPinchDistance === 0) {
  15162. previousPinchDistance = pinchSquaredDistance;
  15163. return;
  15164. }
  15165. if (pinchSquaredDistance !== previousPinchDistance) {
  15166. _this.camera
  15167. .inertialRadiusOffset += (pinchSquaredDistance - previousPinchDistance) /
  15168. (_this.pinchPrecision *
  15169. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  15170. direction);
  15171. previousPinchDistance = pinchSquaredDistance;
  15172. }
  15173. }
  15174. }
  15175. };
  15176. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  15177. this._onContextMenu = function (evt) {
  15178. evt.preventDefault();
  15179. };
  15180. if (!this.camera._useCtrlForPanning) {
  15181. element.addEventListener("contextmenu", this._onContextMenu, false);
  15182. }
  15183. this._onLostFocus = function () {
  15184. //this._keys = [];
  15185. pointA = pointB = undefined;
  15186. previousPinchDistance = 0;
  15187. cacheSoloPointer = null;
  15188. };
  15189. this._onMouseMove = function (evt) {
  15190. if (!engine.isPointerLock) {
  15191. return;
  15192. }
  15193. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  15194. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  15195. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  15196. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  15197. if (!noPreventDefault) {
  15198. evt.preventDefault();
  15199. }
  15200. };
  15201. this._onGestureStart = function (e) {
  15202. if (window.MSGesture === undefined) {
  15203. return;
  15204. }
  15205. if (!_this._MSGestureHandler) {
  15206. _this._MSGestureHandler = new MSGesture();
  15207. _this._MSGestureHandler.target = element;
  15208. }
  15209. _this._MSGestureHandler.addPointer(e.pointerId);
  15210. };
  15211. this._onGesture = function (e) {
  15212. _this.camera.radius *= e.scale;
  15213. if (e.preventDefault) {
  15214. if (!noPreventDefault) {
  15215. e.stopPropagation();
  15216. e.preventDefault();
  15217. }
  15218. }
  15219. };
  15220. element.addEventListener("mousemove", this._onMouseMove, false);
  15221. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  15222. element.addEventListener("MSGestureChange", this._onGesture, false);
  15223. element.addEventListener("keydown", this._onKeyDown, false);
  15224. element.addEventListener("keyup", this._onKeyUp, false);
  15225. BABYLON.Tools.RegisterTopRootEvents([
  15226. { name: "blur", handler: this._onLostFocus }
  15227. ]);
  15228. };
  15229. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  15230. if (element && this._observer) {
  15231. this.camera.getScene().onPointerObservable.remove(this._observer);
  15232. this._observer = null;
  15233. element.removeEventListener("contextmenu", this._onContextMenu);
  15234. element.removeEventListener("mousemove", this._onMouseMove);
  15235. element.removeEventListener("MSPointerDown", this._onGestureStart);
  15236. element.removeEventListener("MSGestureChange", this._onGesture);
  15237. element.removeEventListener("keydown", this._onKeyDown);
  15238. element.removeEventListener("keyup", this._onKeyUp);
  15239. this._isPanClick = false;
  15240. this.pinchInwards = true;
  15241. this._onKeyDown = null;
  15242. this._onKeyUp = null;
  15243. this._onMouseMove = null;
  15244. this._onGestureStart = null;
  15245. this._onGesture = null;
  15246. this._MSGestureHandler = null;
  15247. this._onLostFocus = null;
  15248. this._onContextMenu = null;
  15249. }
  15250. BABYLON.Tools.UnregisterTopRootEvents([
  15251. { name: "blur", handler: this._onLostFocus }
  15252. ]);
  15253. };
  15254. ArcRotateCameraPointersInput.prototype.getTypeName = function () {
  15255. return "ArcRotateCameraPointersInput";
  15256. };
  15257. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  15258. return "pointers";
  15259. };
  15260. return ArcRotateCameraPointersInput;
  15261. }());
  15262. __decorate([
  15263. BABYLON.serialize()
  15264. ], ArcRotateCameraPointersInput.prototype, "buttons", void 0);
  15265. __decorate([
  15266. BABYLON.serialize()
  15267. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  15268. __decorate([
  15269. BABYLON.serialize()
  15270. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  15271. __decorate([
  15272. BABYLON.serialize()
  15273. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  15274. __decorate([
  15275. BABYLON.serialize()
  15276. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  15277. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  15278. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  15279. })(BABYLON || (BABYLON = {}));
  15280. //# sourceMappingURL=babylon.arcrotatecamera.input.pointers.js.map
  15281. var BABYLON;
  15282. (function (BABYLON) {
  15283. var ArcRotateCameraGamepadInput = (function () {
  15284. function ArcRotateCameraGamepadInput() {
  15285. this.gamepadRotationSensibility = 80;
  15286. this.gamepadMoveSensibility = 40;
  15287. }
  15288. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  15289. var _this = this;
  15290. this._gamepads = new BABYLON.Gamepads(function (gamepad) { _this._onNewGameConnected(gamepad); });
  15291. };
  15292. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  15293. if (this._gamepads) {
  15294. this._gamepads.dispose();
  15295. }
  15296. this.gamepad = null;
  15297. };
  15298. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  15299. if (this.gamepad) {
  15300. var camera = this.camera;
  15301. var RSValues = this.gamepad.rightStick;
  15302. if (RSValues.x != 0) {
  15303. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  15304. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  15305. camera.inertialAlphaOffset += normalizedRX;
  15306. }
  15307. }
  15308. if (RSValues.y != 0) {
  15309. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  15310. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  15311. camera.inertialBetaOffset += normalizedRY;
  15312. }
  15313. }
  15314. var LSValues = this.gamepad.leftStick;
  15315. if (LSValues.y != 0) {
  15316. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  15317. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  15318. this.camera.inertialRadiusOffset -= normalizedLY;
  15319. }
  15320. }
  15321. }
  15322. };
  15323. ArcRotateCameraGamepadInput.prototype._onNewGameConnected = function (gamepad) {
  15324. // Only the first gamepad can control the camera
  15325. if (gamepad.index === 0) {
  15326. this.gamepad = gamepad;
  15327. }
  15328. };
  15329. ArcRotateCameraGamepadInput.prototype.getTypeName = function () {
  15330. return "ArcRotateCameraGamepadInput";
  15331. };
  15332. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  15333. return "gamepad";
  15334. };
  15335. return ArcRotateCameraGamepadInput;
  15336. }());
  15337. __decorate([
  15338. BABYLON.serialize()
  15339. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  15340. __decorate([
  15341. BABYLON.serialize()
  15342. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  15343. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  15344. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  15345. })(BABYLON || (BABYLON = {}));
  15346. //# sourceMappingURL=babylon.arcrotatecamera.input.gamepad.js.map
  15347. var BABYLON;
  15348. (function (BABYLON) {
  15349. var ArcRotateCameraVRDeviceOrientationInput = (function () {
  15350. function ArcRotateCameraVRDeviceOrientationInput() {
  15351. this.alphaCorrection = 1;
  15352. this.betaCorrection = 1;
  15353. this.gammaCorrection = 1;
  15354. this._alpha = 0;
  15355. this._beta = 0;
  15356. this._gamma = 0;
  15357. this._dirty = false;
  15358. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  15359. }
  15360. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  15361. this.camera.attachControl(element, noPreventDefault);
  15362. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  15363. };
  15364. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  15365. var camera = this.camera;
  15366. this._alpha = +evt.alpha | 0;
  15367. this._beta = +evt.beta | 0;
  15368. this._gamma = +evt.gamma | 0;
  15369. this._dirty = true;
  15370. };
  15371. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  15372. if (this._dirty) {
  15373. this._dirty = false;
  15374. if (this._gamma < 0) {
  15375. this._gamma = 180 + this._gamma;
  15376. }
  15377. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  15378. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  15379. }
  15380. };
  15381. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  15382. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  15383. };
  15384. ArcRotateCameraVRDeviceOrientationInput.prototype.getTypeName = function () {
  15385. return "ArcRotateCameraVRDeviceOrientationInput";
  15386. };
  15387. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  15388. return "VRDeviceOrientation";
  15389. };
  15390. return ArcRotateCameraVRDeviceOrientationInput;
  15391. }());
  15392. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  15393. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  15394. })(BABYLON || (BABYLON = {}));
  15395. //# sourceMappingURL=babylon.arcrotatecamera.input.vrdeviceorientation.js.map
  15396. var BABYLON;
  15397. (function (BABYLON) {
  15398. var TargetCamera = (function (_super) {
  15399. __extends(TargetCamera, _super);
  15400. function TargetCamera(name, position, scene) {
  15401. var _this = _super.call(this, name, position, scene) || this;
  15402. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  15403. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  15404. _this.rotation = new BABYLON.Vector3(0, 0, 0);
  15405. _this.speed = 2.0;
  15406. _this.noRotationConstraint = false;
  15407. _this.lockedTarget = null;
  15408. _this._currentTarget = BABYLON.Vector3.Zero();
  15409. _this._viewMatrix = BABYLON.Matrix.Zero();
  15410. _this._camMatrix = BABYLON.Matrix.Zero();
  15411. _this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  15412. _this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  15413. _this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  15414. _this._defaultUpVector = new BABYLON.Vector3(0, 1, 0);
  15415. _this._transformedReferencePoint = BABYLON.Vector3.Zero();
  15416. _this._lookAtTemp = BABYLON.Matrix.Zero();
  15417. _this._tempMatrix = BABYLON.Matrix.Zero();
  15418. return _this;
  15419. }
  15420. TargetCamera.prototype.getFrontPosition = function (distance) {
  15421. var direction = this.getTarget().subtract(this.position);
  15422. direction.normalize();
  15423. direction.scaleInPlace(distance);
  15424. return this.globalPosition.add(direction);
  15425. };
  15426. TargetCamera.prototype._getLockedTargetPosition = function () {
  15427. if (!this.lockedTarget) {
  15428. return null;
  15429. }
  15430. if (this.lockedTarget.absolutePosition) {
  15431. this.lockedTarget.computeWorldMatrix();
  15432. }
  15433. return this.lockedTarget.absolutePosition || this.lockedTarget;
  15434. };
  15435. // Cache
  15436. TargetCamera.prototype._initCache = function () {
  15437. _super.prototype._initCache.call(this);
  15438. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  15439. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  15440. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  15441. };
  15442. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  15443. if (!ignoreParentClass) {
  15444. _super.prototype._updateCache.call(this);
  15445. }
  15446. var lockedTargetPosition = this._getLockedTargetPosition();
  15447. if (!lockedTargetPosition) {
  15448. this._cache.lockedTarget = null;
  15449. }
  15450. else {
  15451. if (!this._cache.lockedTarget) {
  15452. this._cache.lockedTarget = lockedTargetPosition.clone();
  15453. }
  15454. else {
  15455. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  15456. }
  15457. }
  15458. this._cache.rotation.copyFrom(this.rotation);
  15459. if (this.rotationQuaternion)
  15460. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  15461. };
  15462. // Synchronized
  15463. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  15464. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  15465. return false;
  15466. }
  15467. var lockedTargetPosition = this._getLockedTargetPosition();
  15468. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  15469. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  15470. };
  15471. // Methods
  15472. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  15473. var engine = this.getEngine();
  15474. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  15475. };
  15476. // Target
  15477. TargetCamera.prototype.setTarget = function (target) {
  15478. this.upVector.normalize();
  15479. BABYLON.Matrix.LookAtLHToRef(this.position, target, this._defaultUpVector, this._camMatrix);
  15480. this._camMatrix.invert();
  15481. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  15482. var vDir = target.subtract(this.position);
  15483. if (vDir.x >= 0.0) {
  15484. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  15485. }
  15486. else {
  15487. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  15488. }
  15489. this.rotation.z = 0;
  15490. if (isNaN(this.rotation.x)) {
  15491. this.rotation.x = 0;
  15492. }
  15493. if (isNaN(this.rotation.y)) {
  15494. this.rotation.y = 0;
  15495. }
  15496. if (isNaN(this.rotation.z)) {
  15497. this.rotation.z = 0;
  15498. }
  15499. if (this.rotationQuaternion) {
  15500. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  15501. }
  15502. };
  15503. TargetCamera.prototype.getTarget = function () {
  15504. return this._currentTarget;
  15505. };
  15506. TargetCamera.prototype._decideIfNeedsToMove = function () {
  15507. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  15508. };
  15509. TargetCamera.prototype._updatePosition = function () {
  15510. this.position.addInPlace(this.cameraDirection);
  15511. };
  15512. TargetCamera.prototype._checkInputs = function () {
  15513. var needToMove = this._decideIfNeedsToMove();
  15514. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  15515. // Move
  15516. if (needToMove) {
  15517. this._updatePosition();
  15518. }
  15519. // Rotate
  15520. if (needToRotate) {
  15521. this.rotation.x += this.cameraRotation.x;
  15522. this.rotation.y += this.cameraRotation.y;
  15523. if (!this.noRotationConstraint) {
  15524. var limit = (Math.PI / 2) * 0.95;
  15525. if (this.rotation.x > limit)
  15526. this.rotation.x = limit;
  15527. if (this.rotation.x < -limit)
  15528. this.rotation.x = -limit;
  15529. }
  15530. }
  15531. // Inertia
  15532. if (needToMove) {
  15533. if (Math.abs(this.cameraDirection.x) < BABYLON.Epsilon) {
  15534. this.cameraDirection.x = 0;
  15535. }
  15536. if (Math.abs(this.cameraDirection.y) < BABYLON.Epsilon) {
  15537. this.cameraDirection.y = 0;
  15538. }
  15539. if (Math.abs(this.cameraDirection.z) < BABYLON.Epsilon) {
  15540. this.cameraDirection.z = 0;
  15541. }
  15542. this.cameraDirection.scaleInPlace(this.inertia);
  15543. }
  15544. if (needToRotate) {
  15545. if (Math.abs(this.cameraRotation.x) < BABYLON.Epsilon) {
  15546. this.cameraRotation.x = 0;
  15547. }
  15548. if (Math.abs(this.cameraRotation.y) < BABYLON.Epsilon) {
  15549. this.cameraRotation.y = 0;
  15550. }
  15551. this.cameraRotation.scaleInPlace(this.inertia);
  15552. }
  15553. _super.prototype._checkInputs.call(this);
  15554. };
  15555. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  15556. if (this.rotationQuaternion) {
  15557. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  15558. //update the up vector!
  15559. BABYLON.Vector3.TransformNormalToRef(this._defaultUpVector, this._cameraRotationMatrix, this.upVector);
  15560. }
  15561. else {
  15562. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  15563. }
  15564. };
  15565. TargetCamera.prototype._getViewMatrix = function () {
  15566. if (!this.lockedTarget) {
  15567. // Compute
  15568. this._updateCameraRotationMatrix();
  15569. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  15570. // Computing target and final matrix
  15571. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  15572. }
  15573. else {
  15574. this._currentTarget.copyFrom(this._getLockedTargetPosition());
  15575. }
  15576. if (this.getScene().useRightHandedSystem) {
  15577. BABYLON.Matrix.LookAtRHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  15578. }
  15579. else {
  15580. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  15581. }
  15582. return this._viewMatrix;
  15583. };
  15584. /**
  15585. * @override
  15586. * Override Camera.createRigCamera
  15587. */
  15588. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  15589. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  15590. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  15591. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
  15592. if (!this.rotationQuaternion) {
  15593. this.rotationQuaternion = new BABYLON.Quaternion();
  15594. }
  15595. rigCamera._cameraRigParams = {};
  15596. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  15597. }
  15598. return rigCamera;
  15599. }
  15600. return null;
  15601. };
  15602. /**
  15603. * @override
  15604. * Override Camera._updateRigCameras
  15605. */
  15606. TargetCamera.prototype._updateRigCameras = function () {
  15607. var camLeft = this._rigCameras[0];
  15608. var camRight = this._rigCameras[1];
  15609. switch (this.cameraRigMode) {
  15610. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  15611. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  15612. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  15613. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  15614. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  15615. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  15616. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  15617. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  15618. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  15619. camLeft.setTarget(this.getTarget());
  15620. camRight.setTarget(this.getTarget());
  15621. break;
  15622. case BABYLON.Camera.RIG_MODE_VR:
  15623. case BABYLON.Camera.RIG_MODE_WEBVR:
  15624. if (camLeft.rotationQuaternion) {
  15625. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  15626. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  15627. }
  15628. else {
  15629. camLeft.rotation.copyFrom(this.rotation);
  15630. camRight.rotation.copyFrom(this.rotation);
  15631. }
  15632. camLeft.position.copyFrom(this.position);
  15633. camRight.position.copyFrom(this.position);
  15634. break;
  15635. }
  15636. _super.prototype._updateRigCameras.call(this);
  15637. };
  15638. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  15639. if (!this._rigCamTransformMatrix) {
  15640. this._rigCamTransformMatrix = new BABYLON.Matrix();
  15641. }
  15642. var target = this.getTarget();
  15643. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  15644. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  15645. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  15646. };
  15647. TargetCamera.prototype.getClassName = function () {
  15648. return "TargetCamera";
  15649. };
  15650. return TargetCamera;
  15651. }(BABYLON.Camera));
  15652. __decorate([
  15653. BABYLON.serializeAsVector3()
  15654. ], TargetCamera.prototype, "rotation", void 0);
  15655. __decorate([
  15656. BABYLON.serialize()
  15657. ], TargetCamera.prototype, "speed", void 0);
  15658. __decorate([
  15659. BABYLON.serializeAsMeshReference("lockedTargetId")
  15660. ], TargetCamera.prototype, "lockedTarget", void 0);
  15661. BABYLON.TargetCamera = TargetCamera;
  15662. })(BABYLON || (BABYLON = {}));
  15663. //# sourceMappingURL=babylon.targetCamera.js.map
  15664. var BABYLON;
  15665. (function (BABYLON) {
  15666. var FreeCamera = (function (_super) {
  15667. __extends(FreeCamera, _super);
  15668. function FreeCamera(name, position, scene) {
  15669. var _this = _super.call(this, name, position, scene) || this;
  15670. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  15671. _this.checkCollisions = false;
  15672. _this.applyGravity = false;
  15673. _this._collider = new BABYLON.Collider();
  15674. _this._needMoveForGravity = false;
  15675. _this._oldPosition = BABYLON.Vector3.Zero();
  15676. _this._diffPosition = BABYLON.Vector3.Zero();
  15677. _this._newPosition = BABYLON.Vector3.Zero();
  15678. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  15679. if (collidedMesh === void 0) { collidedMesh = null; }
  15680. //TODO move this to the collision coordinator!
  15681. if (_this.getScene().workerCollisions)
  15682. newPosition.multiplyInPlace(_this._collider.radius);
  15683. var updatePosition = function (newPos) {
  15684. _this._newPosition.copyFrom(newPos);
  15685. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  15686. var oldPosition = _this.position.clone();
  15687. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  15688. _this.position.addInPlace(_this._diffPosition);
  15689. if (_this.onCollide && collidedMesh) {
  15690. _this.onCollide(collidedMesh);
  15691. }
  15692. }
  15693. };
  15694. updatePosition(newPosition);
  15695. };
  15696. _this.inputs = new BABYLON.FreeCameraInputsManager(_this);
  15697. _this.inputs.addKeyboard().addMouse();
  15698. return _this;
  15699. }
  15700. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  15701. //-- begin properties for backward compatibility for inputs
  15702. get: function () {
  15703. var mouse = this.inputs.attached["mouse"];
  15704. if (mouse)
  15705. return mouse.angularSensibility;
  15706. },
  15707. set: function (value) {
  15708. var mouse = this.inputs.attached["mouse"];
  15709. if (mouse)
  15710. mouse.angularSensibility = value;
  15711. },
  15712. enumerable: true,
  15713. configurable: true
  15714. });
  15715. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  15716. get: function () {
  15717. var keyboard = this.inputs.attached["keyboard"];
  15718. if (keyboard)
  15719. return keyboard.keysUp;
  15720. },
  15721. set: function (value) {
  15722. var keyboard = this.inputs.attached["keyboard"];
  15723. if (keyboard)
  15724. keyboard.keysUp = value;
  15725. },
  15726. enumerable: true,
  15727. configurable: true
  15728. });
  15729. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  15730. get: function () {
  15731. var keyboard = this.inputs.attached["keyboard"];
  15732. if (keyboard)
  15733. return keyboard.keysDown;
  15734. },
  15735. set: function (value) {
  15736. var keyboard = this.inputs.attached["keyboard"];
  15737. if (keyboard)
  15738. keyboard.keysDown = value;
  15739. },
  15740. enumerable: true,
  15741. configurable: true
  15742. });
  15743. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  15744. get: function () {
  15745. var keyboard = this.inputs.attached["keyboard"];
  15746. if (keyboard)
  15747. return keyboard.keysLeft;
  15748. },
  15749. set: function (value) {
  15750. var keyboard = this.inputs.attached["keyboard"];
  15751. if (keyboard)
  15752. keyboard.keysLeft = value;
  15753. },
  15754. enumerable: true,
  15755. configurable: true
  15756. });
  15757. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  15758. get: function () {
  15759. var keyboard = this.inputs.attached["keyboard"];
  15760. if (keyboard)
  15761. return keyboard.keysRight;
  15762. },
  15763. set: function (value) {
  15764. var keyboard = this.inputs.attached["keyboard"];
  15765. if (keyboard)
  15766. keyboard.keysRight = value;
  15767. },
  15768. enumerable: true,
  15769. configurable: true
  15770. });
  15771. // Controls
  15772. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  15773. this.inputs.attachElement(element, noPreventDefault);
  15774. };
  15775. FreeCamera.prototype.detachControl = function (element) {
  15776. this.inputs.detachElement(element);
  15777. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  15778. this.cameraRotation = new BABYLON.Vector2(0, 0);
  15779. };
  15780. FreeCamera.prototype._collideWithWorld = function (velocity) {
  15781. var globalPosition;
  15782. if (this.parent) {
  15783. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  15784. }
  15785. else {
  15786. globalPosition = this.position;
  15787. }
  15788. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  15789. this._collider.radius = this.ellipsoid;
  15790. //no need for clone, as long as gravity is not on.
  15791. var actualVelocity = velocity;
  15792. //add gravity to the velocity to prevent the dual-collision checking
  15793. if (this.applyGravity) {
  15794. //this prevents mending with cameraDirection, a global variable of the free camera class.
  15795. actualVelocity = velocity.add(this.getScene().gravity);
  15796. }
  15797. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  15798. };
  15799. FreeCamera.prototype._checkInputs = function () {
  15800. if (!this._localDirection) {
  15801. this._localDirection = BABYLON.Vector3.Zero();
  15802. this._transformedDirection = BABYLON.Vector3.Zero();
  15803. }
  15804. this.inputs.checkInputs();
  15805. _super.prototype._checkInputs.call(this);
  15806. };
  15807. FreeCamera.prototype._decideIfNeedsToMove = function () {
  15808. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  15809. };
  15810. FreeCamera.prototype._updatePosition = function () {
  15811. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  15812. this._collideWithWorld(this.cameraDirection);
  15813. }
  15814. else {
  15815. this.position.addInPlace(this.cameraDirection);
  15816. }
  15817. };
  15818. FreeCamera.prototype.dispose = function () {
  15819. this.inputs.clear();
  15820. _super.prototype.dispose.call(this);
  15821. };
  15822. FreeCamera.prototype.getClassName = function () {
  15823. return "FreeCamera";
  15824. };
  15825. return FreeCamera;
  15826. }(BABYLON.TargetCamera));
  15827. __decorate([
  15828. BABYLON.serializeAsVector3()
  15829. ], FreeCamera.prototype, "ellipsoid", void 0);
  15830. __decorate([
  15831. BABYLON.serialize()
  15832. ], FreeCamera.prototype, "checkCollisions", void 0);
  15833. __decorate([
  15834. BABYLON.serialize()
  15835. ], FreeCamera.prototype, "applyGravity", void 0);
  15836. BABYLON.FreeCamera = FreeCamera;
  15837. })(BABYLON || (BABYLON = {}));
  15838. //# sourceMappingURL=babylon.freeCamera.js.map
  15839. var BABYLON;
  15840. (function (BABYLON) {
  15841. var FreeCameraInputsManager = (function (_super) {
  15842. __extends(FreeCameraInputsManager, _super);
  15843. function FreeCameraInputsManager(camera) {
  15844. return _super.call(this, camera) || this;
  15845. }
  15846. FreeCameraInputsManager.prototype.addKeyboard = function () {
  15847. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  15848. return this;
  15849. };
  15850. FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  15851. if (touchEnabled === void 0) { touchEnabled = true; }
  15852. this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
  15853. return this;
  15854. };
  15855. FreeCameraInputsManager.prototype.addGamepad = function () {
  15856. this.add(new BABYLON.FreeCameraGamepadInput());
  15857. return this;
  15858. };
  15859. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  15860. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  15861. return this;
  15862. };
  15863. FreeCameraInputsManager.prototype.addTouch = function () {
  15864. this.add(new BABYLON.FreeCameraTouchInput());
  15865. return this;
  15866. };
  15867. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  15868. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  15869. return this;
  15870. };
  15871. return FreeCameraInputsManager;
  15872. }(BABYLON.CameraInputsManager));
  15873. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  15874. })(BABYLON || (BABYLON = {}));
  15875. //# sourceMappingURL=babylon.freeCameraInputsManager.js.map
  15876. var BABYLON;
  15877. (function (BABYLON) {
  15878. var FollowCamera = (function (_super) {
  15879. __extends(FollowCamera, _super);
  15880. function FollowCamera(name, position, scene, lockedTarget) {
  15881. var _this = _super.call(this, name, position, scene) || this;
  15882. _this.radius = 12;
  15883. _this.rotationOffset = 0;
  15884. _this.heightOffset = 4;
  15885. _this.cameraAcceleration = 0.05;
  15886. _this.maxCameraSpeed = 20;
  15887. _this.lockedTarget = lockedTarget;
  15888. return _this;
  15889. }
  15890. FollowCamera.prototype.getRadians = function (degrees) {
  15891. return degrees * Math.PI / 180;
  15892. };
  15893. FollowCamera.prototype.follow = function (cameraTarget) {
  15894. if (!cameraTarget)
  15895. return;
  15896. var yRotation;
  15897. if (cameraTarget.rotationQuaternion) {
  15898. var rotMatrix = new BABYLON.Matrix();
  15899. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  15900. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  15901. }
  15902. else {
  15903. yRotation = cameraTarget.rotation.y;
  15904. }
  15905. var radians = this.getRadians(this.rotationOffset) + yRotation;
  15906. var targetX = cameraTarget.position.x + Math.sin(radians) * this.radius;
  15907. var targetZ = cameraTarget.position.z + Math.cos(radians) * this.radius;
  15908. var dx = targetX - this.position.x;
  15909. var dy = (cameraTarget.position.y + this.heightOffset) - this.position.y;
  15910. var dz = (targetZ) - this.position.z;
  15911. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  15912. var vy = dy * this.cameraAcceleration;
  15913. var vz = dz * this.cameraAcceleration * 2;
  15914. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  15915. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  15916. }
  15917. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  15918. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  15919. }
  15920. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  15921. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  15922. }
  15923. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  15924. this.setTarget(cameraTarget.position);
  15925. };
  15926. FollowCamera.prototype._checkInputs = function () {
  15927. _super.prototype._checkInputs.call(this);
  15928. this.follow(this.lockedTarget);
  15929. };
  15930. FollowCamera.prototype.getClassName = function () {
  15931. return "FollowCamera";
  15932. };
  15933. return FollowCamera;
  15934. }(BABYLON.TargetCamera));
  15935. __decorate([
  15936. BABYLON.serialize()
  15937. ], FollowCamera.prototype, "radius", void 0);
  15938. __decorate([
  15939. BABYLON.serialize()
  15940. ], FollowCamera.prototype, "rotationOffset", void 0);
  15941. __decorate([
  15942. BABYLON.serialize()
  15943. ], FollowCamera.prototype, "heightOffset", void 0);
  15944. __decorate([
  15945. BABYLON.serialize()
  15946. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  15947. __decorate([
  15948. BABYLON.serialize()
  15949. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  15950. __decorate([
  15951. BABYLON.serializeAsMeshReference("lockedTargetId")
  15952. ], FollowCamera.prototype, "lockedTarget", void 0);
  15953. BABYLON.FollowCamera = FollowCamera;
  15954. var ArcFollowCamera = (function (_super) {
  15955. __extends(ArcFollowCamera, _super);
  15956. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  15957. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  15958. _this.alpha = alpha;
  15959. _this.beta = beta;
  15960. _this.radius = radius;
  15961. _this.target = target;
  15962. _this._cartesianCoordinates = BABYLON.Vector3.Zero();
  15963. _this.follow();
  15964. return _this;
  15965. }
  15966. ArcFollowCamera.prototype.follow = function () {
  15967. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  15968. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  15969. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  15970. this.position = this.target.position.add(this._cartesianCoordinates);
  15971. this.setTarget(this.target.position);
  15972. };
  15973. ArcFollowCamera.prototype._checkInputs = function () {
  15974. _super.prototype._checkInputs.call(this);
  15975. this.follow();
  15976. };
  15977. ArcFollowCamera.prototype.getClassName = function () {
  15978. return "ArcFollowCamera";
  15979. };
  15980. return ArcFollowCamera;
  15981. }(BABYLON.TargetCamera));
  15982. BABYLON.ArcFollowCamera = ArcFollowCamera;
  15983. })(BABYLON || (BABYLON = {}));
  15984. //# sourceMappingURL=babylon.followCamera.js.map
  15985. var BABYLON;
  15986. (function (BABYLON) {
  15987. // We're mainly based on the logic defined into the FreeCamera code
  15988. var TouchCamera = (function (_super) {
  15989. __extends(TouchCamera, _super);
  15990. //-- end properties for backward compatibility for inputs
  15991. function TouchCamera(name, position, scene) {
  15992. var _this = _super.call(this, name, position, scene) || this;
  15993. _this.inputs.addTouch();
  15994. _this._setupInputs();
  15995. return _this;
  15996. }
  15997. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  15998. //-- Begin properties for backward compatibility for inputs
  15999. get: function () {
  16000. var touch = this.inputs.attached["touch"];
  16001. if (touch)
  16002. return touch.touchAngularSensibility;
  16003. },
  16004. set: function (value) {
  16005. var touch = this.inputs.attached["touch"];
  16006. if (touch)
  16007. touch.touchAngularSensibility = value;
  16008. },
  16009. enumerable: true,
  16010. configurable: true
  16011. });
  16012. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  16013. get: function () {
  16014. var touch = this.inputs.attached["touch"];
  16015. if (touch)
  16016. return touch.touchMoveSensibility;
  16017. },
  16018. set: function (value) {
  16019. var touch = this.inputs.attached["touch"];
  16020. if (touch)
  16021. touch.touchMoveSensibility = value;
  16022. },
  16023. enumerable: true,
  16024. configurable: true
  16025. });
  16026. TouchCamera.prototype.getClassName = function () {
  16027. return "TouchCamera";
  16028. };
  16029. TouchCamera.prototype._setupInputs = function () {
  16030. var mouse = this.inputs.attached["mouse"];
  16031. if (mouse) {
  16032. mouse.touchEnabled = false;
  16033. }
  16034. };
  16035. return TouchCamera;
  16036. }(BABYLON.FreeCamera));
  16037. BABYLON.TouchCamera = TouchCamera;
  16038. })(BABYLON || (BABYLON = {}));
  16039. //# sourceMappingURL=babylon.touchCamera.js.map
  16040. var BABYLON;
  16041. (function (BABYLON) {
  16042. var ArcRotateCamera = (function (_super) {
  16043. __extends(ArcRotateCamera, _super);
  16044. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  16045. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  16046. _this.inertialAlphaOffset = 0;
  16047. _this.inertialBetaOffset = 0;
  16048. _this.inertialRadiusOffset = 0;
  16049. _this.lowerAlphaLimit = null;
  16050. _this.upperAlphaLimit = null;
  16051. _this.lowerBetaLimit = 0.01;
  16052. _this.upperBetaLimit = Math.PI;
  16053. _this.lowerRadiusLimit = null;
  16054. _this.upperRadiusLimit = null;
  16055. _this.inertialPanningX = 0;
  16056. _this.inertialPanningY = 0;
  16057. //-- end properties for backward compatibility for inputs
  16058. _this.zoomOnFactor = 1;
  16059. _this.targetScreenOffset = BABYLON.Vector2.Zero();
  16060. _this.allowUpsideDown = true;
  16061. _this._viewMatrix = new BABYLON.Matrix();
  16062. // Panning
  16063. _this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  16064. _this.checkCollisions = false;
  16065. _this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  16066. _this._collider = new BABYLON.Collider();
  16067. _this._previousPosition = BABYLON.Vector3.Zero();
  16068. _this._collisionVelocity = BABYLON.Vector3.Zero();
  16069. _this._newPosition = BABYLON.Vector3.Zero();
  16070. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  16071. if (collidedMesh === void 0) { collidedMesh = null; }
  16072. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  16073. newPosition.multiplyInPlace(_this._collider.radius);
  16074. }
  16075. if (!collidedMesh) {
  16076. _this._previousPosition.copyFrom(_this.position);
  16077. }
  16078. else {
  16079. _this.setPosition(newPosition);
  16080. if (_this.onCollide) {
  16081. _this.onCollide(collidedMesh);
  16082. }
  16083. }
  16084. // Recompute because of constraints
  16085. var cosa = Math.cos(_this.alpha);
  16086. var sina = Math.sin(_this.alpha);
  16087. var cosb = Math.cos(_this.beta);
  16088. var sinb = Math.sin(_this.beta);
  16089. if (sinb === 0) {
  16090. sinb = 0.0001;
  16091. }
  16092. var target = _this._getTargetPosition();
  16093. target.addToRef(new BABYLON.Vector3(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb), _this._newPosition);
  16094. _this.position.copyFrom(_this._newPosition);
  16095. var up = _this.upVector;
  16096. if (_this.allowUpsideDown && _this.beta < 0) {
  16097. up = up.clone();
  16098. up = up.negate();
  16099. }
  16100. BABYLON.Matrix.LookAtLHToRef(_this.position, target, up, _this._viewMatrix);
  16101. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  16102. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  16103. _this._collisionTriggered = false;
  16104. };
  16105. if (!target) {
  16106. _this.target = BABYLON.Vector3.Zero();
  16107. }
  16108. else {
  16109. _this.target = target;
  16110. }
  16111. _this.alpha = alpha;
  16112. _this.beta = beta;
  16113. _this.radius = radius;
  16114. _this.getViewMatrix();
  16115. _this.inputs = new BABYLON.ArcRotateCameraInputsManager(_this);
  16116. _this.inputs.addKeyboard().addMouseWheel().addPointers().addGamepad();
  16117. return _this;
  16118. }
  16119. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  16120. //-- begin properties for backward compatibility for inputs
  16121. get: function () {
  16122. var pointers = this.inputs.attached["pointers"];
  16123. if (pointers)
  16124. return pointers.angularSensibilityX;
  16125. },
  16126. set: function (value) {
  16127. var pointers = this.inputs.attached["pointers"];
  16128. if (pointers) {
  16129. pointers.angularSensibilityX = value;
  16130. }
  16131. },
  16132. enumerable: true,
  16133. configurable: true
  16134. });
  16135. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  16136. get: function () {
  16137. var pointers = this.inputs.attached["pointers"];
  16138. if (pointers)
  16139. return pointers.angularSensibilityY;
  16140. },
  16141. set: function (value) {
  16142. var pointers = this.inputs.attached["pointers"];
  16143. if (pointers) {
  16144. pointers.angularSensibilityY = value;
  16145. }
  16146. },
  16147. enumerable: true,
  16148. configurable: true
  16149. });
  16150. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  16151. get: function () {
  16152. var pointers = this.inputs.attached["pointers"];
  16153. if (pointers)
  16154. return pointers.pinchPrecision;
  16155. },
  16156. set: function (value) {
  16157. var pointers = this.inputs.attached["pointers"];
  16158. if (pointers) {
  16159. pointers.pinchPrecision = value;
  16160. }
  16161. },
  16162. enumerable: true,
  16163. configurable: true
  16164. });
  16165. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  16166. get: function () {
  16167. var pointers = this.inputs.attached["pointers"];
  16168. if (pointers)
  16169. return pointers.panningSensibility;
  16170. },
  16171. set: function (value) {
  16172. var pointers = this.inputs.attached["pointers"];
  16173. if (pointers) {
  16174. pointers.panningSensibility = value;
  16175. }
  16176. },
  16177. enumerable: true,
  16178. configurable: true
  16179. });
  16180. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  16181. get: function () {
  16182. var keyboard = this.inputs.attached["keyboard"];
  16183. if (keyboard)
  16184. return keyboard.keysUp;
  16185. },
  16186. set: function (value) {
  16187. var keyboard = this.inputs.attached["keyboard"];
  16188. if (keyboard)
  16189. keyboard.keysUp = value;
  16190. },
  16191. enumerable: true,
  16192. configurable: true
  16193. });
  16194. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  16195. get: function () {
  16196. var keyboard = this.inputs.attached["keyboard"];
  16197. if (keyboard)
  16198. return keyboard.keysDown;
  16199. },
  16200. set: function (value) {
  16201. var keyboard = this.inputs.attached["keyboard"];
  16202. if (keyboard)
  16203. keyboard.keysDown = value;
  16204. },
  16205. enumerable: true,
  16206. configurable: true
  16207. });
  16208. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  16209. get: function () {
  16210. var keyboard = this.inputs.attached["keyboard"];
  16211. if (keyboard)
  16212. return keyboard.keysLeft;
  16213. },
  16214. set: function (value) {
  16215. var keyboard = this.inputs.attached["keyboard"];
  16216. if (keyboard)
  16217. keyboard.keysLeft = value;
  16218. },
  16219. enumerable: true,
  16220. configurable: true
  16221. });
  16222. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  16223. get: function () {
  16224. var keyboard = this.inputs.attached["keyboard"];
  16225. if (keyboard)
  16226. return keyboard.keysRight;
  16227. },
  16228. set: function (value) {
  16229. var keyboard = this.inputs.attached["keyboard"];
  16230. if (keyboard)
  16231. keyboard.keysRight = value;
  16232. },
  16233. enumerable: true,
  16234. configurable: true
  16235. });
  16236. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  16237. get: function () {
  16238. var mousewheel = this.inputs.attached["mousewheel"];
  16239. if (mousewheel)
  16240. return mousewheel.wheelPrecision;
  16241. },
  16242. set: function (value) {
  16243. var mousewheel = this.inputs.attached["mousewheel"];
  16244. if (mousewheel)
  16245. mousewheel.wheelPrecision = value;
  16246. },
  16247. enumerable: true,
  16248. configurable: true
  16249. });
  16250. // Cache
  16251. ArcRotateCamera.prototype._initCache = function () {
  16252. _super.prototype._initCache.call(this);
  16253. this._cache.target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  16254. this._cache.alpha = undefined;
  16255. this._cache.beta = undefined;
  16256. this._cache.radius = undefined;
  16257. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  16258. };
  16259. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  16260. if (!ignoreParentClass) {
  16261. _super.prototype._updateCache.call(this);
  16262. }
  16263. this._cache.target.copyFrom(this._getTargetPosition());
  16264. this._cache.alpha = this.alpha;
  16265. this._cache.beta = this.beta;
  16266. this._cache.radius = this.radius;
  16267. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  16268. };
  16269. ArcRotateCamera.prototype._getTargetPosition = function () {
  16270. if (this.target.getAbsolutePosition) {
  16271. var pos = this.target.getAbsolutePosition();
  16272. return this._targetBoundingCenter ? pos.add(this._targetBoundingCenter) : pos;
  16273. }
  16274. return this.target;
  16275. };
  16276. // Synchronized
  16277. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  16278. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  16279. return false;
  16280. return this._cache.target.equals(this.target)
  16281. && this._cache.alpha === this.alpha
  16282. && this._cache.beta === this.beta
  16283. && this._cache.radius === this.radius
  16284. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  16285. };
  16286. // Methods
  16287. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  16288. var _this = this;
  16289. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  16290. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  16291. this._useCtrlForPanning = useCtrlForPanning;
  16292. this._panningMouseButton = panningMouseButton;
  16293. this.inputs.attachElement(element, noPreventDefault);
  16294. this._reset = function () {
  16295. _this.inertialAlphaOffset = 0;
  16296. _this.inertialBetaOffset = 0;
  16297. _this.inertialRadiusOffset = 0;
  16298. };
  16299. };
  16300. ArcRotateCamera.prototype.detachControl = function (element) {
  16301. this.inputs.detachElement(element);
  16302. if (this._reset) {
  16303. this._reset();
  16304. }
  16305. };
  16306. ArcRotateCamera.prototype._checkInputs = function () {
  16307. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  16308. if (this._collisionTriggered) {
  16309. return;
  16310. }
  16311. this.inputs.checkInputs();
  16312. // Inertia
  16313. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  16314. if (this.getScene().useRightHandedSystem) {
  16315. this.alpha -= this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  16316. }
  16317. else {
  16318. this.alpha += this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  16319. }
  16320. this.beta += this.inertialBetaOffset;
  16321. this.radius -= this.inertialRadiusOffset;
  16322. this.inertialAlphaOffset *= this.inertia;
  16323. this.inertialBetaOffset *= this.inertia;
  16324. this.inertialRadiusOffset *= this.inertia;
  16325. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)
  16326. this.inertialAlphaOffset = 0;
  16327. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)
  16328. this.inertialBetaOffset = 0;
  16329. if (Math.abs(this.inertialRadiusOffset) < BABYLON.Epsilon)
  16330. this.inertialRadiusOffset = 0;
  16331. }
  16332. // Panning inertia
  16333. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  16334. if (!this._localDirection) {
  16335. this._localDirection = BABYLON.Vector3.Zero();
  16336. this._transformedDirection = BABYLON.Vector3.Zero();
  16337. }
  16338. this.inertialPanningX *= this.inertia;
  16339. this.inertialPanningY *= this.inertia;
  16340. if (Math.abs(this.inertialPanningX) < BABYLON.Epsilon)
  16341. this.inertialPanningX = 0;
  16342. if (Math.abs(this.inertialPanningY) < BABYLON.Epsilon)
  16343. this.inertialPanningY = 0;
  16344. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  16345. this._localDirection.multiplyInPlace(this.panningAxis);
  16346. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  16347. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  16348. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  16349. if (!this.panningAxis.y) {
  16350. this._transformedDirection.y = 0;
  16351. }
  16352. if (!this.target.getAbsolutePosition) {
  16353. this.target.addInPlace(this._transformedDirection);
  16354. }
  16355. }
  16356. // Limits
  16357. this._checkLimits();
  16358. _super.prototype._checkInputs.call(this);
  16359. };
  16360. ArcRotateCamera.prototype._checkLimits = function () {
  16361. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  16362. if (this.allowUpsideDown && this.beta > Math.PI) {
  16363. this.beta = this.beta - (2 * Math.PI);
  16364. }
  16365. }
  16366. else {
  16367. if (this.beta < this.lowerBetaLimit) {
  16368. this.beta = this.lowerBetaLimit;
  16369. }
  16370. }
  16371. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  16372. if (this.allowUpsideDown && this.beta < -Math.PI) {
  16373. this.beta = this.beta + (2 * Math.PI);
  16374. }
  16375. }
  16376. else {
  16377. if (this.beta > this.upperBetaLimit) {
  16378. this.beta = this.upperBetaLimit;
  16379. }
  16380. }
  16381. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  16382. this.alpha = this.lowerAlphaLimit;
  16383. }
  16384. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  16385. this.alpha = this.upperAlphaLimit;
  16386. }
  16387. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  16388. this.radius = this.lowerRadiusLimit;
  16389. }
  16390. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  16391. this.radius = this.upperRadiusLimit;
  16392. }
  16393. };
  16394. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  16395. var radiusv3 = this.position.subtract(this._getTargetPosition());
  16396. this.radius = radiusv3.length();
  16397. // Alpha
  16398. this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
  16399. if (radiusv3.z < 0) {
  16400. this.alpha = 2 * Math.PI - this.alpha;
  16401. }
  16402. // Beta
  16403. this.beta = Math.acos(radiusv3.y / this.radius);
  16404. this._checkLimits();
  16405. };
  16406. ArcRotateCamera.prototype.setPosition = function (position) {
  16407. if (this.position.equals(position)) {
  16408. return;
  16409. }
  16410. this.position.copyFrom(position);
  16411. this.rebuildAnglesAndRadius();
  16412. };
  16413. ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter, allowSamePosition) {
  16414. if (toBoundingCenter === void 0) { toBoundingCenter = false; }
  16415. if (allowSamePosition === void 0) { allowSamePosition = false; }
  16416. if (!allowSamePosition && this._getTargetPosition().equals(target)) {
  16417. return;
  16418. }
  16419. if (toBoundingCenter && target.getBoundingInfo) {
  16420. this._targetBoundingCenter = target.getBoundingInfo().boundingBox.center.clone();
  16421. }
  16422. else {
  16423. this._targetBoundingCenter = null;
  16424. }
  16425. this.target = target;
  16426. this.rebuildAnglesAndRadius();
  16427. };
  16428. ArcRotateCamera.prototype._getViewMatrix = function () {
  16429. // Compute
  16430. var cosa = Math.cos(this.alpha);
  16431. var sina = Math.sin(this.alpha);
  16432. var cosb = Math.cos(this.beta);
  16433. var sinb = Math.sin(this.beta);
  16434. if (sinb === 0) {
  16435. sinb = 0.0001;
  16436. }
  16437. var target = this._getTargetPosition();
  16438. target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this._newPosition);
  16439. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  16440. this._collider.radius = this.collisionRadius;
  16441. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  16442. this._collisionTriggered = true;
  16443. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  16444. }
  16445. else {
  16446. this.position.copyFrom(this._newPosition);
  16447. var up = this.upVector;
  16448. if (this.allowUpsideDown && this.beta < 0) {
  16449. up = up.clone();
  16450. up = up.negate();
  16451. }
  16452. if (this.getScene().useRightHandedSystem) {
  16453. BABYLON.Matrix.LookAtRHToRef(this.position, target, up, this._viewMatrix);
  16454. }
  16455. else {
  16456. BABYLON.Matrix.LookAtLHToRef(this.position, target, up, this._viewMatrix);
  16457. }
  16458. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  16459. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  16460. }
  16461. this._currentTarget = target;
  16462. return this._viewMatrix;
  16463. };
  16464. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  16465. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  16466. meshes = meshes || this.getScene().meshes;
  16467. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  16468. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  16469. this.radius = distance * this.zoomOnFactor;
  16470. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  16471. };
  16472. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  16473. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  16474. var meshesOrMinMaxVector;
  16475. var distance;
  16476. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  16477. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  16478. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshesOrMinMaxVector);
  16479. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  16480. }
  16481. else {
  16482. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance;
  16483. distance = meshesOrMinMaxVectorAndDistance.distance;
  16484. }
  16485. this.target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  16486. if (!doNotUpdateMaxZ) {
  16487. this.maxZ = distance * 2;
  16488. }
  16489. };
  16490. /**
  16491. * @override
  16492. * Override Camera.createRigCamera
  16493. */
  16494. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  16495. var alphaShift;
  16496. switch (this.cameraRigMode) {
  16497. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  16498. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  16499. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  16500. case BABYLON.Camera.RIG_MODE_VR:
  16501. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  16502. break;
  16503. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  16504. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  16505. break;
  16506. }
  16507. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this.target, this.getScene());
  16508. rigCam._cameraRigParams = {};
  16509. return rigCam;
  16510. };
  16511. /**
  16512. * @override
  16513. * Override Camera._updateRigCameras
  16514. */
  16515. ArcRotateCamera.prototype._updateRigCameras = function () {
  16516. var camLeft = this._rigCameras[0];
  16517. var camRight = this._rigCameras[1];
  16518. camLeft.beta = camRight.beta = this.beta;
  16519. camLeft.radius = camRight.radius = this.radius;
  16520. switch (this.cameraRigMode) {
  16521. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  16522. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  16523. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  16524. case BABYLON.Camera.RIG_MODE_VR:
  16525. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  16526. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  16527. break;
  16528. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  16529. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  16530. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  16531. break;
  16532. }
  16533. _super.prototype._updateRigCameras.call(this);
  16534. };
  16535. ArcRotateCamera.prototype.dispose = function () {
  16536. this.inputs.clear();
  16537. _super.prototype.dispose.call(this);
  16538. };
  16539. ArcRotateCamera.prototype.getClassName = function () {
  16540. return "ArcRotateCamera";
  16541. };
  16542. return ArcRotateCamera;
  16543. }(BABYLON.TargetCamera));
  16544. __decorate([
  16545. BABYLON.serialize()
  16546. ], ArcRotateCamera.prototype, "alpha", void 0);
  16547. __decorate([
  16548. BABYLON.serialize()
  16549. ], ArcRotateCamera.prototype, "beta", void 0);
  16550. __decorate([
  16551. BABYLON.serialize()
  16552. ], ArcRotateCamera.prototype, "radius", void 0);
  16553. __decorate([
  16554. BABYLON.serializeAsVector3()
  16555. ], ArcRotateCamera.prototype, "target", void 0);
  16556. __decorate([
  16557. BABYLON.serialize()
  16558. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  16559. __decorate([
  16560. BABYLON.serialize()
  16561. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  16562. __decorate([
  16563. BABYLON.serialize()
  16564. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  16565. __decorate([
  16566. BABYLON.serialize()
  16567. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  16568. __decorate([
  16569. BABYLON.serialize()
  16570. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  16571. __decorate([
  16572. BABYLON.serialize()
  16573. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  16574. __decorate([
  16575. BABYLON.serialize()
  16576. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  16577. __decorate([
  16578. BABYLON.serialize()
  16579. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  16580. __decorate([
  16581. BABYLON.serialize()
  16582. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  16583. __decorate([
  16584. BABYLON.serialize()
  16585. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  16586. __decorate([
  16587. BABYLON.serialize()
  16588. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  16589. __decorate([
  16590. BABYLON.serialize()
  16591. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  16592. __decorate([
  16593. BABYLON.serialize()
  16594. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  16595. BABYLON.ArcRotateCamera = ArcRotateCamera;
  16596. })(BABYLON || (BABYLON = {}));
  16597. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  16598. var BABYLON;
  16599. (function (BABYLON) {
  16600. var ArcRotateCameraInputsManager = (function (_super) {
  16601. __extends(ArcRotateCameraInputsManager, _super);
  16602. function ArcRotateCameraInputsManager(camera) {
  16603. return _super.call(this, camera) || this;
  16604. }
  16605. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  16606. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  16607. return this;
  16608. };
  16609. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  16610. this.add(new BABYLON.ArcRotateCameraPointersInput());
  16611. return this;
  16612. };
  16613. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  16614. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  16615. return this;
  16616. };
  16617. ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  16618. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  16619. return this;
  16620. };
  16621. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  16622. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  16623. return this;
  16624. };
  16625. return ArcRotateCameraInputsManager;
  16626. }(BABYLON.CameraInputsManager));
  16627. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  16628. })(BABYLON || (BABYLON = {}));
  16629. //# sourceMappingURL=babylon.arcRotateCameraInputsManager.js.map
  16630. var BABYLON;
  16631. (function (BABYLON) {
  16632. var RenderingManager = (function () {
  16633. function RenderingManager(scene) {
  16634. this._renderingGroups = new Array();
  16635. this._autoClearDepthStencil = {};
  16636. this._customOpaqueSortCompareFn = {};
  16637. this._customAlphaTestSortCompareFn = {};
  16638. this._customTransparentSortCompareFn = {};
  16639. this._renderinGroupInfo = null;
  16640. this._scene = scene;
  16641. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  16642. this._autoClearDepthStencil[i] = { autoClear: true, depth: true, stencil: true };
  16643. }
  16644. }
  16645. RenderingManager.prototype._clearDepthStencilBuffer = function (depth, stencil) {
  16646. if (depth === void 0) { depth = true; }
  16647. if (stencil === void 0) { stencil = true; }
  16648. if (this._depthStencilBufferAlreadyCleaned) {
  16649. return;
  16650. }
  16651. this._scene.getEngine().clear(null, false, depth, stencil);
  16652. this._depthStencilBufferAlreadyCleaned = true;
  16653. };
  16654. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  16655. // Check if there's at least on observer on the onRenderingGroupObservable and initialize things to fire it
  16656. var observable = this._scene.onRenderingGroupObservable.hasObservers() ? this._scene.onRenderingGroupObservable : null;
  16657. var info = null;
  16658. if (observable) {
  16659. if (!this._renderinGroupInfo) {
  16660. this._renderinGroupInfo = new BABYLON.RenderingGroupInfo();
  16661. }
  16662. info = this._renderinGroupInfo;
  16663. info.scene = this._scene;
  16664. info.camera = this._scene.activeCamera;
  16665. }
  16666. // Dispatch sprites
  16667. if (renderSprites) {
  16668. for (var index = 0; index < this._scene.spriteManagers.length; index++) {
  16669. var manager = this._scene.spriteManagers[index];
  16670. this.dispatchSprites(manager);
  16671. }
  16672. }
  16673. // Render
  16674. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  16675. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  16676. var renderingGroup = this._renderingGroups[index];
  16677. if (!renderingGroup && !observable)
  16678. continue;
  16679. this._currentIndex = index;
  16680. var renderingGroupMask = 0;
  16681. // Fire PRECLEAR stage
  16682. if (observable) {
  16683. renderingGroupMask = Math.pow(2, index);
  16684. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRECLEAR;
  16685. info.renderingGroupId = index;
  16686. observable.notifyObservers(info, renderingGroupMask);
  16687. }
  16688. // Clear depth/stencil if needed
  16689. var autoClear = this._autoClearDepthStencil[index];
  16690. if (autoClear && autoClear.autoClear) {
  16691. this._clearDepthStencilBuffer(autoClear.depth, autoClear.stencil);
  16692. }
  16693. if (observable) {
  16694. // Fire PREOPAQUE stage
  16695. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PREOPAQUE;
  16696. observable.notifyObservers(info, renderingGroupMask);
  16697. // Fire PRETRANSPARENT stage
  16698. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRETRANSPARENT;
  16699. observable.notifyObservers(info, renderingGroupMask);
  16700. }
  16701. if (renderingGroup)
  16702. renderingGroup.render(customRenderFunction, renderSprites, renderParticles, activeMeshes);
  16703. // Fire POSTTRANSPARENT stage
  16704. if (observable) {
  16705. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_POSTTRANSPARENT;
  16706. observable.notifyObservers(info, renderingGroupMask);
  16707. }
  16708. }
  16709. };
  16710. RenderingManager.prototype.reset = function () {
  16711. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  16712. var renderingGroup = this._renderingGroups[index];
  16713. if (renderingGroup) {
  16714. renderingGroup.prepare();
  16715. }
  16716. }
  16717. };
  16718. RenderingManager.prototype._prepareRenderingGroup = function (renderingGroupId) {
  16719. if (!this._renderingGroups[renderingGroupId]) {
  16720. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  16721. }
  16722. };
  16723. RenderingManager.prototype.dispatchSprites = function (spriteManager) {
  16724. var renderingGroupId = spriteManager.renderingGroupId || 0;
  16725. this._prepareRenderingGroup(renderingGroupId);
  16726. this._renderingGroups[renderingGroupId].dispatchSprites(spriteManager);
  16727. };
  16728. RenderingManager.prototype.dispatchParticles = function (particleSystem) {
  16729. var renderingGroupId = particleSystem.renderingGroupId || 0;
  16730. this._prepareRenderingGroup(renderingGroupId);
  16731. this._renderingGroups[renderingGroupId].dispatchParticles(particleSystem);
  16732. };
  16733. RenderingManager.prototype.dispatch = function (subMesh) {
  16734. var mesh = subMesh.getMesh();
  16735. var renderingGroupId = mesh.renderingGroupId || 0;
  16736. this._prepareRenderingGroup(renderingGroupId);
  16737. this._renderingGroups[renderingGroupId].dispatch(subMesh);
  16738. };
  16739. /**
  16740. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  16741. * This allowed control for front to back rendering or reversly depending of the special needs.
  16742. *
  16743. * @param renderingGroupId The rendering group id corresponding to its index
  16744. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  16745. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  16746. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  16747. */
  16748. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  16749. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  16750. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  16751. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  16752. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  16753. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  16754. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  16755. if (this._renderingGroups[renderingGroupId]) {
  16756. var group = this._renderingGroups[renderingGroupId];
  16757. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  16758. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  16759. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  16760. }
  16761. };
  16762. /**
  16763. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  16764. *
  16765. * @param renderingGroupId The rendering group id corresponding to its index
  16766. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  16767. * @param depth Automatically clears depth between groups if true and autoClear is true.
  16768. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  16769. */
  16770. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  16771. if (depth === void 0) { depth = true; }
  16772. if (stencil === void 0) { stencil = true; }
  16773. this._autoClearDepthStencil[renderingGroupId] = {
  16774. autoClear: autoClearDepthStencil,
  16775. depth: depth,
  16776. stencil: stencil
  16777. };
  16778. };
  16779. return RenderingManager;
  16780. }());
  16781. /**
  16782. * The max id used for rendering groups (not included)
  16783. */
  16784. RenderingManager.MAX_RENDERINGGROUPS = 4;
  16785. /**
  16786. * The min id used for rendering groups (included)
  16787. */
  16788. RenderingManager.MIN_RENDERINGGROUPS = 0;
  16789. BABYLON.RenderingManager = RenderingManager;
  16790. })(BABYLON || (BABYLON = {}));
  16791. //# sourceMappingURL=babylon.renderingManager.js.map
  16792. var BABYLON;
  16793. (function (BABYLON) {
  16794. var RenderingGroup = (function () {
  16795. /**
  16796. * Creates a new rendering group.
  16797. * @param index The rendering group index
  16798. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  16799. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  16800. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  16801. */
  16802. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  16803. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  16804. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  16805. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  16806. this.index = index;
  16807. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  16808. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  16809. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  16810. this._particleSystems = new BABYLON.SmartArray(256);
  16811. this._spriteManagers = new BABYLON.SmartArray(256);
  16812. this._scene = scene;
  16813. this.opaqueSortCompareFn = opaqueSortCompareFn;
  16814. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  16815. this.transparentSortCompareFn = transparentSortCompareFn;
  16816. }
  16817. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  16818. /**
  16819. * Set the opaque sort comparison function.
  16820. * If null the sub meshes will be render in the order they were created
  16821. */
  16822. set: function (value) {
  16823. this._opaqueSortCompareFn = value;
  16824. if (value) {
  16825. this._renderOpaque = this.renderOpaqueSorted;
  16826. }
  16827. else {
  16828. this._renderOpaque = RenderingGroup.renderUnsorted;
  16829. }
  16830. },
  16831. enumerable: true,
  16832. configurable: true
  16833. });
  16834. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  16835. /**
  16836. * Set the alpha test sort comparison function.
  16837. * If null the sub meshes will be render in the order they were created
  16838. */
  16839. set: function (value) {
  16840. this._alphaTestSortCompareFn = value;
  16841. if (value) {
  16842. this._renderAlphaTest = this.renderAlphaTestSorted;
  16843. }
  16844. else {
  16845. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  16846. }
  16847. },
  16848. enumerable: true,
  16849. configurable: true
  16850. });
  16851. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  16852. /**
  16853. * Set the transparent sort comparison function.
  16854. * If null the sub meshes will be render in the order they were created
  16855. */
  16856. set: function (value) {
  16857. if (value) {
  16858. this._transparentSortCompareFn = value;
  16859. }
  16860. else {
  16861. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  16862. }
  16863. this._renderTransparent = this.renderTransparentSorted;
  16864. },
  16865. enumerable: true,
  16866. configurable: true
  16867. });
  16868. /**
  16869. * Render all the sub meshes contained in the group.
  16870. * @param customRenderFunction Used to override the default render behaviour of the group.
  16871. * @returns true if rendered some submeshes.
  16872. */
  16873. RenderingGroup.prototype.render = function (customRenderFunction, renderSprites, renderParticles, activeMeshes) {
  16874. if (customRenderFunction) {
  16875. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes);
  16876. return;
  16877. }
  16878. var engine = this._scene.getEngine();
  16879. // Opaque
  16880. if (this._opaqueSubMeshes.length !== 0) {
  16881. this._renderOpaque(this._opaqueSubMeshes);
  16882. }
  16883. // Alpha test
  16884. if (this._alphaTestSubMeshes.length !== 0) {
  16885. engine.setAlphaTesting(true);
  16886. this._renderAlphaTest(this._alphaTestSubMeshes);
  16887. engine.setAlphaTesting(false);
  16888. }
  16889. // Sprites
  16890. if (renderSprites) {
  16891. this._renderSprites();
  16892. }
  16893. // Particles
  16894. if (renderParticles) {
  16895. this._renderParticles(activeMeshes);
  16896. }
  16897. if (this.onBeforeTransparentRendering) {
  16898. this.onBeforeTransparentRendering();
  16899. }
  16900. // Transparent
  16901. if (this._transparentSubMeshes.length !== 0) {
  16902. this._renderTransparent(this._transparentSubMeshes);
  16903. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  16904. }
  16905. };
  16906. /**
  16907. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  16908. * @param subMeshes The submeshes to render
  16909. */
  16910. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  16911. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera.globalPosition, false);
  16912. };
  16913. /**
  16914. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  16915. * @param subMeshes The submeshes to render
  16916. */
  16917. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  16918. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera.globalPosition, false);
  16919. };
  16920. /**
  16921. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  16922. * @param subMeshes The submeshes to render
  16923. */
  16924. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  16925. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera.globalPosition, true);
  16926. };
  16927. /**
  16928. * Renders the submeshes in a specified order.
  16929. * @param subMeshes The submeshes to sort before render
  16930. * @param sortCompareFn The comparison function use to sort
  16931. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  16932. * @param transparent Specifies to activate blending if true
  16933. */
  16934. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, cameraPosition, transparent) {
  16935. var subIndex = 0;
  16936. var subMesh;
  16937. for (; subIndex < subMeshes.length; subIndex++) {
  16938. subMesh = subMeshes.data[subIndex];
  16939. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  16940. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  16941. }
  16942. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  16943. sortedArray.sort(sortCompareFn);
  16944. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  16945. subMesh = sortedArray[subIndex];
  16946. subMesh.render(transparent);
  16947. }
  16948. };
  16949. /**
  16950. * Renders the submeshes in the order they were dispatched (no sort applied).
  16951. * @param subMeshes The submeshes to render
  16952. */
  16953. RenderingGroup.renderUnsorted = function (subMeshes) {
  16954. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  16955. var submesh = subMeshes.data[subIndex];
  16956. submesh.render(false);
  16957. }
  16958. };
  16959. /**
  16960. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  16961. * are rendered back to front if in the same alpha index.
  16962. *
  16963. * @param a The first submesh
  16964. * @param b The second submesh
  16965. * @returns The result of the comparison
  16966. */
  16967. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  16968. // Alpha index first
  16969. if (a._alphaIndex > b._alphaIndex) {
  16970. return 1;
  16971. }
  16972. if (a._alphaIndex < b._alphaIndex) {
  16973. return -1;
  16974. }
  16975. // Then distance to camera
  16976. return RenderingGroup.backToFrontSortCompare(a, b);
  16977. };
  16978. /**
  16979. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  16980. * are rendered back to front.
  16981. *
  16982. * @param a The first submesh
  16983. * @param b The second submesh
  16984. * @returns The result of the comparison
  16985. */
  16986. RenderingGroup.backToFrontSortCompare = function (a, b) {
  16987. // Then distance to camera
  16988. if (a._distanceToCamera < b._distanceToCamera) {
  16989. return 1;
  16990. }
  16991. if (a._distanceToCamera > b._distanceToCamera) {
  16992. return -1;
  16993. }
  16994. return 0;
  16995. };
  16996. /**
  16997. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  16998. * are rendered front to back (prevent overdraw).
  16999. *
  17000. * @param a The first submesh
  17001. * @param b The second submesh
  17002. * @returns The result of the comparison
  17003. */
  17004. RenderingGroup.frontToBackSortCompare = function (a, b) {
  17005. // Then distance to camera
  17006. if (a._distanceToCamera < b._distanceToCamera) {
  17007. return -1;
  17008. }
  17009. if (a._distanceToCamera > b._distanceToCamera) {
  17010. return 1;
  17011. }
  17012. return 0;
  17013. };
  17014. /**
  17015. * Resets the different lists of submeshes to prepare a new frame.
  17016. */
  17017. RenderingGroup.prototype.prepare = function () {
  17018. this._opaqueSubMeshes.reset();
  17019. this._transparentSubMeshes.reset();
  17020. this._alphaTestSubMeshes.reset();
  17021. this._particleSystems.reset();
  17022. this._spriteManagers.reset();
  17023. };
  17024. /**
  17025. * Inserts the submesh in its correct queue depending on its material.
  17026. * @param subMesh The submesh to dispatch
  17027. */
  17028. RenderingGroup.prototype.dispatch = function (subMesh) {
  17029. var material = subMesh.getMaterial();
  17030. var mesh = subMesh.getMesh();
  17031. if (material.needAlphaBlending() || mesh.visibility < 1.0 || mesh.hasVertexAlpha) {
  17032. this._transparentSubMeshes.push(subMesh);
  17033. }
  17034. else if (material.needAlphaTesting()) {
  17035. this._alphaTestSubMeshes.push(subMesh);
  17036. }
  17037. else {
  17038. this._opaqueSubMeshes.push(subMesh); // Opaque
  17039. }
  17040. };
  17041. RenderingGroup.prototype.dispatchSprites = function (spriteManager) {
  17042. this._spriteManagers.push(spriteManager);
  17043. };
  17044. RenderingGroup.prototype.dispatchParticles = function (particleSystem) {
  17045. this._particleSystems.push(particleSystem);
  17046. };
  17047. RenderingGroup.prototype._renderParticles = function (activeMeshes) {
  17048. if (this._particleSystems.length === 0) {
  17049. return;
  17050. }
  17051. // Particles
  17052. var activeCamera = this._scene.activeCamera;
  17053. this._scene._particlesDuration.beginMonitoring();
  17054. for (var particleIndex = 0; particleIndex < this._scene._activeParticleSystems.length; particleIndex++) {
  17055. var particleSystem = this._scene._activeParticleSystems.data[particleIndex];
  17056. if ((activeCamera.layerMask & particleSystem.layerMask) === 0) {
  17057. continue;
  17058. }
  17059. if (!particleSystem.emitter.position || !activeMeshes || activeMeshes.indexOf(particleSystem.emitter) !== -1) {
  17060. this._scene._activeParticles.addCount(particleSystem.render(), false);
  17061. }
  17062. }
  17063. this._scene._particlesDuration.endMonitoring(false);
  17064. };
  17065. RenderingGroup.prototype._renderSprites = function () {
  17066. if (!this._scene.spritesEnabled || this._spriteManagers.length === 0) {
  17067. return;
  17068. }
  17069. // Sprites
  17070. var activeCamera = this._scene.activeCamera;
  17071. this._scene._spritesDuration.beginMonitoring();
  17072. for (var id = 0; id < this._spriteManagers.length; id++) {
  17073. var spriteManager = this._scene.spriteManagers[id];
  17074. if (((activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  17075. spriteManager.render();
  17076. }
  17077. }
  17078. this._scene._spritesDuration.endMonitoring(false);
  17079. };
  17080. return RenderingGroup;
  17081. }());
  17082. BABYLON.RenderingGroup = RenderingGroup;
  17083. })(BABYLON || (BABYLON = {}));
  17084. //# sourceMappingURL=babylon.renderingGroup.js.map
  17085. var BABYLON;
  17086. (function (BABYLON) {
  17087. var PointerEventTypes = (function () {
  17088. function PointerEventTypes() {
  17089. }
  17090. Object.defineProperty(PointerEventTypes, "POINTERDOWN", {
  17091. get: function () {
  17092. return PointerEventTypes._POINTERDOWN;
  17093. },
  17094. enumerable: true,
  17095. configurable: true
  17096. });
  17097. Object.defineProperty(PointerEventTypes, "POINTERUP", {
  17098. get: function () {
  17099. return PointerEventTypes._POINTERUP;
  17100. },
  17101. enumerable: true,
  17102. configurable: true
  17103. });
  17104. Object.defineProperty(PointerEventTypes, "POINTERMOVE", {
  17105. get: function () {
  17106. return PointerEventTypes._POINTERMOVE;
  17107. },
  17108. enumerable: true,
  17109. configurable: true
  17110. });
  17111. Object.defineProperty(PointerEventTypes, "POINTERWHEEL", {
  17112. get: function () {
  17113. return PointerEventTypes._POINTERWHEEL;
  17114. },
  17115. enumerable: true,
  17116. configurable: true
  17117. });
  17118. Object.defineProperty(PointerEventTypes, "POINTERPICK", {
  17119. get: function () {
  17120. return PointerEventTypes._POINTERPICK;
  17121. },
  17122. enumerable: true,
  17123. configurable: true
  17124. });
  17125. return PointerEventTypes;
  17126. }());
  17127. PointerEventTypes._POINTERDOWN = 0x01;
  17128. PointerEventTypes._POINTERUP = 0x02;
  17129. PointerEventTypes._POINTERMOVE = 0x04;
  17130. PointerEventTypes._POINTERWHEEL = 0x08;
  17131. PointerEventTypes._POINTERPICK = 0x10;
  17132. BABYLON.PointerEventTypes = PointerEventTypes;
  17133. var PointerInfoBase = (function () {
  17134. function PointerInfoBase(type, event) {
  17135. this.type = type;
  17136. this.event = event;
  17137. }
  17138. return PointerInfoBase;
  17139. }());
  17140. BABYLON.PointerInfoBase = PointerInfoBase;
  17141. /**
  17142. * This class is used to store pointer related info for the onPrePointerObservable event.
  17143. * Set the skipOnPointerObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onPointerObservable
  17144. */
  17145. var PointerInfoPre = (function (_super) {
  17146. __extends(PointerInfoPre, _super);
  17147. function PointerInfoPre(type, event, localX, localY) {
  17148. var _this = _super.call(this, type, event) || this;
  17149. _this.skipOnPointerObservable = false;
  17150. _this.localPosition = new BABYLON.Vector2(localX, localY);
  17151. return _this;
  17152. }
  17153. return PointerInfoPre;
  17154. }(PointerInfoBase));
  17155. BABYLON.PointerInfoPre = PointerInfoPre;
  17156. /**
  17157. * This type contains all the data related to a pointer event in Babylon.js.
  17158. * 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.
  17159. */
  17160. var PointerInfo = (function (_super) {
  17161. __extends(PointerInfo, _super);
  17162. function PointerInfo(type, event, pickInfo) {
  17163. var _this = _super.call(this, type, event) || this;
  17164. _this.pickInfo = pickInfo;
  17165. return _this;
  17166. }
  17167. return PointerInfo;
  17168. }(PointerInfoBase));
  17169. BABYLON.PointerInfo = PointerInfo;
  17170. /**
  17171. * This class is used by the onRenderingGroupObservable
  17172. */
  17173. var RenderingGroupInfo = (function () {
  17174. function RenderingGroupInfo() {
  17175. }
  17176. return RenderingGroupInfo;
  17177. }());
  17178. /**
  17179. * Stage corresponding to the very first hook in the renderingGroup phase: before the render buffer may be cleared
  17180. * This stage will be fired no matter what
  17181. */
  17182. RenderingGroupInfo.STAGE_PRECLEAR = 1;
  17183. /**
  17184. * Called before opaque object are rendered.
  17185. * This stage will be fired only if there's 3D Opaque content to render
  17186. */
  17187. RenderingGroupInfo.STAGE_PREOPAQUE = 2;
  17188. /**
  17189. * Called after the opaque objects are rendered and before the transparent ones
  17190. * This stage will be fired only if there's 3D transparent content to render
  17191. */
  17192. RenderingGroupInfo.STAGE_PRETRANSPARENT = 3;
  17193. /**
  17194. * Called after the transparent object are rendered, last hook of the renderingGroup phase
  17195. * This stage will be fired no matter what
  17196. */
  17197. RenderingGroupInfo.STAGE_POSTTRANSPARENT = 4;
  17198. BABYLON.RenderingGroupInfo = RenderingGroupInfo;
  17199. /**
  17200. * Represents a scene to be rendered by the engine.
  17201. * @see http://doc.babylonjs.com/page.php?p=21911
  17202. */
  17203. var Scene = (function () {
  17204. /**
  17205. * @constructor
  17206. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  17207. */
  17208. function Scene(engine) {
  17209. // Members
  17210. this.autoClear = true;
  17211. this.clearColor = new BABYLON.Color4(0.2, 0.2, 0.3, 1.0);
  17212. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  17213. this.forceWireframe = false;
  17214. this.forcePointsCloud = false;
  17215. this.forceShowBoundingBoxes = false;
  17216. this.animationsEnabled = true;
  17217. this.constantlyUpdateMeshUnderPointer = false;
  17218. this.useRightHandedSystem = false;
  17219. this.hoverCursor = "pointer";
  17220. // Metadata
  17221. this.metadata = null;
  17222. // Events
  17223. /**
  17224. * An event triggered when the scene is disposed.
  17225. * @type {BABYLON.Observable}
  17226. */
  17227. this.onDisposeObservable = new BABYLON.Observable();
  17228. /**
  17229. * An event triggered before rendering the scene
  17230. * @type {BABYLON.Observable}
  17231. */
  17232. this.onBeforeRenderObservable = new BABYLON.Observable();
  17233. /**
  17234. * An event triggered after rendering the scene
  17235. * @type {BABYLON.Observable}
  17236. */
  17237. this.onAfterRenderObservable = new BABYLON.Observable();
  17238. /**
  17239. * An event triggered when the scene is ready
  17240. * @type {BABYLON.Observable}
  17241. */
  17242. this.onReadyObservable = new BABYLON.Observable();
  17243. /**
  17244. * An event triggered before rendering a camera
  17245. * @type {BABYLON.Observable}
  17246. */
  17247. this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  17248. /**
  17249. * An event triggered after rendering a camera
  17250. * @type {BABYLON.Observable}
  17251. */
  17252. this.onAfterCameraRenderObservable = new BABYLON.Observable();
  17253. /**
  17254. * An event triggered when a camera is created
  17255. * @type {BABYLON.Observable}
  17256. */
  17257. this.onNewCameraAddedObservable = new BABYLON.Observable();
  17258. /**
  17259. * An event triggered when a camera is removed
  17260. * @type {BABYLON.Observable}
  17261. */
  17262. this.onCameraRemovedObservable = new BABYLON.Observable();
  17263. /**
  17264. * An event triggered when a light is created
  17265. * @type {BABYLON.Observable}
  17266. */
  17267. this.onNewLightAddedObservable = new BABYLON.Observable();
  17268. /**
  17269. * An event triggered when a light is removed
  17270. * @type {BABYLON.Observable}
  17271. */
  17272. this.onLightRemovedObservable = new BABYLON.Observable();
  17273. /**
  17274. * An event triggered when a geometry is created
  17275. * @type {BABYLON.Observable}
  17276. */
  17277. this.onNewGeometryAddedObservable = new BABYLON.Observable();
  17278. /**
  17279. * An event triggered when a geometry is removed
  17280. * @type {BABYLON.Observable}
  17281. */
  17282. this.onGeometryRemovedObservable = new BABYLON.Observable();
  17283. /**
  17284. * An event triggered when a mesh is created
  17285. * @type {BABYLON.Observable}
  17286. */
  17287. this.onNewMeshAddedObservable = new BABYLON.Observable();
  17288. /**
  17289. * An event triggered when a mesh is removed
  17290. * @type {BABYLON.Observable}
  17291. */
  17292. this.onMeshRemovedObservable = new BABYLON.Observable();
  17293. /**
  17294. * This Observable will be triggered for each stage of each renderingGroup of each rendered camera.
  17295. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  17296. * 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)
  17297. */
  17298. this.onRenderingGroupObservable = new BABYLON.Observable();
  17299. // Animations
  17300. this.animations = [];
  17301. /**
  17302. * 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).
  17303. * You have the possibility to skip the 3D Engine process and the call to onPointerObservable by setting PointerInfoBase.skipOnPointerObservable to true
  17304. */
  17305. this.onPrePointerObservable = new BABYLON.Observable();
  17306. /**
  17307. * Observable event triggered each time an input event is received from the rendering canvas
  17308. */
  17309. this.onPointerObservable = new BABYLON.Observable();
  17310. 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
  17311. this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  17312. this._startingPointerTime = 0;
  17313. // Fog
  17314. /**
  17315. * is fog enabled on this scene.
  17316. * @type {boolean}
  17317. */
  17318. this.fogEnabled = true;
  17319. this.fogMode = Scene.FOGMODE_NONE;
  17320. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  17321. this.fogDensity = 0.1;
  17322. this.fogStart = 0;
  17323. this.fogEnd = 1000.0;
  17324. // Lights
  17325. /**
  17326. * is shadow enabled on this scene.
  17327. * @type {boolean}
  17328. */
  17329. this.shadowsEnabled = true;
  17330. /**
  17331. * is light enabled on this scene.
  17332. * @type {boolean}
  17333. */
  17334. this.lightsEnabled = true;
  17335. /**
  17336. * All of the lights added to this scene.
  17337. * @see BABYLON.Light
  17338. * @type {BABYLON.Light[]}
  17339. */
  17340. this.lights = new Array();
  17341. // Cameras
  17342. /**
  17343. * All of the cameras added to this scene.
  17344. * @see BABYLON.Camera
  17345. * @type {BABYLON.Camera[]}
  17346. */
  17347. this.cameras = new Array();
  17348. this.activeCameras = new Array();
  17349. // Meshes
  17350. /**
  17351. * All of the (abstract) meshes added to this scene.
  17352. * @see BABYLON.AbstractMesh
  17353. * @type {BABYLON.AbstractMesh[]}
  17354. */
  17355. this.meshes = new Array();
  17356. // Geometries
  17357. this._geometries = new Array();
  17358. this.materials = new Array();
  17359. this.multiMaterials = new Array();
  17360. // Textures
  17361. this.texturesEnabled = true;
  17362. this.textures = new Array();
  17363. // Particles
  17364. this.particlesEnabled = true;
  17365. this.particleSystems = new Array();
  17366. // Sprites
  17367. this.spritesEnabled = true;
  17368. this.spriteManagers = new Array();
  17369. // Layers
  17370. this.layers = new Array();
  17371. this.highlightLayers = new Array();
  17372. // Skeletons
  17373. this.skeletonsEnabled = true;
  17374. this.skeletons = new Array();
  17375. // Lens flares
  17376. this.lensFlaresEnabled = true;
  17377. this.lensFlareSystems = new Array();
  17378. // Collisions
  17379. this.collisionsEnabled = true;
  17380. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  17381. // Postprocesses
  17382. this.postProcessesEnabled = true;
  17383. // Customs render targets
  17384. this.renderTargetsEnabled = true;
  17385. this.dumpNextRenderTargets = false;
  17386. this.customRenderTargets = new Array();
  17387. // Imported meshes
  17388. this.importedMeshesFiles = new Array();
  17389. // Probes
  17390. this.probesEnabled = true;
  17391. this.reflectionProbes = new Array();
  17392. this._actionManagers = new Array();
  17393. this._meshesForIntersections = new BABYLON.SmartArray(256);
  17394. // Procedural textures
  17395. this.proceduralTexturesEnabled = true;
  17396. this._proceduralTextures = new Array();
  17397. this.soundTracks = new Array();
  17398. this._audioEnabled = true;
  17399. this._headphone = false;
  17400. // Performance counters
  17401. this._totalMeshesCounter = new BABYLON.PerfCounter();
  17402. this._totalLightsCounter = new BABYLON.PerfCounter();
  17403. this._totalMaterialsCounter = new BABYLON.PerfCounter();
  17404. this._totalTexturesCounter = new BABYLON.PerfCounter();
  17405. this._totalVertices = new BABYLON.PerfCounter();
  17406. this._activeIndices = new BABYLON.PerfCounter();
  17407. this._activeParticles = new BABYLON.PerfCounter();
  17408. this._lastFrameDuration = new BABYLON.PerfCounter();
  17409. this._evaluateActiveMeshesDuration = new BABYLON.PerfCounter();
  17410. this._renderTargetsDuration = new BABYLON.PerfCounter();
  17411. this._particlesDuration = new BABYLON.PerfCounter();
  17412. this._renderDuration = new BABYLON.PerfCounter();
  17413. this._spritesDuration = new BABYLON.PerfCounter();
  17414. this._activeBones = new BABYLON.PerfCounter();
  17415. this._animationTime = 0;
  17416. this.animationTimeScale = 1;
  17417. this._renderId = 0;
  17418. this._executeWhenReadyTimeoutId = -1;
  17419. this._intermediateRendering = false;
  17420. this._toBeDisposed = new BABYLON.SmartArray(256);
  17421. this._pendingData = []; //ANY
  17422. this._activeMeshes = new BABYLON.SmartArray(256);
  17423. this._processedMaterials = new BABYLON.SmartArray(256);
  17424. this._renderTargets = new BABYLON.SmartArray(256);
  17425. this._activeParticleSystems = new BABYLON.SmartArray(256);
  17426. this._activeSkeletons = new BABYLON.SmartArray(32);
  17427. this._softwareSkinnedMeshes = new BABYLON.SmartArray(32);
  17428. this._activeAnimatables = new Array();
  17429. this._transformMatrix = BABYLON.Matrix.Zero();
  17430. this._edgesRenderers = new BABYLON.SmartArray(16);
  17431. this._uniqueIdCounter = 0;
  17432. this._engine = engine;
  17433. engine.scenes.push(this);
  17434. this._externalData = new BABYLON.StringDictionary();
  17435. this._uid = null;
  17436. this._renderingManager = new BABYLON.RenderingManager(this);
  17437. this.postProcessManager = new BABYLON.PostProcessManager(this);
  17438. this.postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  17439. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  17440. if (BABYLON.OutlineRenderer) {
  17441. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  17442. }
  17443. this.attachControl();
  17444. if (BABYLON.SoundTrack) {
  17445. this.mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  17446. }
  17447. //simplification queue
  17448. if (BABYLON.SimplificationQueue) {
  17449. this.simplificationQueue = new BABYLON.SimplificationQueue();
  17450. }
  17451. //collision coordinator initialization. For now legacy per default.
  17452. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  17453. }
  17454. Object.defineProperty(Scene, "FOGMODE_NONE", {
  17455. get: function () {
  17456. return Scene._FOGMODE_NONE;
  17457. },
  17458. enumerable: true,
  17459. configurable: true
  17460. });
  17461. Object.defineProperty(Scene, "FOGMODE_EXP", {
  17462. get: function () {
  17463. return Scene._FOGMODE_EXP;
  17464. },
  17465. enumerable: true,
  17466. configurable: true
  17467. });
  17468. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  17469. get: function () {
  17470. return Scene._FOGMODE_EXP2;
  17471. },
  17472. enumerable: true,
  17473. configurable: true
  17474. });
  17475. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  17476. get: function () {
  17477. return Scene._FOGMODE_LINEAR;
  17478. },
  17479. enumerable: true,
  17480. configurable: true
  17481. });
  17482. Object.defineProperty(Scene.prototype, "onDispose", {
  17483. set: function (callback) {
  17484. if (this._onDisposeObserver) {
  17485. this.onDisposeObservable.remove(this._onDisposeObserver);
  17486. }
  17487. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  17488. },
  17489. enumerable: true,
  17490. configurable: true
  17491. });
  17492. Object.defineProperty(Scene.prototype, "beforeRender", {
  17493. set: function (callback) {
  17494. if (this._onBeforeRenderObserver) {
  17495. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  17496. }
  17497. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  17498. },
  17499. enumerable: true,
  17500. configurable: true
  17501. });
  17502. Object.defineProperty(Scene.prototype, "afterRender", {
  17503. set: function (callback) {
  17504. if (this._onAfterRenderObserver) {
  17505. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  17506. }
  17507. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  17508. },
  17509. enumerable: true,
  17510. configurable: true
  17511. });
  17512. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  17513. set: function (callback) {
  17514. if (this._onBeforeCameraRenderObserver) {
  17515. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  17516. }
  17517. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  17518. },
  17519. enumerable: true,
  17520. configurable: true
  17521. });
  17522. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  17523. set: function (callback) {
  17524. if (this._onAfterCameraRenderObserver) {
  17525. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  17526. }
  17527. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  17528. },
  17529. enumerable: true,
  17530. configurable: true
  17531. });
  17532. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  17533. get: function () {
  17534. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  17535. },
  17536. enumerable: true,
  17537. configurable: true
  17538. });
  17539. Object.defineProperty(Scene.prototype, "defaultMaterial", {
  17540. get: function () {
  17541. if (!this._defaultMaterial) {
  17542. this._defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  17543. }
  17544. return this._defaultMaterial;
  17545. },
  17546. enumerable: true,
  17547. configurable: true
  17548. });
  17549. Object.defineProperty(Scene.prototype, "frustumPlanes", {
  17550. get: function () {
  17551. return this._frustumPlanes;
  17552. },
  17553. enumerable: true,
  17554. configurable: true
  17555. });
  17556. Object.defineProperty(Scene.prototype, "debugLayer", {
  17557. // Properties
  17558. get: function () {
  17559. if (!this._debugLayer) {
  17560. this._debugLayer = new BABYLON.DebugLayer(this);
  17561. }
  17562. return this._debugLayer;
  17563. },
  17564. enumerable: true,
  17565. configurable: true
  17566. });
  17567. Object.defineProperty(Scene.prototype, "workerCollisions", {
  17568. get: function () {
  17569. return this._workerCollisions;
  17570. },
  17571. set: function (enabled) {
  17572. enabled = (enabled && !!Worker);
  17573. this._workerCollisions = enabled;
  17574. if (this.collisionCoordinator) {
  17575. this.collisionCoordinator.destroy();
  17576. }
  17577. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  17578. this.collisionCoordinator.init(this);
  17579. },
  17580. enumerable: true,
  17581. configurable: true
  17582. });
  17583. Object.defineProperty(Scene.prototype, "SelectionOctree", {
  17584. get: function () {
  17585. return this._selectionOctree;
  17586. },
  17587. enumerable: true,
  17588. configurable: true
  17589. });
  17590. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  17591. /**
  17592. * The mesh that is currently under the pointer.
  17593. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  17594. */
  17595. get: function () {
  17596. return this._pointerOverMesh;
  17597. },
  17598. enumerable: true,
  17599. configurable: true
  17600. });
  17601. Object.defineProperty(Scene.prototype, "pointerX", {
  17602. /**
  17603. * Current on-screen X position of the pointer
  17604. * @return {number} X position of the pointer
  17605. */
  17606. get: function () {
  17607. return this._pointerX;
  17608. },
  17609. enumerable: true,
  17610. configurable: true
  17611. });
  17612. Object.defineProperty(Scene.prototype, "pointerY", {
  17613. /**
  17614. * Current on-screen Y position of the pointer
  17615. * @return {number} Y position of the pointer
  17616. */
  17617. get: function () {
  17618. return this._pointerY;
  17619. },
  17620. enumerable: true,
  17621. configurable: true
  17622. });
  17623. Scene.prototype.getCachedMaterial = function () {
  17624. return this._cachedMaterial;
  17625. };
  17626. Scene.prototype.getBoundingBoxRenderer = function () {
  17627. return this._boundingBoxRenderer;
  17628. };
  17629. Scene.prototype.getOutlineRenderer = function () {
  17630. return this._outlineRenderer;
  17631. };
  17632. Scene.prototype.getEngine = function () {
  17633. return this._engine;
  17634. };
  17635. Scene.prototype.getTotalVertices = function () {
  17636. return this._totalVertices.current;
  17637. };
  17638. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  17639. get: function () {
  17640. return this._totalVertices;
  17641. },
  17642. enumerable: true,
  17643. configurable: true
  17644. });
  17645. Scene.prototype.getActiveIndices = function () {
  17646. return this._activeIndices.current;
  17647. };
  17648. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  17649. get: function () {
  17650. return this._activeIndices;
  17651. },
  17652. enumerable: true,
  17653. configurable: true
  17654. });
  17655. Scene.prototype.getActiveParticles = function () {
  17656. return this._activeParticles.current;
  17657. };
  17658. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  17659. get: function () {
  17660. return this._activeParticles;
  17661. },
  17662. enumerable: true,
  17663. configurable: true
  17664. });
  17665. Scene.prototype.getActiveBones = function () {
  17666. return this._activeBones.current;
  17667. };
  17668. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  17669. get: function () {
  17670. return this._activeBones;
  17671. },
  17672. enumerable: true,
  17673. configurable: true
  17674. });
  17675. // Stats
  17676. Scene.prototype.getLastFrameDuration = function () {
  17677. return this._lastFrameDuration.current;
  17678. };
  17679. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  17680. get: function () {
  17681. return this._lastFrameDuration;
  17682. },
  17683. enumerable: true,
  17684. configurable: true
  17685. });
  17686. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  17687. return this._evaluateActiveMeshesDuration.current;
  17688. };
  17689. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  17690. get: function () {
  17691. return this._evaluateActiveMeshesDuration;
  17692. },
  17693. enumerable: true,
  17694. configurable: true
  17695. });
  17696. Scene.prototype.getActiveMeshes = function () {
  17697. return this._activeMeshes;
  17698. };
  17699. Scene.prototype.getRenderTargetsDuration = function () {
  17700. return this._renderTargetsDuration.current;
  17701. };
  17702. Scene.prototype.getRenderDuration = function () {
  17703. return this._renderDuration.current;
  17704. };
  17705. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  17706. get: function () {
  17707. return this._renderDuration;
  17708. },
  17709. enumerable: true,
  17710. configurable: true
  17711. });
  17712. Scene.prototype.getParticlesDuration = function () {
  17713. return this._particlesDuration.current;
  17714. };
  17715. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  17716. get: function () {
  17717. return this._particlesDuration;
  17718. },
  17719. enumerable: true,
  17720. configurable: true
  17721. });
  17722. Scene.prototype.getSpritesDuration = function () {
  17723. return this._spritesDuration.current;
  17724. };
  17725. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  17726. get: function () {
  17727. return this._spritesDuration;
  17728. },
  17729. enumerable: true,
  17730. configurable: true
  17731. });
  17732. Scene.prototype.getAnimationRatio = function () {
  17733. return this._animationRatio;
  17734. };
  17735. Scene.prototype.getRenderId = function () {
  17736. return this._renderId;
  17737. };
  17738. Scene.prototype.incrementRenderId = function () {
  17739. this._renderId++;
  17740. };
  17741. Scene.prototype._updatePointerPosition = function (evt) {
  17742. var canvasRect = this._engine.getRenderingCanvasClientRect();
  17743. this._pointerX = evt.clientX - canvasRect.left;
  17744. this._pointerY = evt.clientY - canvasRect.top;
  17745. this._unTranslatedPointerX = this._pointerX;
  17746. this._unTranslatedPointerY = this._pointerY;
  17747. if (this.cameraToUseForPointers) {
  17748. this._pointerX = this._pointerX - this.cameraToUseForPointers.viewport.x * this._engine.getRenderWidth();
  17749. this._pointerY = this._pointerY - this.cameraToUseForPointers.viewport.y * this._engine.getRenderHeight();
  17750. }
  17751. };
  17752. // Pointers handling
  17753. /**
  17754. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  17755. * @param attachUp defines if you want to attach events to pointerup
  17756. * @param attachDown defines if you want to attach events to pointerdown
  17757. * @param attachMove defines if you want to attach events to pointermove
  17758. */
  17759. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  17760. var _this = this;
  17761. if (attachUp === void 0) { attachUp = true; }
  17762. if (attachDown === void 0) { attachDown = true; }
  17763. if (attachMove === void 0) { attachMove = true; }
  17764. var spritePredicate = function (sprite) {
  17765. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  17766. };
  17767. this._onPointerMove = function (evt) {
  17768. _this._updatePointerPosition(evt);
  17769. // PreObservable support
  17770. if (_this.onPrePointerObservable.hasObservers()) {
  17771. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? PointerEventTypes.POINTERWHEEL : PointerEventTypes.POINTERMOVE;
  17772. var pi = new PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  17773. _this.onPrePointerObservable.notifyObservers(pi, type);
  17774. if (pi.skipOnPointerObservable) {
  17775. return;
  17776. }
  17777. }
  17778. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  17779. return;
  17780. }
  17781. var canvas = _this._engine.getRenderingCanvas();
  17782. if (!_this.pointerMovePredicate) {
  17783. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && (_this.constantlyUpdateMeshUnderPointer || mesh.actionManager !== null && mesh.actionManager !== undefined); };
  17784. }
  17785. // Meshes
  17786. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  17787. if (pickResult.hit && pickResult.pickedMesh) {
  17788. _this.setPointerOverSprite(null);
  17789. _this.setPointerOverMesh(pickResult.pickedMesh);
  17790. if (_this._pointerOverMesh.actionManager && _this._pointerOverMesh.actionManager.hasPointerTriggers) {
  17791. if (_this._pointerOverMesh.actionManager.hoverCursor) {
  17792. canvas.style.cursor = _this._pointerOverMesh.actionManager.hoverCursor;
  17793. }
  17794. else {
  17795. canvas.style.cursor = _this.hoverCursor;
  17796. }
  17797. }
  17798. else {
  17799. canvas.style.cursor = "";
  17800. }
  17801. }
  17802. else {
  17803. _this.setPointerOverMesh(null);
  17804. // Sprites
  17805. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, spritePredicate, false, _this.cameraToUseForPointers);
  17806. if (pickResult.hit && pickResult.pickedSprite) {
  17807. _this.setPointerOverSprite(pickResult.pickedSprite);
  17808. if (_this._pointerOverSprite.actionManager && _this._pointerOverSprite.actionManager.hoverCursor) {
  17809. canvas.style.cursor = _this._pointerOverSprite.actionManager.hoverCursor;
  17810. }
  17811. else {
  17812. canvas.style.cursor = _this.hoverCursor;
  17813. }
  17814. }
  17815. else {
  17816. _this.setPointerOverSprite(null);
  17817. // Restore pointer
  17818. canvas.style.cursor = "";
  17819. }
  17820. }
  17821. if (_this.onPointerMove) {
  17822. _this.onPointerMove(evt, pickResult);
  17823. }
  17824. if (_this.onPointerObservable.hasObservers()) {
  17825. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? PointerEventTypes.POINTERWHEEL : PointerEventTypes.POINTERMOVE;
  17826. var pi = new PointerInfo(type, evt, pickResult);
  17827. _this.onPointerObservable.notifyObservers(pi, type);
  17828. }
  17829. };
  17830. this._onPointerDown = function (evt) {
  17831. _this._updatePointerPosition(evt);
  17832. // PreObservable support
  17833. if (_this.onPrePointerObservable.hasObservers()) {
  17834. var type = PointerEventTypes.POINTERDOWN;
  17835. var pi = new PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  17836. _this.onPrePointerObservable.notifyObservers(pi, type);
  17837. if (pi.skipOnPointerObservable) {
  17838. return;
  17839. }
  17840. }
  17841. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  17842. return;
  17843. }
  17844. _this._startingPointerPosition.x = _this._pointerX;
  17845. _this._startingPointerPosition.y = _this._pointerY;
  17846. _this._startingPointerTime = new Date().getTime();
  17847. if (!_this.pointerDownPredicate) {
  17848. _this.pointerDownPredicate = function (mesh) {
  17849. return mesh.isPickable && mesh.isVisible && mesh.isReady();
  17850. };
  17851. }
  17852. // Meshes
  17853. _this._pickedDownMesh = null;
  17854. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  17855. if (pickResult.hit && pickResult.pickedMesh) {
  17856. if (pickResult.pickedMesh.actionManager) {
  17857. _this._pickedDownMesh = pickResult.pickedMesh;
  17858. if (pickResult.pickedMesh.actionManager.hasPickTriggers) {
  17859. switch (evt.button) {
  17860. case 0:
  17861. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  17862. break;
  17863. case 1:
  17864. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  17865. break;
  17866. case 2:
  17867. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  17868. break;
  17869. }
  17870. if (pickResult.pickedMesh.actionManager) {
  17871. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  17872. }
  17873. }
  17874. if (pickResult.pickedMesh.actionManager && pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  17875. var that = _this;
  17876. window.setTimeout(function () {
  17877. var pickResult = that.pick(that._unTranslatedPointerX, that._unTranslatedPointerY, function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.actionManager && mesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger); }, false, that.cameraToUseForPointers);
  17878. if (pickResult.hit && pickResult.pickedMesh) {
  17879. if (pickResult.pickedMesh.actionManager) {
  17880. if (that._startingPointerTime !== 0 && ((new Date().getTime() - that._startingPointerTime) > BABYLON.ActionManager.LongPressDelay) && (Math.abs(that._startingPointerPosition.x - that._pointerX) < BABYLON.ActionManager.DragMovementThreshold && Math.abs(that._startingPointerPosition.y - that._pointerY) < BABYLON.ActionManager.DragMovementThreshold)) {
  17881. that._startingPointerTime = 0;
  17882. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  17883. }
  17884. }
  17885. }
  17886. }, BABYLON.ActionManager.LongPressDelay);
  17887. }
  17888. }
  17889. }
  17890. if (_this.onPointerDown) {
  17891. _this.onPointerDown(evt, pickResult);
  17892. }
  17893. if (_this.onPointerObservable.hasObservers()) {
  17894. var type = PointerEventTypes.POINTERDOWN;
  17895. var pi = new PointerInfo(type, evt, pickResult);
  17896. _this.onPointerObservable.notifyObservers(pi, type);
  17897. }
  17898. // Sprites
  17899. _this._pickedDownSprite = null;
  17900. if (_this.spriteManagers.length > 0) {
  17901. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, spritePredicate, false, _this.cameraToUseForPointers);
  17902. if (pickResult.hit && pickResult.pickedSprite) {
  17903. if (pickResult.pickedSprite.actionManager) {
  17904. _this._pickedDownSprite = pickResult.pickedSprite;
  17905. switch (evt.button) {
  17906. case 0:
  17907. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  17908. break;
  17909. case 1:
  17910. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  17911. break;
  17912. case 2:
  17913. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  17914. break;
  17915. }
  17916. if (pickResult.pickedSprite.actionManager) {
  17917. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  17918. }
  17919. }
  17920. }
  17921. }
  17922. };
  17923. this._onPointerUp = function (evt) {
  17924. _this._updatePointerPosition(evt);
  17925. // PreObservable support
  17926. if (_this.onPrePointerObservable.hasObservers()) {
  17927. var type = PointerEventTypes.POINTERUP;
  17928. var pi = new PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  17929. _this.onPrePointerObservable.notifyObservers(pi, type);
  17930. if (pi.skipOnPointerObservable) {
  17931. return;
  17932. }
  17933. }
  17934. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  17935. return;
  17936. }
  17937. if (!_this.pointerUpPredicate) {
  17938. _this.pointerUpPredicate = function (mesh) {
  17939. return mesh.isPickable && mesh.isVisible && mesh.isReady();
  17940. };
  17941. }
  17942. // Meshes
  17943. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerUpPredicate, false, _this.cameraToUseForPointers);
  17944. if (pickResult.hit && pickResult.pickedMesh) {
  17945. if (_this._pickedDownMesh != null && pickResult.pickedMesh == _this._pickedDownMesh) {
  17946. if (_this.onPointerPick) {
  17947. _this.onPointerPick(evt, pickResult);
  17948. }
  17949. if (_this.onPointerObservable.hasObservers()) {
  17950. var type = PointerEventTypes.POINTERPICK;
  17951. var pi = new PointerInfo(type, evt, pickResult);
  17952. _this.onPointerObservable.notifyObservers(pi, type);
  17953. }
  17954. }
  17955. if (pickResult.pickedMesh.actionManager) {
  17956. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  17957. if (pickResult.pickedMesh.actionManager) {
  17958. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < BABYLON.ActionManager.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < BABYLON.ActionManager.DragMovementThreshold) {
  17959. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  17960. }
  17961. }
  17962. }
  17963. }
  17964. if (_this._pickedDownMesh && _this._pickedDownMesh.actionManager && _this._pickedDownMesh !== pickResult.pickedMesh) {
  17965. _this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(_this._pickedDownMesh, evt));
  17966. }
  17967. if (_this.onPointerUp) {
  17968. _this.onPointerUp(evt, pickResult);
  17969. }
  17970. if (_this.onPointerObservable.hasObservers()) {
  17971. var type = PointerEventTypes.POINTERUP;
  17972. var pi = new PointerInfo(type, evt, pickResult);
  17973. _this.onPointerObservable.notifyObservers(pi, type);
  17974. }
  17975. _this._startingPointerTime = 0;
  17976. // Sprites
  17977. if (_this.spriteManagers.length > 0) {
  17978. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, spritePredicate, false, _this.cameraToUseForPointers);
  17979. if (pickResult.hit && pickResult.pickedSprite) {
  17980. if (pickResult.pickedSprite.actionManager) {
  17981. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  17982. if (pickResult.pickedSprite.actionManager) {
  17983. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < BABYLON.ActionManager.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < BABYLON.ActionManager.DragMovementThreshold) {
  17984. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  17985. }
  17986. }
  17987. }
  17988. }
  17989. if (_this._pickedDownSprite && _this._pickedDownSprite.actionManager && _this._pickedDownSprite !== pickResult.pickedSprite) {
  17990. _this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(_this._pickedDownSprite, _this, evt));
  17991. }
  17992. }
  17993. };
  17994. this._onKeyDown = function (evt) {
  17995. if (_this.actionManager) {
  17996. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  17997. }
  17998. };
  17999. this._onKeyUp = function (evt) {
  18000. if (_this.actionManager) {
  18001. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  18002. }
  18003. };
  18004. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  18005. var canvas = this._engine.getRenderingCanvas();
  18006. if (attachMove) {
  18007. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  18008. // Wheel
  18009. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  18010. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  18011. }
  18012. if (attachDown) {
  18013. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  18014. }
  18015. if (attachUp) {
  18016. canvas.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  18017. }
  18018. canvas.tabIndex = 1;
  18019. canvas.addEventListener("keydown", this._onKeyDown, false);
  18020. canvas.addEventListener("keyup", this._onKeyUp, false);
  18021. };
  18022. Scene.prototype.detachControl = function () {
  18023. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  18024. var canvas = this._engine.getRenderingCanvas();
  18025. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  18026. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  18027. canvas.removeEventListener(eventPrefix + "up", this._onPointerUp);
  18028. // Wheel
  18029. canvas.removeEventListener('mousewheel', this._onPointerMove);
  18030. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  18031. canvas.removeEventListener("keydown", this._onKeyDown);
  18032. canvas.removeEventListener("keyup", this._onKeyUp);
  18033. };
  18034. // Ready
  18035. Scene.prototype.isReady = function () {
  18036. if (this._pendingData.length > 0) {
  18037. return false;
  18038. }
  18039. var index;
  18040. for (index = 0; index < this._geometries.length; index++) {
  18041. var geometry = this._geometries[index];
  18042. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  18043. return false;
  18044. }
  18045. }
  18046. for (index = 0; index < this.meshes.length; index++) {
  18047. var mesh = this.meshes[index];
  18048. if (!mesh.isReady()) {
  18049. return false;
  18050. }
  18051. var mat = mesh.material;
  18052. if (mat) {
  18053. if (!mat.isReady(mesh)) {
  18054. return false;
  18055. }
  18056. }
  18057. }
  18058. return true;
  18059. };
  18060. Scene.prototype.resetCachedMaterial = function () {
  18061. this._cachedMaterial = null;
  18062. };
  18063. Scene.prototype.registerBeforeRender = function (func) {
  18064. this.onBeforeRenderObservable.add(func);
  18065. };
  18066. Scene.prototype.unregisterBeforeRender = function (func) {
  18067. this.onBeforeRenderObservable.removeCallback(func);
  18068. };
  18069. Scene.prototype.registerAfterRender = function (func) {
  18070. this.onAfterRenderObservable.add(func);
  18071. };
  18072. Scene.prototype.unregisterAfterRender = function (func) {
  18073. this.onAfterRenderObservable.removeCallback(func);
  18074. };
  18075. Scene.prototype._addPendingData = function (data) {
  18076. this._pendingData.push(data);
  18077. };
  18078. Scene.prototype._removePendingData = function (data) {
  18079. var index = this._pendingData.indexOf(data);
  18080. if (index !== -1) {
  18081. this._pendingData.splice(index, 1);
  18082. }
  18083. };
  18084. Scene.prototype.getWaitingItemsCount = function () {
  18085. return this._pendingData.length;
  18086. };
  18087. /**
  18088. * Registers a function to be executed when the scene is ready.
  18089. * @param {Function} func - the function to be executed.
  18090. */
  18091. Scene.prototype.executeWhenReady = function (func) {
  18092. var _this = this;
  18093. this.onReadyObservable.add(func);
  18094. if (this._executeWhenReadyTimeoutId !== -1) {
  18095. return;
  18096. }
  18097. this._executeWhenReadyTimeoutId = setTimeout(function () {
  18098. _this._checkIsReady();
  18099. }, 150);
  18100. };
  18101. Scene.prototype._checkIsReady = function () {
  18102. var _this = this;
  18103. if (this.isReady()) {
  18104. this.onReadyObservable.notifyObservers(this);
  18105. this.onReadyObservable.clear();
  18106. this._executeWhenReadyTimeoutId = -1;
  18107. return;
  18108. }
  18109. this._executeWhenReadyTimeoutId = setTimeout(function () {
  18110. _this._checkIsReady();
  18111. }, 150);
  18112. };
  18113. // Animations
  18114. /**
  18115. * Will start the animation sequence of a given target
  18116. * @param target - the target
  18117. * @param {number} from - from which frame should animation start
  18118. * @param {number} to - till which frame should animation run.
  18119. * @param {boolean} [loop] - should the animation loop
  18120. * @param {number} [speedRatio] - the speed in which to run the animation
  18121. * @param {Function} [onAnimationEnd] function to be executed when the animation ended.
  18122. * @param {BABYLON.Animatable} [animatable] an animatable object. If not provided a new one will be created from the given params.
  18123. * @return {BABYLON.Animatable} the animatable object created for this animation
  18124. * @see BABYLON.Animatable
  18125. * @see http://doc.babylonjs.com/page.php?p=22081
  18126. */
  18127. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  18128. if (speedRatio === void 0) { speedRatio = 1.0; }
  18129. this.stopAnimation(target);
  18130. if (!animatable) {
  18131. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  18132. }
  18133. // Local animations
  18134. if (target.animations) {
  18135. animatable.appendAnimations(target, target.animations);
  18136. }
  18137. // Children animations
  18138. if (target.getAnimatables) {
  18139. var animatables = target.getAnimatables();
  18140. for (var index = 0; index < animatables.length; index++) {
  18141. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  18142. }
  18143. }
  18144. animatable.reset();
  18145. return animatable;
  18146. };
  18147. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  18148. if (speedRatio === undefined) {
  18149. speedRatio = 1.0;
  18150. }
  18151. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  18152. return animatable;
  18153. };
  18154. Scene.prototype.getAnimatableByTarget = function (target) {
  18155. for (var index = 0; index < this._activeAnimatables.length; index++) {
  18156. if (this._activeAnimatables[index].target === target) {
  18157. return this._activeAnimatables[index];
  18158. }
  18159. }
  18160. return null;
  18161. };
  18162. Object.defineProperty(Scene.prototype, "Animatables", {
  18163. get: function () {
  18164. return this._activeAnimatables;
  18165. },
  18166. enumerable: true,
  18167. configurable: true
  18168. });
  18169. /**
  18170. * Will stop the animation of the given target
  18171. * @param target - the target
  18172. * @param animationName - the name of the animation to stop (all animations will be stopped is empty)
  18173. * @see beginAnimation
  18174. */
  18175. Scene.prototype.stopAnimation = function (target, animationName) {
  18176. var animatable = this.getAnimatableByTarget(target);
  18177. if (animatable) {
  18178. animatable.stop(animationName);
  18179. }
  18180. };
  18181. Scene.prototype._animate = function () {
  18182. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  18183. return;
  18184. }
  18185. // Getting time
  18186. var now = BABYLON.Tools.Now;
  18187. if (!this._animationTimeLast) {
  18188. if (this._pendingData.length > 0) {
  18189. return;
  18190. }
  18191. this._animationTimeLast = now;
  18192. }
  18193. var deltaTime = (now - this._animationTimeLast) * this.animationTimeScale;
  18194. this._animationTime += deltaTime;
  18195. this._animationTimeLast = now;
  18196. for (var index = 0; index < this._activeAnimatables.length; index++) {
  18197. this._activeAnimatables[index]._animate(this._animationTime);
  18198. }
  18199. };
  18200. // Matrix
  18201. Scene.prototype.getViewMatrix = function () {
  18202. return this._viewMatrix;
  18203. };
  18204. Scene.prototype.getProjectionMatrix = function () {
  18205. return this._projectionMatrix;
  18206. };
  18207. Scene.prototype.getTransformMatrix = function () {
  18208. return this._transformMatrix;
  18209. };
  18210. Scene.prototype.setTransformMatrix = function (view, projection) {
  18211. this._viewMatrix = view;
  18212. this._projectionMatrix = projection;
  18213. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  18214. // Update frustum
  18215. if (!this._frustumPlanes) {
  18216. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  18217. }
  18218. else {
  18219. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  18220. }
  18221. };
  18222. // Methods
  18223. Scene.prototype.addMesh = function (newMesh) {
  18224. newMesh.uniqueId = this._uniqueIdCounter++;
  18225. var position = this.meshes.push(newMesh);
  18226. //notify the collision coordinator
  18227. this.collisionCoordinator.onMeshAdded(newMesh);
  18228. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  18229. };
  18230. Scene.prototype.removeMesh = function (toRemove) {
  18231. var index = this.meshes.indexOf(toRemove);
  18232. if (index !== -1) {
  18233. // Remove from the scene if mesh found
  18234. this.meshes.splice(index, 1);
  18235. }
  18236. //notify the collision coordinator
  18237. this.collisionCoordinator.onMeshRemoved(toRemove);
  18238. this.onMeshRemovedObservable.notifyObservers(toRemove);
  18239. return index;
  18240. };
  18241. Scene.prototype.removeSkeleton = function (toRemove) {
  18242. var index = this.skeletons.indexOf(toRemove);
  18243. if (index !== -1) {
  18244. // Remove from the scene if mesh found
  18245. this.skeletons.splice(index, 1);
  18246. }
  18247. return index;
  18248. };
  18249. Scene.prototype.removeLight = function (toRemove) {
  18250. var index = this.lights.indexOf(toRemove);
  18251. if (index !== -1) {
  18252. // Remove from the scene if mesh found
  18253. this.lights.splice(index, 1);
  18254. }
  18255. this.onLightRemovedObservable.notifyObservers(toRemove);
  18256. return index;
  18257. };
  18258. Scene.prototype.removeCamera = function (toRemove) {
  18259. var index = this.cameras.indexOf(toRemove);
  18260. if (index !== -1) {
  18261. // Remove from the scene if mesh found
  18262. this.cameras.splice(index, 1);
  18263. }
  18264. // Remove from activeCameras
  18265. var index2 = this.activeCameras.indexOf(toRemove);
  18266. if (index2 !== -1) {
  18267. // Remove from the scene if mesh found
  18268. this.activeCameras.splice(index2, 1);
  18269. }
  18270. // Reset the activeCamera
  18271. if (this.activeCamera === toRemove) {
  18272. if (this.cameras.length > 0) {
  18273. this.activeCamera = this.cameras[0];
  18274. }
  18275. else {
  18276. this.activeCamera = null;
  18277. }
  18278. }
  18279. this.onCameraRemovedObservable.notifyObservers(toRemove);
  18280. return index;
  18281. };
  18282. Scene.prototype.addLight = function (newLight) {
  18283. newLight.uniqueId = this._uniqueIdCounter++;
  18284. var position = this.lights.push(newLight);
  18285. this.onNewLightAddedObservable.notifyObservers(newLight);
  18286. };
  18287. Scene.prototype.addCamera = function (newCamera) {
  18288. newCamera.uniqueId = this._uniqueIdCounter++;
  18289. var position = this.cameras.push(newCamera);
  18290. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  18291. };
  18292. /**
  18293. * Switch active camera
  18294. * @param {Camera} newCamera - new active camera
  18295. * @param {boolean} attachControl - call attachControl for the new active camera (default: true)
  18296. */
  18297. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  18298. if (attachControl === void 0) { attachControl = true; }
  18299. var canvas = this._engine.getRenderingCanvas();
  18300. this.activeCamera.detachControl(canvas);
  18301. this.activeCamera = newCamera;
  18302. if (attachControl) {
  18303. newCamera.attachControl(canvas);
  18304. }
  18305. };
  18306. /**
  18307. * sets the active camera of the scene using its ID
  18308. * @param {string} id - the camera's ID
  18309. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  18310. * @see activeCamera
  18311. */
  18312. Scene.prototype.setActiveCameraByID = function (id) {
  18313. var camera = this.getCameraByID(id);
  18314. if (camera) {
  18315. this.activeCamera = camera;
  18316. return camera;
  18317. }
  18318. return null;
  18319. };
  18320. /**
  18321. * sets the active camera of the scene using its name
  18322. * @param {string} name - the camera's name
  18323. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  18324. * @see activeCamera
  18325. */
  18326. Scene.prototype.setActiveCameraByName = function (name) {
  18327. var camera = this.getCameraByName(name);
  18328. if (camera) {
  18329. this.activeCamera = camera;
  18330. return camera;
  18331. }
  18332. return null;
  18333. };
  18334. /**
  18335. * get a material using its id
  18336. * @param {string} the material's ID
  18337. * @return {BABYLON.Material|null} the material or null if none found.
  18338. */
  18339. Scene.prototype.getMaterialByID = function (id) {
  18340. for (var index = 0; index < this.materials.length; index++) {
  18341. if (this.materials[index].id === id) {
  18342. return this.materials[index];
  18343. }
  18344. }
  18345. return null;
  18346. };
  18347. /**
  18348. * get a material using its name
  18349. * @param {string} the material's name
  18350. * @return {BABYLON.Material|null} the material or null if none found.
  18351. */
  18352. Scene.prototype.getMaterialByName = function (name) {
  18353. for (var index = 0; index < this.materials.length; index++) {
  18354. if (this.materials[index].name === name) {
  18355. return this.materials[index];
  18356. }
  18357. }
  18358. return null;
  18359. };
  18360. Scene.prototype.getLensFlareSystemByName = function (name) {
  18361. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  18362. if (this.lensFlareSystems[index].name === name) {
  18363. return this.lensFlareSystems[index];
  18364. }
  18365. }
  18366. return null;
  18367. };
  18368. Scene.prototype.getLensFlareSystemByID = function (id) {
  18369. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  18370. if (this.lensFlareSystems[index].id === id) {
  18371. return this.lensFlareSystems[index];
  18372. }
  18373. }
  18374. return null;
  18375. };
  18376. Scene.prototype.getCameraByID = function (id) {
  18377. for (var index = 0; index < this.cameras.length; index++) {
  18378. if (this.cameras[index].id === id) {
  18379. return this.cameras[index];
  18380. }
  18381. }
  18382. return null;
  18383. };
  18384. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  18385. for (var index = 0; index < this.cameras.length; index++) {
  18386. if (this.cameras[index].uniqueId === uniqueId) {
  18387. return this.cameras[index];
  18388. }
  18389. }
  18390. return null;
  18391. };
  18392. /**
  18393. * get a camera using its name
  18394. * @param {string} the camera's name
  18395. * @return {BABYLON.Camera|null} the camera or null if none found.
  18396. */
  18397. Scene.prototype.getCameraByName = function (name) {
  18398. for (var index = 0; index < this.cameras.length; index++) {
  18399. if (this.cameras[index].name === name) {
  18400. return this.cameras[index];
  18401. }
  18402. }
  18403. return null;
  18404. };
  18405. /**
  18406. * get a bone using its id
  18407. * @param {string} the bone's id
  18408. * @return {BABYLON.Bone|null} the bone or null if not found
  18409. */
  18410. Scene.prototype.getBoneByID = function (id) {
  18411. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  18412. var skeleton = this.skeletons[skeletonIndex];
  18413. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  18414. if (skeleton.bones[boneIndex].id === id) {
  18415. return skeleton.bones[boneIndex];
  18416. }
  18417. }
  18418. }
  18419. return null;
  18420. };
  18421. /**
  18422. * get a bone using its id
  18423. * @param {string} the bone's name
  18424. * @return {BABYLON.Bone|null} the bone or null if not found
  18425. */
  18426. Scene.prototype.getBoneByName = function (name) {
  18427. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  18428. var skeleton = this.skeletons[skeletonIndex];
  18429. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  18430. if (skeleton.bones[boneIndex].name === name) {
  18431. return skeleton.bones[boneIndex];
  18432. }
  18433. }
  18434. }
  18435. return null;
  18436. };
  18437. /**
  18438. * get a light node using its name
  18439. * @param {string} the light's name
  18440. * @return {BABYLON.Light|null} the light or null if none found.
  18441. */
  18442. Scene.prototype.getLightByName = function (name) {
  18443. for (var index = 0; index < this.lights.length; index++) {
  18444. if (this.lights[index].name === name) {
  18445. return this.lights[index];
  18446. }
  18447. }
  18448. return null;
  18449. };
  18450. /**
  18451. * get a light node using its ID
  18452. * @param {string} the light's id
  18453. * @return {BABYLON.Light|null} the light or null if none found.
  18454. */
  18455. Scene.prototype.getLightByID = function (id) {
  18456. for (var index = 0; index < this.lights.length; index++) {
  18457. if (this.lights[index].id === id) {
  18458. return this.lights[index];
  18459. }
  18460. }
  18461. return null;
  18462. };
  18463. /**
  18464. * get a light node using its scene-generated unique ID
  18465. * @param {number} the light's unique id
  18466. * @return {BABYLON.Light|null} the light or null if none found.
  18467. */
  18468. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  18469. for (var index = 0; index < this.lights.length; index++) {
  18470. if (this.lights[index].uniqueId === uniqueId) {
  18471. return this.lights[index];
  18472. }
  18473. }
  18474. return null;
  18475. };
  18476. /**
  18477. * get a particle system by id
  18478. * @param id {number} the particle system id
  18479. * @return {BABYLON.ParticleSystem|null} the corresponding system or null if none found.
  18480. */
  18481. Scene.prototype.getParticleSystemByID = function (id) {
  18482. for (var index = 0; index < this.particleSystems.length; index++) {
  18483. if (this.particleSystems[index].id === id) {
  18484. return this.particleSystems[index];
  18485. }
  18486. }
  18487. return null;
  18488. };
  18489. /**
  18490. * get a geometry using its ID
  18491. * @param {string} the geometry's id
  18492. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  18493. */
  18494. Scene.prototype.getGeometryByID = function (id) {
  18495. for (var index = 0; index < this._geometries.length; index++) {
  18496. if (this._geometries[index].id === id) {
  18497. return this._geometries[index];
  18498. }
  18499. }
  18500. return null;
  18501. };
  18502. /**
  18503. * add a new geometry to this scene.
  18504. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  18505. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  18506. * @return {boolean} was the geometry added or not
  18507. */
  18508. Scene.prototype.pushGeometry = function (geometry, force) {
  18509. if (!force && this.getGeometryByID(geometry.id)) {
  18510. return false;
  18511. }
  18512. this._geometries.push(geometry);
  18513. //notify the collision coordinator
  18514. this.collisionCoordinator.onGeometryAdded(geometry);
  18515. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  18516. return true;
  18517. };
  18518. /**
  18519. * Removes an existing geometry
  18520. * @param {BABYLON.Geometry} geometry - the geometry to be removed from the scene.
  18521. * @return {boolean} was the geometry removed or not
  18522. */
  18523. Scene.prototype.removeGeometry = function (geometry) {
  18524. var index = this._geometries.indexOf(geometry);
  18525. if (index > -1) {
  18526. this._geometries.splice(index, 1);
  18527. //notify the collision coordinator
  18528. this.collisionCoordinator.onGeometryDeleted(geometry);
  18529. this.onGeometryRemovedObservable.notifyObservers(geometry);
  18530. return true;
  18531. }
  18532. return false;
  18533. };
  18534. Scene.prototype.getGeometries = function () {
  18535. return this._geometries;
  18536. };
  18537. /**
  18538. * Get the first added mesh found of a given ID
  18539. * @param {string} id - the id to search for
  18540. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  18541. */
  18542. Scene.prototype.getMeshByID = function (id) {
  18543. for (var index = 0; index < this.meshes.length; index++) {
  18544. if (this.meshes[index].id === id) {
  18545. return this.meshes[index];
  18546. }
  18547. }
  18548. return null;
  18549. };
  18550. Scene.prototype.getMeshesByID = function (id) {
  18551. return this.meshes.filter(function (m) {
  18552. return m.id === id;
  18553. });
  18554. };
  18555. /**
  18556. * Get a mesh with its auto-generated unique id
  18557. * @param {number} uniqueId - the unique id to search for
  18558. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  18559. */
  18560. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  18561. for (var index = 0; index < this.meshes.length; index++) {
  18562. if (this.meshes[index].uniqueId === uniqueId) {
  18563. return this.meshes[index];
  18564. }
  18565. }
  18566. return null;
  18567. };
  18568. /**
  18569. * Get a the last added mesh found of a given ID
  18570. * @param {string} id - the id to search for
  18571. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  18572. */
  18573. Scene.prototype.getLastMeshByID = function (id) {
  18574. for (var index = this.meshes.length - 1; index >= 0; index--) {
  18575. if (this.meshes[index].id === id) {
  18576. return this.meshes[index];
  18577. }
  18578. }
  18579. return null;
  18580. };
  18581. /**
  18582. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  18583. * @param {string} id - the id to search for
  18584. * @return {BABYLON.Node|null} the node found or null if not found at all.
  18585. */
  18586. Scene.prototype.getLastEntryByID = function (id) {
  18587. var index;
  18588. for (index = this.meshes.length - 1; index >= 0; index--) {
  18589. if (this.meshes[index].id === id) {
  18590. return this.meshes[index];
  18591. }
  18592. }
  18593. for (index = this.cameras.length - 1; index >= 0; index--) {
  18594. if (this.cameras[index].id === id) {
  18595. return this.cameras[index];
  18596. }
  18597. }
  18598. for (index = this.lights.length - 1; index >= 0; index--) {
  18599. if (this.lights[index].id === id) {
  18600. return this.lights[index];
  18601. }
  18602. }
  18603. return null;
  18604. };
  18605. Scene.prototype.getNodeByID = function (id) {
  18606. var mesh = this.getMeshByID(id);
  18607. if (mesh) {
  18608. return mesh;
  18609. }
  18610. var light = this.getLightByID(id);
  18611. if (light) {
  18612. return light;
  18613. }
  18614. var camera = this.getCameraByID(id);
  18615. if (camera) {
  18616. return camera;
  18617. }
  18618. var bone = this.getBoneByID(id);
  18619. return bone;
  18620. };
  18621. Scene.prototype.getNodeByName = function (name) {
  18622. var mesh = this.getMeshByName(name);
  18623. if (mesh) {
  18624. return mesh;
  18625. }
  18626. var light = this.getLightByName(name);
  18627. if (light) {
  18628. return light;
  18629. }
  18630. var camera = this.getCameraByName(name);
  18631. if (camera) {
  18632. return camera;
  18633. }
  18634. var bone = this.getBoneByName(name);
  18635. return bone;
  18636. };
  18637. Scene.prototype.getMeshByName = function (name) {
  18638. for (var index = 0; index < this.meshes.length; index++) {
  18639. if (this.meshes[index].name === name) {
  18640. return this.meshes[index];
  18641. }
  18642. }
  18643. return null;
  18644. };
  18645. Scene.prototype.getSoundByName = function (name) {
  18646. var index;
  18647. if (BABYLON.AudioEngine) {
  18648. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  18649. if (this.mainSoundTrack.soundCollection[index].name === name) {
  18650. return this.mainSoundTrack.soundCollection[index];
  18651. }
  18652. }
  18653. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  18654. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  18655. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  18656. return this.soundTracks[sdIndex].soundCollection[index];
  18657. }
  18658. }
  18659. }
  18660. }
  18661. return null;
  18662. };
  18663. Scene.prototype.getLastSkeletonByID = function (id) {
  18664. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  18665. if (this.skeletons[index].id === id) {
  18666. return this.skeletons[index];
  18667. }
  18668. }
  18669. return null;
  18670. };
  18671. Scene.prototype.getSkeletonById = function (id) {
  18672. for (var index = 0; index < this.skeletons.length; index++) {
  18673. if (this.skeletons[index].id === id) {
  18674. return this.skeletons[index];
  18675. }
  18676. }
  18677. return null;
  18678. };
  18679. Scene.prototype.getSkeletonByName = function (name) {
  18680. for (var index = 0; index < this.skeletons.length; index++) {
  18681. if (this.skeletons[index].name === name) {
  18682. return this.skeletons[index];
  18683. }
  18684. }
  18685. return null;
  18686. };
  18687. Scene.prototype.isActiveMesh = function (mesh) {
  18688. return (this._activeMeshes.indexOf(mesh) !== -1);
  18689. };
  18690. Object.defineProperty(Scene.prototype, "uid", {
  18691. /**
  18692. * Return a unique id as a string which can serve as an identifier for the scene
  18693. */
  18694. get: function () {
  18695. if (!this._uid) {
  18696. this._uid = BABYLON.Tools.RandomId();
  18697. }
  18698. return this._uid;
  18699. },
  18700. enumerable: true,
  18701. configurable: true
  18702. });
  18703. /**
  18704. * Add an externaly attached data from its key.
  18705. * This method call will fail and return false, if such key already exists.
  18706. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  18707. * @param key the unique key that identifies the data
  18708. * @param data the data object to associate to the key for this Engine instance
  18709. * @return true if no such key were already present and the data was added successfully, false otherwise
  18710. */
  18711. Scene.prototype.addExternalData = function (key, data) {
  18712. return this._externalData.add(key, data);
  18713. };
  18714. /**
  18715. * Get an externaly attached data from its key
  18716. * @param key the unique key that identifies the data
  18717. * @return the associated data, if present (can be null), or undefined if not present
  18718. */
  18719. Scene.prototype.getExternalData = function (key) {
  18720. return this._externalData.get(key);
  18721. };
  18722. /**
  18723. * Get an externaly attached data from its key, create it using a factory if it's not already present
  18724. * @param key the unique key that identifies the data
  18725. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  18726. * @return the associated data, can be null if the factory returned null.
  18727. */
  18728. Scene.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  18729. return this._externalData.getOrAddWithFactory(key, factory);
  18730. };
  18731. /**
  18732. * Remove an externaly attached data from the Engine instance
  18733. * @param key the unique key that identifies the data
  18734. * @return true if the data was successfully removed, false if it doesn't exist
  18735. */
  18736. Scene.prototype.removeExternalData = function (key) {
  18737. return this._externalData.remove(key);
  18738. };
  18739. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  18740. if (mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  18741. var material = subMesh.getMaterial();
  18742. if (mesh.showSubMeshesBoundingBox) {
  18743. this._boundingBoxRenderer.renderList.push(subMesh.getBoundingInfo().boundingBox);
  18744. }
  18745. if (material) {
  18746. // Render targets
  18747. if (material.getRenderTargetTextures) {
  18748. if (this._processedMaterials.indexOf(material) === -1) {
  18749. this._processedMaterials.push(material);
  18750. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  18751. }
  18752. }
  18753. // Dispatch
  18754. this._activeIndices.addCount(subMesh.indexCount, false);
  18755. this._renderingManager.dispatch(subMesh);
  18756. }
  18757. }
  18758. };
  18759. Scene.prototype._isInIntermediateRendering = function () {
  18760. return this._intermediateRendering;
  18761. };
  18762. Scene.prototype._evaluateActiveMeshes = function () {
  18763. this.activeCamera._activeMeshes.reset();
  18764. this._activeMeshes.reset();
  18765. this._renderingManager.reset();
  18766. this._processedMaterials.reset();
  18767. this._activeParticleSystems.reset();
  18768. this._activeSkeletons.reset();
  18769. this._softwareSkinnedMeshes.reset();
  18770. this._boundingBoxRenderer.reset();
  18771. this._edgesRenderers.reset();
  18772. // Meshes
  18773. var meshes;
  18774. var len;
  18775. if (this._selectionOctree) {
  18776. var selection = this._selectionOctree.select(this._frustumPlanes);
  18777. meshes = selection.data;
  18778. len = selection.length;
  18779. }
  18780. else {
  18781. len = this.meshes.length;
  18782. meshes = this.meshes;
  18783. }
  18784. for (var meshIndex = 0; meshIndex < len; meshIndex++) {
  18785. var mesh = meshes[meshIndex];
  18786. if (mesh.isBlocked) {
  18787. continue;
  18788. }
  18789. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  18790. if (!mesh.isReady() || !mesh.isEnabled()) {
  18791. continue;
  18792. }
  18793. mesh.computeWorldMatrix();
  18794. // Intersections
  18795. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  18796. this._meshesForIntersections.pushNoDuplicate(mesh);
  18797. }
  18798. // Switch to current LOD
  18799. var meshLOD = mesh.getLOD(this.activeCamera);
  18800. if (!meshLOD) {
  18801. continue;
  18802. }
  18803. mesh._preActivate();
  18804. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  18805. this._activeMeshes.push(mesh);
  18806. this.activeCamera._activeMeshes.push(mesh);
  18807. mesh._activate(this._renderId);
  18808. this._activeMesh(mesh, meshLOD);
  18809. }
  18810. }
  18811. // Particle systems
  18812. this._particlesDuration.beginMonitoring();
  18813. var beforeParticlesDate = BABYLON.Tools.Now;
  18814. if (this.particlesEnabled) {
  18815. BABYLON.Tools.StartPerformanceCounter("Particles", this.particleSystems.length > 0);
  18816. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  18817. var particleSystem = this.particleSystems[particleIndex];
  18818. if (!particleSystem.isStarted()) {
  18819. continue;
  18820. }
  18821. if (!particleSystem.emitter.position || (particleSystem.emitter && particleSystem.emitter.isEnabled())) {
  18822. this._activeParticleSystems.push(particleSystem);
  18823. particleSystem.animate();
  18824. this._renderingManager.dispatchParticles(particleSystem);
  18825. }
  18826. }
  18827. BABYLON.Tools.EndPerformanceCounter("Particles", this.particleSystems.length > 0);
  18828. }
  18829. this._particlesDuration.endMonitoring(false);
  18830. };
  18831. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  18832. if (mesh.skeleton && this.skeletonsEnabled) {
  18833. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  18834. mesh.skeleton.prepare();
  18835. }
  18836. if (!mesh.computeBonesUsingShaders) {
  18837. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  18838. }
  18839. }
  18840. if (sourceMesh.showBoundingBox || this.forceShowBoundingBoxes) {
  18841. this._boundingBoxRenderer.renderList.push(sourceMesh.getBoundingInfo().boundingBox);
  18842. }
  18843. if (sourceMesh._edgesRenderer) {
  18844. this._edgesRenderers.push(sourceMesh._edgesRenderer);
  18845. }
  18846. if (mesh && mesh.subMeshes) {
  18847. // Submeshes Octrees
  18848. var len;
  18849. var subMeshes;
  18850. if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) {
  18851. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  18852. len = intersections.length;
  18853. subMeshes = intersections.data;
  18854. }
  18855. else {
  18856. subMeshes = mesh.subMeshes;
  18857. len = subMeshes.length;
  18858. }
  18859. for (var subIndex = 0; subIndex < len; subIndex++) {
  18860. var subMesh = subMeshes[subIndex];
  18861. this._evaluateSubMesh(subMesh, mesh);
  18862. }
  18863. }
  18864. };
  18865. Scene.prototype.updateTransformMatrix = function (force) {
  18866. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  18867. };
  18868. Scene.prototype._renderForCamera = function (camera) {
  18869. var engine = this._engine;
  18870. var startTime = BABYLON.Tools.Now;
  18871. this.activeCamera = camera;
  18872. if (!this.activeCamera)
  18873. throw new Error("Active camera not set");
  18874. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  18875. // Viewport
  18876. engine.setViewport(this.activeCamera.viewport);
  18877. // Camera
  18878. this.resetCachedMaterial();
  18879. this._renderId++;
  18880. this.updateTransformMatrix();
  18881. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  18882. // Meshes
  18883. this._evaluateActiveMeshesDuration.beginMonitoring();
  18884. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  18885. this._evaluateActiveMeshes();
  18886. this._evaluateActiveMeshesDuration.endMonitoring(false);
  18887. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  18888. // Software skinning
  18889. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  18890. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  18891. mesh.applySkeleton(mesh.skeleton);
  18892. }
  18893. // Render targets
  18894. this._renderTargetsDuration.beginMonitoring();
  18895. var needsRestoreFrameBuffer = false;
  18896. var beforeRenderTargetDate = BABYLON.Tools.Now;
  18897. if (this.renderTargetsEnabled && this._renderTargets.length > 0) {
  18898. this._intermediateRendering = true;
  18899. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  18900. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  18901. var renderTarget = this._renderTargets.data[renderIndex];
  18902. if (renderTarget._shouldRender()) {
  18903. this._renderId++;
  18904. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  18905. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  18906. }
  18907. }
  18908. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  18909. this._intermediateRendering = false;
  18910. this._renderId++;
  18911. needsRestoreFrameBuffer = true; // Restore back buffer
  18912. }
  18913. // Render HighlightLayer Texture
  18914. var stencilState = this._engine.getStencilBuffer();
  18915. var renderhighlights = false;
  18916. if (this.renderTargetsEnabled && this.highlightLayers && this.highlightLayers.length > 0) {
  18917. this._intermediateRendering = true;
  18918. for (var i = 0; i < this.highlightLayers.length; i++) {
  18919. var highlightLayer = this.highlightLayers[i];
  18920. if (highlightLayer.shouldRender() &&
  18921. (!highlightLayer.camera ||
  18922. (highlightLayer.camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE && camera === highlightLayer.camera) ||
  18923. (highlightLayer.camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE && highlightLayer.camera._rigCameras.indexOf(camera) > -1))) {
  18924. renderhighlights = true;
  18925. var renderTarget = highlightLayer._mainTexture;
  18926. if (renderTarget._shouldRender()) {
  18927. this._renderId++;
  18928. renderTarget.render(false, false);
  18929. needsRestoreFrameBuffer = true;
  18930. }
  18931. }
  18932. }
  18933. this._intermediateRendering = false;
  18934. this._renderId++;
  18935. }
  18936. if (needsRestoreFrameBuffer) {
  18937. engine.restoreDefaultFramebuffer();
  18938. }
  18939. this._renderTargetsDuration.endMonitoring(false);
  18940. // Prepare Frame
  18941. this.postProcessManager._prepareFrame();
  18942. this._renderDuration.beginMonitoring();
  18943. // Backgrounds
  18944. var layerIndex;
  18945. var layer;
  18946. if (this.layers.length) {
  18947. engine.setDepthBuffer(false);
  18948. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  18949. layer = this.layers[layerIndex];
  18950. if (layer.isBackground) {
  18951. layer.render();
  18952. }
  18953. }
  18954. engine.setDepthBuffer(true);
  18955. }
  18956. // Render
  18957. BABYLON.Tools.StartPerformanceCounter("Main render");
  18958. // Activate HighlightLayer stencil
  18959. if (renderhighlights) {
  18960. this._engine.setStencilBuffer(true);
  18961. }
  18962. this._renderingManager.render(null, null, true, true);
  18963. // Restore HighlightLayer stencil
  18964. if (renderhighlights) {
  18965. this._engine.setStencilBuffer(stencilState);
  18966. }
  18967. BABYLON.Tools.EndPerformanceCounter("Main render");
  18968. // Bounding boxes
  18969. this._boundingBoxRenderer.render();
  18970. // Edges
  18971. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  18972. this._edgesRenderers.data[edgesRendererIndex].render();
  18973. }
  18974. // Lens flares
  18975. if (this.lensFlaresEnabled) {
  18976. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  18977. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  18978. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  18979. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  18980. lensFlareSystem.render();
  18981. }
  18982. }
  18983. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  18984. }
  18985. // Foregrounds
  18986. if (this.layers.length) {
  18987. engine.setDepthBuffer(false);
  18988. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  18989. layer = this.layers[layerIndex];
  18990. if (!layer.isBackground) {
  18991. layer.render();
  18992. }
  18993. }
  18994. engine.setDepthBuffer(true);
  18995. }
  18996. // Highlight Layer
  18997. if (renderhighlights) {
  18998. engine.setDepthBuffer(false);
  18999. for (var i = 0; i < this.highlightLayers.length; i++) {
  19000. if (this.highlightLayers[i].shouldRender()) {
  19001. this.highlightLayers[i].render();
  19002. }
  19003. }
  19004. engine.setDepthBuffer(true);
  19005. }
  19006. this._renderDuration.endMonitoring(false);
  19007. // Finalize frame
  19008. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  19009. // Update camera
  19010. this.activeCamera._updateFromScene();
  19011. // Reset some special arrays
  19012. this._renderTargets.reset();
  19013. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  19014. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  19015. };
  19016. Scene.prototype._processSubCameras = function (camera) {
  19017. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  19018. this._renderForCamera(camera);
  19019. return;
  19020. }
  19021. // rig cameras
  19022. for (var index = 0; index < camera._rigCameras.length; index++) {
  19023. this._renderForCamera(camera._rigCameras[index]);
  19024. }
  19025. this.activeCamera = camera;
  19026. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  19027. // Update camera
  19028. this.activeCamera._updateFromScene();
  19029. };
  19030. Scene.prototype._checkIntersections = function () {
  19031. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  19032. var sourceMesh = this._meshesForIntersections.data[index];
  19033. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  19034. var action = sourceMesh.actionManager.actions[actionIndex];
  19035. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  19036. var parameters = action.getTriggerParameter();
  19037. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  19038. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  19039. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  19040. if (areIntersecting && currentIntersectionInProgress === -1) {
  19041. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  19042. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  19043. sourceMesh._intersectionsInProgress.push(otherMesh);
  19044. }
  19045. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  19046. sourceMesh._intersectionsInProgress.push(otherMesh);
  19047. }
  19048. }
  19049. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  19050. //They intersected, and now they don't.
  19051. //is this trigger an exit trigger? execute an event.
  19052. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  19053. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  19054. }
  19055. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  19056. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  19057. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  19058. }
  19059. }
  19060. }
  19061. }
  19062. }
  19063. };
  19064. Scene.prototype.render = function () {
  19065. this._lastFrameDuration.beginMonitoring();
  19066. this._particlesDuration.fetchNewFrame();
  19067. this._spritesDuration.fetchNewFrame();
  19068. this._activeParticles.fetchNewFrame();
  19069. this._renderDuration.fetchNewFrame();
  19070. this._renderTargetsDuration.fetchNewFrame();
  19071. this._evaluateActiveMeshesDuration.fetchNewFrame();
  19072. this._totalVertices.fetchNewFrame();
  19073. this._activeIndices.fetchNewFrame();
  19074. this._activeBones.fetchNewFrame();
  19075. this.getEngine().drawCallsPerfCounter.fetchNewFrame();
  19076. this._meshesForIntersections.reset();
  19077. this.resetCachedMaterial();
  19078. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  19079. // Actions
  19080. if (this.actionManager) {
  19081. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger, null);
  19082. }
  19083. //Simplification Queue
  19084. if (this.simplificationQueue && !this.simplificationQueue.running) {
  19085. this.simplificationQueue.executeNext();
  19086. }
  19087. // Animations
  19088. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  19089. this._animationRatio = deltaTime * (60.0 / 1000.0);
  19090. this._animate();
  19091. // Physics
  19092. if (this._physicsEngine) {
  19093. BABYLON.Tools.StartPerformanceCounter("Physics");
  19094. this._physicsEngine._step(deltaTime / 1000.0);
  19095. BABYLON.Tools.EndPerformanceCounter("Physics");
  19096. }
  19097. // Before render
  19098. this.onBeforeRenderObservable.notifyObservers(this);
  19099. // Customs render targets
  19100. this._renderTargetsDuration.beginMonitoring();
  19101. var beforeRenderTargetDate = BABYLON.Tools.Now;
  19102. var engine = this.getEngine();
  19103. var currentActiveCamera = this.activeCamera;
  19104. if (this.renderTargetsEnabled) {
  19105. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  19106. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  19107. var renderTarget = this.customRenderTargets[customIndex];
  19108. if (renderTarget._shouldRender()) {
  19109. this._renderId++;
  19110. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  19111. if (!this.activeCamera)
  19112. throw new Error("Active camera not set");
  19113. // Viewport
  19114. engine.setViewport(this.activeCamera.viewport);
  19115. // Camera
  19116. this.updateTransformMatrix();
  19117. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  19118. }
  19119. }
  19120. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  19121. this._renderId++;
  19122. }
  19123. if (this.customRenderTargets.length > 0) {
  19124. engine.restoreDefaultFramebuffer();
  19125. }
  19126. this._renderTargetsDuration.endMonitoring();
  19127. this.activeCamera = currentActiveCamera;
  19128. // Procedural textures
  19129. if (this.proceduralTexturesEnabled) {
  19130. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  19131. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  19132. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  19133. if (proceduralTexture._shouldRender()) {
  19134. proceduralTexture.render();
  19135. }
  19136. }
  19137. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  19138. }
  19139. // Clear
  19140. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, true, true);
  19141. // Shadows
  19142. if (this.shadowsEnabled) {
  19143. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  19144. var light = this.lights[lightIndex];
  19145. var shadowGenerator = light.getShadowGenerator();
  19146. if (light.isEnabled() && shadowGenerator && shadowGenerator.getShadowMap().getScene().textures.indexOf(shadowGenerator.getShadowMap()) !== -1) {
  19147. this._renderTargets.push(shadowGenerator.getShadowMap());
  19148. }
  19149. }
  19150. }
  19151. // Depth renderer
  19152. if (this._depthRenderer) {
  19153. this._renderTargets.push(this._depthRenderer.getDepthMap());
  19154. }
  19155. // RenderPipeline
  19156. this.postProcessRenderPipelineManager.update();
  19157. // Multi-cameras?
  19158. if (this.activeCameras.length > 0) {
  19159. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  19160. if (cameraIndex > 0) {
  19161. this._engine.clear(null, false, true, true);
  19162. }
  19163. this._processSubCameras(this.activeCameras[cameraIndex]);
  19164. }
  19165. }
  19166. else {
  19167. if (!this.activeCamera) {
  19168. throw new Error("No camera defined");
  19169. }
  19170. this._processSubCameras(this.activeCamera);
  19171. }
  19172. // Intersection checks
  19173. this._checkIntersections();
  19174. // Update the audio listener attached to the camera
  19175. if (BABYLON.AudioEngine) {
  19176. this._updateAudioParameters();
  19177. }
  19178. // After render
  19179. if (this.afterRender) {
  19180. this.afterRender();
  19181. }
  19182. this.onAfterRenderObservable.notifyObservers(this);
  19183. // Cleaning
  19184. for (var index = 0; index < this._toBeDisposed.length; index++) {
  19185. this._toBeDisposed.data[index].dispose();
  19186. this._toBeDisposed[index] = null;
  19187. }
  19188. this._toBeDisposed.reset();
  19189. if (this.dumpNextRenderTargets) {
  19190. this.dumpNextRenderTargets = false;
  19191. }
  19192. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  19193. this._lastFrameDuration.endMonitoring();
  19194. this._totalMeshesCounter.addCount(this.meshes.length, true);
  19195. this._totalLightsCounter.addCount(this.lights.length, true);
  19196. this._totalMaterialsCounter.addCount(this.materials.length, true);
  19197. this._totalTexturesCounter.addCount(this.textures.length, true);
  19198. this._activeBones.addCount(0, true);
  19199. this._activeIndices.addCount(0, true);
  19200. this._activeParticles.addCount(0, true);
  19201. };
  19202. Scene.prototype._updateAudioParameters = function () {
  19203. if (!this.audioEnabled || (this.mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  19204. return;
  19205. }
  19206. var listeningCamera;
  19207. var audioEngine = BABYLON.Engine.audioEngine;
  19208. if (this.activeCameras.length > 0) {
  19209. listeningCamera = this.activeCameras[0];
  19210. }
  19211. else {
  19212. listeningCamera = this.activeCamera;
  19213. }
  19214. if (listeningCamera && audioEngine.canUseWebAudio) {
  19215. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  19216. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  19217. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  19218. cameraDirection.normalize();
  19219. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  19220. var i;
  19221. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  19222. var sound = this.mainSoundTrack.soundCollection[i];
  19223. if (sound.useCustomAttenuation) {
  19224. sound.updateDistanceFromListener();
  19225. }
  19226. }
  19227. for (i = 0; i < this.soundTracks.length; i++) {
  19228. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  19229. sound = this.soundTracks[i].soundCollection[j];
  19230. if (sound.useCustomAttenuation) {
  19231. sound.updateDistanceFromListener();
  19232. }
  19233. }
  19234. }
  19235. }
  19236. };
  19237. Object.defineProperty(Scene.prototype, "audioEnabled", {
  19238. // Audio
  19239. get: function () {
  19240. return this._audioEnabled;
  19241. },
  19242. set: function (value) {
  19243. this._audioEnabled = value;
  19244. if (BABYLON.AudioEngine) {
  19245. if (this._audioEnabled) {
  19246. this._enableAudio();
  19247. }
  19248. else {
  19249. this._disableAudio();
  19250. }
  19251. }
  19252. },
  19253. enumerable: true,
  19254. configurable: true
  19255. });
  19256. Scene.prototype._disableAudio = function () {
  19257. var i;
  19258. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  19259. this.mainSoundTrack.soundCollection[i].pause();
  19260. }
  19261. for (i = 0; i < this.soundTracks.length; i++) {
  19262. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  19263. this.soundTracks[i].soundCollection[j].pause();
  19264. }
  19265. }
  19266. };
  19267. Scene.prototype._enableAudio = function () {
  19268. var i;
  19269. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  19270. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  19271. this.mainSoundTrack.soundCollection[i].play();
  19272. }
  19273. }
  19274. for (i = 0; i < this.soundTracks.length; i++) {
  19275. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  19276. if (this.soundTracks[i].soundCollection[j].isPaused) {
  19277. this.soundTracks[i].soundCollection[j].play();
  19278. }
  19279. }
  19280. }
  19281. };
  19282. Object.defineProperty(Scene.prototype, "headphone", {
  19283. get: function () {
  19284. return this._headphone;
  19285. },
  19286. set: function (value) {
  19287. this._headphone = value;
  19288. if (BABYLON.AudioEngine) {
  19289. if (this._headphone) {
  19290. this._switchAudioModeForHeadphones();
  19291. }
  19292. else {
  19293. this._switchAudioModeForNormalSpeakers();
  19294. }
  19295. }
  19296. },
  19297. enumerable: true,
  19298. configurable: true
  19299. });
  19300. Scene.prototype._switchAudioModeForHeadphones = function () {
  19301. this.mainSoundTrack.switchPanningModelToHRTF();
  19302. for (var i = 0; i < this.soundTracks.length; i++) {
  19303. this.soundTracks[i].switchPanningModelToHRTF();
  19304. }
  19305. };
  19306. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  19307. this.mainSoundTrack.switchPanningModelToEqualPower();
  19308. for (var i = 0; i < this.soundTracks.length; i++) {
  19309. this.soundTracks[i].switchPanningModelToEqualPower();
  19310. }
  19311. };
  19312. Scene.prototype.enableDepthRenderer = function () {
  19313. if (this._depthRenderer) {
  19314. return this._depthRenderer;
  19315. }
  19316. this._depthRenderer = new BABYLON.DepthRenderer(this);
  19317. return this._depthRenderer;
  19318. };
  19319. Scene.prototype.disableDepthRenderer = function () {
  19320. if (!this._depthRenderer) {
  19321. return;
  19322. }
  19323. this._depthRenderer.dispose();
  19324. this._depthRenderer = null;
  19325. };
  19326. Scene.prototype.freezeMaterials = function () {
  19327. for (var i = 0; i < this.materials.length; i++) {
  19328. this.materials[i].freeze();
  19329. }
  19330. };
  19331. Scene.prototype.unfreezeMaterials = function () {
  19332. for (var i = 0; i < this.materials.length; i++) {
  19333. this.materials[i].unfreeze();
  19334. }
  19335. };
  19336. Scene.prototype.dispose = function () {
  19337. this.beforeRender = null;
  19338. this.afterRender = null;
  19339. this.skeletons = [];
  19340. this._boundingBoxRenderer.dispose();
  19341. if (this._depthRenderer) {
  19342. this._depthRenderer.dispose();
  19343. }
  19344. // Debug layer
  19345. if (this._debugLayer) {
  19346. this._debugLayer.hide();
  19347. }
  19348. // Events
  19349. this.onDisposeObservable.notifyObservers(this);
  19350. this.onDisposeObservable.clear();
  19351. this.onBeforeRenderObservable.clear();
  19352. this.onAfterRenderObservable.clear();
  19353. this.detachControl();
  19354. // Release sounds & sounds tracks
  19355. if (BABYLON.AudioEngine) {
  19356. this.disposeSounds();
  19357. }
  19358. // Detach cameras
  19359. var canvas = this._engine.getRenderingCanvas();
  19360. var index;
  19361. for (index = 0; index < this.cameras.length; index++) {
  19362. this.cameras[index].detachControl(canvas);
  19363. }
  19364. // Release lights
  19365. while (this.lights.length) {
  19366. this.lights[0].dispose();
  19367. }
  19368. // Release meshes
  19369. while (this.meshes.length) {
  19370. this.meshes[0].dispose(true);
  19371. }
  19372. // Release cameras
  19373. while (this.cameras.length) {
  19374. this.cameras[0].dispose();
  19375. }
  19376. // Release materials
  19377. while (this.materials.length) {
  19378. this.materials[0].dispose();
  19379. }
  19380. // Release particles
  19381. while (this.particleSystems.length) {
  19382. this.particleSystems[0].dispose();
  19383. }
  19384. // Release sprites
  19385. while (this.spriteManagers.length) {
  19386. this.spriteManagers[0].dispose();
  19387. }
  19388. // Release layers
  19389. while (this.layers.length) {
  19390. this.layers[0].dispose();
  19391. }
  19392. while (this.highlightLayers.length) {
  19393. this.highlightLayers[0].dispose();
  19394. }
  19395. // Release textures
  19396. while (this.textures.length) {
  19397. this.textures[0].dispose();
  19398. }
  19399. // Post-processes
  19400. this.postProcessManager.dispose();
  19401. // Physics
  19402. if (this._physicsEngine) {
  19403. this.disablePhysicsEngine();
  19404. }
  19405. // Remove from engine
  19406. index = this._engine.scenes.indexOf(this);
  19407. if (index > -1) {
  19408. this._engine.scenes.splice(index, 1);
  19409. }
  19410. this._engine.wipeCaches();
  19411. };
  19412. // Release sounds & sounds tracks
  19413. Scene.prototype.disposeSounds = function () {
  19414. this.mainSoundTrack.dispose();
  19415. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  19416. this.soundTracks[scIndex].dispose();
  19417. }
  19418. };
  19419. // Octrees
  19420. Scene.prototype.getWorldExtends = function () {
  19421. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  19422. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  19423. for (var index = 0; index < this.meshes.length; index++) {
  19424. var mesh = this.meshes[index];
  19425. mesh.computeWorldMatrix(true);
  19426. var minBox = mesh.getBoundingInfo().boundingBox.minimumWorld;
  19427. var maxBox = mesh.getBoundingInfo().boundingBox.maximumWorld;
  19428. BABYLON.Tools.CheckExtends(minBox, min, max);
  19429. BABYLON.Tools.CheckExtends(maxBox, min, max);
  19430. }
  19431. return {
  19432. min: min,
  19433. max: max
  19434. };
  19435. };
  19436. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  19437. if (maxCapacity === void 0) { maxCapacity = 64; }
  19438. if (maxDepth === void 0) { maxDepth = 2; }
  19439. if (!this._selectionOctree) {
  19440. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  19441. }
  19442. var worldExtends = this.getWorldExtends();
  19443. // Update octree
  19444. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  19445. return this._selectionOctree;
  19446. };
  19447. // Picking
  19448. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  19449. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  19450. var engine = this._engine;
  19451. if (!camera) {
  19452. if (!this.activeCamera)
  19453. throw new Error("Active camera not set");
  19454. camera = this.activeCamera;
  19455. }
  19456. var cameraViewport = camera.viewport;
  19457. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  19458. // Moving coordinates to local viewport world
  19459. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  19460. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  19461. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  19462. // return BABYLON.Ray.CreateNew(x / window.devicePixelRatio, y / window.devicePixelRatio, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  19463. };
  19464. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  19465. var engine = this._engine;
  19466. if (!camera) {
  19467. if (!this.activeCamera)
  19468. throw new Error("Active camera not set");
  19469. camera = this.activeCamera;
  19470. }
  19471. var cameraViewport = camera.viewport;
  19472. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  19473. var identity = BABYLON.Matrix.Identity();
  19474. // Moving coordinates to local viewport world
  19475. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  19476. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  19477. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  19478. };
  19479. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  19480. var pickingInfo = null;
  19481. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  19482. var mesh = this.meshes[meshIndex];
  19483. if (predicate) {
  19484. if (!predicate(mesh)) {
  19485. continue;
  19486. }
  19487. }
  19488. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  19489. continue;
  19490. }
  19491. var world = mesh.getWorldMatrix();
  19492. var ray = rayFunction(world);
  19493. var result = mesh.intersects(ray, fastCheck);
  19494. if (!result || !result.hit)
  19495. continue;
  19496. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  19497. continue;
  19498. pickingInfo = result;
  19499. if (fastCheck) {
  19500. break;
  19501. }
  19502. }
  19503. return pickingInfo || new BABYLON.PickingInfo();
  19504. };
  19505. Scene.prototype._internalMultiPick = function (rayFunction, predicate) {
  19506. var pickingInfos = new Array();
  19507. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  19508. var mesh = this.meshes[meshIndex];
  19509. if (predicate) {
  19510. if (!predicate(mesh)) {
  19511. continue;
  19512. }
  19513. }
  19514. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  19515. continue;
  19516. }
  19517. var world = mesh.getWorldMatrix();
  19518. var ray = rayFunction(world);
  19519. var result = mesh.intersects(ray, false);
  19520. if (!result || !result.hit)
  19521. continue;
  19522. pickingInfos.push(result);
  19523. }
  19524. return pickingInfos;
  19525. };
  19526. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  19527. var pickingInfo = null;
  19528. camera = camera || this.activeCamera;
  19529. if (this.spriteManagers.length > 0) {
  19530. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  19531. var spriteManager = this.spriteManagers[spriteIndex];
  19532. if (!spriteManager.isPickable) {
  19533. continue;
  19534. }
  19535. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  19536. if (!result || !result.hit)
  19537. continue;
  19538. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  19539. continue;
  19540. pickingInfo = result;
  19541. if (fastCheck) {
  19542. break;
  19543. }
  19544. }
  19545. }
  19546. return pickingInfo || new BABYLON.PickingInfo();
  19547. };
  19548. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  19549. /// <param name="x">X position on screen</param>
  19550. /// <param name="y">Y position on screen</param>
  19551. /// <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>
  19552. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  19553. /// <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>
  19554. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  19555. var _this = this;
  19556. return this._internalPick(function (world) { return _this.createPickingRay(x, y, world, camera); }, predicate, fastCheck);
  19557. };
  19558. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  19559. /// <param name="x">X position on screen</param>
  19560. /// <param name="y">Y position on screen</param>
  19561. /// <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>
  19562. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  19563. /// <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>
  19564. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  19565. return this._internalPickSprites(this.createPickingRayInCameraSpace(x, y, camera), predicate, fastCheck, camera);
  19566. };
  19567. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  19568. var _this = this;
  19569. return this._internalPick(function (world) {
  19570. if (!_this._pickWithRayInverseMatrix) {
  19571. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  19572. }
  19573. world.invertToRef(_this._pickWithRayInverseMatrix);
  19574. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  19575. }, predicate, fastCheck);
  19576. };
  19577. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  19578. /// <param name="x">X position on screen</param>
  19579. /// <param name="y">Y position on screen</param>
  19580. /// <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>
  19581. /// <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>
  19582. Scene.prototype.multiPick = function (x, y, predicate, camera) {
  19583. var _this = this;
  19584. return this._internalMultiPick(function (world) { return _this.createPickingRay(x, y, world, camera); }, predicate);
  19585. };
  19586. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  19587. /// <param name="ray">Ray to use</param>
  19588. /// <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>
  19589. Scene.prototype.multiPickWithRay = function (ray, predicate) {
  19590. var _this = this;
  19591. return this._internalMultiPick(function (world) {
  19592. if (!_this._pickWithRayInverseMatrix) {
  19593. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  19594. }
  19595. world.invertToRef(_this._pickWithRayInverseMatrix);
  19596. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  19597. }, predicate);
  19598. };
  19599. Scene.prototype.setPointerOverMesh = function (mesh) {
  19600. if (this._pointerOverMesh === mesh) {
  19601. return;
  19602. }
  19603. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  19604. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  19605. }
  19606. this._pointerOverMesh = mesh;
  19607. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  19608. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  19609. }
  19610. };
  19611. Scene.prototype.getPointerOverMesh = function () {
  19612. return this._pointerOverMesh;
  19613. };
  19614. Scene.prototype.setPointerOverSprite = function (sprite) {
  19615. if (this._pointerOverSprite === sprite) {
  19616. return;
  19617. }
  19618. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  19619. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  19620. }
  19621. this._pointerOverSprite = sprite;
  19622. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  19623. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  19624. }
  19625. };
  19626. Scene.prototype.getPointerOverSprite = function () {
  19627. return this._pointerOverSprite;
  19628. };
  19629. // Physics
  19630. Scene.prototype.getPhysicsEngine = function () {
  19631. return this._physicsEngine;
  19632. };
  19633. /**
  19634. * Enables physics to the current scene
  19635. * @param {BABYLON.Vector3} [gravity] - the scene's gravity for the physics engine
  19636. * @param {BABYLON.IPhysicsEnginePlugin} [plugin] - The physics engine to be used. defaults to OimoJS.
  19637. * @return {boolean} was the physics engine initialized
  19638. */
  19639. Scene.prototype.enablePhysics = function (gravity, plugin) {
  19640. if (this._physicsEngine) {
  19641. return true;
  19642. }
  19643. try {
  19644. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  19645. return true;
  19646. }
  19647. catch (e) {
  19648. BABYLON.Tools.Error(e.message);
  19649. return false;
  19650. }
  19651. };
  19652. Scene.prototype.disablePhysicsEngine = function () {
  19653. if (!this._physicsEngine) {
  19654. return;
  19655. }
  19656. this._physicsEngine.dispose();
  19657. this._physicsEngine = undefined;
  19658. };
  19659. Scene.prototype.isPhysicsEnabled = function () {
  19660. return this._physicsEngine !== undefined;
  19661. };
  19662. /**
  19663. *
  19664. * Sets the gravity of the physics engine (and NOT of the scene)
  19665. * @param {BABYLON.Vector3} [gravity] - the new gravity to be used
  19666. */
  19667. Scene.prototype.setGravity = function (gravity) {
  19668. BABYLON.Tools.Warn("Deprecated, please use 'scene.getPhysicsEngine().setGravity()'");
  19669. if (!this._physicsEngine) {
  19670. return;
  19671. }
  19672. this._physicsEngine.setGravity(gravity);
  19673. };
  19674. /**
  19675. * Legacy support, using the new API
  19676. * @Deprecated
  19677. */
  19678. Scene.prototype.createCompoundImpostor = function (parts, options) {
  19679. BABYLON.Tools.Warn("Scene.createCompoundImpostor is deprecated. Please use PhysicsImpostor parent/child");
  19680. if (parts.parts) {
  19681. options = parts;
  19682. parts = parts.parts;
  19683. }
  19684. var mainMesh = parts[0].mesh;
  19685. mainMesh.physicsImpostor = new BABYLON.PhysicsImpostor(mainMesh, parts[0].impostor, options, this);
  19686. for (var index = 1; index < parts.length; index++) {
  19687. var mesh = parts[index].mesh;
  19688. if (mesh.parent !== mainMesh) {
  19689. mesh.position = mesh.position.subtract(mainMesh.position);
  19690. mesh.parent = mainMesh;
  19691. }
  19692. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parts[index].impostor, options, this);
  19693. }
  19694. mainMesh.physicsImpostor.forceUpdate();
  19695. };
  19696. Scene.prototype.deleteCompoundImpostor = function (compound) {
  19697. var mesh = compound.parts[0].mesh;
  19698. mesh.physicsImpostor.dispose();
  19699. mesh.physicsImpostor = null;
  19700. };
  19701. // Misc.
  19702. Scene.prototype.createDefaultCameraOrLight = function (createArcRotateCamera) {
  19703. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  19704. // Light
  19705. if (this.lights.length === 0) {
  19706. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  19707. }
  19708. // Camera
  19709. if (!this.activeCamera) {
  19710. // Compute position
  19711. var worldExtends = this.getWorldExtends();
  19712. var worldCenter = worldExtends.min.add(worldExtends.max.subtract(worldExtends.min).scale(0.5));
  19713. var camera;
  19714. if (createArcRotateCamera) {
  19715. camera = new BABYLON.ArcRotateCamera("default camera", 0, 0, 10, BABYLON.Vector3.Zero(), this);
  19716. camera.setPosition(new BABYLON.Vector3(worldCenter.x, worldCenter.y, worldExtends.min.z - (worldExtends.max.z - worldExtends.min.z)));
  19717. camera.setTarget(worldCenter);
  19718. }
  19719. else {
  19720. camera = new BABYLON.FreeCamera("default camera", BABYLON.Vector3.Zero(), this);
  19721. camera.position = new BABYLON.Vector3(worldCenter.x, worldCenter.y, worldExtends.min.z - (worldExtends.max.z - worldExtends.min.z));
  19722. camera.setTarget(worldCenter);
  19723. }
  19724. this.activeCamera = camera;
  19725. }
  19726. };
  19727. // Tags
  19728. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  19729. if (tagsQuery === undefined) {
  19730. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  19731. return list;
  19732. }
  19733. var listByTags = [];
  19734. forEach = forEach || (function (item) { return; });
  19735. for (var i in list) {
  19736. var item = list[i];
  19737. if (BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  19738. listByTags.push(item);
  19739. forEach(item);
  19740. }
  19741. }
  19742. return listByTags;
  19743. };
  19744. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  19745. return this._getByTags(this.meshes, tagsQuery, forEach);
  19746. };
  19747. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  19748. return this._getByTags(this.cameras, tagsQuery, forEach);
  19749. };
  19750. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  19751. return this._getByTags(this.lights, tagsQuery, forEach);
  19752. };
  19753. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  19754. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  19755. };
  19756. /**
  19757. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  19758. * This allowed control for front to back rendering or reversly depending of the special needs.
  19759. *
  19760. * @param renderingGroupId The rendering group id corresponding to its index
  19761. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  19762. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  19763. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  19764. */
  19765. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  19766. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  19767. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  19768. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  19769. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  19770. };
  19771. /**
  19772. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  19773. *
  19774. * @param renderingGroupId The rendering group id corresponding to its index
  19775. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  19776. * @param depth Automatically clears depth between groups if true and autoClear is true.
  19777. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  19778. */
  19779. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  19780. if (depth === void 0) { depth = true; }
  19781. if (stencil === void 0) { stencil = true; }
  19782. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
  19783. };
  19784. return Scene;
  19785. }());
  19786. // Statics
  19787. Scene._FOGMODE_NONE = 0;
  19788. Scene._FOGMODE_EXP = 1;
  19789. Scene._FOGMODE_EXP2 = 2;
  19790. Scene._FOGMODE_LINEAR = 3;
  19791. Scene.MinDeltaTime = 1.0;
  19792. Scene.MaxDeltaTime = 1000.0;
  19793. BABYLON.Scene = Scene;
  19794. })(BABYLON || (BABYLON = {}));
  19795. //# sourceMappingURL=babylon.scene.js.map
  19796. var BABYLON;
  19797. (function (BABYLON) {
  19798. var Buffer = (function () {
  19799. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced) {
  19800. if (engine instanceof BABYLON.Mesh) {
  19801. this._engine = engine.getScene().getEngine();
  19802. }
  19803. else {
  19804. this._engine = engine;
  19805. }
  19806. this._updatable = updatable;
  19807. this._data = data;
  19808. this._strideSize = stride;
  19809. if (!postponeInternalCreation) {
  19810. this.create();
  19811. }
  19812. this._instanced = instanced;
  19813. }
  19814. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride) {
  19815. // a lot of these parameters are ignored as they are overriden by the buffer
  19816. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, stride ? stride : this._strideSize, this._instanced, offset, size);
  19817. };
  19818. // Properties
  19819. Buffer.prototype.isUpdatable = function () {
  19820. return this._updatable;
  19821. };
  19822. Buffer.prototype.getData = function () {
  19823. return this._data;
  19824. };
  19825. Buffer.prototype.getBuffer = function () {
  19826. return this._buffer;
  19827. };
  19828. Buffer.prototype.getStrideSize = function () {
  19829. return this._strideSize;
  19830. };
  19831. Buffer.prototype.getIsInstanced = function () {
  19832. return this._instanced;
  19833. };
  19834. // Methods
  19835. Buffer.prototype.create = function (data) {
  19836. if (!data && this._buffer) {
  19837. return; // nothing to do
  19838. }
  19839. data = data || this._data;
  19840. if (!this._buffer) {
  19841. if (this._updatable) {
  19842. this._buffer = this._engine.createDynamicVertexBuffer(data);
  19843. this._data = data;
  19844. }
  19845. else {
  19846. this._buffer = this._engine.createVertexBuffer(data);
  19847. }
  19848. }
  19849. else if (this._updatable) {
  19850. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  19851. this._data = data;
  19852. }
  19853. };
  19854. Buffer.prototype.update = function (data) {
  19855. this.create(data);
  19856. };
  19857. Buffer.prototype.updateDirectly = function (data, offset, vertexCount) {
  19858. if (!this._buffer) {
  19859. return;
  19860. }
  19861. if (this._updatable) {
  19862. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset, (vertexCount ? vertexCount * this.getStrideSize() : undefined));
  19863. this._data = null;
  19864. }
  19865. };
  19866. Buffer.prototype.dispose = function () {
  19867. if (!this._buffer) {
  19868. return;
  19869. }
  19870. if (this._engine._releaseBuffer(this._buffer)) {
  19871. this._buffer = null;
  19872. }
  19873. };
  19874. return Buffer;
  19875. }());
  19876. BABYLON.Buffer = Buffer;
  19877. })(BABYLON || (BABYLON = {}));
  19878. //# sourceMappingURL=babylon.buffer.js.map
  19879. var BABYLON;
  19880. (function (BABYLON) {
  19881. var VertexBuffer = (function () {
  19882. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size) {
  19883. if (!stride) {
  19884. // Deduce stride from kind
  19885. switch (kind) {
  19886. case VertexBuffer.PositionKind:
  19887. stride = 3;
  19888. break;
  19889. case VertexBuffer.NormalKind:
  19890. stride = 3;
  19891. break;
  19892. case VertexBuffer.UVKind:
  19893. case VertexBuffer.UV2Kind:
  19894. case VertexBuffer.UV3Kind:
  19895. case VertexBuffer.UV4Kind:
  19896. case VertexBuffer.UV5Kind:
  19897. case VertexBuffer.UV6Kind:
  19898. stride = 2;
  19899. break;
  19900. case VertexBuffer.ColorKind:
  19901. stride = 4;
  19902. break;
  19903. case VertexBuffer.MatricesIndicesKind:
  19904. case VertexBuffer.MatricesIndicesExtraKind:
  19905. stride = 4;
  19906. break;
  19907. case VertexBuffer.MatricesWeightsKind:
  19908. case VertexBuffer.MatricesWeightsExtraKind:
  19909. stride = 4;
  19910. break;
  19911. }
  19912. }
  19913. if (data instanceof BABYLON.Buffer) {
  19914. if (!stride) {
  19915. stride = data.getStrideSize();
  19916. }
  19917. this._buffer = data;
  19918. this._ownsBuffer = false;
  19919. }
  19920. else {
  19921. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced);
  19922. this._ownsBuffer = true;
  19923. }
  19924. this._stride = stride;
  19925. this._offset = offset ? offset : 0;
  19926. this._size = size ? size : stride;
  19927. this._kind = kind;
  19928. }
  19929. VertexBuffer.prototype.getKind = function () {
  19930. return this._kind;
  19931. };
  19932. // Properties
  19933. VertexBuffer.prototype.isUpdatable = function () {
  19934. return this._buffer.isUpdatable();
  19935. };
  19936. VertexBuffer.prototype.getData = function () {
  19937. return this._buffer.getData();
  19938. };
  19939. VertexBuffer.prototype.getBuffer = function () {
  19940. return this._buffer.getBuffer();
  19941. };
  19942. VertexBuffer.prototype.getStrideSize = function () {
  19943. return this._stride;
  19944. };
  19945. VertexBuffer.prototype.getOffset = function () {
  19946. return this._offset;
  19947. };
  19948. VertexBuffer.prototype.getSize = function () {
  19949. return this._size;
  19950. };
  19951. VertexBuffer.prototype.getIsInstanced = function () {
  19952. return this._buffer.getIsInstanced();
  19953. };
  19954. // Methods
  19955. VertexBuffer.prototype.create = function (data) {
  19956. return this._buffer.create(data);
  19957. };
  19958. VertexBuffer.prototype.update = function (data) {
  19959. return this._buffer.update(data);
  19960. };
  19961. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  19962. return this._buffer.updateDirectly(data, offset);
  19963. };
  19964. VertexBuffer.prototype.dispose = function () {
  19965. if (this._ownsBuffer) {
  19966. this._buffer.dispose();
  19967. }
  19968. };
  19969. Object.defineProperty(VertexBuffer, "PositionKind", {
  19970. get: function () {
  19971. return VertexBuffer._PositionKind;
  19972. },
  19973. enumerable: true,
  19974. configurable: true
  19975. });
  19976. Object.defineProperty(VertexBuffer, "NormalKind", {
  19977. get: function () {
  19978. return VertexBuffer._NormalKind;
  19979. },
  19980. enumerable: true,
  19981. configurable: true
  19982. });
  19983. Object.defineProperty(VertexBuffer, "UVKind", {
  19984. get: function () {
  19985. return VertexBuffer._UVKind;
  19986. },
  19987. enumerable: true,
  19988. configurable: true
  19989. });
  19990. Object.defineProperty(VertexBuffer, "UV2Kind", {
  19991. get: function () {
  19992. return VertexBuffer._UV2Kind;
  19993. },
  19994. enumerable: true,
  19995. configurable: true
  19996. });
  19997. Object.defineProperty(VertexBuffer, "UV3Kind", {
  19998. get: function () {
  19999. return VertexBuffer._UV3Kind;
  20000. },
  20001. enumerable: true,
  20002. configurable: true
  20003. });
  20004. Object.defineProperty(VertexBuffer, "UV4Kind", {
  20005. get: function () {
  20006. return VertexBuffer._UV4Kind;
  20007. },
  20008. enumerable: true,
  20009. configurable: true
  20010. });
  20011. Object.defineProperty(VertexBuffer, "UV5Kind", {
  20012. get: function () {
  20013. return VertexBuffer._UV5Kind;
  20014. },
  20015. enumerable: true,
  20016. configurable: true
  20017. });
  20018. Object.defineProperty(VertexBuffer, "UV6Kind", {
  20019. get: function () {
  20020. return VertexBuffer._UV6Kind;
  20021. },
  20022. enumerable: true,
  20023. configurable: true
  20024. });
  20025. Object.defineProperty(VertexBuffer, "ColorKind", {
  20026. get: function () {
  20027. return VertexBuffer._ColorKind;
  20028. },
  20029. enumerable: true,
  20030. configurable: true
  20031. });
  20032. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  20033. get: function () {
  20034. return VertexBuffer._MatricesIndicesKind;
  20035. },
  20036. enumerable: true,
  20037. configurable: true
  20038. });
  20039. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  20040. get: function () {
  20041. return VertexBuffer._MatricesWeightsKind;
  20042. },
  20043. enumerable: true,
  20044. configurable: true
  20045. });
  20046. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  20047. get: function () {
  20048. return VertexBuffer._MatricesIndicesExtraKind;
  20049. },
  20050. enumerable: true,
  20051. configurable: true
  20052. });
  20053. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  20054. get: function () {
  20055. return VertexBuffer._MatricesWeightsExtraKind;
  20056. },
  20057. enumerable: true,
  20058. configurable: true
  20059. });
  20060. return VertexBuffer;
  20061. }());
  20062. // Enums
  20063. VertexBuffer._PositionKind = "position";
  20064. VertexBuffer._NormalKind = "normal";
  20065. VertexBuffer._UVKind = "uv";
  20066. VertexBuffer._UV2Kind = "uv2";
  20067. VertexBuffer._UV3Kind = "uv3";
  20068. VertexBuffer._UV4Kind = "uv4";
  20069. VertexBuffer._UV5Kind = "uv5";
  20070. VertexBuffer._UV6Kind = "uv6";
  20071. VertexBuffer._ColorKind = "color";
  20072. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  20073. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  20074. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  20075. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  20076. BABYLON.VertexBuffer = VertexBuffer;
  20077. })(BABYLON || (BABYLON = {}));
  20078. //# sourceMappingURL=babylon.vertexBuffer.js.map
  20079. var BABYLON;
  20080. (function (BABYLON) {
  20081. /**
  20082. * Creates an instance based on a source mesh.
  20083. */
  20084. var InstancedMesh = (function (_super) {
  20085. __extends(InstancedMesh, _super);
  20086. function InstancedMesh(name, source) {
  20087. var _this = _super.call(this, name, source.getScene()) || this;
  20088. source.instances.push(_this);
  20089. _this._sourceMesh = source;
  20090. _this.position.copyFrom(source.position);
  20091. _this.rotation.copyFrom(source.rotation);
  20092. _this.scaling.copyFrom(source.scaling);
  20093. if (source.rotationQuaternion) {
  20094. _this.rotationQuaternion = source.rotationQuaternion.clone();
  20095. }
  20096. _this.infiniteDistance = source.infiniteDistance;
  20097. _this.setPivotMatrix(source.getPivotMatrix());
  20098. _this.refreshBoundingInfo();
  20099. _this._syncSubMeshes();
  20100. return _this;
  20101. }
  20102. InstancedMesh.prototype.getClassName = function () {
  20103. return "InstancedMesh";
  20104. };
  20105. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  20106. // Methods
  20107. get: function () {
  20108. return this._sourceMesh.receiveShadows;
  20109. },
  20110. enumerable: true,
  20111. configurable: true
  20112. });
  20113. Object.defineProperty(InstancedMesh.prototype, "material", {
  20114. get: function () {
  20115. return this._sourceMesh.material;
  20116. },
  20117. enumerable: true,
  20118. configurable: true
  20119. });
  20120. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  20121. get: function () {
  20122. return this._sourceMesh.visibility;
  20123. },
  20124. enumerable: true,
  20125. configurable: true
  20126. });
  20127. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  20128. get: function () {
  20129. return this._sourceMesh.skeleton;
  20130. },
  20131. enumerable: true,
  20132. configurable: true
  20133. });
  20134. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  20135. get: function () {
  20136. return this._sourceMesh.renderingGroupId;
  20137. },
  20138. enumerable: true,
  20139. configurable: true
  20140. });
  20141. InstancedMesh.prototype.getTotalVertices = function () {
  20142. return this._sourceMesh.getTotalVertices();
  20143. };
  20144. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  20145. get: function () {
  20146. return this._sourceMesh;
  20147. },
  20148. enumerable: true,
  20149. configurable: true
  20150. });
  20151. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  20152. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  20153. };
  20154. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  20155. return this._sourceMesh.isVerticesDataPresent(kind);
  20156. };
  20157. InstancedMesh.prototype.getIndices = function () {
  20158. return this._sourceMesh.getIndices();
  20159. };
  20160. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  20161. get: function () {
  20162. return this._sourceMesh._positions;
  20163. },
  20164. enumerable: true,
  20165. configurable: true
  20166. });
  20167. InstancedMesh.prototype.refreshBoundingInfo = function () {
  20168. var meshBB = this._sourceMesh.getBoundingInfo();
  20169. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  20170. this._updateBoundingInfo();
  20171. };
  20172. InstancedMesh.prototype._preActivate = function () {
  20173. if (this._currentLOD) {
  20174. this._currentLOD._preActivate();
  20175. }
  20176. };
  20177. InstancedMesh.prototype._activate = function (renderId) {
  20178. if (this._currentLOD) {
  20179. this._currentLOD._registerInstanceForRenderId(this, renderId);
  20180. }
  20181. };
  20182. InstancedMesh.prototype.getLOD = function (camera) {
  20183. this._currentLOD = this.sourceMesh.getLOD(this.getScene().activeCamera, this.getBoundingInfo().boundingSphere);
  20184. if (this._currentLOD === this.sourceMesh) {
  20185. return this;
  20186. }
  20187. return this._currentLOD;
  20188. };
  20189. InstancedMesh.prototype._syncSubMeshes = function () {
  20190. this.releaseSubMeshes();
  20191. if (this._sourceMesh.subMeshes) {
  20192. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  20193. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  20194. }
  20195. }
  20196. };
  20197. InstancedMesh.prototype._generatePointsArray = function () {
  20198. return this._sourceMesh._generatePointsArray();
  20199. };
  20200. // Clone
  20201. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  20202. var result = this._sourceMesh.createInstance(name);
  20203. // Deep copy
  20204. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes"], []);
  20205. // Bounding info
  20206. this.refreshBoundingInfo();
  20207. // Parent
  20208. if (newParent) {
  20209. result.parent = newParent;
  20210. }
  20211. if (!doNotCloneChildren) {
  20212. // Children
  20213. for (var index = 0; index < this.getScene().meshes.length; index++) {
  20214. var mesh = this.getScene().meshes[index];
  20215. if (mesh.parent === this) {
  20216. mesh.clone(mesh.name, result);
  20217. }
  20218. }
  20219. }
  20220. result.computeWorldMatrix(true);
  20221. return result;
  20222. };
  20223. // Dispose
  20224. InstancedMesh.prototype.dispose = function (doNotRecurse) {
  20225. // Remove from mesh
  20226. var index = this._sourceMesh.instances.indexOf(this);
  20227. this._sourceMesh.instances.splice(index, 1);
  20228. _super.prototype.dispose.call(this, doNotRecurse);
  20229. };
  20230. return InstancedMesh;
  20231. }(BABYLON.AbstractMesh));
  20232. BABYLON.InstancedMesh = InstancedMesh;
  20233. })(BABYLON || (BABYLON = {}));
  20234. //# sourceMappingURL=babylon.instancedMesh.js.map
  20235. var BABYLON;
  20236. (function (BABYLON) {
  20237. var _InstancesBatch = (function () {
  20238. function _InstancesBatch() {
  20239. this.mustReturn = false;
  20240. this.visibleInstances = new Array();
  20241. this.renderSelf = new Array();
  20242. }
  20243. return _InstancesBatch;
  20244. }());
  20245. BABYLON._InstancesBatch = _InstancesBatch;
  20246. var Mesh = (function (_super) {
  20247. __extends(Mesh, _super);
  20248. /**
  20249. * @constructor
  20250. * @param {string} name The value used by scene.getMeshByName() to do a lookup.
  20251. * @param {Scene} scene The scene to add this mesh to.
  20252. * @param {Node} parent The parent of this mesh, if it has one
  20253. * @param {Mesh} source An optional Mesh from which geometry is shared, cloned.
  20254. * @param {boolean} doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  20255. * When false, achieved by calling a clone(), also passing False.
  20256. * This will make creation of children, recursive.
  20257. * @param {boolean} clonePhysicsImpostor When cloning, include cloning mesh physics impostor, default True.
  20258. */
  20259. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  20260. if (parent === void 0) { parent = null; }
  20261. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  20262. var _this = _super.call(this, name, scene) || this;
  20263. // Events
  20264. /**
  20265. * An event triggered before rendering the mesh
  20266. * @type {BABYLON.Observable}
  20267. */
  20268. _this.onBeforeRenderObservable = new BABYLON.Observable();
  20269. /**
  20270. * An event triggered after rendering the mesh
  20271. * @type {BABYLON.Observable}
  20272. */
  20273. _this.onAfterRenderObservable = new BABYLON.Observable();
  20274. /**
  20275. * An event triggered before drawing the mesh
  20276. * @type {BABYLON.Observable}
  20277. */
  20278. _this.onBeforeDrawObservable = new BABYLON.Observable();
  20279. // Members
  20280. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  20281. _this.instances = new Array();
  20282. _this._LODLevels = new Array();
  20283. _this._visibleInstances = {};
  20284. _this._renderIdForInstances = new Array();
  20285. _this._batchCache = new _InstancesBatch();
  20286. _this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  20287. _this._sideOrientation = Mesh._DEFAULTSIDE;
  20288. _this._areNormalsFrozen = false; // Will be used by ribbons mainly
  20289. // Will be used to save a source mesh reference, If any
  20290. _this._source = null;
  20291. if (source) {
  20292. // Source mesh
  20293. _this._source = source;
  20294. // Geometry
  20295. if (source._geometry) {
  20296. source._geometry.applyToMesh(_this);
  20297. }
  20298. // Deep copy
  20299. BABYLON.Tools.DeepCopy(source, _this, ["name", "material", "skeleton", "instances", "parent"], ["_poseMatrix"]);
  20300. // Parent
  20301. _this.parent = source.parent;
  20302. // Pivot
  20303. _this.setPivotMatrix(source.getPivotMatrix());
  20304. _this.id = name + "." + source.id;
  20305. // Material
  20306. _this.material = source.material;
  20307. var index;
  20308. if (!doNotCloneChildren) {
  20309. // Children
  20310. for (index = 0; index < scene.meshes.length; index++) {
  20311. var mesh = scene.meshes[index];
  20312. if (mesh.parent === source) {
  20313. // doNotCloneChildren is always going to be False
  20314. var newChild = mesh.clone(name + "." + mesh.name, _this, doNotCloneChildren);
  20315. }
  20316. }
  20317. }
  20318. // Physics clone
  20319. var physicsEngine = _this.getScene().getPhysicsEngine();
  20320. if (clonePhysicsImpostor && physicsEngine) {
  20321. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  20322. if (impostor) {
  20323. _this.physicsImpostor = impostor.clone(_this);
  20324. }
  20325. }
  20326. // Particles
  20327. for (index = 0; index < scene.particleSystems.length; index++) {
  20328. var system = scene.particleSystems[index];
  20329. if (system.emitter === source) {
  20330. system.clone(system.name, _this);
  20331. }
  20332. }
  20333. _this.computeWorldMatrix(true);
  20334. }
  20335. // Parent
  20336. if (parent !== null) {
  20337. _this.parent = parent;
  20338. }
  20339. return _this;
  20340. }
  20341. Object.defineProperty(Mesh, "FRONTSIDE", {
  20342. /**
  20343. * Mesh side orientation : usually the external or front surface
  20344. */
  20345. get: function () {
  20346. return Mesh._FRONTSIDE;
  20347. },
  20348. enumerable: true,
  20349. configurable: true
  20350. });
  20351. Object.defineProperty(Mesh, "BACKSIDE", {
  20352. /**
  20353. * Mesh side orientation : usually the internal or back surface
  20354. */
  20355. get: function () {
  20356. return Mesh._BACKSIDE;
  20357. },
  20358. enumerable: true,
  20359. configurable: true
  20360. });
  20361. Object.defineProperty(Mesh, "DOUBLESIDE", {
  20362. /**
  20363. * Mesh side orientation : both internal and external or front and back surfaces
  20364. */
  20365. get: function () {
  20366. return Mesh._DOUBLESIDE;
  20367. },
  20368. enumerable: true,
  20369. configurable: true
  20370. });
  20371. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  20372. /**
  20373. * Mesh side orientation : by default, `FRONTSIDE`
  20374. */
  20375. get: function () {
  20376. return Mesh._DEFAULTSIDE;
  20377. },
  20378. enumerable: true,
  20379. configurable: true
  20380. });
  20381. Object.defineProperty(Mesh, "NO_CAP", {
  20382. /**
  20383. * Mesh cap setting : no cap
  20384. */
  20385. get: function () {
  20386. return Mesh._NO_CAP;
  20387. },
  20388. enumerable: true,
  20389. configurable: true
  20390. });
  20391. Object.defineProperty(Mesh, "CAP_START", {
  20392. /**
  20393. * Mesh cap setting : one cap at the beginning of the mesh
  20394. */
  20395. get: function () {
  20396. return Mesh._CAP_START;
  20397. },
  20398. enumerable: true,
  20399. configurable: true
  20400. });
  20401. Object.defineProperty(Mesh, "CAP_END", {
  20402. /**
  20403. * Mesh cap setting : one cap at the end of the mesh
  20404. */
  20405. get: function () {
  20406. return Mesh._CAP_END;
  20407. },
  20408. enumerable: true,
  20409. configurable: true
  20410. });
  20411. Object.defineProperty(Mesh, "CAP_ALL", {
  20412. /**
  20413. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  20414. */
  20415. get: function () {
  20416. return Mesh._CAP_ALL;
  20417. },
  20418. enumerable: true,
  20419. configurable: true
  20420. });
  20421. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  20422. set: function (callback) {
  20423. if (this._onBeforeDrawObserver) {
  20424. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  20425. }
  20426. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  20427. },
  20428. enumerable: true,
  20429. configurable: true
  20430. });
  20431. Object.defineProperty(Mesh.prototype, "source", {
  20432. get: function () {
  20433. return this._source;
  20434. },
  20435. enumerable: true,
  20436. configurable: true
  20437. });
  20438. // Methods
  20439. Mesh.prototype.getClassName = function () {
  20440. return "Mesh";
  20441. };
  20442. /**
  20443. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  20444. */
  20445. Mesh.prototype.toString = function (fullDetails) {
  20446. var ret = _super.prototype.toString.call(this, fullDetails);
  20447. ret += ", n vertices: " + this.getTotalVertices();
  20448. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  20449. if (this.animations) {
  20450. for (var i = 0; i < this.animations.length; i++) {
  20451. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  20452. }
  20453. }
  20454. if (fullDetails) {
  20455. ret += ", flat shading: " + (this._geometry ? (this.getVerticesData(BABYLON.VertexBuffer.PositionKind).length / 3 === this.getIndices().length ? "YES" : "NO") : "UNKNOWN");
  20456. }
  20457. return ret;
  20458. };
  20459. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  20460. get: function () {
  20461. return this._LODLevels.length > 0;
  20462. },
  20463. enumerable: true,
  20464. configurable: true
  20465. });
  20466. Mesh.prototype._sortLODLevels = function () {
  20467. this._LODLevels.sort(function (a, b) {
  20468. if (a.distance < b.distance) {
  20469. return 1;
  20470. }
  20471. if (a.distance > b.distance) {
  20472. return -1;
  20473. }
  20474. return 0;
  20475. });
  20476. };
  20477. /**
  20478. * Add a mesh as LOD level triggered at the given distance.
  20479. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  20480. * @param {number} distance The distance from the center of the object to show this level
  20481. * @param {Mesh} mesh The mesh to be added as LOD level
  20482. * @return {Mesh} This mesh (for chaining)
  20483. */
  20484. Mesh.prototype.addLODLevel = function (distance, mesh) {
  20485. if (mesh && mesh._masterMesh) {
  20486. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  20487. return this;
  20488. }
  20489. var level = new BABYLON.Internals.MeshLODLevel(distance, mesh);
  20490. this._LODLevels.push(level);
  20491. if (mesh) {
  20492. mesh._masterMesh = this;
  20493. }
  20494. this._sortLODLevels();
  20495. return this;
  20496. };
  20497. /**
  20498. * Returns the LOD level mesh at the passed distance or null if not found.
  20499. * It is related to the method `addLODLevel(distance, mesh)`.
  20500. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  20501. */
  20502. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  20503. for (var index = 0; index < this._LODLevels.length; index++) {
  20504. var level = this._LODLevels[index];
  20505. if (level.distance === distance) {
  20506. return level.mesh;
  20507. }
  20508. }
  20509. return null;
  20510. };
  20511. /**
  20512. * Remove a mesh from the LOD array
  20513. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  20514. * @param {Mesh} mesh The mesh to be removed.
  20515. * @return {Mesh} This mesh (for chaining)
  20516. */
  20517. Mesh.prototype.removeLODLevel = function (mesh) {
  20518. for (var index = 0; index < this._LODLevels.length; index++) {
  20519. if (this._LODLevels[index].mesh === mesh) {
  20520. this._LODLevels.splice(index, 1);
  20521. if (mesh) {
  20522. mesh._masterMesh = null;
  20523. }
  20524. }
  20525. }
  20526. this._sortLODLevels();
  20527. return this;
  20528. };
  20529. /**
  20530. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  20531. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  20532. */
  20533. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  20534. if (!this._LODLevels || this._LODLevels.length === 0) {
  20535. return this;
  20536. }
  20537. var distanceToCamera = (boundingSphere ? boundingSphere : this.getBoundingInfo().boundingSphere).centerWorld.subtract(camera.globalPosition).length();
  20538. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  20539. if (this.onLODLevelSelection) {
  20540. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  20541. }
  20542. return this;
  20543. }
  20544. for (var index = 0; index < this._LODLevels.length; index++) {
  20545. var level = this._LODLevels[index];
  20546. if (level.distance < distanceToCamera) {
  20547. if (level.mesh) {
  20548. level.mesh._preActivate();
  20549. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  20550. }
  20551. if (this.onLODLevelSelection) {
  20552. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  20553. }
  20554. return level.mesh;
  20555. }
  20556. }
  20557. if (this.onLODLevelSelection) {
  20558. this.onLODLevelSelection(distanceToCamera, this, this);
  20559. }
  20560. return this;
  20561. };
  20562. Object.defineProperty(Mesh.prototype, "geometry", {
  20563. /**
  20564. * Returns the mesh internal Geometry object.
  20565. */
  20566. get: function () {
  20567. return this._geometry;
  20568. },
  20569. enumerable: true,
  20570. configurable: true
  20571. });
  20572. /**
  20573. * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  20574. */
  20575. Mesh.prototype.getTotalVertices = function () {
  20576. if (!this._geometry) {
  20577. return 0;
  20578. }
  20579. return this._geometry.getTotalVertices();
  20580. };
  20581. /**
  20582. * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
  20583. * 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.
  20584. * Returns null if the mesh has no geometry or no vertex buffer.
  20585. * Possible `kind` values :
  20586. * - BABYLON.VertexBuffer.PositionKind
  20587. * - BABYLON.VertexBuffer.UVKind
  20588. * - BABYLON.VertexBuffer.UV2Kind
  20589. * - BABYLON.VertexBuffer.UV3Kind
  20590. * - BABYLON.VertexBuffer.UV4Kind
  20591. * - BABYLON.VertexBuffer.UV5Kind
  20592. * - BABYLON.VertexBuffer.UV6Kind
  20593. * - BABYLON.VertexBuffer.ColorKind
  20594. * - BABYLON.VertexBuffer.MatricesIndicesKind
  20595. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  20596. * - BABYLON.VertexBuffer.MatricesWeightsKind
  20597. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  20598. */
  20599. Mesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  20600. if (!this._geometry) {
  20601. return null;
  20602. }
  20603. return this._geometry.getVerticesData(kind, copyWhenShared);
  20604. };
  20605. /**
  20606. * Returns the mesh VertexBuffer object from the requested `kind` : positions, indices, normals, etc.
  20607. * Returns `undefined` if the mesh has no geometry.
  20608. * Possible `kind` values :
  20609. * - BABYLON.VertexBuffer.PositionKind
  20610. * - BABYLON.VertexBuffer.UVKind
  20611. * - BABYLON.VertexBuffer.UV2Kind
  20612. * - BABYLON.VertexBuffer.UV3Kind
  20613. * - BABYLON.VertexBuffer.UV4Kind
  20614. * - BABYLON.VertexBuffer.UV5Kind
  20615. * - BABYLON.VertexBuffer.UV6Kind
  20616. * - BABYLON.VertexBuffer.ColorKind
  20617. * - BABYLON.VertexBuffer.MatricesIndicesKind
  20618. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  20619. * - BABYLON.VertexBuffer.MatricesWeightsKind
  20620. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  20621. */
  20622. Mesh.prototype.getVertexBuffer = function (kind) {
  20623. if (!this._geometry) {
  20624. return undefined;
  20625. }
  20626. return this._geometry.getVertexBuffer(kind);
  20627. };
  20628. /**
  20629. * Returns a boolean depending on the existence of the Vertex Data for the requested `kind`.
  20630. * Possible `kind` values :
  20631. * - BABYLON.VertexBuffer.PositionKind
  20632. * - BABYLON.VertexBuffer.UVKind
  20633. * - BABYLON.VertexBuffer.UV2Kind
  20634. * - BABYLON.VertexBuffer.UV3Kind
  20635. * - BABYLON.VertexBuffer.UV4Kind
  20636. * - BABYLON.VertexBuffer.UV5Kind
  20637. * - BABYLON.VertexBuffer.UV6Kind
  20638. * - BABYLON.VertexBuffer.ColorKind
  20639. * - BABYLON.VertexBuffer.MatricesIndicesKind
  20640. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  20641. * - BABYLON.VertexBuffer.MatricesWeightsKind
  20642. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  20643. */
  20644. Mesh.prototype.isVerticesDataPresent = function (kind) {
  20645. if (!this._geometry) {
  20646. if (this._delayInfo) {
  20647. return this._delayInfo.indexOf(kind) !== -1;
  20648. }
  20649. return false;
  20650. }
  20651. return this._geometry.isVerticesDataPresent(kind);
  20652. };
  20653. /**
  20654. * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
  20655. * Possible `kind` values :
  20656. * - BABYLON.VertexBuffer.PositionKind
  20657. * - BABYLON.VertexBuffer.UVKind
  20658. * - BABYLON.VertexBuffer.UV2Kind
  20659. * - BABYLON.VertexBuffer.UV3Kind
  20660. * - BABYLON.VertexBuffer.UV4Kind
  20661. * - BABYLON.VertexBuffer.UV5Kind
  20662. * - BABYLON.VertexBuffer.UV6Kind
  20663. * - BABYLON.VertexBuffer.ColorKind
  20664. * - BABYLON.VertexBuffer.MatricesIndicesKind
  20665. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  20666. * - BABYLON.VertexBuffer.MatricesWeightsKind
  20667. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  20668. */
  20669. Mesh.prototype.getVerticesDataKinds = function () {
  20670. if (!this._geometry) {
  20671. var result = [];
  20672. if (this._delayInfo) {
  20673. this._delayInfo.forEach(function (kind, index, array) {
  20674. result.push(kind);
  20675. });
  20676. }
  20677. return result;
  20678. }
  20679. return this._geometry.getVerticesDataKinds();
  20680. };
  20681. /**
  20682. * Returns a positive integer : the total number of indices in this mesh geometry.
  20683. * Returns zero if the mesh has no geometry.
  20684. */
  20685. Mesh.prototype.getTotalIndices = function () {
  20686. if (!this._geometry) {
  20687. return 0;
  20688. }
  20689. return this._geometry.getTotalIndices();
  20690. };
  20691. /**
  20692. * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
  20693. * 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.
  20694. * Returns an empty array if the mesh has no geometry.
  20695. */
  20696. Mesh.prototype.getIndices = function (copyWhenShared) {
  20697. if (!this._geometry) {
  20698. return [];
  20699. }
  20700. return this._geometry.getIndices(copyWhenShared);
  20701. };
  20702. Object.defineProperty(Mesh.prototype, "isBlocked", {
  20703. get: function () {
  20704. return this._masterMesh !== null && this._masterMesh !== undefined;
  20705. },
  20706. enumerable: true,
  20707. configurable: true
  20708. });
  20709. /**
  20710. * Boolean : true once the mesh is ready after all the delayed process (loading, etc) are complete.
  20711. */
  20712. Mesh.prototype.isReady = function () {
  20713. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  20714. return false;
  20715. }
  20716. return _super.prototype.isReady.call(this);
  20717. };
  20718. /**
  20719. * Boolean : true if the mesh has been disposed.
  20720. */
  20721. Mesh.prototype.isDisposed = function () {
  20722. return this._isDisposed;
  20723. };
  20724. Object.defineProperty(Mesh.prototype, "sideOrientation", {
  20725. get: function () {
  20726. return this._sideOrientation;
  20727. },
  20728. /**
  20729. * Sets the mesh side orientation : BABYLON.Mesh.FRONTSIDE, BABYLON.Mesh.BACKSIDE, BABYLON.Mesh.DOUBLESIDE or BABYLON.Mesh.DEFAULTSIDE
  20730. * tuto : http://doc.babylonjs.com/tutorials/Discover_Basic_Elements#side-orientation
  20731. */
  20732. set: function (sideO) {
  20733. this._sideOrientation = sideO;
  20734. },
  20735. enumerable: true,
  20736. configurable: true
  20737. });
  20738. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  20739. /**
  20740. * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
  20741. * This property is pertinent only for updatable parametric shapes.
  20742. */
  20743. get: function () {
  20744. return this._areNormalsFrozen;
  20745. },
  20746. enumerable: true,
  20747. configurable: true
  20748. });
  20749. /**
  20750. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  20751. * It has no effect at all on other shapes.
  20752. * It prevents the mesh normals from being recomputed on next `positions` array update.
  20753. */
  20754. Mesh.prototype.freezeNormals = function () {
  20755. this._areNormalsFrozen = true;
  20756. };
  20757. /**
  20758. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  20759. * It has no effect at all on other shapes.
  20760. * It reactivates the mesh normals computation if it was previously frozen.
  20761. */
  20762. Mesh.prototype.unfreezeNormals = function () {
  20763. this._areNormalsFrozen = false;
  20764. };
  20765. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  20766. /**
  20767. * Overrides instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  20768. */
  20769. set: function (count) {
  20770. this._overridenInstanceCount = count;
  20771. },
  20772. enumerable: true,
  20773. configurable: true
  20774. });
  20775. // Methods
  20776. Mesh.prototype._preActivate = function () {
  20777. var sceneRenderId = this.getScene().getRenderId();
  20778. if (this._preActivateId === sceneRenderId) {
  20779. return;
  20780. }
  20781. this._preActivateId = sceneRenderId;
  20782. this._visibleInstances = null;
  20783. };
  20784. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  20785. if (this._visibleInstances) {
  20786. this._visibleInstances.intermediateDefaultRenderId = renderId;
  20787. }
  20788. };
  20789. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  20790. if (!this._visibleInstances) {
  20791. this._visibleInstances = {};
  20792. this._visibleInstances.defaultRenderId = renderId;
  20793. this._visibleInstances.selfDefaultRenderId = this._renderId;
  20794. }
  20795. if (!this._visibleInstances[renderId]) {
  20796. this._visibleInstances[renderId] = new Array();
  20797. }
  20798. this._visibleInstances[renderId].push(instance);
  20799. };
  20800. /**
  20801. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  20802. * This means the mesh underlying bounding box and sphere are recomputed.
  20803. */
  20804. Mesh.prototype.refreshBoundingInfo = function () {
  20805. if (this._boundingInfo.isLocked) {
  20806. return;
  20807. }
  20808. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  20809. if (data) {
  20810. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  20811. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  20812. }
  20813. if (this.subMeshes) {
  20814. for (var index = 0; index < this.subMeshes.length; index++) {
  20815. this.subMeshes[index].refreshBoundingInfo();
  20816. }
  20817. }
  20818. this._updateBoundingInfo();
  20819. };
  20820. Mesh.prototype._createGlobalSubMesh = function () {
  20821. var totalVertices = this.getTotalVertices();
  20822. if (!totalVertices || !this.getIndices()) {
  20823. return null;
  20824. }
  20825. this.releaseSubMeshes();
  20826. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  20827. };
  20828. Mesh.prototype.subdivide = function (count) {
  20829. if (count < 1) {
  20830. return;
  20831. }
  20832. var totalIndices = this.getTotalIndices();
  20833. var subdivisionSize = (totalIndices / count) | 0;
  20834. var offset = 0;
  20835. // Ensure that subdivisionSize is a multiple of 3
  20836. while (subdivisionSize % 3 !== 0) {
  20837. subdivisionSize++;
  20838. }
  20839. this.releaseSubMeshes();
  20840. for (var index = 0; index < count; index++) {
  20841. if (offset >= totalIndices) {
  20842. break;
  20843. }
  20844. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  20845. offset += subdivisionSize;
  20846. }
  20847. this.synchronizeInstances();
  20848. };
  20849. /**
  20850. * Sets the vertex data of the mesh geometry for the requested `kind`.
  20851. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  20852. * The `data` are either a numeric array either a Float32Array.
  20853. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  20854. * 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).
  20855. * Note that a new underlying VertexBuffer object is created each call.
  20856. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  20857. *
  20858. * Possible `kind` values :
  20859. * - BABYLON.VertexBuffer.PositionKind
  20860. * - BABYLON.VertexBuffer.UVKind
  20861. * - BABYLON.VertexBuffer.UV2Kind
  20862. * - BABYLON.VertexBuffer.UV3Kind
  20863. * - BABYLON.VertexBuffer.UV4Kind
  20864. * - BABYLON.VertexBuffer.UV5Kind
  20865. * - BABYLON.VertexBuffer.UV6Kind
  20866. * - BABYLON.VertexBuffer.ColorKind
  20867. * - BABYLON.VertexBuffer.MatricesIndicesKind
  20868. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  20869. * - BABYLON.VertexBuffer.MatricesWeightsKind
  20870. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  20871. */
  20872. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  20873. if (!this._geometry) {
  20874. var vertexData = new BABYLON.VertexData();
  20875. vertexData.set(data, kind);
  20876. var scene = this.getScene();
  20877. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  20878. }
  20879. else {
  20880. this._geometry.setVerticesData(kind, data, updatable, stride);
  20881. }
  20882. };
  20883. Mesh.prototype.setVerticesBuffer = function (buffer) {
  20884. if (!this._geometry) {
  20885. var scene = this.getScene();
  20886. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene).applyToMesh(this);
  20887. }
  20888. this._geometry.setVerticesBuffer(buffer);
  20889. };
  20890. /**
  20891. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  20892. * If the mesh has no geometry, it is simply returned as it is.
  20893. * The `data` are either a numeric array either a Float32Array.
  20894. * No new underlying VertexBuffer object is created.
  20895. * 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.
  20896. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  20897. *
  20898. * Possible `kind` values :
  20899. * - BABYLON.VertexBuffer.PositionKind
  20900. * - BABYLON.VertexBuffer.UVKind
  20901. * - BABYLON.VertexBuffer.UV2Kind
  20902. * - BABYLON.VertexBuffer.UV3Kind
  20903. * - BABYLON.VertexBuffer.UV4Kind
  20904. * - BABYLON.VertexBuffer.UV5Kind
  20905. * - BABYLON.VertexBuffer.UV6Kind
  20906. * - BABYLON.VertexBuffer.ColorKind
  20907. * - BABYLON.VertexBuffer.MatricesIndicesKind
  20908. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  20909. * - BABYLON.VertexBuffer.MatricesWeightsKind
  20910. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  20911. */
  20912. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  20913. if (!this._geometry) {
  20914. return;
  20915. }
  20916. if (!makeItUnique) {
  20917. this._geometry.updateVerticesData(kind, data, updateExtends);
  20918. }
  20919. else {
  20920. this.makeGeometryUnique();
  20921. this.updateVerticesData(kind, data, updateExtends, false);
  20922. }
  20923. };
  20924. /**
  20925. * Deprecated since BabylonJS v2.3
  20926. */
  20927. Mesh.prototype.updateVerticesDataDirectly = function (kind, data, offset, makeItUnique) {
  20928. BABYLON.Tools.Warn("Mesh.updateVerticesDataDirectly deprecated since 2.3.");
  20929. if (!this._geometry) {
  20930. return;
  20931. }
  20932. if (!makeItUnique) {
  20933. this._geometry.updateVerticesDataDirectly(kind, data, offset);
  20934. }
  20935. else {
  20936. this.makeGeometryUnique();
  20937. this.updateVerticesDataDirectly(kind, data, offset, false);
  20938. }
  20939. };
  20940. /**
  20941. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  20942. * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  20943. * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
  20944. * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
  20945. */
  20946. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  20947. if (computeNormals === void 0) { computeNormals = true; }
  20948. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  20949. positionFunction(positions);
  20950. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  20951. if (computeNormals) {
  20952. var indices = this.getIndices();
  20953. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  20954. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  20955. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  20956. }
  20957. };
  20958. Mesh.prototype.makeGeometryUnique = function () {
  20959. if (!this._geometry) {
  20960. return;
  20961. }
  20962. var oldGeometry = this._geometry;
  20963. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  20964. oldGeometry.releaseForMesh(this, true);
  20965. geometry.applyToMesh(this);
  20966. };
  20967. /**
  20968. * Sets the mesh indices.
  20969. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  20970. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  20971. * This method creates a new index buffer each call.
  20972. */
  20973. Mesh.prototype.setIndices = function (indices, totalVertices) {
  20974. if (!this._geometry) {
  20975. var vertexData = new BABYLON.VertexData();
  20976. vertexData.indices = indices;
  20977. var scene = this.getScene();
  20978. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, false, this);
  20979. }
  20980. else {
  20981. this._geometry.setIndices(indices, totalVertices);
  20982. }
  20983. };
  20984. /**
  20985. * Invert the geometry to move from a right handed system to a left handed one.
  20986. */
  20987. Mesh.prototype.toLeftHanded = function () {
  20988. if (!this._geometry) {
  20989. return;
  20990. }
  20991. this._geometry.toLeftHanded();
  20992. };
  20993. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  20994. var engine = this.getScene().getEngine();
  20995. // Wireframe
  20996. var indexToBind;
  20997. if (this._unIndexed) {
  20998. indexToBind = null;
  20999. }
  21000. else {
  21001. switch (fillMode) {
  21002. case BABYLON.Material.PointFillMode:
  21003. indexToBind = null;
  21004. break;
  21005. case BABYLON.Material.WireFrameFillMode:
  21006. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  21007. break;
  21008. default:
  21009. case BABYLON.Material.TriangleFillMode:
  21010. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  21011. break;
  21012. }
  21013. }
  21014. // VBOs
  21015. this._geometry._bind(effect, indexToBind);
  21016. };
  21017. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  21018. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  21019. return;
  21020. }
  21021. this.onBeforeDrawObservable.notifyObservers(this);
  21022. var engine = this.getScene().getEngine();
  21023. // Draw order
  21024. switch (fillMode) {
  21025. case BABYLON.Material.PointFillMode:
  21026. engine.drawPointClouds(subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  21027. break;
  21028. case BABYLON.Material.WireFrameFillMode:
  21029. if (this._unIndexed) {
  21030. engine.drawUnIndexed(false, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  21031. }
  21032. else {
  21033. engine.draw(false, 0, instancesCount > 0 ? subMesh.linesIndexCount / 2 : subMesh.linesIndexCount, instancesCount);
  21034. }
  21035. break;
  21036. default:
  21037. if (this._unIndexed) {
  21038. engine.drawUnIndexed(true, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  21039. }
  21040. else {
  21041. engine.draw(true, subMesh.indexStart, subMesh.indexCount, instancesCount);
  21042. }
  21043. }
  21044. };
  21045. /**
  21046. * Registers for this mesh a javascript function called just before the rendering process.
  21047. * This function is passed the current mesh and doesn't return anything.
  21048. */
  21049. Mesh.prototype.registerBeforeRender = function (func) {
  21050. this.onBeforeRenderObservable.add(func);
  21051. };
  21052. /**
  21053. * Disposes a previously registered javascript function called before the rendering.
  21054. * This function is passed the current mesh and doesn't return anything.
  21055. */
  21056. Mesh.prototype.unregisterBeforeRender = function (func) {
  21057. this.onBeforeRenderObservable.removeCallback(func);
  21058. };
  21059. /**
  21060. * Registers for this mesh a javascript function called just after the rendering is complete.
  21061. * This function is passed the current mesh and doesn't return anything.
  21062. */
  21063. Mesh.prototype.registerAfterRender = function (func) {
  21064. this.onAfterRenderObservable.add(func);
  21065. };
  21066. /**
  21067. * Disposes a previously registered javascript function called after the rendering.
  21068. * This function is passed the current mesh and doesn't return anything.
  21069. */
  21070. Mesh.prototype.unregisterAfterRender = function (func) {
  21071. this.onAfterRenderObservable.removeCallback(func);
  21072. };
  21073. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  21074. var scene = this.getScene();
  21075. this._batchCache.mustReturn = false;
  21076. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  21077. this._batchCache.visibleInstances[subMeshId] = null;
  21078. if (this._visibleInstances) {
  21079. var currentRenderId = scene.getRenderId();
  21080. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  21081. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  21082. var selfRenderId = this._renderId;
  21083. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  21084. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  21085. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  21086. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  21087. }
  21088. if (this._batchCache.visibleInstances[subMeshId] && this._batchCache.visibleInstances[subMeshId].length) {
  21089. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  21090. this._batchCache.mustReturn = true;
  21091. return this._batchCache;
  21092. }
  21093. if (currentRenderId !== selfRenderId) {
  21094. this._batchCache.renderSelf[subMeshId] = false;
  21095. }
  21096. }
  21097. this._renderIdForInstances[subMeshId] = currentRenderId;
  21098. }
  21099. return this._batchCache;
  21100. };
  21101. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  21102. var visibleInstances = batch.visibleInstances[subMesh._id];
  21103. var matricesCount = visibleInstances.length + 1;
  21104. var bufferSize = matricesCount * 16 * 4;
  21105. var currentInstancesBufferSize = this._instancesBufferSize;
  21106. var instancesBuffer = this._instancesBuffer;
  21107. while (this._instancesBufferSize < bufferSize) {
  21108. this._instancesBufferSize *= 2;
  21109. }
  21110. if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) {
  21111. this._instancesData = new Float32Array(this._instancesBufferSize / 4);
  21112. }
  21113. var offset = 0;
  21114. var instancesCount = 0;
  21115. var world = this.getWorldMatrix();
  21116. if (batch.renderSelf[subMesh._id]) {
  21117. world.copyToArray(this._instancesData, offset);
  21118. offset += 16;
  21119. instancesCount++;
  21120. }
  21121. if (visibleInstances) {
  21122. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  21123. var instance = visibleInstances[instanceIndex];
  21124. instance.getWorldMatrix().copyToArray(this._instancesData, offset);
  21125. offset += 16;
  21126. instancesCount++;
  21127. }
  21128. }
  21129. if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) {
  21130. if (instancesBuffer) {
  21131. instancesBuffer.dispose();
  21132. }
  21133. instancesBuffer = new BABYLON.Buffer(engine, this._instancesData, true, 16, false, true);
  21134. this._instancesBuffer = instancesBuffer;
  21135. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  21136. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  21137. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  21138. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  21139. }
  21140. else {
  21141. instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount);
  21142. }
  21143. this.geometry._bind(effect);
  21144. this._draw(subMesh, fillMode, instancesCount);
  21145. engine.unbindInstanceAttributes();
  21146. };
  21147. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  21148. var scene = this.getScene();
  21149. var engine = scene.getEngine();
  21150. if (hardwareInstancedRendering) {
  21151. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  21152. }
  21153. else {
  21154. if (batch.renderSelf[subMesh._id]) {
  21155. // Draw
  21156. if (onBeforeDraw) {
  21157. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  21158. }
  21159. this._draw(subMesh, fillMode, this._overridenInstanceCount);
  21160. }
  21161. if (batch.visibleInstances[subMesh._id]) {
  21162. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  21163. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  21164. // World
  21165. var world = instance.getWorldMatrix();
  21166. if (onBeforeDraw) {
  21167. onBeforeDraw(true, world, effectiveMaterial);
  21168. }
  21169. // Draw
  21170. this._draw(subMesh, fillMode);
  21171. }
  21172. }
  21173. }
  21174. };
  21175. /**
  21176. * Triggers the draw call for the mesh.
  21177. * Usually, you don't need to call this method by your own because the mesh rendering is handled by the scene rendering manager.
  21178. */
  21179. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  21180. var scene = this.getScene();
  21181. // Managing instances
  21182. var batch = this._getInstancesRenderList(subMesh._id);
  21183. if (batch.mustReturn) {
  21184. return;
  21185. }
  21186. // Checking geometry state
  21187. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  21188. return;
  21189. }
  21190. var callbackIndex;
  21191. this.onBeforeRenderObservable.notifyObservers(this);
  21192. var engine = scene.getEngine();
  21193. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  21194. // Material
  21195. var effectiveMaterial = subMesh.getMaterial();
  21196. if (!effectiveMaterial || !effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  21197. return;
  21198. }
  21199. // Outline - step 1
  21200. var savedDepthWrite = engine.getDepthWrite();
  21201. if (this.renderOutline) {
  21202. engine.setDepthWrite(false);
  21203. scene.getOutlineRenderer().render(subMesh, batch);
  21204. engine.setDepthWrite(savedDepthWrite);
  21205. }
  21206. effectiveMaterial._preBind();
  21207. var effect = effectiveMaterial.getEffect();
  21208. // Bind
  21209. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : effectiveMaterial.fillMode);
  21210. this._bind(subMesh, effect, fillMode);
  21211. var world = this.getWorldMatrix();
  21212. effectiveMaterial.bind(world, this);
  21213. // Alpha mode
  21214. if (enableAlphaMode) {
  21215. engine.setAlphaMode(effectiveMaterial.alphaMode);
  21216. }
  21217. // Draw
  21218. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, effectiveMaterial);
  21219. // Unbind
  21220. effectiveMaterial.unbind();
  21221. // Outline - step 2
  21222. if (this.renderOutline && savedDepthWrite) {
  21223. engine.setDepthWrite(true);
  21224. engine.setColorWrite(false);
  21225. scene.getOutlineRenderer().render(subMesh, batch);
  21226. engine.setColorWrite(true);
  21227. }
  21228. // Overlay
  21229. if (this.renderOverlay) {
  21230. var currentMode = engine.getAlphaMode();
  21231. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  21232. scene.getOutlineRenderer().render(subMesh, batch, true);
  21233. engine.setAlphaMode(currentMode);
  21234. }
  21235. this.onAfterRenderObservable.notifyObservers(this);
  21236. };
  21237. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  21238. if (isInstance) {
  21239. effectiveMaterial.bindOnlyWorldMatrix(world);
  21240. }
  21241. };
  21242. /**
  21243. * Returns an array populated with ParticleSystem objects whose the mesh is the emitter.
  21244. */
  21245. Mesh.prototype.getEmittedParticleSystems = function () {
  21246. var results = new Array();
  21247. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  21248. var particleSystem = this.getScene().particleSystems[index];
  21249. if (particleSystem.emitter === this) {
  21250. results.push(particleSystem);
  21251. }
  21252. }
  21253. return results;
  21254. };
  21255. /**
  21256. * Returns an array populated with ParticleSystem objects whose the mesh or its children are the emitter.
  21257. */
  21258. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  21259. var results = new Array();
  21260. var descendants = this.getDescendants();
  21261. descendants.push(this);
  21262. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  21263. var particleSystem = this.getScene().particleSystems[index];
  21264. if (descendants.indexOf(particleSystem.emitter) !== -1) {
  21265. results.push(particleSystem);
  21266. }
  21267. }
  21268. return results;
  21269. };
  21270. Mesh.prototype._checkDelayState = function () {
  21271. var scene = this.getScene();
  21272. if (this._geometry) {
  21273. this._geometry.load(scene);
  21274. }
  21275. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  21276. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  21277. this._queueLoad(this, scene);
  21278. }
  21279. };
  21280. Mesh.prototype._queueLoad = function (mesh, scene) {
  21281. var _this = this;
  21282. scene._addPendingData(mesh);
  21283. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  21284. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  21285. if (data instanceof ArrayBuffer) {
  21286. _this._delayLoadingFunction(data, _this);
  21287. }
  21288. else {
  21289. _this._delayLoadingFunction(JSON.parse(data), _this);
  21290. }
  21291. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  21292. scene._removePendingData(_this);
  21293. }, function () { }, scene.database, getBinaryData);
  21294. };
  21295. /**
  21296. * Boolean, true is the mesh in the frustum defined by the Plane objects from the `frustumPlanes` array parameter.
  21297. */
  21298. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  21299. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  21300. return false;
  21301. }
  21302. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  21303. return false;
  21304. }
  21305. this._checkDelayState();
  21306. return true;
  21307. };
  21308. /**
  21309. * Sets the mesh material by the material or multiMaterial `id` property.
  21310. * The material `id` is a string identifying the material or the multiMaterial.
  21311. * This method returns nothing.
  21312. */
  21313. Mesh.prototype.setMaterialByID = function (id) {
  21314. var materials = this.getScene().materials;
  21315. var index;
  21316. for (index = 0; index < materials.length; index++) {
  21317. if (materials[index].id === id) {
  21318. this.material = materials[index];
  21319. return;
  21320. }
  21321. }
  21322. // Multi
  21323. var multiMaterials = this.getScene().multiMaterials;
  21324. for (index = 0; index < multiMaterials.length; index++) {
  21325. if (multiMaterials[index].id === id) {
  21326. this.material = multiMaterials[index];
  21327. return;
  21328. }
  21329. }
  21330. };
  21331. /**
  21332. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  21333. */
  21334. Mesh.prototype.getAnimatables = function () {
  21335. var results = [];
  21336. if (this.material) {
  21337. results.push(this.material);
  21338. }
  21339. if (this.skeleton) {
  21340. results.push(this.skeleton);
  21341. }
  21342. return results;
  21343. };
  21344. /**
  21345. * Modifies the mesh geometry according to the passed transformation matrix.
  21346. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  21347. * The mesh normals are modified accordingly the same transformation.
  21348. * tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  21349. * Note that, under the hood, this method sets a new VertexBuffer each call.
  21350. */
  21351. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  21352. // Position
  21353. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  21354. return;
  21355. }
  21356. var submeshes = this.subMeshes.splice(0);
  21357. this._resetPointsArrayCache();
  21358. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21359. var temp = [];
  21360. var index;
  21361. for (index = 0; index < data.length; index += 3) {
  21362. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  21363. }
  21364. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  21365. // Normals
  21366. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  21367. return;
  21368. }
  21369. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  21370. temp = [];
  21371. for (index = 0; index < data.length; index += 3) {
  21372. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  21373. }
  21374. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  21375. // flip faces?
  21376. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  21377. this.flipFaces();
  21378. }
  21379. // Restore submeshes
  21380. this.releaseSubMeshes();
  21381. this.subMeshes = submeshes;
  21382. };
  21383. /**
  21384. * Modifies the mesh geometry according to its own current World Matrix.
  21385. * The mesh World Matrix is then reset.
  21386. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  21387. * tuto : tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  21388. * Note that, under the hood, this method sets a new VertexBuffer each call.
  21389. */
  21390. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  21391. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  21392. this.scaling.copyFromFloats(1, 1, 1);
  21393. this.position.copyFromFloats(0, 0, 0);
  21394. this.rotation.copyFromFloats(0, 0, 0);
  21395. //only if quaternion is already set
  21396. if (this.rotationQuaternion) {
  21397. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  21398. }
  21399. this._worldMatrix = BABYLON.Matrix.Identity();
  21400. };
  21401. // Cache
  21402. Mesh.prototype._resetPointsArrayCache = function () {
  21403. this._positions = null;
  21404. };
  21405. Mesh.prototype._generatePointsArray = function () {
  21406. if (this._positions)
  21407. return true;
  21408. this._positions = [];
  21409. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21410. if (!data) {
  21411. return false;
  21412. }
  21413. for (var index = 0; index < data.length; index += 3) {
  21414. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  21415. }
  21416. return true;
  21417. };
  21418. /**
  21419. * Returns a new Mesh object generated from the current mesh properties.
  21420. * This method must not get confused with createInstance().
  21421. * The parameter `name` is a string, the name given to the new mesh.
  21422. * The optional parameter `newParent` can be any Node object (default `null`).
  21423. * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any.
  21424. * 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.
  21425. */
  21426. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  21427. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  21428. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  21429. };
  21430. /**
  21431. * Disposes the mesh.
  21432. * This also frees the memory allocated under the hood to all the buffers used by WebGL.
  21433. */
  21434. Mesh.prototype.dispose = function (doNotRecurse) {
  21435. var _this = this;
  21436. if (this._geometry) {
  21437. this._geometry.releaseForMesh(this, true);
  21438. }
  21439. // Sources
  21440. var meshes = this.getScene().meshes;
  21441. meshes.forEach(function (mesh) {
  21442. if (mesh._source && mesh._source === _this) {
  21443. mesh._source = null;
  21444. }
  21445. });
  21446. this._source = null;
  21447. // Instances
  21448. if (this._instancesBuffer) {
  21449. this._instancesBuffer.dispose();
  21450. this._instancesBuffer = null;
  21451. }
  21452. while (this.instances.length) {
  21453. this.instances[0].dispose();
  21454. }
  21455. // Highlight layers.
  21456. var highlightLayers = this.getScene().highlightLayers;
  21457. for (var i = 0; i < highlightLayers.length; i++) {
  21458. var highlightLayer = highlightLayers[i];
  21459. if (highlightLayer) {
  21460. highlightLayer.removeMesh(this);
  21461. highlightLayer.removeExcludedMesh(this);
  21462. }
  21463. }
  21464. _super.prototype.dispose.call(this, doNotRecurse);
  21465. };
  21466. /**
  21467. * Modifies the mesh geometry according to a displacement map.
  21468. * 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.
  21469. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  21470. * This method returns nothing.
  21471. * The parameter `url` is a string, the URL from the image file is to be downloaded.
  21472. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  21473. * 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.
  21474. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  21475. * The parameter `uvScale` is an optional vector2 used to scale UV.
  21476. */
  21477. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess, uvOffset, uvScale) {
  21478. var _this = this;
  21479. var scene = this.getScene();
  21480. var onload = function (img) {
  21481. // Getting height map data
  21482. var canvas = document.createElement("canvas");
  21483. var context = canvas.getContext("2d");
  21484. var heightMapWidth = img.width;
  21485. var heightMapHeight = img.height;
  21486. canvas.width = heightMapWidth;
  21487. canvas.height = heightMapHeight;
  21488. context.drawImage(img, 0, 0);
  21489. // Create VertexData from map data
  21490. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  21491. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  21492. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale);
  21493. //execute success callback, if set
  21494. if (onSuccess) {
  21495. onSuccess(_this);
  21496. }
  21497. };
  21498. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  21499. };
  21500. /**
  21501. * Modifies the mesh geometry according to a displacementMap buffer.
  21502. * 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.
  21503. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  21504. * This method returns nothing.
  21505. * 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.
  21506. * The parameters `heightMapWidth` and `heightMapHeight` are positive integers to set the width and height of the buffer image.
  21507. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  21508. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  21509. * The parameter `uvScale` is an optional vector2 used to scale UV.
  21510. */
  21511. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale) {
  21512. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  21513. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  21514. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  21515. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  21516. return;
  21517. }
  21518. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21519. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  21520. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  21521. var position = BABYLON.Vector3.Zero();
  21522. var normal = BABYLON.Vector3.Zero();
  21523. var uv = BABYLON.Vector2.Zero();
  21524. uvOffset = uvOffset || BABYLON.Vector2.Zero();
  21525. uvScale = uvScale || new BABYLON.Vector2(1, 1);
  21526. for (var index = 0; index < positions.length; index += 3) {
  21527. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  21528. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  21529. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  21530. // Compute height
  21531. var u = ((Math.abs(uv.x * uvScale.x + uvOffset.x) * heightMapWidth) % heightMapWidth) | 0;
  21532. var v = ((Math.abs(uv.y * uvScale.y + uvOffset.y) * heightMapHeight) % heightMapHeight) | 0;
  21533. var pos = (u + v * heightMapWidth) * 4;
  21534. var r = buffer[pos] / 255.0;
  21535. var g = buffer[pos + 1] / 255.0;
  21536. var b = buffer[pos + 2] / 255.0;
  21537. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  21538. normal.normalize();
  21539. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  21540. position = position.add(normal);
  21541. position.toArray(positions, index);
  21542. }
  21543. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  21544. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  21545. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  21546. };
  21547. /**
  21548. * Modify the mesh to get a flat shading rendering.
  21549. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  21550. * This method returns nothing.
  21551. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  21552. */
  21553. Mesh.prototype.convertToFlatShadedMesh = function () {
  21554. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  21555. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  21556. var kinds = this.getVerticesDataKinds();
  21557. var vbs = [];
  21558. var data = [];
  21559. var newdata = [];
  21560. var updatableNormals = false;
  21561. var kindIndex;
  21562. var kind;
  21563. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  21564. kind = kinds[kindIndex];
  21565. var vertexBuffer = this.getVertexBuffer(kind);
  21566. if (kind === BABYLON.VertexBuffer.NormalKind) {
  21567. updatableNormals = vertexBuffer.isUpdatable();
  21568. kinds.splice(kindIndex, 1);
  21569. kindIndex--;
  21570. continue;
  21571. }
  21572. vbs[kind] = vertexBuffer;
  21573. data[kind] = vbs[kind].getData();
  21574. newdata[kind] = [];
  21575. }
  21576. // Save previous submeshes
  21577. var previousSubmeshes = this.subMeshes.slice(0);
  21578. var indices = this.getIndices();
  21579. var totalIndices = this.getTotalIndices();
  21580. // Generating unique vertices per face
  21581. var index;
  21582. for (index = 0; index < totalIndices; index++) {
  21583. var vertexIndex = indices[index];
  21584. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  21585. kind = kinds[kindIndex];
  21586. var stride = vbs[kind].getStrideSize();
  21587. for (var offset = 0; offset < stride; offset++) {
  21588. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  21589. }
  21590. }
  21591. }
  21592. // Updating faces & normal
  21593. var normals = [];
  21594. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  21595. for (index = 0; index < totalIndices; index += 3) {
  21596. indices[index] = index;
  21597. indices[index + 1] = index + 1;
  21598. indices[index + 2] = index + 2;
  21599. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  21600. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  21601. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  21602. var p1p2 = p1.subtract(p2);
  21603. var p3p2 = p3.subtract(p2);
  21604. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  21605. // Store same normals for every vertex
  21606. for (var localIndex = 0; localIndex < 3; localIndex++) {
  21607. normals.push(normal.x);
  21608. normals.push(normal.y);
  21609. normals.push(normal.z);
  21610. }
  21611. }
  21612. this.setIndices(indices);
  21613. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  21614. // Updating vertex buffers
  21615. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  21616. kind = kinds[kindIndex];
  21617. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  21618. }
  21619. // Updating submeshes
  21620. this.releaseSubMeshes();
  21621. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  21622. var previousOne = previousSubmeshes[submeshIndex];
  21623. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  21624. }
  21625. this.synchronizeInstances();
  21626. };
  21627. /**
  21628. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  21629. * In other words, more vertices, no more indices and a single bigger VBO.
  21630. * This method returns nothing.
  21631. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  21632. *
  21633. */
  21634. Mesh.prototype.convertToUnIndexedMesh = function () {
  21635. /// <summary>Remove indices by unfolding faces into buffers</summary>
  21636. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  21637. var kinds = this.getVerticesDataKinds();
  21638. var vbs = [];
  21639. var data = [];
  21640. var newdata = [];
  21641. var updatableNormals = false;
  21642. var kindIndex;
  21643. var kind;
  21644. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  21645. kind = kinds[kindIndex];
  21646. var vertexBuffer = this.getVertexBuffer(kind);
  21647. vbs[kind] = vertexBuffer;
  21648. data[kind] = vbs[kind].getData();
  21649. newdata[kind] = [];
  21650. }
  21651. // Save previous submeshes
  21652. var previousSubmeshes = this.subMeshes.slice(0);
  21653. var indices = this.getIndices();
  21654. var totalIndices = this.getTotalIndices();
  21655. // Generating unique vertices per face
  21656. var index;
  21657. for (index = 0; index < totalIndices; index++) {
  21658. var vertexIndex = indices[index];
  21659. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  21660. kind = kinds[kindIndex];
  21661. var stride = vbs[kind].getStrideSize();
  21662. for (var offset = 0; offset < stride; offset++) {
  21663. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  21664. }
  21665. }
  21666. }
  21667. // Updating indices
  21668. for (index = 0; index < totalIndices; index += 3) {
  21669. indices[index] = index;
  21670. indices[index + 1] = index + 1;
  21671. indices[index + 2] = index + 2;
  21672. }
  21673. this.setIndices(indices);
  21674. // Updating vertex buffers
  21675. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  21676. kind = kinds[kindIndex];
  21677. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  21678. }
  21679. // Updating submeshes
  21680. this.releaseSubMeshes();
  21681. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  21682. var previousOne = previousSubmeshes[submeshIndex];
  21683. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  21684. }
  21685. this._unIndexed = true;
  21686. this.synchronizeInstances();
  21687. };
  21688. /**
  21689. * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true.
  21690. * This method returns nothing.
  21691. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  21692. */
  21693. Mesh.prototype.flipFaces = function (flipNormals) {
  21694. if (flipNormals === void 0) { flipNormals = false; }
  21695. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  21696. var i;
  21697. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  21698. for (i = 0; i < vertex_data.normals.length; i++) {
  21699. vertex_data.normals[i] *= -1;
  21700. }
  21701. }
  21702. var temp;
  21703. for (i = 0; i < vertex_data.indices.length; i += 3) {
  21704. // reassign indices
  21705. temp = vertex_data.indices[i + 1];
  21706. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  21707. vertex_data.indices[i + 2] = temp;
  21708. }
  21709. vertex_data.applyToMesh(this);
  21710. };
  21711. // Instances
  21712. /**
  21713. * Creates a new InstancedMesh object from the mesh model.
  21714. * An instance shares the same properties and the same material than its model.
  21715. * Only these properties of each instance can then be set individually :
  21716. * - position
  21717. * - rotation
  21718. * - rotationQuaternion
  21719. * - setPivotMatrix
  21720. * - scaling
  21721. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_Instances
  21722. * Warning : this method is not supported for Line mesh and LineSystem
  21723. */
  21724. Mesh.prototype.createInstance = function (name) {
  21725. return new BABYLON.InstancedMesh(name, this);
  21726. };
  21727. /**
  21728. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  21729. * After this call, all the mesh instances have the same submeshes than the current mesh.
  21730. * This method returns nothing.
  21731. */
  21732. Mesh.prototype.synchronizeInstances = function () {
  21733. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  21734. var instance = this.instances[instanceIndex];
  21735. instance._syncSubMeshes();
  21736. }
  21737. };
  21738. /**
  21739. * Simplify the mesh according to the given array of settings.
  21740. * Function will return immediately and will simplify async. It returns nothing.
  21741. * @param settings a collection of simplification settings.
  21742. * @param parallelProcessing should all levels calculate parallel or one after the other.
  21743. * @param type the type of simplification to run.
  21744. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  21745. */
  21746. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  21747. if (parallelProcessing === void 0) { parallelProcessing = true; }
  21748. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  21749. this.getScene().simplificationQueue.addTask({
  21750. settings: settings,
  21751. parallelProcessing: parallelProcessing,
  21752. mesh: this,
  21753. simplificationType: simplificationType,
  21754. successCallback: successCallback
  21755. });
  21756. };
  21757. /**
  21758. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  21759. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  21760. * This should be used together with the simplification to avoid disappearing triangles.
  21761. * @param successCallback an optional success callback to be called after the optimization finished.
  21762. */
  21763. Mesh.prototype.optimizeIndices = function (successCallback) {
  21764. var _this = this;
  21765. var indices = this.getIndices();
  21766. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21767. var vectorPositions = [];
  21768. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  21769. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  21770. }
  21771. var dupes = [];
  21772. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  21773. var realPos = vectorPositions.length - 1 - iteration;
  21774. var testedPosition = vectorPositions[realPos];
  21775. for (var j = 0; j < realPos; ++j) {
  21776. var againstPosition = vectorPositions[j];
  21777. if (testedPosition.equals(againstPosition)) {
  21778. dupes[realPos] = j;
  21779. break;
  21780. }
  21781. }
  21782. }, function () {
  21783. for (var i = 0; i < indices.length; ++i) {
  21784. indices[i] = dupes[indices[i]] || indices[i];
  21785. }
  21786. //indices are now reordered
  21787. var originalSubMeshes = _this.subMeshes.slice(0);
  21788. _this.setIndices(indices);
  21789. _this.subMeshes = originalSubMeshes;
  21790. if (successCallback) {
  21791. successCallback(_this);
  21792. }
  21793. });
  21794. };
  21795. // Statics
  21796. /**
  21797. * Returns a new Mesh object what is a deep copy of the passed mesh.
  21798. * The parameter `parsedMesh` is the mesh to be copied.
  21799. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  21800. */
  21801. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  21802. var mesh = new Mesh(parsedMesh.name, scene);
  21803. mesh.id = parsedMesh.id;
  21804. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  21805. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  21806. if (parsedMesh.metadata !== undefined) {
  21807. mesh.metadata = parsedMesh.metadata;
  21808. }
  21809. if (parsedMesh.rotationQuaternion) {
  21810. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  21811. }
  21812. else if (parsedMesh.rotation) {
  21813. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  21814. }
  21815. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  21816. if (parsedMesh.localMatrix) {
  21817. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  21818. }
  21819. else if (parsedMesh.pivotMatrix) {
  21820. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  21821. }
  21822. mesh.setEnabled(parsedMesh.isEnabled);
  21823. mesh.isVisible = parsedMesh.isVisible;
  21824. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  21825. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  21826. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  21827. if (parsedMesh.applyFog !== undefined) {
  21828. mesh.applyFog = parsedMesh.applyFog;
  21829. }
  21830. if (parsedMesh.pickable !== undefined) {
  21831. mesh.isPickable = parsedMesh.pickable;
  21832. }
  21833. if (parsedMesh.alphaIndex !== undefined) {
  21834. mesh.alphaIndex = parsedMesh.alphaIndex;
  21835. }
  21836. mesh.receiveShadows = parsedMesh.receiveShadows;
  21837. mesh.billboardMode = parsedMesh.billboardMode;
  21838. if (parsedMesh.visibility !== undefined) {
  21839. mesh.visibility = parsedMesh.visibility;
  21840. }
  21841. mesh.checkCollisions = parsedMesh.checkCollisions;
  21842. if (parsedMesh.isBlocker !== undefined) {
  21843. mesh.isBlocker = parsedMesh.isBlocker;
  21844. }
  21845. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  21846. // freezeWorldMatrix
  21847. if (parsedMesh.freezeWorldMatrix) {
  21848. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  21849. }
  21850. // Parent
  21851. if (parsedMesh.parentId) {
  21852. mesh._waitingParentId = parsedMesh.parentId;
  21853. }
  21854. // Actions
  21855. if (parsedMesh.actions !== undefined) {
  21856. mesh._waitingActions = parsedMesh.actions;
  21857. }
  21858. // Overlay
  21859. if (parsedMesh.overlayAlpha !== undefined) {
  21860. mesh.overlayAlpha = parsedMesh.overlayAlpha;
  21861. }
  21862. if (parsedMesh.overlayColor !== undefined) {
  21863. mesh.overlayColor = BABYLON.Color3.FromArray(parsedMesh.overlayColor);
  21864. }
  21865. if (parsedMesh.renderOverlay !== undefined) {
  21866. mesh.renderOverlay = parsedMesh.renderOverlay;
  21867. }
  21868. // Geometry
  21869. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  21870. if (parsedMesh.delayLoadingFile) {
  21871. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  21872. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  21873. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  21874. if (parsedMesh._binaryInfo) {
  21875. mesh._binaryInfo = parsedMesh._binaryInfo;
  21876. }
  21877. mesh._delayInfo = [];
  21878. if (parsedMesh.hasUVs) {
  21879. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  21880. }
  21881. if (parsedMesh.hasUVs2) {
  21882. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  21883. }
  21884. if (parsedMesh.hasUVs3) {
  21885. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  21886. }
  21887. if (parsedMesh.hasUVs4) {
  21888. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  21889. }
  21890. if (parsedMesh.hasUVs5) {
  21891. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  21892. }
  21893. if (parsedMesh.hasUVs6) {
  21894. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  21895. }
  21896. if (parsedMesh.hasColors) {
  21897. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  21898. }
  21899. if (parsedMesh.hasMatricesIndices) {
  21900. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  21901. }
  21902. if (parsedMesh.hasMatricesWeights) {
  21903. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  21904. }
  21905. mesh._delayLoadingFunction = BABYLON.Geometry.ImportGeometry;
  21906. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  21907. mesh._checkDelayState();
  21908. }
  21909. }
  21910. else {
  21911. BABYLON.Geometry.ImportGeometry(parsedMesh, mesh);
  21912. }
  21913. // Material
  21914. if (parsedMesh.materialId) {
  21915. mesh.setMaterialByID(parsedMesh.materialId);
  21916. }
  21917. else {
  21918. mesh.material = null;
  21919. }
  21920. // Skeleton
  21921. if (parsedMesh.skeletonId > -1) {
  21922. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  21923. if (parsedMesh.numBoneInfluencers) {
  21924. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  21925. }
  21926. }
  21927. // Animations
  21928. if (parsedMesh.animations) {
  21929. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  21930. var parsedAnimation = parsedMesh.animations[animationIndex];
  21931. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  21932. }
  21933. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  21934. }
  21935. if (parsedMesh.autoAnimate) {
  21936. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  21937. }
  21938. // Layer Mask
  21939. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  21940. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  21941. }
  21942. else {
  21943. mesh.layerMask = 0x0FFFFFFF;
  21944. }
  21945. //(Deprecated) physics
  21946. if (parsedMesh.physicsImpostor) {
  21947. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  21948. mass: parsedMesh.physicsMass,
  21949. friction: parsedMesh.physicsFriction,
  21950. restitution: parsedMesh.physicsRestitution
  21951. }, scene);
  21952. }
  21953. // Instances
  21954. if (parsedMesh.instances) {
  21955. for (var index = 0; index < parsedMesh.instances.length; index++) {
  21956. var parsedInstance = parsedMesh.instances[index];
  21957. var instance = mesh.createInstance(parsedInstance.name);
  21958. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  21959. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  21960. if (parsedInstance.parentId) {
  21961. instance._waitingParentId = parsedInstance.parentId;
  21962. }
  21963. if (parsedInstance.rotationQuaternion) {
  21964. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  21965. }
  21966. else if (parsedInstance.rotation) {
  21967. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  21968. }
  21969. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  21970. instance.checkCollisions = mesh.checkCollisions;
  21971. if (parsedMesh.animations) {
  21972. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  21973. parsedAnimation = parsedMesh.animations[animationIndex];
  21974. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  21975. }
  21976. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  21977. }
  21978. }
  21979. }
  21980. return mesh;
  21981. };
  21982. /**
  21983. * Creates a ribbon mesh.
  21984. * Please consider using the same method from the MeshBuilder class instead.
  21985. * 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.
  21986. *
  21987. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  21988. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  21989. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  21990. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  21991. * 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.
  21992. * 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.
  21993. * 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
  21994. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21995. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21996. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21997. */
  21998. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  21999. return BABYLON.MeshBuilder.CreateRibbon(name, {
  22000. pathArray: pathArray,
  22001. closeArray: closeArray,
  22002. closePath: closePath,
  22003. offset: offset,
  22004. updatable: updatable,
  22005. sideOrientation: sideOrientation,
  22006. instance: instance
  22007. }, scene);
  22008. };
  22009. /**
  22010. * Creates a plane polygonal mesh. By default, this is a disc.
  22011. * Please consider using the same method from the MeshBuilder class instead.
  22012. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  22013. * 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.
  22014. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22015. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22016. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22017. */
  22018. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  22019. var options = {
  22020. radius: radius,
  22021. tessellation: tessellation,
  22022. sideOrientation: sideOrientation,
  22023. updatable: updatable
  22024. };
  22025. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  22026. };
  22027. /**
  22028. * Creates a box mesh.
  22029. * Please consider using the same method from the MeshBuilder class instead.
  22030. * The parameter `size` sets the size (float) of each box side (default 1).
  22031. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22032. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22033. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22034. */
  22035. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  22036. var options = {
  22037. size: size,
  22038. sideOrientation: sideOrientation,
  22039. updatable: updatable
  22040. };
  22041. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  22042. };
  22043. /**
  22044. * Creates a sphere mesh.
  22045. * Please consider using the same method from the MeshBuilder class instead.
  22046. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  22047. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  22048. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22049. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22050. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22051. */
  22052. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  22053. var options = {
  22054. segments: segments,
  22055. diameterX: diameter,
  22056. diameterY: diameter,
  22057. diameterZ: diameter,
  22058. sideOrientation: sideOrientation,
  22059. updatable: updatable
  22060. };
  22061. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  22062. };
  22063. /**
  22064. * Creates a cylinder or a cone mesh.
  22065. * Please consider using the same method from the MeshBuilder class instead.
  22066. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  22067. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  22068. * 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.
  22069. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  22070. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  22071. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22072. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22073. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22074. */
  22075. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  22076. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  22077. if (scene !== undefined) {
  22078. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  22079. updatable = scene;
  22080. }
  22081. scene = subdivisions;
  22082. subdivisions = 1;
  22083. }
  22084. var options = {
  22085. height: height,
  22086. diameterTop: diameterTop,
  22087. diameterBottom: diameterBottom,
  22088. tessellation: tessellation,
  22089. subdivisions: subdivisions,
  22090. sideOrientation: sideOrientation,
  22091. updatable: updatable
  22092. };
  22093. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  22094. };
  22095. // Torus (Code from SharpDX.org)
  22096. /**
  22097. * Creates a torus mesh.
  22098. * Please consider using the same method from the MeshBuilder class instead.
  22099. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  22100. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  22101. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  22102. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22103. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22104. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22105. */
  22106. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  22107. var options = {
  22108. diameter: diameter,
  22109. thickness: thickness,
  22110. tessellation: tessellation,
  22111. sideOrientation: sideOrientation,
  22112. updatable: updatable
  22113. };
  22114. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  22115. };
  22116. /**
  22117. * Creates a torus knot mesh.
  22118. * Please consider using the same method from the MeshBuilder class instead.
  22119. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  22120. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  22121. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  22122. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  22123. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22124. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22125. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22126. */
  22127. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  22128. var options = {
  22129. radius: radius,
  22130. tube: tube,
  22131. radialSegments: radialSegments,
  22132. tubularSegments: tubularSegments,
  22133. p: p,
  22134. q: q,
  22135. sideOrientation: sideOrientation,
  22136. updatable: updatable
  22137. };
  22138. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  22139. };
  22140. /**
  22141. * Creates a line mesh.
  22142. * Please consider using the same method from the MeshBuilder class instead.
  22143. * 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.
  22144. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  22145. * The parameter `points` is an array successive Vector3.
  22146. * 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
  22147. * When updating an instance, remember that only point positions can change, not the number of points.
  22148. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22149. */
  22150. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  22151. var options = {
  22152. points: points,
  22153. updatable: updatable,
  22154. instance: instance
  22155. };
  22156. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  22157. };
  22158. /**
  22159. * Creates a dashed line mesh.
  22160. * Please consider using the same method from the MeshBuilder class instead.
  22161. * 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.
  22162. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  22163. * The parameter `points` is an array successive Vector3.
  22164. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  22165. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  22166. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  22167. * 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
  22168. * When updating an instance, remember that only point positions can change, not the number of points.
  22169. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22170. */
  22171. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  22172. var options = {
  22173. points: points,
  22174. dashSize: dashSize,
  22175. gapSize: gapSize,
  22176. dashNb: dashNb,
  22177. updatable: updatable,
  22178. instance: instance
  22179. };
  22180. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  22181. };
  22182. /**
  22183. * Creates an extruded shape mesh.
  22184. * 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.
  22185. * Please consider using the same method from the MeshBuilder class instead.
  22186. *
  22187. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  22188. * 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
  22189. * extruded along the Z axis.
  22190. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  22191. * 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.
  22192. * The parameter `scale` (float, default 1) is the value to scale the shape.
  22193. * 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
  22194. * 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
  22195. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  22196. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22197. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22198. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22199. */
  22200. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  22201. var options = {
  22202. shape: shape,
  22203. path: path,
  22204. scale: scale,
  22205. rotation: rotation,
  22206. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  22207. sideOrientation: sideOrientation,
  22208. instance: instance,
  22209. updatable: updatable
  22210. };
  22211. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  22212. };
  22213. /**
  22214. * Creates an custom extruded shape mesh.
  22215. * 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.
  22216. * Please consider using the same method from the MeshBuilder class instead.
  22217. *
  22218. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  22219. * 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
  22220. * extruded along the Z axis.
  22221. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  22222. * 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
  22223. * and the distance of this point from the begining of the path :
  22224. * ```javascript
  22225. * var rotationFunction = function(i, distance) {
  22226. * // do things
  22227. * return rotationValue; }
  22228. * ```
  22229. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  22230. * 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
  22231. * and the distance of this point from the begining of the path :
  22232. * ```javascript
  22233. * var scaleFunction = function(i, distance) {
  22234. * // do things
  22235. * return scaleValue;}
  22236. * ```
  22237. * It must returns a float value that will be the scale value applied to the shape on each path point.
  22238. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  22239. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  22240. * 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
  22241. * 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
  22242. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  22243. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22244. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22245. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22246. */
  22247. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  22248. var options = {
  22249. shape: shape,
  22250. path: path,
  22251. scaleFunction: scaleFunction,
  22252. rotationFunction: rotationFunction,
  22253. ribbonCloseArray: ribbonCloseArray,
  22254. ribbonClosePath: ribbonClosePath,
  22255. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  22256. sideOrientation: sideOrientation,
  22257. instance: instance,
  22258. updatable: updatable
  22259. };
  22260. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  22261. };
  22262. /**
  22263. * Creates lathe mesh.
  22264. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  22265. * Please consider using the same method from the MeshBuilder class instead.
  22266. * 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
  22267. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  22268. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  22269. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  22270. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22271. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22272. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22273. */
  22274. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  22275. var options = {
  22276. shape: shape,
  22277. radius: radius,
  22278. tessellation: tessellation,
  22279. sideOrientation: sideOrientation,
  22280. updatable: updatable
  22281. };
  22282. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  22283. };
  22284. /**
  22285. * Creates a plane mesh.
  22286. * Please consider using the same method from the MeshBuilder class instead.
  22287. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  22288. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22289. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22290. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22291. */
  22292. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  22293. var options = {
  22294. size: size,
  22295. width: size,
  22296. height: size,
  22297. sideOrientation: sideOrientation,
  22298. updatable: updatable
  22299. };
  22300. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  22301. };
  22302. /**
  22303. * Creates a ground mesh.
  22304. * Please consider using the same method from the MeshBuilder class instead.
  22305. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  22306. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  22307. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22308. */
  22309. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  22310. var options = {
  22311. width: width,
  22312. height: height,
  22313. subdivisions: subdivisions,
  22314. updatable: updatable
  22315. };
  22316. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  22317. };
  22318. /**
  22319. * Creates a tiled ground mesh.
  22320. * Please consider using the same method from the MeshBuilder class instead.
  22321. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  22322. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  22323. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  22324. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  22325. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  22326. * numbers of subdivisions on the ground width and height of each tile.
  22327. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22328. */
  22329. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  22330. var options = {
  22331. xmin: xmin,
  22332. zmin: zmin,
  22333. xmax: xmax,
  22334. zmax: zmax,
  22335. subdivisions: subdivisions,
  22336. precision: precision,
  22337. updatable: updatable
  22338. };
  22339. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  22340. };
  22341. /**
  22342. * Creates a ground mesh from a height map.
  22343. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  22344. * Please consider using the same method from the MeshBuilder class instead.
  22345. * The parameter `url` sets the URL of the height map image resource.
  22346. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  22347. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  22348. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  22349. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  22350. * 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).
  22351. * This function is passed the newly built mesh :
  22352. * ```javascript
  22353. * function(mesh) { // do things
  22354. * return; }
  22355. * ```
  22356. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22357. */
  22358. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  22359. var options = {
  22360. width: width,
  22361. height: height,
  22362. subdivisions: subdivisions,
  22363. minHeight: minHeight,
  22364. maxHeight: maxHeight,
  22365. updatable: updatable,
  22366. onReady: onReady
  22367. };
  22368. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  22369. };
  22370. /**
  22371. * Creates a tube mesh.
  22372. * 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.
  22373. * Please consider using the same method from the MeshBuilder class instead.
  22374. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  22375. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  22376. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  22377. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  22378. * 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.
  22379. * It must return a radius value (positive float) :
  22380. * ```javascript
  22381. * var radiusFunction = function(i, distance) {
  22382. * // do things
  22383. * return radius; }
  22384. * ```
  22385. * 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
  22386. * 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
  22387. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22388. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22389. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22390. */
  22391. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  22392. var options = {
  22393. path: path,
  22394. radius: radius,
  22395. tessellation: tessellation,
  22396. radiusFunction: radiusFunction,
  22397. arc: 1,
  22398. cap: cap,
  22399. updatable: updatable,
  22400. sideOrientation: sideOrientation,
  22401. instance: instance
  22402. };
  22403. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  22404. };
  22405. /**
  22406. * Creates a polyhedron mesh.
  22407. * Please consider using the same method from the MeshBuilder class instead.
  22408. * 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
  22409. * to choose the wanted type.
  22410. * The parameter `size` (positive float, default 1) sets the polygon size.
  22411. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  22412. * 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`.
  22413. * 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
  22414. * 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)`).
  22415. * 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
  22416. * 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.
  22417. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22418. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22419. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22420. */
  22421. Mesh.CreatePolyhedron = function (name, options, scene) {
  22422. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  22423. };
  22424. /**
  22425. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  22426. * Please consider using the same method from the MeshBuilder class instead.
  22427. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  22428. * 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`).
  22429. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  22430. * 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.
  22431. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22432. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22433. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22434. */
  22435. Mesh.CreateIcoSphere = function (name, options, scene) {
  22436. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  22437. };
  22438. /**
  22439. * Creates a decal mesh.
  22440. * Please consider using the same method from the MeshBuilder class instead.
  22441. * 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.
  22442. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  22443. * The parameter `normal` (Vector3, default Vector3.Up) sets the normal of the mesh where the decal is applied onto in World coordinates.
  22444. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  22445. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  22446. */
  22447. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  22448. var options = {
  22449. position: position,
  22450. normal: normal,
  22451. size: size,
  22452. angle: angle
  22453. };
  22454. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  22455. };
  22456. // Skeletons
  22457. /**
  22458. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  22459. */
  22460. Mesh.prototype.setPositionsForCPUSkinning = function () {
  22461. var source;
  22462. if (!this._sourcePositions) {
  22463. source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  22464. this._sourcePositions = new Float32Array(source);
  22465. if (!this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable()) {
  22466. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  22467. }
  22468. }
  22469. return this._sourcePositions;
  22470. };
  22471. /**
  22472. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  22473. */
  22474. Mesh.prototype.setNormalsForCPUSkinning = function () {
  22475. var source;
  22476. if (!this._sourceNormals) {
  22477. source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  22478. this._sourceNormals = new Float32Array(source);
  22479. if (!this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable()) {
  22480. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  22481. }
  22482. }
  22483. return this._sourceNormals;
  22484. };
  22485. /**
  22486. * Update the vertex buffers by applying transformation from the bones
  22487. * @param {skeleton} skeleton to apply
  22488. */
  22489. Mesh.prototype.applySkeleton = function (skeleton) {
  22490. if (!this.geometry) {
  22491. return;
  22492. }
  22493. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  22494. return;
  22495. }
  22496. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  22497. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  22498. return this;
  22499. }
  22500. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  22501. return this;
  22502. }
  22503. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  22504. return this;
  22505. }
  22506. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  22507. return this;
  22508. }
  22509. if (!this._sourcePositions) {
  22510. var submeshes = this.subMeshes.slice();
  22511. this.setPositionsForCPUSkinning();
  22512. this.subMeshes = submeshes;
  22513. }
  22514. if (!this._sourceNormals) {
  22515. this.setNormalsForCPUSkinning();
  22516. }
  22517. // positionsData checks for not being Float32Array will only pass at most once
  22518. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  22519. if (!(positionsData instanceof Float32Array)) {
  22520. positionsData = new Float32Array(positionsData);
  22521. }
  22522. // normalsData checks for not being Float32Array will only pass at most once
  22523. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  22524. if (!(normalsData instanceof Float32Array)) {
  22525. normalsData = new Float32Array(normalsData);
  22526. }
  22527. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  22528. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  22529. var needExtras = this.numBoneInfluencers > 4;
  22530. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  22531. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  22532. var skeletonMatrices = skeleton.getTransformMatrices(this);
  22533. var tempVector3 = BABYLON.Vector3.Zero();
  22534. var finalMatrix = new BABYLON.Matrix();
  22535. var tempMatrix = new BABYLON.Matrix();
  22536. var matWeightIdx = 0;
  22537. var inf;
  22538. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  22539. var weight;
  22540. for (inf = 0; inf < 4; inf++) {
  22541. weight = matricesWeightsData[matWeightIdx + inf];
  22542. if (weight > 0) {
  22543. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[matWeightIdx + inf] * 16, weight, tempMatrix);
  22544. finalMatrix.addToSelf(tempMatrix);
  22545. }
  22546. else
  22547. break;
  22548. }
  22549. if (needExtras) {
  22550. for (inf = 0; inf < 4; inf++) {
  22551. weight = matricesWeightsExtraData[matWeightIdx + inf];
  22552. if (weight > 0) {
  22553. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesExtraData[matWeightIdx + inf] * 16, weight, tempMatrix);
  22554. finalMatrix.addToSelf(tempMatrix);
  22555. }
  22556. else
  22557. break;
  22558. }
  22559. }
  22560. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  22561. tempVector3.toArray(positionsData, index);
  22562. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  22563. tempVector3.toArray(normalsData, index);
  22564. finalMatrix.reset();
  22565. }
  22566. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  22567. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  22568. return this;
  22569. };
  22570. // Tools
  22571. /**
  22572. * Returns an object `{min:` Vector3`, max:` Vector3`}`
  22573. * This min and max Vector3 are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system
  22574. */
  22575. Mesh.MinMax = function (meshes) {
  22576. var minVector = null;
  22577. var maxVector = null;
  22578. meshes.forEach(function (mesh, index, array) {
  22579. var boundingBox = mesh.getBoundingInfo().boundingBox;
  22580. if (!minVector) {
  22581. minVector = boundingBox.minimumWorld;
  22582. maxVector = boundingBox.maximumWorld;
  22583. }
  22584. else {
  22585. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  22586. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  22587. }
  22588. });
  22589. return {
  22590. min: minVector,
  22591. max: maxVector
  22592. };
  22593. };
  22594. /**
  22595. * Returns a Vector3, the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array.
  22596. */
  22597. Mesh.Center = function (meshesOrMinMaxVector) {
  22598. var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? BABYLON.Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
  22599. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  22600. };
  22601. /**
  22602. * Merge the array of meshes into a single mesh for performance reasons.
  22603. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  22604. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  22605. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  22606. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  22607. */
  22608. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass) {
  22609. if (disposeSource === void 0) { disposeSource = true; }
  22610. var index;
  22611. if (!allow32BitsIndices) {
  22612. var totalVertices = 0;
  22613. // Counting vertices
  22614. for (index = 0; index < meshes.length; index++) {
  22615. if (meshes[index]) {
  22616. totalVertices += meshes[index].getTotalVertices();
  22617. if (totalVertices > 65536) {
  22618. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  22619. return null;
  22620. }
  22621. }
  22622. }
  22623. }
  22624. // Merge
  22625. var vertexData;
  22626. var otherVertexData;
  22627. var source;
  22628. for (index = 0; index < meshes.length; index++) {
  22629. if (meshes[index]) {
  22630. meshes[index].computeWorldMatrix(true);
  22631. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  22632. otherVertexData.transform(meshes[index].getWorldMatrix());
  22633. if (vertexData) {
  22634. vertexData.merge(otherVertexData);
  22635. }
  22636. else {
  22637. vertexData = otherVertexData;
  22638. source = meshes[index];
  22639. }
  22640. }
  22641. }
  22642. if (!meshSubclass) {
  22643. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  22644. }
  22645. vertexData.applyToMesh(meshSubclass);
  22646. // Setting properties
  22647. meshSubclass.material = source.material;
  22648. meshSubclass.checkCollisions = source.checkCollisions;
  22649. // Cleaning
  22650. if (disposeSource) {
  22651. for (index = 0; index < meshes.length; index++) {
  22652. if (meshes[index]) {
  22653. meshes[index].dispose();
  22654. }
  22655. }
  22656. }
  22657. return meshSubclass;
  22658. };
  22659. return Mesh;
  22660. }(BABYLON.AbstractMesh));
  22661. // Consts
  22662. Mesh._FRONTSIDE = 0;
  22663. Mesh._BACKSIDE = 1;
  22664. Mesh._DOUBLESIDE = 2;
  22665. Mesh._DEFAULTSIDE = 0;
  22666. Mesh._NO_CAP = 0;
  22667. Mesh._CAP_START = 1;
  22668. Mesh._CAP_END = 2;
  22669. Mesh._CAP_ALL = 3;
  22670. BABYLON.Mesh = Mesh;
  22671. })(BABYLON || (BABYLON = {}));
  22672. //# sourceMappingURL=babylon.mesh.js.map
  22673. var BABYLON;
  22674. (function (BABYLON) {
  22675. var SubMesh = (function () {
  22676. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  22677. if (createBoundingBox === void 0) { createBoundingBox = true; }
  22678. this.materialIndex = materialIndex;
  22679. this.verticesStart = verticesStart;
  22680. this.verticesCount = verticesCount;
  22681. this.indexStart = indexStart;
  22682. this.indexCount = indexCount;
  22683. this._renderId = 0;
  22684. this._mesh = mesh;
  22685. this._renderingMesh = renderingMesh || mesh;
  22686. mesh.subMeshes.push(this);
  22687. this._trianglePlanes = [];
  22688. this._id = mesh.subMeshes.length - 1;
  22689. if (createBoundingBox) {
  22690. this.refreshBoundingInfo();
  22691. mesh.computeWorldMatrix(true);
  22692. }
  22693. }
  22694. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  22695. get: function () {
  22696. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  22697. },
  22698. enumerable: true,
  22699. configurable: true
  22700. });
  22701. SubMesh.prototype.getBoundingInfo = function () {
  22702. if (this.IsGlobal) {
  22703. return this._mesh.getBoundingInfo();
  22704. }
  22705. return this._boundingInfo;
  22706. };
  22707. SubMesh.prototype.setBoundingInfo = function (boundingInfo) {
  22708. this._boundingInfo = boundingInfo;
  22709. };
  22710. SubMesh.prototype.getMesh = function () {
  22711. return this._mesh;
  22712. };
  22713. SubMesh.prototype.getRenderingMesh = function () {
  22714. return this._renderingMesh;
  22715. };
  22716. SubMesh.prototype.getMaterial = function () {
  22717. var rootMaterial = this._renderingMesh.material;
  22718. if (rootMaterial && rootMaterial instanceof BABYLON.MultiMaterial) {
  22719. var multiMaterial = rootMaterial;
  22720. return multiMaterial.getSubMaterial(this.materialIndex);
  22721. }
  22722. if (!rootMaterial) {
  22723. return this._mesh.getScene().defaultMaterial;
  22724. }
  22725. return rootMaterial;
  22726. };
  22727. // Methods
  22728. SubMesh.prototype.refreshBoundingInfo = function () {
  22729. this._lastColliderWorldVertices = null;
  22730. if (this.IsGlobal) {
  22731. return;
  22732. }
  22733. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  22734. if (!data) {
  22735. this._boundingInfo = this._mesh._boundingInfo;
  22736. return;
  22737. }
  22738. var indices = this._renderingMesh.getIndices();
  22739. var extend;
  22740. //is this the only submesh?
  22741. if (this.indexStart === 0 && this.indexCount === indices.length) {
  22742. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  22743. extend = { minimum: this._renderingMesh.getBoundingInfo().minimum.clone(), maximum: this._renderingMesh.getBoundingInfo().maximum.clone() };
  22744. }
  22745. else {
  22746. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  22747. }
  22748. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  22749. };
  22750. SubMesh.prototype._checkCollision = function (collider) {
  22751. return this.getBoundingInfo()._checkCollision(collider);
  22752. };
  22753. SubMesh.prototype.updateBoundingInfo = function (world) {
  22754. if (!this.getBoundingInfo()) {
  22755. this.refreshBoundingInfo();
  22756. }
  22757. this.getBoundingInfo().update(world);
  22758. };
  22759. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  22760. return this.getBoundingInfo().isInFrustum(frustumPlanes);
  22761. };
  22762. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  22763. return this.getBoundingInfo().isCompletelyInFrustum(frustumPlanes);
  22764. };
  22765. SubMesh.prototype.render = function (enableAlphaMode) {
  22766. this._renderingMesh.render(this, enableAlphaMode);
  22767. };
  22768. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  22769. if (!this._linesIndexBuffer) {
  22770. var linesIndices = [];
  22771. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  22772. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  22773. }
  22774. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  22775. this.linesIndexCount = linesIndices.length;
  22776. }
  22777. return this._linesIndexBuffer;
  22778. };
  22779. SubMesh.prototype.canIntersects = function (ray) {
  22780. return ray.intersectsBox(this.getBoundingInfo().boundingBox);
  22781. };
  22782. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  22783. var intersectInfo = null;
  22784. // LineMesh first as it's also a Mesh...
  22785. if (this._mesh instanceof BABYLON.LinesMesh) {
  22786. var lineMesh = this._mesh;
  22787. // Line test
  22788. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  22789. var p0 = positions[indices[index]];
  22790. var p1 = positions[indices[index + 1]];
  22791. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  22792. if (length < 0) {
  22793. continue;
  22794. }
  22795. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  22796. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  22797. if (fastCheck) {
  22798. break;
  22799. }
  22800. }
  22801. }
  22802. }
  22803. else {
  22804. // Triangles test
  22805. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  22806. var p0 = positions[indices[index]];
  22807. var p1 = positions[indices[index + 1]];
  22808. var p2 = positions[indices[index + 2]];
  22809. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  22810. if (currentIntersectInfo) {
  22811. if (currentIntersectInfo.distance < 0) {
  22812. continue;
  22813. }
  22814. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  22815. intersectInfo = currentIntersectInfo;
  22816. intersectInfo.faceId = index / 3;
  22817. if (fastCheck) {
  22818. break;
  22819. }
  22820. }
  22821. }
  22822. }
  22823. }
  22824. return intersectInfo;
  22825. };
  22826. // Clone
  22827. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  22828. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  22829. if (!this.IsGlobal) {
  22830. result._boundingInfo = new BABYLON.BoundingInfo(this.getBoundingInfo().minimum, this.getBoundingInfo().maximum);
  22831. }
  22832. return result;
  22833. };
  22834. // Dispose
  22835. SubMesh.prototype.dispose = function () {
  22836. if (this._linesIndexBuffer) {
  22837. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  22838. this._linesIndexBuffer = null;
  22839. }
  22840. // Remove from mesh
  22841. var index = this._mesh.subMeshes.indexOf(this);
  22842. this._mesh.subMeshes.splice(index, 1);
  22843. };
  22844. // Statics
  22845. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  22846. var minVertexIndex = Number.MAX_VALUE;
  22847. var maxVertexIndex = -Number.MAX_VALUE;
  22848. renderingMesh = renderingMesh || mesh;
  22849. var indices = renderingMesh.getIndices();
  22850. for (var index = startIndex; index < startIndex + indexCount; index++) {
  22851. var vertexIndex = indices[index];
  22852. if (vertexIndex < minVertexIndex)
  22853. minVertexIndex = vertexIndex;
  22854. if (vertexIndex > maxVertexIndex)
  22855. maxVertexIndex = vertexIndex;
  22856. }
  22857. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  22858. };
  22859. return SubMesh;
  22860. }());
  22861. BABYLON.SubMesh = SubMesh;
  22862. })(BABYLON || (BABYLON = {}));
  22863. //# sourceMappingURL=babylon.subMesh.js.map
  22864. var BABYLON;
  22865. (function (BABYLON) {
  22866. var MeshBuilder = (function () {
  22867. function MeshBuilder() {
  22868. }
  22869. MeshBuilder.updateSideOrientation = function (orientation, scene) {
  22870. if (orientation == BABYLON.Mesh.DOUBLESIDE) {
  22871. return BABYLON.Mesh.DOUBLESIDE;
  22872. }
  22873. if (orientation === undefined || orientation === null) {
  22874. return BABYLON.Mesh.FRONTSIDE;
  22875. }
  22876. return orientation;
  22877. };
  22878. /**
  22879. * Creates a box mesh.
  22880. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  22881. * The parameter `size` sets the size (float) of each box side (default 1).
  22882. * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`).
  22883. * 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).
  22884. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  22885. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22886. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22887. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22888. */
  22889. MeshBuilder.CreateBox = function (name, options, scene) {
  22890. var box = new BABYLON.Mesh(name, scene);
  22891. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  22892. box.sideOrientation = options.sideOrientation;
  22893. var vertexData = BABYLON.VertexData.CreateBox(options);
  22894. vertexData.applyToMesh(box, options.updatable);
  22895. return box;
  22896. };
  22897. /**
  22898. * Creates a sphere mesh.
  22899. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  22900. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  22901. * 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`).
  22902. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  22903. * 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
  22904. * 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).
  22905. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22906. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22907. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22908. */
  22909. MeshBuilder.CreateSphere = function (name, options, scene) {
  22910. var sphere = new BABYLON.Mesh(name, scene);
  22911. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  22912. sphere.sideOrientation = options.sideOrientation;
  22913. var vertexData = BABYLON.VertexData.CreateSphere(options);
  22914. vertexData.applyToMesh(sphere, options.updatable);
  22915. return sphere;
  22916. };
  22917. /**
  22918. * Creates a plane polygonal mesh. By default, this is a disc.
  22919. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#disc
  22920. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  22921. * 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.
  22922. * 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
  22923. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22924. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22925. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22926. */
  22927. MeshBuilder.CreateDisc = function (name, options, scene) {
  22928. var disc = new BABYLON.Mesh(name, scene);
  22929. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  22930. disc.sideOrientation = options.sideOrientation;
  22931. var vertexData = BABYLON.VertexData.CreateDisc(options);
  22932. vertexData.applyToMesh(disc, options.updatable);
  22933. return disc;
  22934. };
  22935. /**
  22936. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  22937. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#icosphere
  22938. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  22939. * 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`).
  22940. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  22941. * 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.
  22942. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22943. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22944. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22945. */
  22946. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  22947. var sphere = new BABYLON.Mesh(name, scene);
  22948. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  22949. sphere.sideOrientation = options.sideOrientation;
  22950. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  22951. vertexData.applyToMesh(sphere, options.updatable);
  22952. return sphere;
  22953. };
  22954. ;
  22955. /**
  22956. * Creates a ribbon mesh.
  22957. * 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.
  22958. *
  22959. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  22960. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  22961. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  22962. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  22963. * 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.
  22964. * 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.
  22965. * 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
  22966. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22967. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22968. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  22969. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22970. */
  22971. MeshBuilder.CreateRibbon = function (name, options, scene) {
  22972. var pathArray = options.pathArray;
  22973. var closeArray = options.closeArray;
  22974. var closePath = options.closePath;
  22975. var offset = options.offset;
  22976. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  22977. var instance = options.instance;
  22978. var updatable = options.updatable;
  22979. if (instance) {
  22980. // positionFunction : ribbon case
  22981. // only pathArray and sideOrientation parameters are taken into account for positions update
  22982. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum
  22983. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]);
  22984. var positionFunction = function (positions) {
  22985. var minlg = pathArray[0].length;
  22986. var i = 0;
  22987. var ns = (instance.sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  22988. for (var si = 1; si <= ns; si++) {
  22989. for (var p = 0; p < pathArray.length; p++) {
  22990. var path = pathArray[p];
  22991. var l = path.length;
  22992. minlg = (minlg < l) ? minlg : l;
  22993. var j = 0;
  22994. while (j < minlg) {
  22995. positions[i] = path[j].x;
  22996. positions[i + 1] = path[j].y;
  22997. positions[i + 2] = path[j].z;
  22998. if (path[j].x < BABYLON.Tmp.Vector3[0].x) {
  22999. BABYLON.Tmp.Vector3[0].x = path[j].x;
  23000. }
  23001. if (path[j].x > BABYLON.Tmp.Vector3[1].x) {
  23002. BABYLON.Tmp.Vector3[1].x = path[j].x;
  23003. }
  23004. if (path[j].y < BABYLON.Tmp.Vector3[0].y) {
  23005. BABYLON.Tmp.Vector3[0].y = path[j].y;
  23006. }
  23007. if (path[j].y > BABYLON.Tmp.Vector3[1].y) {
  23008. BABYLON.Tmp.Vector3[1].y = path[j].y;
  23009. }
  23010. if (path[j].z < BABYLON.Tmp.Vector3[0].z) {
  23011. BABYLON.Tmp.Vector3[0].z = path[j].z;
  23012. }
  23013. if (path[j].z > BABYLON.Tmp.Vector3[1].z) {
  23014. BABYLON.Tmp.Vector3[1].z = path[j].z;
  23015. }
  23016. j++;
  23017. i += 3;
  23018. }
  23019. if (instance._closePath) {
  23020. positions[i] = path[0].x;
  23021. positions[i + 1] = path[0].y;
  23022. positions[i + 2] = path[0].z;
  23023. i += 3;
  23024. }
  23025. }
  23026. }
  23027. };
  23028. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  23029. positionFunction(positions);
  23030. instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Vector3[1]);
  23031. instance._boundingInfo.update(instance._worldMatrix);
  23032. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  23033. if (!instance.areNormalsFrozen || instance.isFacetDataEnabled) {
  23034. var indices = instance.getIndices();
  23035. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  23036. var params = instance.isFacetDataEnabled ? instance.getFacetDataParameters() : null;
  23037. BABYLON.VertexData.ComputeNormals(positions, indices, normals, params);
  23038. if (instance._closePath) {
  23039. var indexFirst = 0;
  23040. var indexLast = 0;
  23041. for (var p = 0; p < pathArray.length; p++) {
  23042. indexFirst = instance._idx[p] * 3;
  23043. if (p + 1 < pathArray.length) {
  23044. indexLast = (instance._idx[p + 1] - 1) * 3;
  23045. }
  23046. else {
  23047. indexLast = normals.length - 3;
  23048. }
  23049. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  23050. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  23051. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  23052. normals[indexLast] = normals[indexFirst];
  23053. normals[indexLast + 1] = normals[indexFirst + 1];
  23054. normals[indexLast + 2] = normals[indexFirst + 2];
  23055. }
  23056. }
  23057. if (!(instance.areNormalsFrozen)) {
  23058. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  23059. }
  23060. }
  23061. return instance;
  23062. }
  23063. else {
  23064. var ribbon = new BABYLON.Mesh(name, scene);
  23065. ribbon.sideOrientation = sideOrientation;
  23066. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  23067. if (closePath) {
  23068. ribbon._idx = vertexData._idx;
  23069. }
  23070. ribbon._closePath = closePath;
  23071. ribbon._closeArray = closeArray;
  23072. vertexData.applyToMesh(ribbon, updatable);
  23073. return ribbon;
  23074. }
  23075. };
  23076. /**
  23077. * Creates a cylinder or a cone mesh.
  23078. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  23079. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  23080. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  23081. * 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.
  23082. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  23083. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  23084. * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  23085. * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  23086. * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  23087. * 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).
  23088. * 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
  23089. * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  23090. * 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
  23091. * 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.
  23092. * If `enclose` is false, a ring surface is one element.
  23093. * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  23094. * 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
  23095. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  23096. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  23097. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23098. */
  23099. MeshBuilder.CreateCylinder = function (name, options, scene) {
  23100. var cylinder = new BABYLON.Mesh(name, scene);
  23101. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  23102. cylinder.sideOrientation = options.sideOrientation;
  23103. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  23104. vertexData.applyToMesh(cylinder, options.updatable);
  23105. return cylinder;
  23106. };
  23107. /**
  23108. * Creates a torus mesh.
  23109. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  23110. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  23111. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  23112. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  23113. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  23114. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  23115. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23116. */
  23117. MeshBuilder.CreateTorus = function (name, options, scene) {
  23118. var torus = new BABYLON.Mesh(name, scene);
  23119. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  23120. torus.sideOrientation = options.sideOrientation;
  23121. var vertexData = BABYLON.VertexData.CreateTorus(options);
  23122. vertexData.applyToMesh(torus, options.updatable);
  23123. return torus;
  23124. };
  23125. /**
  23126. * Creates a torus knot mesh.
  23127. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  23128. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  23129. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  23130. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  23131. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  23132. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  23133. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  23134. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23135. */
  23136. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  23137. var torusKnot = new BABYLON.Mesh(name, scene);
  23138. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  23139. torusKnot.sideOrientation = options.sideOrientation;
  23140. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  23141. vertexData.applyToMesh(torusKnot, options.updatable);
  23142. return torusKnot;
  23143. };
  23144. /**
  23145. * Creates a line system mesh.
  23146. * A line system is a pool of many lines gathered in a single mesh.
  23147. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#linesystem
  23148. * 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.
  23149. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function.
  23150. * The parameter `lines` is an array of lines, each line being an array of successive Vector3.
  23151. * 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
  23152. * 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
  23153. * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines.
  23154. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23155. */
  23156. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  23157. var instance = options.instance;
  23158. var lines = options.lines;
  23159. if (instance) {
  23160. var positionFunction = function (positions) {
  23161. var i = 0;
  23162. for (var l = 0; l < lines.length; l++) {
  23163. var points = lines[l];
  23164. for (var p = 0; p < points.length; p++) {
  23165. positions[i] = points[p].x;
  23166. positions[i + 1] = points[p].y;
  23167. positions[i + 2] = points[p].z;
  23168. i += 3;
  23169. }
  23170. }
  23171. };
  23172. instance.updateMeshPositions(positionFunction, false);
  23173. return instance;
  23174. }
  23175. // line system creation
  23176. var lineSystem = new BABYLON.LinesMesh(name, scene);
  23177. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  23178. vertexData.applyToMesh(lineSystem, options.updatable);
  23179. return lineSystem;
  23180. };
  23181. /**
  23182. * Creates a line mesh.
  23183. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lines
  23184. * 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.
  23185. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  23186. * The parameter `points` is an array successive Vector3.
  23187. * 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
  23188. * When updating an instance, remember that only point positions can change, not the number of points.
  23189. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23190. */
  23191. MeshBuilder.CreateLines = function (name, options, scene) {
  23192. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance }, scene);
  23193. return lines;
  23194. };
  23195. /**
  23196. * Creates a dashed line mesh.
  23197. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#dashed-lines
  23198. * 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.
  23199. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  23200. * The parameter `points` is an array successive Vector3.
  23201. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  23202. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  23203. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  23204. * 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
  23205. * When updating an instance, remember that only point positions can change, not the number of points.
  23206. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23207. */
  23208. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  23209. var points = options.points;
  23210. var instance = options.instance;
  23211. var gapSize = options.gapSize;
  23212. var dashNb = options.dashNb;
  23213. var dashSize = options.dashSize;
  23214. if (instance) {
  23215. var positionFunction = function (positions) {
  23216. var curvect = BABYLON.Vector3.Zero();
  23217. var nbSeg = positions.length / 6;
  23218. var lg = 0;
  23219. var nb = 0;
  23220. var shft = 0;
  23221. var dashshft = 0;
  23222. var curshft = 0;
  23223. var p = 0;
  23224. var i = 0;
  23225. var j = 0;
  23226. for (i = 0; i < points.length - 1; i++) {
  23227. points[i + 1].subtractToRef(points[i], curvect);
  23228. lg += curvect.length();
  23229. }
  23230. shft = lg / nbSeg;
  23231. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  23232. for (i = 0; i < points.length - 1; i++) {
  23233. points[i + 1].subtractToRef(points[i], curvect);
  23234. nb = Math.floor(curvect.length() / shft);
  23235. curvect.normalize();
  23236. j = 0;
  23237. while (j < nb && p < positions.length) {
  23238. curshft = shft * j;
  23239. positions[p] = points[i].x + curshft * curvect.x;
  23240. positions[p + 1] = points[i].y + curshft * curvect.y;
  23241. positions[p + 2] = points[i].z + curshft * curvect.z;
  23242. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  23243. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  23244. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  23245. p += 6;
  23246. j++;
  23247. }
  23248. }
  23249. while (p < positions.length) {
  23250. positions[p] = points[i].x;
  23251. positions[p + 1] = points[i].y;
  23252. positions[p + 2] = points[i].z;
  23253. p += 3;
  23254. }
  23255. };
  23256. instance.updateMeshPositions(positionFunction, false);
  23257. return instance;
  23258. }
  23259. // dashed lines creation
  23260. var dashedLines = new BABYLON.LinesMesh(name, scene);
  23261. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  23262. vertexData.applyToMesh(dashedLines, options.updatable);
  23263. dashedLines.dashSize = dashSize;
  23264. dashedLines.gapSize = gapSize;
  23265. return dashedLines;
  23266. };
  23267. /**
  23268. * Creates an extruded shape mesh.
  23269. * 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.
  23270. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#extruded-shapes
  23271. *
  23272. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  23273. * 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
  23274. * extruded along the Z axis.
  23275. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  23276. * 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.
  23277. * The parameter `scale` (float, default 1) is the value to scale the shape.
  23278. * 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
  23279. * 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
  23280. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  23281. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  23282. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  23283. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  23284. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23285. */
  23286. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  23287. var path = options.path;
  23288. var shape = options.shape;
  23289. var scale = options.scale || 1;
  23290. var rotation = options.rotation || 0;
  23291. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  23292. var updatable = options.updatable;
  23293. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  23294. var instance = options.instance;
  23295. var invertUV = options.invertUV || false;
  23296. return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, scale, rotation, null, null, false, false, cap, false, scene, updatable, sideOrientation, instance, invertUV);
  23297. };
  23298. /**
  23299. * Creates an custom extruded shape mesh.
  23300. * 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.
  23301. * tuto :http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#custom-extruded-shapes
  23302. *
  23303. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  23304. * 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
  23305. * extruded along the Z axis.
  23306. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  23307. * 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
  23308. * and the distance of this point from the begining of the path :
  23309. * ```javascript
  23310. * var rotationFunction = function(i, distance) {
  23311. * // do things
  23312. * return rotationValue; }
  23313. * ```
  23314. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  23315. * 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
  23316. * and the distance of this point from the begining of the path :
  23317. * ```javascript
  23318. * var scaleFunction = function(i, distance) {
  23319. * // do things
  23320. * return scaleValue;}
  23321. * ```
  23322. * It must returns a float value that will be the scale value applied to the shape on each path point.
  23323. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  23324. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  23325. * 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
  23326. * 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
  23327. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  23328. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  23329. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  23330. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  23331. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23332. */
  23333. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  23334. var path = options.path;
  23335. var shape = options.shape;
  23336. var scaleFunction = options.scaleFunction || (function () { return 1; });
  23337. var rotationFunction = options.rotationFunction || (function () { return 0; });
  23338. var ribbonCloseArray = options.ribbonCloseArray || false;
  23339. var ribbonClosePath = options.ribbonClosePath || false;
  23340. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  23341. var updatable = options.updatable;
  23342. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  23343. var instance = options.instance;
  23344. var invertUV = options.invertUV || false;
  23345. return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, null, null, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, true, scene, updatable, sideOrientation, instance, invertUV);
  23346. };
  23347. /**
  23348. * Creates lathe mesh.
  23349. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  23350. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lathe
  23351. *
  23352. * 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
  23353. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  23354. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  23355. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  23356. * 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.
  23357. * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc".
  23358. * 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
  23359. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  23360. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  23361. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  23362. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23363. */
  23364. MeshBuilder.CreateLathe = function (name, options, scene) {
  23365. var arc = options.arc ? ((options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc) : 1.0;
  23366. var closed = (options.closed === undefined) ? true : options.closed;
  23367. var shape = options.shape;
  23368. var radius = options.radius || 1;
  23369. var tessellation = options.tessellation || 64;
  23370. var updatable = options.updatable;
  23371. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  23372. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  23373. var pi2 = Math.PI * 2;
  23374. var paths = new Array();
  23375. var invertUV = options.invertUV || false;
  23376. var i = 0;
  23377. var p = 0;
  23378. var step = pi2 / tessellation * arc;
  23379. var rotated;
  23380. var path = new Array();
  23381. ;
  23382. for (i = 0; i <= tessellation; i++) {
  23383. var path = [];
  23384. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  23385. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  23386. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  23387. }
  23388. for (p = 0; p < shape.length; p++) {
  23389. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  23390. path.push(rotated);
  23391. }
  23392. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  23393. 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));
  23394. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  23395. }
  23396. paths.push(path);
  23397. }
  23398. // lathe ribbon
  23399. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV }, scene);
  23400. return lathe;
  23401. };
  23402. /**
  23403. * Creates a plane mesh.
  23404. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  23405. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  23406. * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`).
  23407. * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane.
  23408. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  23409. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  23410. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23411. */
  23412. MeshBuilder.CreatePlane = function (name, options, scene) {
  23413. var plane = new BABYLON.Mesh(name, scene);
  23414. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  23415. plane.sideOrientation = options.sideOrientation;
  23416. var vertexData = BABYLON.VertexData.CreatePlane(options);
  23417. vertexData.applyToMesh(plane, options.updatable);
  23418. if (options.sourcePlane) {
  23419. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  23420. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  23421. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  23422. plane.rotate(vectorProduct, product);
  23423. }
  23424. return plane;
  23425. };
  23426. /**
  23427. * Creates a ground mesh.
  23428. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  23429. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  23430. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  23431. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23432. */
  23433. MeshBuilder.CreateGround = function (name, options, scene) {
  23434. var ground = new BABYLON.GroundMesh(name, scene);
  23435. ground._setReady(false);
  23436. ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  23437. ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  23438. ground._width = options.width || 1;
  23439. ground._height = options.height || 1;
  23440. ground._maxX = ground._width / 2;
  23441. ground._maxZ = ground._height / 2;
  23442. ground._minX = -ground._maxX;
  23443. ground._minZ = -ground._maxZ;
  23444. var vertexData = BABYLON.VertexData.CreateGround(options);
  23445. vertexData.applyToMesh(ground, options.updatable);
  23446. ground._setReady(true);
  23447. return ground;
  23448. };
  23449. /**
  23450. * Creates a tiled ground mesh.
  23451. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  23452. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  23453. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  23454. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  23455. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  23456. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  23457. * numbers of subdivisions on the ground width and height of each tile.
  23458. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23459. */
  23460. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  23461. var tiledGround = new BABYLON.Mesh(name, scene);
  23462. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  23463. vertexData.applyToMesh(tiledGround, options.updatable);
  23464. return tiledGround;
  23465. };
  23466. /**
  23467. * Creates a ground mesh from a height map.
  23468. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  23469. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  23470. * The parameter `url` sets the URL of the height map image resource.
  23471. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  23472. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  23473. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  23474. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  23475. * 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).
  23476. * This function is passed the newly built mesh :
  23477. * ```javascript
  23478. * function(mesh) { // do things
  23479. * return; }
  23480. * ```
  23481. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23482. */
  23483. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  23484. var width = options.width || 10.0;
  23485. var height = options.height || 10.0;
  23486. var subdivisions = options.subdivisions || 1 | 0;
  23487. var minHeight = options.minHeight || 0.0;
  23488. var maxHeight = options.maxHeight || 10.0;
  23489. var updatable = options.updatable;
  23490. var onReady = options.onReady;
  23491. var ground = new BABYLON.GroundMesh(name, scene);
  23492. ground._subdivisionsX = subdivisions;
  23493. ground._subdivisionsY = subdivisions;
  23494. ground._width = width;
  23495. ground._height = height;
  23496. ground._maxX = ground._width / 2.0;
  23497. ground._maxZ = ground._height / 2.0;
  23498. ground._minX = -ground._maxX;
  23499. ground._minZ = -ground._maxZ;
  23500. ground._setReady(false);
  23501. var onload = function (img) {
  23502. // Getting height map data
  23503. var canvas = document.createElement("canvas");
  23504. var context = canvas.getContext("2d");
  23505. var bufferWidth = img.width;
  23506. var bufferHeight = img.height;
  23507. canvas.width = bufferWidth;
  23508. canvas.height = bufferHeight;
  23509. context.drawImage(img, 0, 0);
  23510. // Create VertexData from map data
  23511. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  23512. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  23513. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  23514. width: width, height: height,
  23515. subdivisions: subdivisions,
  23516. minHeight: minHeight, maxHeight: maxHeight,
  23517. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  23518. });
  23519. vertexData.applyToMesh(ground, updatable);
  23520. ground._setReady(true);
  23521. //execute ready callback, if set
  23522. if (onReady) {
  23523. onReady(ground);
  23524. }
  23525. };
  23526. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  23527. return ground;
  23528. };
  23529. /**
  23530. * Creates a tube mesh.
  23531. * 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.
  23532. *
  23533. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  23534. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  23535. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  23536. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  23537. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  23538. * 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.
  23539. * It must return a radius value (positive float) :
  23540. * ```javascript
  23541. * var radiusFunction = function(i, distance) {
  23542. * // do things
  23543. * return radius; }
  23544. * ```
  23545. * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc.
  23546. * 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
  23547. * 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
  23548. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  23549. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  23550. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  23551. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23552. */
  23553. MeshBuilder.CreateTube = function (name, options, scene) {
  23554. var path = options.path;
  23555. var radius = options.radius || 1.0;
  23556. var tessellation = options.tessellation || 64 | 0;
  23557. var radiusFunction = options.radiusFunction;
  23558. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  23559. var invertUV = options.invertUV || false;
  23560. var updatable = options.updatable;
  23561. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  23562. var instance = options.instance;
  23563. options.arc = (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  23564. // tube geometry
  23565. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  23566. var tangents = path3D.getTangents();
  23567. var normals = path3D.getNormals();
  23568. var distances = path3D.getDistances();
  23569. var pi2 = Math.PI * 2;
  23570. var step = pi2 / tessellation * arc;
  23571. var returnRadius = function () { return radius; };
  23572. var radiusFunctionFinal = radiusFunction || returnRadius;
  23573. var circlePath;
  23574. var rad;
  23575. var normal;
  23576. var rotated;
  23577. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  23578. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  23579. for (var i = 0; i < path.length; i++) {
  23580. rad = radiusFunctionFinal(i, distances[i]); // current radius
  23581. circlePath = Array(); // current circle array
  23582. normal = normals[i]; // current normal
  23583. for (var t = 0; t < tessellation; t++) {
  23584. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  23585. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  23586. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  23587. rotated.scaleInPlace(rad).addInPlace(path[i]);
  23588. circlePath[t] = rotated;
  23589. }
  23590. circlePaths[index] = circlePath;
  23591. index++;
  23592. }
  23593. // cap
  23594. var capPath = function (nbPoints, pathIndex) {
  23595. var pointCap = Array();
  23596. for (var i = 0; i < nbPoints; i++) {
  23597. pointCap.push(path[pathIndex]);
  23598. }
  23599. return pointCap;
  23600. };
  23601. switch (cap) {
  23602. case BABYLON.Mesh.NO_CAP:
  23603. break;
  23604. case BABYLON.Mesh.CAP_START:
  23605. circlePaths[0] = capPath(tessellation, 0);
  23606. circlePaths[1] = circlePaths[2].slice(0);
  23607. break;
  23608. case BABYLON.Mesh.CAP_END:
  23609. circlePaths[index] = circlePaths[index - 1].slice(0);
  23610. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  23611. break;
  23612. case BABYLON.Mesh.CAP_ALL:
  23613. circlePaths[0] = capPath(tessellation, 0);
  23614. circlePaths[1] = circlePaths[2].slice(0);
  23615. circlePaths[index] = circlePaths[index - 1].slice(0);
  23616. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  23617. break;
  23618. default:
  23619. break;
  23620. }
  23621. return circlePaths;
  23622. };
  23623. var path3D;
  23624. var pathArray;
  23625. if (instance) {
  23626. var arc = options.arc || instance.arc;
  23627. path3D = (instance.path3D).update(path);
  23628. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  23629. instance = MeshBuilder.CreateRibbon(null, { pathArray: pathArray, instance: instance });
  23630. instance.path3D = path3D;
  23631. instance.pathArray = pathArray;
  23632. instance.arc = arc;
  23633. return instance;
  23634. }
  23635. // tube creation
  23636. path3D = new BABYLON.Path3D(path);
  23637. var newPathArray = new Array();
  23638. cap = (cap < 0 || cap > 3) ? 0 : cap;
  23639. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  23640. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV }, scene);
  23641. tube.pathArray = pathArray;
  23642. tube.path3D = path3D;
  23643. tube.tessellation = tessellation;
  23644. tube.cap = cap;
  23645. tube.arc = options.arc;
  23646. return tube;
  23647. };
  23648. /**
  23649. * Creates a polyhedron mesh.
  23650. *
  23651. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#polyhedron
  23652. * 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
  23653. * to choose the wanted type.
  23654. * The parameter `size` (positive float, default 1) sets the polygon size.
  23655. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  23656. * 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`.
  23657. * 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
  23658. * 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)`).
  23659. * 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
  23660. * 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.
  23661. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  23662. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  23663. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23664. */
  23665. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  23666. var polyhedron = new BABYLON.Mesh(name, scene);
  23667. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  23668. polyhedron.sideOrientation = options.sideOrientation;
  23669. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  23670. vertexData.applyToMesh(polyhedron, options.updatable);
  23671. return polyhedron;
  23672. };
  23673. /**
  23674. * Creates a decal mesh.
  23675. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#decals
  23676. * 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.
  23677. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  23678. * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates.
  23679. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  23680. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  23681. */
  23682. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  23683. var indices = sourceMesh.getIndices();
  23684. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  23685. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  23686. var position = options.position || BABYLON.Vector3.Zero();
  23687. var normal = options.normal || BABYLON.Vector3.Up();
  23688. var size = options.size || new BABYLON.Vector3(1, 1, 1);
  23689. var angle = options.angle || 0;
  23690. // Getting correct rotation
  23691. if (!normal) {
  23692. var target = new BABYLON.Vector3(0, 0, 1);
  23693. var camera = sourceMesh.getScene().activeCamera;
  23694. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  23695. normal = camera.globalPosition.subtract(cameraWorldTarget);
  23696. }
  23697. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  23698. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  23699. var pitch = Math.atan2(normal.y, len);
  23700. // Matrix
  23701. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  23702. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  23703. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  23704. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  23705. var vertexData = new BABYLON.VertexData();
  23706. vertexData.indices = [];
  23707. vertexData.positions = [];
  23708. vertexData.normals = [];
  23709. vertexData.uvs = [];
  23710. var currentVertexDataIndex = 0;
  23711. var extractDecalVector3 = function (indexId) {
  23712. var vertexId = indices[indexId];
  23713. var result = new BABYLON.PositionNormalVertex();
  23714. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  23715. // Send vector to decal local world
  23716. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  23717. // Get normal
  23718. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  23719. result.normal = BABYLON.Vector3.TransformNormal(result.normal, transformMatrix);
  23720. return result;
  23721. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  23722. var clip = function (vertices, axis) {
  23723. if (vertices.length === 0) {
  23724. return vertices;
  23725. }
  23726. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  23727. var clipVertices = function (v0, v1) {
  23728. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  23729. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  23730. };
  23731. var result = new Array();
  23732. for (var index = 0; index < vertices.length; index += 3) {
  23733. var v1Out;
  23734. var v2Out;
  23735. var v3Out;
  23736. var total = 0;
  23737. var nV1, nV2, nV3, nV4;
  23738. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  23739. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  23740. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  23741. v1Out = d1 > 0;
  23742. v2Out = d2 > 0;
  23743. v3Out = d3 > 0;
  23744. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  23745. switch (total) {
  23746. case 0:
  23747. result.push(vertices[index]);
  23748. result.push(vertices[index + 1]);
  23749. result.push(vertices[index + 2]);
  23750. break;
  23751. case 1:
  23752. if (v1Out) {
  23753. nV1 = vertices[index + 1];
  23754. nV2 = vertices[index + 2];
  23755. nV3 = clipVertices(vertices[index], nV1);
  23756. nV4 = clipVertices(vertices[index], nV2);
  23757. }
  23758. if (v2Out) {
  23759. nV1 = vertices[index];
  23760. nV2 = vertices[index + 2];
  23761. nV3 = clipVertices(vertices[index + 1], nV1);
  23762. nV4 = clipVertices(vertices[index + 1], nV2);
  23763. result.push(nV3);
  23764. result.push(nV2.clone());
  23765. result.push(nV1.clone());
  23766. result.push(nV2.clone());
  23767. result.push(nV3.clone());
  23768. result.push(nV4);
  23769. break;
  23770. }
  23771. if (v3Out) {
  23772. nV1 = vertices[index];
  23773. nV2 = vertices[index + 1];
  23774. nV3 = clipVertices(vertices[index + 2], nV1);
  23775. nV4 = clipVertices(vertices[index + 2], nV2);
  23776. }
  23777. result.push(nV1.clone());
  23778. result.push(nV2.clone());
  23779. result.push(nV3);
  23780. result.push(nV4);
  23781. result.push(nV3.clone());
  23782. result.push(nV2.clone());
  23783. break;
  23784. case 2:
  23785. if (!v1Out) {
  23786. nV1 = vertices[index].clone();
  23787. nV2 = clipVertices(nV1, vertices[index + 1]);
  23788. nV3 = clipVertices(nV1, vertices[index + 2]);
  23789. result.push(nV1);
  23790. result.push(nV2);
  23791. result.push(nV3);
  23792. }
  23793. if (!v2Out) {
  23794. nV1 = vertices[index + 1].clone();
  23795. nV2 = clipVertices(nV1, vertices[index + 2]);
  23796. nV3 = clipVertices(nV1, vertices[index]);
  23797. result.push(nV1);
  23798. result.push(nV2);
  23799. result.push(nV3);
  23800. }
  23801. if (!v3Out) {
  23802. nV1 = vertices[index + 2].clone();
  23803. nV2 = clipVertices(nV1, vertices[index]);
  23804. nV3 = clipVertices(nV1, vertices[index + 1]);
  23805. result.push(nV1);
  23806. result.push(nV2);
  23807. result.push(nV3);
  23808. }
  23809. break;
  23810. case 3:
  23811. break;
  23812. }
  23813. }
  23814. return result;
  23815. };
  23816. for (var index = 0; index < indices.length; index += 3) {
  23817. var faceVertices = new Array();
  23818. faceVertices.push(extractDecalVector3(index));
  23819. faceVertices.push(extractDecalVector3(index + 1));
  23820. faceVertices.push(extractDecalVector3(index + 2));
  23821. // Clip
  23822. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  23823. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  23824. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  23825. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  23826. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  23827. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  23828. if (faceVertices.length === 0) {
  23829. continue;
  23830. }
  23831. // Add UVs and get back to world
  23832. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  23833. var vertex = faceVertices[vIndex];
  23834. //TODO check for Int32Array | Uint32Array | Uint16Array
  23835. vertexData.indices.push(currentVertexDataIndex);
  23836. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  23837. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  23838. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  23839. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  23840. currentVertexDataIndex++;
  23841. }
  23842. }
  23843. // Return mesh
  23844. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  23845. vertexData.applyToMesh(decal);
  23846. decal.position = position.clone();
  23847. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  23848. return decal;
  23849. };
  23850. // Privates
  23851. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV) {
  23852. // extrusion geometry
  23853. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  23854. var tangents = path3D.getTangents();
  23855. var normals = path3D.getNormals();
  23856. var binormals = path3D.getBinormals();
  23857. var distances = path3D.getDistances();
  23858. var angle = 0;
  23859. var returnScale = function () { return scale; };
  23860. var returnRotation = function () { return rotation; };
  23861. var rotate = custom ? rotateFunction : returnRotation;
  23862. var scl = custom ? scaleFunction : returnScale;
  23863. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  23864. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  23865. for (var i = 0; i < curve.length; i++) {
  23866. var shapePath = new Array();
  23867. var angleStep = rotate(i, distances[i]);
  23868. var scaleRatio = scl(i, distances[i]);
  23869. for (var p = 0; p < shape.length; p++) {
  23870. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  23871. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  23872. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  23873. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  23874. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  23875. shapePath[p] = rotated;
  23876. }
  23877. shapePaths[index] = shapePath;
  23878. angle += angleStep;
  23879. index++;
  23880. }
  23881. // cap
  23882. var capPath = function (shapePath) {
  23883. var pointCap = Array();
  23884. var barycenter = BABYLON.Vector3.Zero();
  23885. var i;
  23886. for (i = 0; i < shapePath.length; i++) {
  23887. barycenter.addInPlace(shapePath[i]);
  23888. }
  23889. barycenter.scaleInPlace(1.0 / shapePath.length);
  23890. for (i = 0; i < shapePath.length; i++) {
  23891. pointCap.push(barycenter);
  23892. }
  23893. return pointCap;
  23894. };
  23895. switch (cap) {
  23896. case BABYLON.Mesh.NO_CAP:
  23897. break;
  23898. case BABYLON.Mesh.CAP_START:
  23899. shapePaths[0] = capPath(shapePaths[2]);
  23900. shapePaths[1] = shapePaths[2];
  23901. break;
  23902. case BABYLON.Mesh.CAP_END:
  23903. shapePaths[index] = shapePaths[index - 1];
  23904. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  23905. break;
  23906. case BABYLON.Mesh.CAP_ALL:
  23907. shapePaths[0] = capPath(shapePaths[2]);
  23908. shapePaths[1] = shapePaths[2];
  23909. shapePaths[index] = shapePaths[index - 1];
  23910. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  23911. break;
  23912. default:
  23913. break;
  23914. }
  23915. return shapePaths;
  23916. };
  23917. var path3D;
  23918. var pathArray;
  23919. if (instance) {
  23920. path3D = (instance.path3D).update(curve);
  23921. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  23922. instance = BABYLON.Mesh.CreateRibbon(null, pathArray, null, null, null, scene, null, null, instance);
  23923. return instance;
  23924. }
  23925. // extruded shape creation
  23926. path3D = new BABYLON.Path3D(curve);
  23927. var newShapePaths = new Array();
  23928. cap = (cap < 0 || cap > 3) ? 0 : cap;
  23929. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  23930. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV }, scene);
  23931. extrudedGeneric.pathArray = pathArray;
  23932. extrudedGeneric.path3D = path3D;
  23933. extrudedGeneric.cap = cap;
  23934. return extrudedGeneric;
  23935. };
  23936. return MeshBuilder;
  23937. }());
  23938. BABYLON.MeshBuilder = MeshBuilder;
  23939. })(BABYLON || (BABYLON = {}));
  23940. //# sourceMappingURL=babylon.meshBuilder.js.map
  23941. var BABYLON;
  23942. (function (BABYLON) {
  23943. var BaseTexture = (function () {
  23944. function BaseTexture(scene) {
  23945. this.hasAlpha = false;
  23946. this.getAlphaFromRGB = false;
  23947. this.level = 1;
  23948. this.coordinatesIndex = 0;
  23949. this.coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  23950. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  23951. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  23952. this.anisotropicFilteringLevel = 4;
  23953. this.isCube = false;
  23954. this.isRenderTarget = false;
  23955. this.animations = new Array();
  23956. /**
  23957. * An event triggered when the texture is disposed.
  23958. * @type {BABYLON.Observable}
  23959. */
  23960. this.onDisposeObservable = new BABYLON.Observable();
  23961. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  23962. this._scene = scene;
  23963. this._scene.textures.push(this);
  23964. this._uid = null;
  23965. }
  23966. Object.defineProperty(BaseTexture.prototype, "uid", {
  23967. get: function () {
  23968. if (!this._uid) {
  23969. this._uid = BABYLON.Tools.RandomId();
  23970. }
  23971. return this._uid;
  23972. },
  23973. enumerable: true,
  23974. configurable: true
  23975. });
  23976. BaseTexture.prototype.toString = function () {
  23977. return this.name;
  23978. };
  23979. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  23980. set: function (callback) {
  23981. if (this._onDisposeObserver) {
  23982. this.onDisposeObservable.remove(this._onDisposeObserver);
  23983. }
  23984. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  23985. },
  23986. enumerable: true,
  23987. configurable: true
  23988. });
  23989. BaseTexture.prototype.getScene = function () {
  23990. return this._scene;
  23991. };
  23992. BaseTexture.prototype.getTextureMatrix = function () {
  23993. return null;
  23994. };
  23995. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  23996. return null;
  23997. };
  23998. BaseTexture.prototype.getInternalTexture = function () {
  23999. return this._texture;
  24000. };
  24001. BaseTexture.prototype.isReady = function () {
  24002. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  24003. return true;
  24004. }
  24005. if (this._texture) {
  24006. return this._texture.isReady;
  24007. }
  24008. return false;
  24009. };
  24010. BaseTexture.prototype.getSize = function () {
  24011. if (this._texture._width) {
  24012. return new BABYLON.Size(this._texture._width, this._texture._height);
  24013. }
  24014. if (this._texture._size) {
  24015. return new BABYLON.Size(this._texture._size, this._texture._size);
  24016. }
  24017. return BABYLON.Size.Zero();
  24018. };
  24019. BaseTexture.prototype.getBaseSize = function () {
  24020. if (!this.isReady() || !this._texture)
  24021. return BABYLON.Size.Zero();
  24022. if (this._texture._size) {
  24023. return new BABYLON.Size(this._texture._size, this._texture._size);
  24024. }
  24025. return new BABYLON.Size(this._texture._baseWidth, this._texture._baseHeight);
  24026. };
  24027. BaseTexture.prototype.scale = function (ratio) {
  24028. };
  24029. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  24030. get: function () {
  24031. return false;
  24032. },
  24033. enumerable: true,
  24034. configurable: true
  24035. });
  24036. BaseTexture.prototype._removeFromCache = function (url, noMipmap) {
  24037. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  24038. for (var index = 0; index < texturesCache.length; index++) {
  24039. var texturesCacheEntry = texturesCache[index];
  24040. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  24041. texturesCache.splice(index, 1);
  24042. return;
  24043. }
  24044. }
  24045. };
  24046. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  24047. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  24048. for (var index = 0; index < texturesCache.length; index++) {
  24049. var texturesCacheEntry = texturesCache[index];
  24050. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  24051. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  24052. texturesCacheEntry.references++;
  24053. return texturesCacheEntry;
  24054. }
  24055. }
  24056. }
  24057. return null;
  24058. };
  24059. BaseTexture.prototype.delayLoad = function () {
  24060. };
  24061. BaseTexture.prototype.clone = function () {
  24062. return null;
  24063. };
  24064. BaseTexture.prototype.releaseInternalTexture = function () {
  24065. if (this._texture) {
  24066. this._scene.getEngine().releaseInternalTexture(this._texture);
  24067. delete this._texture;
  24068. }
  24069. };
  24070. BaseTexture.prototype.dispose = function () {
  24071. // Animations
  24072. this.getScene().stopAnimation(this);
  24073. // Remove from scene
  24074. var index = this._scene.textures.indexOf(this);
  24075. if (index >= 0) {
  24076. this._scene.textures.splice(index, 1);
  24077. }
  24078. if (this._texture === undefined) {
  24079. return;
  24080. }
  24081. // Release
  24082. this.releaseInternalTexture();
  24083. // Callback
  24084. this.onDisposeObservable.notifyObservers(this);
  24085. this.onDisposeObservable.clear();
  24086. };
  24087. BaseTexture.prototype.serialize = function () {
  24088. if (!this.name) {
  24089. return null;
  24090. }
  24091. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  24092. // Animations
  24093. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  24094. return serializationObject;
  24095. };
  24096. return BaseTexture;
  24097. }());
  24098. __decorate([
  24099. BABYLON.serialize()
  24100. ], BaseTexture.prototype, "name", void 0);
  24101. __decorate([
  24102. BABYLON.serialize()
  24103. ], BaseTexture.prototype, "hasAlpha", void 0);
  24104. __decorate([
  24105. BABYLON.serialize()
  24106. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  24107. __decorate([
  24108. BABYLON.serialize()
  24109. ], BaseTexture.prototype, "level", void 0);
  24110. __decorate([
  24111. BABYLON.serialize()
  24112. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  24113. __decorate([
  24114. BABYLON.serialize()
  24115. ], BaseTexture.prototype, "coordinatesMode", void 0);
  24116. __decorate([
  24117. BABYLON.serialize()
  24118. ], BaseTexture.prototype, "wrapU", void 0);
  24119. __decorate([
  24120. BABYLON.serialize()
  24121. ], BaseTexture.prototype, "wrapV", void 0);
  24122. __decorate([
  24123. BABYLON.serialize()
  24124. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  24125. __decorate([
  24126. BABYLON.serialize()
  24127. ], BaseTexture.prototype, "isCube", void 0);
  24128. __decorate([
  24129. BABYLON.serialize()
  24130. ], BaseTexture.prototype, "isRenderTarget", void 0);
  24131. BABYLON.BaseTexture = BaseTexture;
  24132. })(BABYLON || (BABYLON = {}));
  24133. //# sourceMappingURL=babylon.baseTexture.js.map
  24134. var BABYLON;
  24135. (function (BABYLON) {
  24136. var Texture = (function (_super) {
  24137. __extends(Texture, _super);
  24138. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer) {
  24139. if (noMipmap === void 0) { noMipmap = false; }
  24140. if (invertY === void 0) { invertY = true; }
  24141. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  24142. if (onLoad === void 0) { onLoad = null; }
  24143. if (onError === void 0) { onError = null; }
  24144. if (buffer === void 0) { buffer = null; }
  24145. if (deleteBuffer === void 0) { deleteBuffer = false; }
  24146. var _this = _super.call(this, scene) || this;
  24147. _this.uOffset = 0;
  24148. _this.vOffset = 0;
  24149. _this.uScale = 1.0;
  24150. _this.vScale = 1.0;
  24151. _this.uAng = 0;
  24152. _this.vAng = 0;
  24153. _this.wAng = 0;
  24154. _this.name = url;
  24155. _this.url = url;
  24156. _this._noMipmap = noMipmap;
  24157. _this._invertY = invertY;
  24158. _this._samplingMode = samplingMode;
  24159. _this._buffer = buffer;
  24160. _this._deleteBuffer = deleteBuffer;
  24161. if (!url) {
  24162. return _this;
  24163. }
  24164. _this._texture = _this._getFromCache(url, noMipmap, samplingMode);
  24165. var load = function () {
  24166. if (_this._onLoadObservarble && _this._onLoadObservarble.hasObservers()) {
  24167. _this.onLoadObservable.notifyObservers(true);
  24168. }
  24169. if (onLoad) {
  24170. onLoad();
  24171. }
  24172. };
  24173. if (!_this._texture) {
  24174. if (!scene.useDelayedTextureLoading) {
  24175. _this._texture = scene.getEngine().createTexture(url, noMipmap, invertY, scene, _this._samplingMode, load, onError, _this._buffer);
  24176. if (deleteBuffer) {
  24177. delete _this._buffer;
  24178. }
  24179. }
  24180. else {
  24181. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  24182. _this._delayedOnLoad = load;
  24183. _this._delayedOnError = onError;
  24184. }
  24185. }
  24186. else {
  24187. if (_this._texture.isReady) {
  24188. BABYLON.Tools.SetImmediate(function () { return load(); });
  24189. }
  24190. else {
  24191. _this._texture.onLoadedCallbacks.push(load);
  24192. }
  24193. }
  24194. return _this;
  24195. }
  24196. Object.defineProperty(Texture.prototype, "noMipmap", {
  24197. get: function () {
  24198. return this._noMipmap;
  24199. },
  24200. enumerable: true,
  24201. configurable: true
  24202. });
  24203. Texture.prototype.delayLoad = function () {
  24204. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  24205. return;
  24206. }
  24207. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  24208. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  24209. if (!this._texture) {
  24210. this._texture = this.getScene().getEngine().createTexture(this.url, this._noMipmap, this._invertY, this.getScene(), this._samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer);
  24211. if (this._deleteBuffer) {
  24212. delete this._buffer;
  24213. }
  24214. }
  24215. };
  24216. Texture.prototype.updateSamplingMode = function (samplingMode) {
  24217. if (!this._texture) {
  24218. return;
  24219. }
  24220. this._samplingMode = samplingMode;
  24221. this.getScene().getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  24222. };
  24223. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  24224. x *= this.uScale;
  24225. y *= this.vScale;
  24226. x -= 0.5 * this.uScale;
  24227. y -= 0.5 * this.vScale;
  24228. z -= 0.5;
  24229. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  24230. t.x += 0.5 * this.uScale + this.uOffset;
  24231. t.y += 0.5 * this.vScale + this.vOffset;
  24232. t.z += 0.5;
  24233. };
  24234. Texture.prototype.getTextureMatrix = function () {
  24235. if (this.uOffset === this._cachedUOffset &&
  24236. this.vOffset === this._cachedVOffset &&
  24237. this.uScale === this._cachedUScale &&
  24238. this.vScale === this._cachedVScale &&
  24239. this.uAng === this._cachedUAng &&
  24240. this.vAng === this._cachedVAng &&
  24241. this.wAng === this._cachedWAng) {
  24242. return this._cachedTextureMatrix;
  24243. }
  24244. this._cachedUOffset = this.uOffset;
  24245. this._cachedVOffset = this.vOffset;
  24246. this._cachedUScale = this.uScale;
  24247. this._cachedVScale = this.vScale;
  24248. this._cachedUAng = this.uAng;
  24249. this._cachedVAng = this.vAng;
  24250. this._cachedWAng = this.wAng;
  24251. if (!this._cachedTextureMatrix) {
  24252. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  24253. this._rowGenerationMatrix = new BABYLON.Matrix();
  24254. this._t0 = BABYLON.Vector3.Zero();
  24255. this._t1 = BABYLON.Vector3.Zero();
  24256. this._t2 = BABYLON.Vector3.Zero();
  24257. }
  24258. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  24259. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  24260. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  24261. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  24262. this._t1.subtractInPlace(this._t0);
  24263. this._t2.subtractInPlace(this._t0);
  24264. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  24265. this._cachedTextureMatrix.m[0] = this._t1.x;
  24266. this._cachedTextureMatrix.m[1] = this._t1.y;
  24267. this._cachedTextureMatrix.m[2] = this._t1.z;
  24268. this._cachedTextureMatrix.m[4] = this._t2.x;
  24269. this._cachedTextureMatrix.m[5] = this._t2.y;
  24270. this._cachedTextureMatrix.m[6] = this._t2.z;
  24271. this._cachedTextureMatrix.m[8] = this._t0.x;
  24272. this._cachedTextureMatrix.m[9] = this._t0.y;
  24273. this._cachedTextureMatrix.m[10] = this._t0.z;
  24274. return this._cachedTextureMatrix;
  24275. };
  24276. Texture.prototype.getReflectionTextureMatrix = function () {
  24277. if (this.uOffset === this._cachedUOffset &&
  24278. this.vOffset === this._cachedVOffset &&
  24279. this.uScale === this._cachedUScale &&
  24280. this.vScale === this._cachedVScale &&
  24281. this.coordinatesMode === this._cachedCoordinatesMode) {
  24282. return this._cachedTextureMatrix;
  24283. }
  24284. if (!this._cachedTextureMatrix) {
  24285. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  24286. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  24287. }
  24288. this._cachedCoordinatesMode = this.coordinatesMode;
  24289. switch (this.coordinatesMode) {
  24290. case Texture.PLANAR_MODE:
  24291. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  24292. this._cachedTextureMatrix[0] = this.uScale;
  24293. this._cachedTextureMatrix[5] = this.vScale;
  24294. this._cachedTextureMatrix[12] = this.uOffset;
  24295. this._cachedTextureMatrix[13] = this.vOffset;
  24296. break;
  24297. case Texture.PROJECTION_MODE:
  24298. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  24299. this._projectionModeMatrix.m[0] = 0.5;
  24300. this._projectionModeMatrix.m[5] = -0.5;
  24301. this._projectionModeMatrix.m[10] = 0.0;
  24302. this._projectionModeMatrix.m[12] = 0.5;
  24303. this._projectionModeMatrix.m[13] = 0.5;
  24304. this._projectionModeMatrix.m[14] = 1.0;
  24305. this._projectionModeMatrix.m[15] = 1.0;
  24306. this.getScene().getProjectionMatrix().multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  24307. break;
  24308. default:
  24309. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  24310. break;
  24311. }
  24312. return this._cachedTextureMatrix;
  24313. };
  24314. Texture.prototype.clone = function () {
  24315. var _this = this;
  24316. return BABYLON.SerializationHelper.Clone(function () {
  24317. return new Texture(_this._texture.url, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  24318. }, this);
  24319. };
  24320. Object.defineProperty(Texture.prototype, "onLoadObservable", {
  24321. get: function () {
  24322. if (!this._onLoadObservarble) {
  24323. this._onLoadObservarble = new BABYLON.Observable();
  24324. }
  24325. return this._onLoadObservarble;
  24326. },
  24327. enumerable: true,
  24328. configurable: true
  24329. });
  24330. // Statics
  24331. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError) {
  24332. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  24333. if (onLoad === void 0) { onLoad = null; }
  24334. if (onError === void 0) { onError = null; }
  24335. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data);
  24336. };
  24337. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  24338. if (parsedTexture.customType) {
  24339. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  24340. return customTexture.Parse(parsedTexture, scene, rootUrl);
  24341. }
  24342. if (parsedTexture.isCube) {
  24343. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  24344. }
  24345. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  24346. return null;
  24347. }
  24348. var texture = BABYLON.SerializationHelper.Parse(function () {
  24349. if (parsedTexture.mirrorPlane) {
  24350. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  24351. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  24352. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  24353. return mirrorTexture;
  24354. }
  24355. else if (parsedTexture.isRenderTarget) {
  24356. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  24357. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  24358. return renderTargetTexture;
  24359. }
  24360. else {
  24361. var texture;
  24362. if (parsedTexture.base64String) {
  24363. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene);
  24364. }
  24365. else {
  24366. texture = new Texture(rootUrl + parsedTexture.name, scene);
  24367. }
  24368. return texture;
  24369. }
  24370. }, parsedTexture, scene);
  24371. // Animations
  24372. if (parsedTexture.animations) {
  24373. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  24374. var parsedAnimation = parsedTexture.animations[animationIndex];
  24375. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  24376. }
  24377. }
  24378. return texture;
  24379. };
  24380. Texture.LoadFromDataString = function (name, buffer, scene, deleteBuffer, noMipmap, invertY, samplingMode, onLoad, onError) {
  24381. if (deleteBuffer === void 0) { deleteBuffer = false; }
  24382. if (noMipmap === void 0) { noMipmap = false; }
  24383. if (invertY === void 0) { invertY = true; }
  24384. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  24385. if (onLoad === void 0) { onLoad = null; }
  24386. if (onError === void 0) { onError = null; }
  24387. if (name.substr(0, 5) !== "data:") {
  24388. name = "data:" + name;
  24389. }
  24390. return new Texture(name, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer);
  24391. };
  24392. return Texture;
  24393. }(BABYLON.BaseTexture));
  24394. // Constants
  24395. Texture.NEAREST_SAMPLINGMODE = 1;
  24396. Texture.BILINEAR_SAMPLINGMODE = 2;
  24397. Texture.TRILINEAR_SAMPLINGMODE = 3;
  24398. Texture.EXPLICIT_MODE = 0;
  24399. Texture.SPHERICAL_MODE = 1;
  24400. Texture.PLANAR_MODE = 2;
  24401. Texture.CUBIC_MODE = 3;
  24402. Texture.PROJECTION_MODE = 4;
  24403. Texture.SKYBOX_MODE = 5;
  24404. Texture.INVCUBIC_MODE = 6;
  24405. Texture.EQUIRECTANGULAR_MODE = 7;
  24406. Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
  24407. Texture.CLAMP_ADDRESSMODE = 0;
  24408. Texture.WRAP_ADDRESSMODE = 1;
  24409. Texture.MIRROR_ADDRESSMODE = 2;
  24410. __decorate([
  24411. BABYLON.serialize()
  24412. ], Texture.prototype, "url", void 0);
  24413. __decorate([
  24414. BABYLON.serialize()
  24415. ], Texture.prototype, "uOffset", void 0);
  24416. __decorate([
  24417. BABYLON.serialize()
  24418. ], Texture.prototype, "vOffset", void 0);
  24419. __decorate([
  24420. BABYLON.serialize()
  24421. ], Texture.prototype, "uScale", void 0);
  24422. __decorate([
  24423. BABYLON.serialize()
  24424. ], Texture.prototype, "vScale", void 0);
  24425. __decorate([
  24426. BABYLON.serialize()
  24427. ], Texture.prototype, "uAng", void 0);
  24428. __decorate([
  24429. BABYLON.serialize()
  24430. ], Texture.prototype, "vAng", void 0);
  24431. __decorate([
  24432. BABYLON.serialize()
  24433. ], Texture.prototype, "wAng", void 0);
  24434. BABYLON.Texture = Texture;
  24435. })(BABYLON || (BABYLON = {}));
  24436. //# sourceMappingURL=babylon.texture.js.map
  24437. var BABYLON;
  24438. (function (BABYLON) {
  24439. var CubeTexture = (function (_super) {
  24440. __extends(CubeTexture, _super);
  24441. function CubeTexture(rootUrl, scene, extensions, noMipmap, files, onLoad, onError) {
  24442. if (onLoad === void 0) { onLoad = null; }
  24443. if (onError === void 0) { onError = null; }
  24444. var _this = _super.call(this, scene) || this;
  24445. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  24446. _this.name = rootUrl;
  24447. _this.url = rootUrl;
  24448. _this._noMipmap = noMipmap;
  24449. _this.hasAlpha = false;
  24450. if (!rootUrl && !files) {
  24451. return _this;
  24452. }
  24453. _this._texture = _this._getFromCache(rootUrl, noMipmap);
  24454. if (!files) {
  24455. if (!extensions) {
  24456. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  24457. }
  24458. files = [];
  24459. for (var index = 0; index < extensions.length; index++) {
  24460. files.push(rootUrl + extensions[index]);
  24461. }
  24462. _this._extensions = extensions;
  24463. }
  24464. _this._files = files;
  24465. if (!_this._texture) {
  24466. if (!scene.useDelayedTextureLoading) {
  24467. _this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap, onLoad, onError);
  24468. }
  24469. else {
  24470. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  24471. }
  24472. }
  24473. else if (onLoad) {
  24474. if (_this._texture.isReady) {
  24475. BABYLON.Tools.SetImmediate(function () { return onLoad(); });
  24476. }
  24477. else {
  24478. _this._texture.onLoadedCallbacks.push(onLoad);
  24479. }
  24480. }
  24481. _this.isCube = true;
  24482. _this._textureMatrix = BABYLON.Matrix.Identity();
  24483. return _this;
  24484. }
  24485. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  24486. return new CubeTexture("", scene, null, noMipmap, files);
  24487. };
  24488. // Methods
  24489. CubeTexture.prototype.delayLoad = function () {
  24490. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  24491. return;
  24492. }
  24493. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  24494. this._texture = this._getFromCache(this.url, this._noMipmap);
  24495. if (!this._texture) {
  24496. this._texture = this.getScene().getEngine().createCubeTexture(this.url, this.getScene(), this._files, this._noMipmap);
  24497. }
  24498. };
  24499. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  24500. return this._textureMatrix;
  24501. };
  24502. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  24503. var texture = BABYLON.SerializationHelper.Parse(function () {
  24504. return new BABYLON.CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions);
  24505. }, parsedTexture, scene);
  24506. // Animations
  24507. if (parsedTexture.animations) {
  24508. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  24509. var parsedAnimation = parsedTexture.animations[animationIndex];
  24510. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  24511. }
  24512. }
  24513. return texture;
  24514. };
  24515. CubeTexture.prototype.clone = function () {
  24516. var _this = this;
  24517. return BABYLON.SerializationHelper.Clone(function () {
  24518. return new CubeTexture(_this.url, _this.getScene(), _this._extensions, _this._noMipmap, _this._files);
  24519. }, this);
  24520. };
  24521. return CubeTexture;
  24522. }(BABYLON.BaseTexture));
  24523. BABYLON.CubeTexture = CubeTexture;
  24524. })(BABYLON || (BABYLON = {}));
  24525. //# sourceMappingURL=babylon.cubeTexture.js.map
  24526. var BABYLON;
  24527. (function (BABYLON) {
  24528. var RenderTargetTexture = (function (_super) {
  24529. __extends(RenderTargetTexture, _super);
  24530. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer) {
  24531. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  24532. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  24533. if (isCube === void 0) { isCube = false; }
  24534. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  24535. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  24536. if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
  24537. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  24538. _this.isCube = isCube;
  24539. /**
  24540. * Use this list to define the list of mesh you want to render.
  24541. */
  24542. _this.renderList = new Array();
  24543. _this.renderParticles = true;
  24544. _this.renderSprites = false;
  24545. _this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  24546. // Events
  24547. /**
  24548. * An event triggered when the texture is unbind.
  24549. * @type {BABYLON.Observable}
  24550. */
  24551. _this.onAfterUnbindObservable = new BABYLON.Observable();
  24552. /**
  24553. * An event triggered before rendering the texture
  24554. * @type {BABYLON.Observable}
  24555. */
  24556. _this.onBeforeRenderObservable = new BABYLON.Observable();
  24557. /**
  24558. * An event triggered after rendering the texture
  24559. * @type {BABYLON.Observable}
  24560. */
  24561. _this.onAfterRenderObservable = new BABYLON.Observable();
  24562. /**
  24563. * An event triggered after the texture clear
  24564. * @type {BABYLON.Observable}
  24565. */
  24566. _this.onClearObservable = new BABYLON.Observable();
  24567. _this._currentRefreshId = -1;
  24568. _this._refreshRate = 1;
  24569. _this.name = name;
  24570. _this.isRenderTarget = true;
  24571. _this._size = size;
  24572. _this._generateMipMaps = generateMipMaps;
  24573. _this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  24574. _this._renderTargetOptions = {
  24575. generateMipMaps: generateMipMaps,
  24576. type: type,
  24577. samplingMode: samplingMode,
  24578. generateDepthBuffer: generateDepthBuffer,
  24579. generateStencilBuffer: generateStencilBuffer
  24580. };
  24581. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  24582. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  24583. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  24584. }
  24585. if (isCube) {
  24586. _this._texture = scene.getEngine().createRenderTargetCubeTexture(size, _this._renderTargetOptions);
  24587. _this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  24588. _this._textureMatrix = BABYLON.Matrix.Identity();
  24589. }
  24590. else {
  24591. _this._texture = scene.getEngine().createRenderTargetTexture(size, _this._renderTargetOptions);
  24592. }
  24593. // Rendering groups
  24594. _this._renderingManager = new BABYLON.RenderingManager(scene);
  24595. return _this;
  24596. }
  24597. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  24598. get: function () {
  24599. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  24600. },
  24601. enumerable: true,
  24602. configurable: true
  24603. });
  24604. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  24605. get: function () {
  24606. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  24607. },
  24608. enumerable: true,
  24609. configurable: true
  24610. });
  24611. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  24612. get: function () {
  24613. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  24614. },
  24615. enumerable: true,
  24616. configurable: true
  24617. });
  24618. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  24619. set: function (callback) {
  24620. if (this._onAfterUnbindObserver) {
  24621. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  24622. }
  24623. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  24624. },
  24625. enumerable: true,
  24626. configurable: true
  24627. });
  24628. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  24629. set: function (callback) {
  24630. if (this._onBeforeRenderObserver) {
  24631. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  24632. }
  24633. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  24634. },
  24635. enumerable: true,
  24636. configurable: true
  24637. });
  24638. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  24639. set: function (callback) {
  24640. if (this._onAfterRenderObserver) {
  24641. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  24642. }
  24643. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  24644. },
  24645. enumerable: true,
  24646. configurable: true
  24647. });
  24648. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  24649. set: function (callback) {
  24650. if (this._onClearObserver) {
  24651. this.onClearObservable.remove(this._onClearObserver);
  24652. }
  24653. this._onClearObserver = this.onClearObservable.add(callback);
  24654. },
  24655. enumerable: true,
  24656. configurable: true
  24657. });
  24658. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  24659. this._currentRefreshId = -1;
  24660. };
  24661. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  24662. get: function () {
  24663. return this._refreshRate;
  24664. },
  24665. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  24666. set: function (value) {
  24667. this._refreshRate = value;
  24668. this.resetRefreshCounter();
  24669. },
  24670. enumerable: true,
  24671. configurable: true
  24672. });
  24673. RenderTargetTexture.prototype._shouldRender = function () {
  24674. if (this._currentRefreshId === -1) {
  24675. this._currentRefreshId = 1;
  24676. return true;
  24677. }
  24678. if (this.refreshRate === this._currentRefreshId) {
  24679. this._currentRefreshId = 1;
  24680. return true;
  24681. }
  24682. this._currentRefreshId++;
  24683. return false;
  24684. };
  24685. RenderTargetTexture.prototype.isReady = function () {
  24686. if (!this.getScene().renderTargetsEnabled) {
  24687. return false;
  24688. }
  24689. return _super.prototype.isReady.call(this);
  24690. };
  24691. RenderTargetTexture.prototype.getRenderSize = function () {
  24692. return this._size;
  24693. };
  24694. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  24695. get: function () {
  24696. return true;
  24697. },
  24698. enumerable: true,
  24699. configurable: true
  24700. });
  24701. RenderTargetTexture.prototype.scale = function (ratio) {
  24702. var newSize = this._size * ratio;
  24703. this.resize(newSize);
  24704. };
  24705. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  24706. if (this.isCube) {
  24707. return this._textureMatrix;
  24708. }
  24709. return _super.prototype.getReflectionTextureMatrix.call(this);
  24710. };
  24711. RenderTargetTexture.prototype.resize = function (size) {
  24712. this.releaseInternalTexture();
  24713. if (this.isCube) {
  24714. this._texture = this.getScene().getEngine().createRenderTargetCubeTexture(size, this._renderTargetOptions);
  24715. }
  24716. else {
  24717. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, this._renderTargetOptions);
  24718. }
  24719. };
  24720. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  24721. var scene = this.getScene();
  24722. var engine = scene.getEngine();
  24723. if (this.useCameraPostProcesses !== undefined) {
  24724. useCameraPostProcess = this.useCameraPostProcesses;
  24725. }
  24726. if (this._waitingRenderList) {
  24727. this.renderList = [];
  24728. for (var index = 0; index < this._waitingRenderList.length; index++) {
  24729. var id = this._waitingRenderList[index];
  24730. this.renderList.push(scene.getMeshByID(id));
  24731. }
  24732. delete this._waitingRenderList;
  24733. }
  24734. // Is predicate defined?
  24735. if (this.renderListPredicate) {
  24736. this.renderList.splice(0); // Clear previous renderList
  24737. var sceneMeshes = this.getScene().meshes;
  24738. for (var index = 0; index < sceneMeshes.length; index++) {
  24739. var mesh = sceneMeshes[index];
  24740. if (this.renderListPredicate(mesh)) {
  24741. this.renderList.push(mesh);
  24742. }
  24743. }
  24744. }
  24745. if (this.renderList && this.renderList.length === 0) {
  24746. return;
  24747. }
  24748. // Set custom projection.
  24749. // Needs to be before binding to prevent changing the aspect ratio.
  24750. if (this.activeCamera) {
  24751. engine.setViewport(this.activeCamera.viewport);
  24752. if (this.activeCamera !== scene.activeCamera) {
  24753. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  24754. }
  24755. }
  24756. else {
  24757. engine.setViewport(scene.activeCamera.viewport);
  24758. }
  24759. // Prepare renderingManager
  24760. this._renderingManager.reset();
  24761. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  24762. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  24763. var sceneRenderId = scene.getRenderId();
  24764. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  24765. var mesh = currentRenderList[meshIndex];
  24766. if (mesh) {
  24767. if (!mesh.isReady()) {
  24768. // Reset _currentRefreshId
  24769. this.resetRefreshCounter();
  24770. continue;
  24771. }
  24772. mesh._preActivateForIntermediateRendering(sceneRenderId);
  24773. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && ((mesh.layerMask & scene.activeCamera.layerMask) !== 0)) {
  24774. mesh._activate(sceneRenderId);
  24775. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  24776. var subMesh = mesh.subMeshes[subIndex];
  24777. scene._activeIndices.addCount(subMesh.indexCount, false);
  24778. this._renderingManager.dispatch(subMesh);
  24779. }
  24780. }
  24781. }
  24782. }
  24783. if (this.isCube) {
  24784. for (var face = 0; face < 6; face++) {
  24785. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  24786. scene.incrementRenderId();
  24787. scene.resetCachedMaterial();
  24788. }
  24789. }
  24790. else {
  24791. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  24792. }
  24793. this.onAfterUnbindObservable.notifyObservers(this);
  24794. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  24795. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  24796. }
  24797. engine.setViewport(scene.activeCamera.viewport);
  24798. scene.resetCachedMaterial();
  24799. };
  24800. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  24801. var scene = this.getScene();
  24802. var engine = scene.getEngine();
  24803. // Bind
  24804. if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  24805. if (this.isCube) {
  24806. engine.bindFramebuffer(this._texture, faceIndex);
  24807. }
  24808. else {
  24809. engine.bindFramebuffer(this._texture);
  24810. }
  24811. }
  24812. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  24813. // Clear
  24814. if (this.onClearObservable.hasObservers()) {
  24815. this.onClearObservable.notifyObservers(engine);
  24816. }
  24817. else {
  24818. engine.clear(scene.clearColor, true, true, true);
  24819. }
  24820. if (!this._doNotChangeAspectRatio) {
  24821. scene.updateTransformMatrix(true);
  24822. }
  24823. // Render
  24824. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  24825. if (useCameraPostProcess) {
  24826. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  24827. }
  24828. if (!this._doNotChangeAspectRatio) {
  24829. scene.updateTransformMatrix(true);
  24830. }
  24831. this.onAfterRenderObservable.notifyObservers(faceIndex);
  24832. // Dump ?
  24833. if (dumpForDebug) {
  24834. BABYLON.Tools.DumpFramebuffer(this._size, this._size, engine);
  24835. }
  24836. // Unbind
  24837. if (!this.isCube || faceIndex === 5) {
  24838. if (this.isCube) {
  24839. if (faceIndex === 5) {
  24840. engine.generateMipMapsForCubemap(this._texture);
  24841. }
  24842. }
  24843. engine.unBindFramebuffer(this._texture, this.isCube);
  24844. }
  24845. };
  24846. /**
  24847. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  24848. * This allowed control for front to back rendering or reversly depending of the special needs.
  24849. *
  24850. * @param renderingGroupId The rendering group id corresponding to its index
  24851. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  24852. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  24853. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  24854. */
  24855. RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  24856. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  24857. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  24858. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  24859. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  24860. };
  24861. /**
  24862. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  24863. *
  24864. * @param renderingGroupId The rendering group id corresponding to its index
  24865. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  24866. */
  24867. RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  24868. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  24869. };
  24870. RenderTargetTexture.prototype.clone = function () {
  24871. var textureSize = this.getSize();
  24872. 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);
  24873. // Base texture
  24874. newTexture.hasAlpha = this.hasAlpha;
  24875. newTexture.level = this.level;
  24876. // RenderTarget Texture
  24877. newTexture.coordinatesMode = this.coordinatesMode;
  24878. newTexture.renderList = this.renderList.slice(0);
  24879. return newTexture;
  24880. };
  24881. RenderTargetTexture.prototype.serialize = function () {
  24882. if (!this.name) {
  24883. return null;
  24884. }
  24885. var serializationObject = _super.prototype.serialize.call(this);
  24886. serializationObject.renderTargetSize = this.getRenderSize();
  24887. serializationObject.renderList = [];
  24888. for (var index = 0; index < this.renderList.length; index++) {
  24889. serializationObject.renderList.push(this.renderList[index].id);
  24890. }
  24891. return serializationObject;
  24892. };
  24893. return RenderTargetTexture;
  24894. }(BABYLON.Texture));
  24895. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  24896. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  24897. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  24898. BABYLON.RenderTargetTexture = RenderTargetTexture;
  24899. })(BABYLON || (BABYLON = {}));
  24900. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  24901. var BABYLON;
  24902. (function (BABYLON) {
  24903. var ProceduralTexture = (function (_super) {
  24904. __extends(ProceduralTexture, _super);
  24905. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  24906. if (generateMipMaps === void 0) { generateMipMaps = true; }
  24907. if (isCube === void 0) { isCube = false; }
  24908. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  24909. _this.isCube = isCube;
  24910. _this.isEnabled = true;
  24911. _this._currentRefreshId = -1;
  24912. _this._refreshRate = 1;
  24913. _this._vertexBuffers = {};
  24914. _this._uniforms = new Array();
  24915. _this._samplers = new Array();
  24916. _this._textures = new Array();
  24917. _this._floats = new Array();
  24918. _this._floatsArrays = {};
  24919. _this._colors3 = new Array();
  24920. _this._colors4 = new Array();
  24921. _this._vectors2 = new Array();
  24922. _this._vectors3 = new Array();
  24923. _this._matrices = new Array();
  24924. _this._fallbackTextureUsed = false;
  24925. scene._proceduralTextures.push(_this);
  24926. _this.name = name;
  24927. _this.isRenderTarget = true;
  24928. _this._size = size;
  24929. _this._generateMipMaps = generateMipMaps;
  24930. _this.setFragment(fragment);
  24931. _this._fallbackTexture = fallbackTexture;
  24932. var engine = scene.getEngine();
  24933. if (isCube) {
  24934. _this._texture = engine.createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  24935. _this.setFloat("face", 0);
  24936. }
  24937. else {
  24938. _this._texture = engine.createRenderTargetTexture(size, generateMipMaps);
  24939. }
  24940. // VBO
  24941. var vertices = [];
  24942. vertices.push(1, 1);
  24943. vertices.push(-1, 1);
  24944. vertices.push(-1, -1);
  24945. vertices.push(1, -1);
  24946. _this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  24947. // Indices
  24948. var indices = [];
  24949. indices.push(0);
  24950. indices.push(1);
  24951. indices.push(2);
  24952. indices.push(0);
  24953. indices.push(2);
  24954. indices.push(3);
  24955. _this._indexBuffer = engine.createIndexBuffer(indices);
  24956. return _this;
  24957. }
  24958. ProceduralTexture.prototype.reset = function () {
  24959. if (this._effect === undefined) {
  24960. return;
  24961. }
  24962. var engine = this.getScene().getEngine();
  24963. engine._releaseEffect(this._effect);
  24964. };
  24965. ProceduralTexture.prototype.isReady = function () {
  24966. var _this = this;
  24967. var engine = this.getScene().getEngine();
  24968. var shaders;
  24969. if (!this._fragment) {
  24970. return false;
  24971. }
  24972. if (this._fallbackTextureUsed) {
  24973. return true;
  24974. }
  24975. if (this._fragment.fragmentElement !== undefined) {
  24976. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  24977. }
  24978. else {
  24979. shaders = { vertex: "procedural", fragment: this._fragment };
  24980. }
  24981. this._effect = engine.createEffect(shaders, [BABYLON.VertexBuffer.PositionKind], this._uniforms, this._samplers, "", null, null, function () {
  24982. _this.releaseInternalTexture();
  24983. if (_this._fallbackTexture) {
  24984. _this._texture = _this._fallbackTexture._texture;
  24985. _this._texture.references++;
  24986. }
  24987. _this._fallbackTextureUsed = true;
  24988. });
  24989. return this._effect.isReady();
  24990. };
  24991. ProceduralTexture.prototype.resetRefreshCounter = function () {
  24992. this._currentRefreshId = -1;
  24993. };
  24994. ProceduralTexture.prototype.setFragment = function (fragment) {
  24995. this._fragment = fragment;
  24996. };
  24997. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  24998. get: function () {
  24999. return this._refreshRate;
  25000. },
  25001. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  25002. set: function (value) {
  25003. this._refreshRate = value;
  25004. this.resetRefreshCounter();
  25005. },
  25006. enumerable: true,
  25007. configurable: true
  25008. });
  25009. ProceduralTexture.prototype._shouldRender = function () {
  25010. if (!this.isEnabled || !this.isReady() || !this._texture) {
  25011. return false;
  25012. }
  25013. if (this._fallbackTextureUsed) {
  25014. return false;
  25015. }
  25016. if (this._currentRefreshId === -1) {
  25017. this._currentRefreshId = 1;
  25018. return true;
  25019. }
  25020. if (this.refreshRate === this._currentRefreshId) {
  25021. this._currentRefreshId = 1;
  25022. return true;
  25023. }
  25024. this._currentRefreshId++;
  25025. return false;
  25026. };
  25027. ProceduralTexture.prototype.getRenderSize = function () {
  25028. return this._size;
  25029. };
  25030. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  25031. if (this._fallbackTextureUsed) {
  25032. return;
  25033. }
  25034. this.releaseInternalTexture();
  25035. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  25036. };
  25037. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  25038. if (this._uniforms.indexOf(uniformName) === -1) {
  25039. this._uniforms.push(uniformName);
  25040. }
  25041. };
  25042. ProceduralTexture.prototype.setTexture = function (name, texture) {
  25043. if (this._samplers.indexOf(name) === -1) {
  25044. this._samplers.push(name);
  25045. }
  25046. this._textures[name] = texture;
  25047. return this;
  25048. };
  25049. ProceduralTexture.prototype.setFloat = function (name, value) {
  25050. this._checkUniform(name);
  25051. this._floats[name] = value;
  25052. return this;
  25053. };
  25054. ProceduralTexture.prototype.setFloats = function (name, value) {
  25055. this._checkUniform(name);
  25056. this._floatsArrays[name] = value;
  25057. return this;
  25058. };
  25059. ProceduralTexture.prototype.setColor3 = function (name, value) {
  25060. this._checkUniform(name);
  25061. this._colors3[name] = value;
  25062. return this;
  25063. };
  25064. ProceduralTexture.prototype.setColor4 = function (name, value) {
  25065. this._checkUniform(name);
  25066. this._colors4[name] = value;
  25067. return this;
  25068. };
  25069. ProceduralTexture.prototype.setVector2 = function (name, value) {
  25070. this._checkUniform(name);
  25071. this._vectors2[name] = value;
  25072. return this;
  25073. };
  25074. ProceduralTexture.prototype.setVector3 = function (name, value) {
  25075. this._checkUniform(name);
  25076. this._vectors3[name] = value;
  25077. return this;
  25078. };
  25079. ProceduralTexture.prototype.setMatrix = function (name, value) {
  25080. this._checkUniform(name);
  25081. this._matrices[name] = value;
  25082. return this;
  25083. };
  25084. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  25085. var scene = this.getScene();
  25086. var engine = scene.getEngine();
  25087. // Render
  25088. engine.enableEffect(this._effect);
  25089. engine.setState(false);
  25090. // Texture
  25091. for (var name in this._textures) {
  25092. this._effect.setTexture(name, this._textures[name]);
  25093. }
  25094. // Float
  25095. for (name in this._floats) {
  25096. this._effect.setFloat(name, this._floats[name]);
  25097. }
  25098. // Floats
  25099. for (name in this._floatsArrays) {
  25100. this._effect.setArray(name, this._floatsArrays[name]);
  25101. }
  25102. // Color3
  25103. for (name in this._colors3) {
  25104. this._effect.setColor3(name, this._colors3[name]);
  25105. }
  25106. // Color4
  25107. for (name in this._colors4) {
  25108. var color = this._colors4[name];
  25109. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  25110. }
  25111. // Vector2
  25112. for (name in this._vectors2) {
  25113. this._effect.setVector2(name, this._vectors2[name]);
  25114. }
  25115. // Vector3
  25116. for (name in this._vectors3) {
  25117. this._effect.setVector3(name, this._vectors3[name]);
  25118. }
  25119. // Matrix
  25120. for (name in this._matrices) {
  25121. this._effect.setMatrix(name, this._matrices[name]);
  25122. }
  25123. if (this.isCube) {
  25124. for (var face = 0; face < 6; face++) {
  25125. engine.bindFramebuffer(this._texture, face);
  25126. // VBOs
  25127. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  25128. this._effect.setFloat("face", face);
  25129. // Clear
  25130. engine.clear(scene.clearColor, true, true, true);
  25131. // Draw order
  25132. engine.draw(true, 0, 6);
  25133. // Mipmaps
  25134. if (face === 5) {
  25135. engine.generateMipMapsForCubemap(this._texture);
  25136. }
  25137. }
  25138. }
  25139. else {
  25140. engine.bindFramebuffer(this._texture);
  25141. // VBOs
  25142. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  25143. // Clear
  25144. engine.clear(scene.clearColor, true, true, true);
  25145. // Draw order
  25146. engine.draw(true, 0, 6);
  25147. }
  25148. // Unbind
  25149. engine.unBindFramebuffer(this._texture, this.isCube);
  25150. if (this.onGenerated) {
  25151. this.onGenerated();
  25152. }
  25153. };
  25154. ProceduralTexture.prototype.clone = function () {
  25155. var textureSize = this.getSize();
  25156. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  25157. // Base texture
  25158. newTexture.hasAlpha = this.hasAlpha;
  25159. newTexture.level = this.level;
  25160. // RenderTarget Texture
  25161. newTexture.coordinatesMode = this.coordinatesMode;
  25162. return newTexture;
  25163. };
  25164. ProceduralTexture.prototype.dispose = function () {
  25165. var index = this.getScene()._proceduralTextures.indexOf(this);
  25166. if (index >= 0) {
  25167. this.getScene()._proceduralTextures.splice(index, 1);
  25168. }
  25169. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  25170. if (vertexBuffer) {
  25171. vertexBuffer.dispose();
  25172. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  25173. }
  25174. if (this._indexBuffer && this.getScene().getEngine()._releaseBuffer(this._indexBuffer)) {
  25175. this._indexBuffer = null;
  25176. }
  25177. _super.prototype.dispose.call(this);
  25178. };
  25179. return ProceduralTexture;
  25180. }(BABYLON.Texture));
  25181. BABYLON.ProceduralTexture = ProceduralTexture;
  25182. })(BABYLON || (BABYLON = {}));
  25183. //# sourceMappingURL=babylon.proceduralTexture.js.map
  25184. var BABYLON;
  25185. (function (BABYLON) {
  25186. var MirrorTexture = (function (_super) {
  25187. __extends(MirrorTexture, _super);
  25188. function MirrorTexture(name, size, scene, generateMipMaps, type, samplingMode, generateDepthBuffer) {
  25189. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  25190. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  25191. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  25192. var _this = _super.call(this, name, size, scene, generateMipMaps, true, type, false, samplingMode, generateDepthBuffer) || this;
  25193. _this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  25194. _this._transformMatrix = BABYLON.Matrix.Zero();
  25195. _this._mirrorMatrix = BABYLON.Matrix.Zero();
  25196. _this.onBeforeRenderObservable.add(function () {
  25197. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  25198. _this._savedViewMatrix = scene.getViewMatrix();
  25199. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  25200. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  25201. scene.clipPlane = _this.mirrorPlane;
  25202. scene.getEngine().cullBackFaces = false;
  25203. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.position, _this._mirrorMatrix);
  25204. });
  25205. _this.onAfterRenderObservable.add(function () {
  25206. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  25207. scene.getEngine().cullBackFaces = true;
  25208. scene._mirroredCameraPosition = null;
  25209. delete scene.clipPlane;
  25210. });
  25211. return _this;
  25212. }
  25213. MirrorTexture.prototype.clone = function () {
  25214. var textureSize = this.getSize();
  25215. var newTexture = new MirrorTexture(this.name, textureSize.width, this.getScene(), this._renderTargetOptions.generateMipMaps, this._renderTargetOptions.type, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer);
  25216. // Base texture
  25217. newTexture.hasAlpha = this.hasAlpha;
  25218. newTexture.level = this.level;
  25219. // Mirror Texture
  25220. newTexture.mirrorPlane = this.mirrorPlane.clone();
  25221. newTexture.renderList = this.renderList.slice(0);
  25222. return newTexture;
  25223. };
  25224. MirrorTexture.prototype.serialize = function () {
  25225. if (!this.name) {
  25226. return null;
  25227. }
  25228. var serializationObject = _super.prototype.serialize.call(this);
  25229. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  25230. return serializationObject;
  25231. };
  25232. return MirrorTexture;
  25233. }(BABYLON.RenderTargetTexture));
  25234. BABYLON.MirrorTexture = MirrorTexture;
  25235. })(BABYLON || (BABYLON = {}));
  25236. //# sourceMappingURL=babylon.mirrorTexture.js.map
  25237. var BABYLON;
  25238. (function (BABYLON) {
  25239. /**
  25240. * Creates a refraction texture used by refraction channel of the standard material.
  25241. * @param name the texture name
  25242. * @param size size of the underlying texture
  25243. * @param scene root scene
  25244. */
  25245. var RefractionTexture = (function (_super) {
  25246. __extends(RefractionTexture, _super);
  25247. function RefractionTexture(name, size, scene, generateMipMaps) {
  25248. var _this = _super.call(this, name, size, scene, generateMipMaps, true) || this;
  25249. _this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  25250. _this.depth = 2.0;
  25251. _this.onBeforeRenderObservable.add(function () {
  25252. scene.clipPlane = _this.refractionPlane;
  25253. });
  25254. _this.onAfterRenderObservable.add(function () {
  25255. delete scene.clipPlane;
  25256. });
  25257. return _this;
  25258. }
  25259. RefractionTexture.prototype.clone = function () {
  25260. var textureSize = this.getSize();
  25261. var newTexture = new RefractionTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  25262. // Base texture
  25263. newTexture.hasAlpha = this.hasAlpha;
  25264. newTexture.level = this.level;
  25265. // Refraction Texture
  25266. newTexture.refractionPlane = this.refractionPlane.clone();
  25267. newTexture.renderList = this.renderList.slice(0);
  25268. newTexture.depth = this.depth;
  25269. return newTexture;
  25270. };
  25271. RefractionTexture.prototype.serialize = function () {
  25272. if (!this.name) {
  25273. return null;
  25274. }
  25275. var serializationObject = _super.prototype.serialize.call(this);
  25276. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  25277. serializationObject.depth = this.depth;
  25278. return serializationObject;
  25279. };
  25280. return RefractionTexture;
  25281. }(BABYLON.RenderTargetTexture));
  25282. BABYLON.RefractionTexture = RefractionTexture;
  25283. })(BABYLON || (BABYLON = {}));
  25284. //# sourceMappingURL=babylon.refractionTexture.js.map
  25285. var BABYLON;
  25286. (function (BABYLON) {
  25287. var DynamicTexture = (function (_super) {
  25288. __extends(DynamicTexture, _super);
  25289. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode) {
  25290. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  25291. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  25292. _this.name = name;
  25293. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  25294. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  25295. _this._generateMipMaps = generateMipMaps;
  25296. if (options.getContext) {
  25297. _this._canvas = options;
  25298. _this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  25299. }
  25300. else {
  25301. _this._canvas = document.createElement("canvas");
  25302. if (options.width) {
  25303. _this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  25304. }
  25305. else {
  25306. _this._texture = scene.getEngine().createDynamicTexture(options, options, generateMipMaps, samplingMode);
  25307. }
  25308. }
  25309. var textureSize = _this.getSize();
  25310. _this._canvas.width = textureSize.width;
  25311. _this._canvas.height = textureSize.height;
  25312. _this._context = _this._canvas.getContext("2d");
  25313. return _this;
  25314. }
  25315. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  25316. get: function () {
  25317. return true;
  25318. },
  25319. enumerable: true,
  25320. configurable: true
  25321. });
  25322. DynamicTexture.prototype.scale = function (ratio) {
  25323. var textureSize = this.getSize();
  25324. textureSize.width *= ratio;
  25325. textureSize.height *= ratio;
  25326. this._canvas.width = textureSize.width;
  25327. this._canvas.height = textureSize.height;
  25328. this.releaseInternalTexture();
  25329. this._texture = this.getScene().getEngine().createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  25330. };
  25331. DynamicTexture.prototype.getContext = function () {
  25332. return this._context;
  25333. };
  25334. DynamicTexture.prototype.clear = function () {
  25335. var size = this.getSize();
  25336. this._context.fillRect(0, 0, size.width, size.height);
  25337. };
  25338. DynamicTexture.prototype.update = function (invertY) {
  25339. this.getScene().getEngine().updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY);
  25340. };
  25341. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  25342. if (update === void 0) { update = true; }
  25343. var size = this.getSize();
  25344. if (clearColor) {
  25345. this._context.fillStyle = clearColor;
  25346. this._context.fillRect(0, 0, size.width, size.height);
  25347. }
  25348. this._context.font = font;
  25349. if (x === null) {
  25350. var textSize = this._context.measureText(text);
  25351. x = (size.width - textSize.width) / 2;
  25352. }
  25353. this._context.fillStyle = color;
  25354. this._context.fillText(text, x, y);
  25355. if (update) {
  25356. this.update(invertY);
  25357. }
  25358. };
  25359. DynamicTexture.prototype.clone = function () {
  25360. var textureSize = this.getSize();
  25361. var newTexture = new DynamicTexture(this.name, textureSize, this.getScene(), this._generateMipMaps);
  25362. // Base texture
  25363. newTexture.hasAlpha = this.hasAlpha;
  25364. newTexture.level = this.level;
  25365. // Dynamic Texture
  25366. newTexture.wrapU = this.wrapU;
  25367. newTexture.wrapV = this.wrapV;
  25368. return newTexture;
  25369. };
  25370. return DynamicTexture;
  25371. }(BABYLON.Texture));
  25372. BABYLON.DynamicTexture = DynamicTexture;
  25373. })(BABYLON || (BABYLON = {}));
  25374. //# sourceMappingURL=babylon.dynamicTexture.js.map
  25375. var BABYLON;
  25376. (function (BABYLON) {
  25377. var VideoTexture = (function (_super) {
  25378. __extends(VideoTexture, _super);
  25379. /**
  25380. * Creates a video texture.
  25381. * Sample : https://doc.babylonjs.com/tutorials/01._Advanced_Texturing
  25382. * @param {Array} urlsOrVideo can be used to provide an array of urls or an already setup HTML video element.
  25383. * @param {BABYLON.Scene} scene is obviously the current scene.
  25384. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  25385. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  25386. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  25387. */
  25388. function VideoTexture(name, urlsOrVideo, scene, generateMipMaps, invertY, samplingMode) {
  25389. if (generateMipMaps === void 0) { generateMipMaps = false; }
  25390. if (invertY === void 0) { invertY = false; }
  25391. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  25392. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  25393. _this._autoLaunch = true;
  25394. var urls;
  25395. _this.name = name;
  25396. if (urlsOrVideo instanceof HTMLVideoElement) {
  25397. _this.video = urlsOrVideo;
  25398. }
  25399. else {
  25400. urls = urlsOrVideo;
  25401. _this.video = document.createElement("video");
  25402. _this.video.autoplay = false;
  25403. _this.video.loop = true;
  25404. }
  25405. _this._generateMipMaps = generateMipMaps;
  25406. _this._samplingMode = samplingMode;
  25407. if (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight)) {
  25408. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  25409. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  25410. }
  25411. else {
  25412. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  25413. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  25414. _this._generateMipMaps = false;
  25415. }
  25416. if (urls) {
  25417. _this.video.addEventListener("canplaythrough", function () {
  25418. _this._createTexture();
  25419. });
  25420. urls.forEach(function (url) {
  25421. var source = document.createElement("source");
  25422. source.src = url;
  25423. _this.video.appendChild(source);
  25424. });
  25425. }
  25426. else {
  25427. _this._createTexture();
  25428. }
  25429. _this._lastUpdate = BABYLON.Tools.Now;
  25430. return _this;
  25431. }
  25432. VideoTexture.prototype._createTexture = function () {
  25433. this._texture = this.getScene().getEngine().createDynamicTexture(this.video.videoWidth, this.video.videoHeight, this._generateMipMaps, this._samplingMode);
  25434. this._texture.isReady = true;
  25435. };
  25436. VideoTexture.prototype.update = function () {
  25437. if (this._autoLaunch) {
  25438. this._autoLaunch = false;
  25439. this.video.play();
  25440. }
  25441. var now = BABYLON.Tools.Now;
  25442. if (now - this._lastUpdate < 15 || this.video.readyState !== this.video.HAVE_ENOUGH_DATA) {
  25443. return false;
  25444. }
  25445. this._lastUpdate = now;
  25446. this.getScene().getEngine().updateVideoTexture(this._texture, this.video, this._invertY);
  25447. return true;
  25448. };
  25449. VideoTexture.CreateFromWebCam = function (scene, onReady, constraints) {
  25450. var video = document.createElement("video");
  25451. navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia;
  25452. window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
  25453. if (navigator.getUserMedia) {
  25454. navigator.getUserMedia({
  25455. video: {
  25456. width: {
  25457. min: (constraints && constraints.minWidth) || 256,
  25458. max: (constraints && constraints.maxWidth) || 640
  25459. },
  25460. height: {
  25461. min: (constraints && constraints.minHeight) || 256,
  25462. max: (constraints && constraints.maxHeight) || 480
  25463. }
  25464. }
  25465. }, function (stream) {
  25466. if (video.mozSrcObject !== undefined) {
  25467. video.mozSrcObject = stream;
  25468. }
  25469. else {
  25470. video.src = (window.URL && window.URL.createObjectURL(stream)) || stream;
  25471. }
  25472. video.play();
  25473. if (onReady) {
  25474. onReady(new BABYLON.VideoTexture("video", video, scene, true, true));
  25475. }
  25476. }, function (e) {
  25477. BABYLON.Tools.Error(e.name);
  25478. });
  25479. }
  25480. };
  25481. return VideoTexture;
  25482. }(BABYLON.Texture));
  25483. BABYLON.VideoTexture = VideoTexture;
  25484. })(BABYLON || (BABYLON = {}));
  25485. //# sourceMappingURL=babylon.videoTexture.js.map
  25486. var BABYLON;
  25487. (function (BABYLON) {
  25488. var CustomProceduralTexture = (function (_super) {
  25489. __extends(CustomProceduralTexture, _super);
  25490. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  25491. var _this = _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps) || this;
  25492. _this._animate = true;
  25493. _this._time = 0;
  25494. _this._texturePath = texturePath;
  25495. //Try to load json
  25496. _this.loadJson(texturePath);
  25497. _this.refreshRate = 1;
  25498. return _this;
  25499. }
  25500. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  25501. var _this = this;
  25502. var that = this;
  25503. function noConfigFile() {
  25504. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  25505. try {
  25506. that.setFragment(that._texturePath);
  25507. }
  25508. catch (ex) {
  25509. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  25510. }
  25511. }
  25512. var configFileUrl = jsonUrl + "/config.json";
  25513. var xhr = new XMLHttpRequest();
  25514. xhr.open("GET", configFileUrl, true);
  25515. xhr.addEventListener("load", function () {
  25516. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  25517. try {
  25518. _this._config = JSON.parse(xhr.response);
  25519. _this.updateShaderUniforms();
  25520. _this.updateTextures();
  25521. _this.setFragment(_this._texturePath + "/custom");
  25522. _this._animate = _this._config.animate;
  25523. _this.refreshRate = _this._config.refreshrate;
  25524. }
  25525. catch (ex) {
  25526. noConfigFile();
  25527. }
  25528. }
  25529. else {
  25530. noConfigFile();
  25531. }
  25532. }, false);
  25533. xhr.addEventListener("error", function () {
  25534. noConfigFile();
  25535. }, false);
  25536. try {
  25537. xhr.send();
  25538. }
  25539. catch (ex) {
  25540. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  25541. }
  25542. };
  25543. CustomProceduralTexture.prototype.isReady = function () {
  25544. if (!_super.prototype.isReady.call(this)) {
  25545. return false;
  25546. }
  25547. for (var name in this._textures) {
  25548. var texture = this._textures[name];
  25549. if (!texture.isReady()) {
  25550. return false;
  25551. }
  25552. }
  25553. return true;
  25554. };
  25555. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  25556. if (this._animate) {
  25557. this._time += this.getScene().getAnimationRatio() * 0.03;
  25558. this.updateShaderUniforms();
  25559. }
  25560. _super.prototype.render.call(this, useCameraPostProcess);
  25561. };
  25562. CustomProceduralTexture.prototype.updateTextures = function () {
  25563. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  25564. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  25565. }
  25566. };
  25567. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  25568. if (this._config) {
  25569. for (var j = 0; j < this._config.uniforms.length; j++) {
  25570. var uniform = this._config.uniforms[j];
  25571. switch (uniform.type) {
  25572. case "float":
  25573. this.setFloat(uniform.name, uniform.value);
  25574. break;
  25575. case "color3":
  25576. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  25577. break;
  25578. case "color4":
  25579. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  25580. break;
  25581. case "vector2":
  25582. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  25583. break;
  25584. case "vector3":
  25585. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  25586. break;
  25587. }
  25588. }
  25589. }
  25590. this.setFloat("time", this._time);
  25591. };
  25592. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  25593. get: function () {
  25594. return this._animate;
  25595. },
  25596. set: function (value) {
  25597. this._animate = value;
  25598. },
  25599. enumerable: true,
  25600. configurable: true
  25601. });
  25602. return CustomProceduralTexture;
  25603. }(BABYLON.ProceduralTexture));
  25604. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  25605. })(BABYLON || (BABYLON = {}));
  25606. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  25607. var BABYLON;
  25608. (function (BABYLON) {
  25609. var EffectFallbacks = (function () {
  25610. function EffectFallbacks() {
  25611. this._defines = {};
  25612. this._currentRank = 32;
  25613. this._maxRank = -1;
  25614. }
  25615. EffectFallbacks.prototype.addFallback = function (rank, define) {
  25616. if (!this._defines[rank]) {
  25617. if (rank < this._currentRank) {
  25618. this._currentRank = rank;
  25619. }
  25620. if (rank > this._maxRank) {
  25621. this._maxRank = rank;
  25622. }
  25623. this._defines[rank] = new Array();
  25624. }
  25625. this._defines[rank].push(define);
  25626. };
  25627. EffectFallbacks.prototype.addCPUSkinningFallback = function (rank, mesh) {
  25628. this._meshRank = rank;
  25629. this._mesh = mesh;
  25630. if (rank > this._maxRank) {
  25631. this._maxRank = rank;
  25632. }
  25633. };
  25634. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  25635. get: function () {
  25636. return this._currentRank <= this._maxRank;
  25637. },
  25638. enumerable: true,
  25639. configurable: true
  25640. });
  25641. EffectFallbacks.prototype.reduce = function (currentDefines) {
  25642. var currentFallbacks = this._defines[this._currentRank];
  25643. for (var index = 0; index < currentFallbacks.length; index++) {
  25644. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  25645. }
  25646. if (this._mesh && this._currentRank === this._meshRank) {
  25647. this._mesh.computeBonesUsingShaders = false;
  25648. currentDefines = currentDefines.replace("#define NUM_BONE_INFLUENCERS " + this._mesh.numBoneInfluencers, "#define NUM_BONE_INFLUENCERS 0");
  25649. BABYLON.Tools.Log("Falling back to CPU skinning for " + this._mesh.name);
  25650. }
  25651. this._currentRank++;
  25652. return currentDefines;
  25653. };
  25654. return EffectFallbacks;
  25655. }());
  25656. BABYLON.EffectFallbacks = EffectFallbacks;
  25657. var Effect = (function () {
  25658. function Effect(baseName, attributesNames, uniformsNames, samplers, engine, defines, fallbacks, onCompiled, onError, indexParameters) {
  25659. var _this = this;
  25660. this.uniqueId = 0;
  25661. this._isReady = false;
  25662. this._compilationError = "";
  25663. this._valueCache = {};
  25664. this._engine = engine;
  25665. this.name = baseName;
  25666. this.defines = defines;
  25667. this._uniformsNames = uniformsNames.concat(samplers);
  25668. this._samplers = samplers;
  25669. this._attributesNames = attributesNames;
  25670. this.onError = onError;
  25671. this.onCompiled = onCompiled;
  25672. this._indexParameters = indexParameters;
  25673. this.uniqueId = Effect._uniqueIdSeed++;
  25674. var vertexSource;
  25675. var fragmentSource;
  25676. if (baseName.vertexElement) {
  25677. vertexSource = document.getElementById(baseName.vertexElement);
  25678. if (!vertexSource) {
  25679. vertexSource = baseName.vertexElement;
  25680. }
  25681. }
  25682. else {
  25683. vertexSource = baseName.vertex || baseName;
  25684. }
  25685. if (baseName.fragmentElement) {
  25686. fragmentSource = document.getElementById(baseName.fragmentElement);
  25687. if (!fragmentSource) {
  25688. fragmentSource = baseName.fragmentElement;
  25689. }
  25690. }
  25691. else {
  25692. fragmentSource = baseName.fragment || baseName;
  25693. }
  25694. this._loadVertexShader(vertexSource, function (vertexCode) {
  25695. _this._processIncludes(vertexCode, function (vertexCodeWithIncludes) {
  25696. _this._processShaderConversion(vertexCodeWithIncludes, false, function (migratedVertexCode) {
  25697. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  25698. _this._processIncludes(fragmentCode, function (fragmentCodeWithIncludes) {
  25699. _this._processShaderConversion(fragmentCodeWithIncludes, true, function (migratedFragmentCode) {
  25700. _this._prepareEffect(migratedVertexCode, migratedFragmentCode, attributesNames, defines, fallbacks);
  25701. });
  25702. });
  25703. });
  25704. });
  25705. });
  25706. });
  25707. }
  25708. Object.defineProperty(Effect.prototype, "key", {
  25709. get: function () {
  25710. return this._key;
  25711. },
  25712. enumerable: true,
  25713. configurable: true
  25714. });
  25715. // Properties
  25716. Effect.prototype.isReady = function () {
  25717. return this._isReady;
  25718. };
  25719. Effect.prototype.getProgram = function () {
  25720. return this._program;
  25721. };
  25722. Effect.prototype.getAttributesNames = function () {
  25723. return this._attributesNames;
  25724. };
  25725. Effect.prototype.getAttributeLocation = function (index) {
  25726. return this._attributes[index];
  25727. };
  25728. Effect.prototype.getAttributeLocationByName = function (name) {
  25729. var index = this._attributesNames.indexOf(name);
  25730. return this._attributes[index];
  25731. };
  25732. Effect.prototype.getAttributesCount = function () {
  25733. return this._attributes.length;
  25734. };
  25735. Effect.prototype.getUniformIndex = function (uniformName) {
  25736. return this._uniformsNames.indexOf(uniformName);
  25737. };
  25738. Effect.prototype.getUniform = function (uniformName) {
  25739. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  25740. };
  25741. Effect.prototype.getSamplers = function () {
  25742. return this._samplers;
  25743. };
  25744. Effect.prototype.getCompilationError = function () {
  25745. return this._compilationError;
  25746. };
  25747. Effect.prototype.getVertexShaderSource = function () {
  25748. return this._evaluateDefinesOnString(this._engine.getVertexShaderSource(this._program));
  25749. };
  25750. Effect.prototype.getFragmentShaderSource = function () {
  25751. return this._evaluateDefinesOnString(this._engine.getFragmentShaderSource(this._program));
  25752. };
  25753. // Methods
  25754. Effect.prototype._loadVertexShader = function (vertex, callback) {
  25755. // DOM element ?
  25756. if (vertex instanceof HTMLElement) {
  25757. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  25758. callback(vertexCode);
  25759. return;
  25760. }
  25761. // Base64 encoded ?
  25762. if (vertex.substr(0, 7) === "base64:") {
  25763. var vertexBinary = window.atob(vertex.substr(7));
  25764. callback(vertexBinary);
  25765. return;
  25766. }
  25767. // Is in local store ?
  25768. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  25769. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  25770. return;
  25771. }
  25772. var vertexShaderUrl;
  25773. if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
  25774. vertexShaderUrl = vertex;
  25775. }
  25776. else {
  25777. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  25778. }
  25779. // Vertex shader
  25780. BABYLON.Tools.LoadFile(vertexShaderUrl + ".vertex.fx", callback);
  25781. };
  25782. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  25783. // DOM element ?
  25784. if (fragment instanceof HTMLElement) {
  25785. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  25786. callback(fragmentCode);
  25787. return;
  25788. }
  25789. // Base64 encoded ?
  25790. if (fragment.substr(0, 7) === "base64:") {
  25791. var fragmentBinary = window.atob(fragment.substr(7));
  25792. callback(fragmentBinary);
  25793. return;
  25794. }
  25795. // Is in local store ?
  25796. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  25797. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  25798. return;
  25799. }
  25800. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  25801. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  25802. return;
  25803. }
  25804. var fragmentShaderUrl;
  25805. if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
  25806. fragmentShaderUrl = fragment;
  25807. }
  25808. else {
  25809. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  25810. }
  25811. // Fragment shader
  25812. BABYLON.Tools.LoadFile(fragmentShaderUrl + ".fragment.fx", callback);
  25813. };
  25814. Effect.prototype._dumpShadersName = function () {
  25815. if (this.name.vertexElement) {
  25816. BABYLON.Tools.Error("Vertex shader:" + this.name.vertexElement);
  25817. BABYLON.Tools.Error("Fragment shader:" + this.name.fragmentElement);
  25818. }
  25819. else if (this.name.vertex) {
  25820. BABYLON.Tools.Error("Vertex shader:" + this.name.vertex);
  25821. BABYLON.Tools.Error("Fragment shader:" + this.name.fragment);
  25822. }
  25823. else {
  25824. BABYLON.Tools.Error("Vertex shader:" + this.name);
  25825. BABYLON.Tools.Error("Fragment shader:" + this.name);
  25826. }
  25827. };
  25828. Effect.prototype._processShaderConversion = function (sourceCode, isFragment, callback) {
  25829. var preparedSourceCode = this._processPrecision(sourceCode);
  25830. if (this._engine.webGLVersion == 1) {
  25831. callback(preparedSourceCode);
  25832. return;
  25833. }
  25834. // Already converted
  25835. if (preparedSourceCode.indexOf("#version 3") !== -1) {
  25836. callback(preparedSourceCode);
  25837. return;
  25838. }
  25839. // Remove extensions
  25840. // #extension GL_OES_standard_derivatives : enable
  25841. // #extension GL_EXT_shader_texture_lod : enable
  25842. // #extension GL_EXT_frag_depth : enable
  25843. var regex = /#extension.+(GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_frag_depth).+enable/g;
  25844. var result = preparedSourceCode.replace(regex, "");
  25845. // Migrate to GLSL v300
  25846. result = result.replace(/varying\s/g, isFragment ? "in " : "out ");
  25847. result = result.replace(/attribute[ \t]/g, "in ");
  25848. result = result.replace(/[ \t]attribute/g, " in");
  25849. if (isFragment) {
  25850. result = result.replace(/textureCubeLodEXT\(/g, "textureLod(");
  25851. result = result.replace(/texture2D\(/g, "texture(");
  25852. result = result.replace(/textureCube\(/g, "texture(");
  25853. result = result.replace(/gl_FragDepthEXT/g, "gl_FragDepth");
  25854. result = result.replace(/gl_FragColor/g, "glFragColor");
  25855. result = result.replace(/void\s+?main\(/g, "out vec4 glFragColor;\nvoid main(");
  25856. }
  25857. callback(result);
  25858. };
  25859. Effect.prototype._processIncludes = function (sourceCode, callback) {
  25860. var _this = this;
  25861. var regex = /#include<(.+)>(\((.*)\))*(\[(.*)\])*/g;
  25862. var match = regex.exec(sourceCode);
  25863. var returnValue = new String(sourceCode);
  25864. while (match != null) {
  25865. var includeFile = match[1];
  25866. if (Effect.IncludesShadersStore[includeFile]) {
  25867. // Substitution
  25868. var includeContent = Effect.IncludesShadersStore[includeFile];
  25869. if (match[2]) {
  25870. var splits = match[3].split(",");
  25871. for (var index = 0; index < splits.length; index += 2) {
  25872. var source = new RegExp(splits[index], "g");
  25873. var dest = splits[index + 1];
  25874. includeContent = includeContent.replace(source, dest);
  25875. }
  25876. }
  25877. if (match[4]) {
  25878. var indexString = match[5];
  25879. if (indexString.indexOf("..") !== -1) {
  25880. var indexSplits = indexString.split("..");
  25881. var minIndex = parseInt(indexSplits[0]);
  25882. var maxIndex = parseInt(indexSplits[1]);
  25883. var sourceIncludeContent = includeContent.slice(0);
  25884. includeContent = "";
  25885. if (isNaN(maxIndex)) {
  25886. maxIndex = this._indexParameters[indexSplits[1]];
  25887. }
  25888. for (var i = minIndex; i <= maxIndex; i++) {
  25889. includeContent += sourceIncludeContent.replace(/\{X\}/g, i) + "\n";
  25890. }
  25891. }
  25892. else {
  25893. includeContent = includeContent.replace(/\{X\}/g, indexString);
  25894. }
  25895. }
  25896. // Replace
  25897. returnValue = returnValue.replace(match[0], includeContent);
  25898. }
  25899. else {
  25900. var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
  25901. BABYLON.Tools.LoadFile(includeShaderUrl, function (fileContent) {
  25902. Effect.IncludesShadersStore[includeFile] = fileContent;
  25903. _this._processIncludes(returnValue, callback);
  25904. });
  25905. return;
  25906. }
  25907. match = regex.exec(sourceCode);
  25908. }
  25909. callback(returnValue);
  25910. };
  25911. Effect.prototype._processPrecision = function (source) {
  25912. if (source.indexOf("precision highp float") === -1) {
  25913. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  25914. source = "precision mediump float;\n" + source;
  25915. }
  25916. else {
  25917. source = "precision highp float;\n" + source;
  25918. }
  25919. }
  25920. else {
  25921. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  25922. source = source.replace("precision highp float", "precision mediump float");
  25923. }
  25924. }
  25925. return source;
  25926. };
  25927. Effect.prototype._prepareEffect = function (vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks) {
  25928. try {
  25929. var engine = this._engine;
  25930. this._program = engine.createShaderProgram(vertexSourceCode, fragmentSourceCode, defines);
  25931. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  25932. this._attributes = engine.getAttributes(this._program, attributesNames);
  25933. var index;
  25934. for (index = 0; index < this._samplers.length; index++) {
  25935. var sampler = this.getUniform(this._samplers[index]);
  25936. if (sampler == null) {
  25937. this._samplers.splice(index, 1);
  25938. index--;
  25939. }
  25940. }
  25941. engine.bindSamplers(this);
  25942. this._compilationError = "";
  25943. this._isReady = true;
  25944. if (this.onCompiled) {
  25945. this.onCompiled(this);
  25946. }
  25947. }
  25948. catch (e) {
  25949. this._compilationError = e.message;
  25950. // Let's go through fallbacks then
  25951. BABYLON.Tools.Error("Unable to compile effect: ");
  25952. BABYLON.Tools.Error("Defines: " + defines);
  25953. BABYLON.Tools.Error("Error: " + this._compilationError);
  25954. this._dumpShadersName();
  25955. if (fallbacks && fallbacks.isMoreFallbacks) {
  25956. BABYLON.Tools.Error("Trying next fallback.");
  25957. defines = fallbacks.reduce(defines);
  25958. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  25959. }
  25960. else {
  25961. if (this.onError) {
  25962. this.onError(this, this._compilationError);
  25963. }
  25964. }
  25965. }
  25966. };
  25967. Object.defineProperty(Effect.prototype, "isSupported", {
  25968. get: function () {
  25969. return this._compilationError === "";
  25970. },
  25971. enumerable: true,
  25972. configurable: true
  25973. });
  25974. Effect.prototype._bindTexture = function (channel, texture) {
  25975. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  25976. };
  25977. Effect.prototype.setTexture = function (channel, texture) {
  25978. this._engine.setTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  25979. };
  25980. Effect.prototype.setTextureArray = function (channel, textures) {
  25981. if (this._samplers.indexOf(channel + "Ex") === -1) {
  25982. var initialPos = this._samplers.indexOf(channel);
  25983. for (var index = 1; index < textures.length; index++) {
  25984. this._samplers.splice(initialPos + index, 0, channel + "Ex");
  25985. }
  25986. }
  25987. this._engine.setTextureArray(this._samplers.indexOf(channel), this.getUniform(channel), textures);
  25988. };
  25989. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  25990. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  25991. };
  25992. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  25993. var changed = false;
  25994. var cache = this._valueCache[uniformName];
  25995. if (!cache || !(cache instanceof BABYLON.Matrix)) {
  25996. changed = true;
  25997. cache = new BABYLON.Matrix();
  25998. }
  25999. var tm = cache.m;
  26000. var om = matrix.m;
  26001. for (var index = 0; index < 16; index++) {
  26002. if (tm[index] !== om[index]) {
  26003. tm[index] = om[index];
  26004. changed = true;
  26005. }
  26006. }
  26007. this._valueCache[uniformName] = cache;
  26008. return changed;
  26009. };
  26010. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  26011. var cache = this._valueCache[uniformName];
  26012. if (!cache) {
  26013. cache = [x, y];
  26014. this._valueCache[uniformName] = cache;
  26015. return true;
  26016. }
  26017. var changed = false;
  26018. if (cache[0] !== x) {
  26019. cache[0] = x;
  26020. changed = true;
  26021. }
  26022. if (cache[1] !== y) {
  26023. cache[1] = y;
  26024. changed = true;
  26025. }
  26026. return changed;
  26027. };
  26028. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  26029. var cache = this._valueCache[uniformName];
  26030. if (!cache) {
  26031. cache = [x, y, z];
  26032. this._valueCache[uniformName] = cache;
  26033. return true;
  26034. }
  26035. var changed = false;
  26036. if (cache[0] !== x) {
  26037. cache[0] = x;
  26038. changed = true;
  26039. }
  26040. if (cache[1] !== y) {
  26041. cache[1] = y;
  26042. changed = true;
  26043. }
  26044. if (cache[2] !== z) {
  26045. cache[2] = z;
  26046. changed = true;
  26047. }
  26048. return changed;
  26049. };
  26050. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  26051. var cache = this._valueCache[uniformName];
  26052. if (!cache) {
  26053. cache = [x, y, z, w];
  26054. this._valueCache[uniformName] = cache;
  26055. return true;
  26056. }
  26057. var changed = false;
  26058. if (cache[0] !== x) {
  26059. cache[0] = x;
  26060. changed = true;
  26061. }
  26062. if (cache[1] !== y) {
  26063. cache[1] = y;
  26064. changed = true;
  26065. }
  26066. if (cache[2] !== z) {
  26067. cache[2] = z;
  26068. changed = true;
  26069. }
  26070. if (cache[3] !== w) {
  26071. cache[3] = w;
  26072. changed = true;
  26073. }
  26074. return changed;
  26075. };
  26076. Effect.prototype.setIntArray = function (uniformName, array) {
  26077. this._valueCache[uniformName] = null;
  26078. this._engine.setIntArray(this.getUniform(uniformName), array);
  26079. return this;
  26080. };
  26081. Effect.prototype.setIntArray2 = function (uniformName, array) {
  26082. this._valueCache[uniformName] = null;
  26083. this._engine.setIntArray2(this.getUniform(uniformName), array);
  26084. return this;
  26085. };
  26086. Effect.prototype.setIntArray3 = function (uniformName, array) {
  26087. this._valueCache[uniformName] = null;
  26088. this._engine.setIntArray3(this.getUniform(uniformName), array);
  26089. return this;
  26090. };
  26091. Effect.prototype.setIntArray4 = function (uniformName, array) {
  26092. this._valueCache[uniformName] = null;
  26093. this._engine.setIntArray4(this.getUniform(uniformName), array);
  26094. return this;
  26095. };
  26096. Effect.prototype.setFloatArray = function (uniformName, array) {
  26097. this._valueCache[uniformName] = null;
  26098. this._engine.setFloatArray(this.getUniform(uniformName), array);
  26099. return this;
  26100. };
  26101. Effect.prototype.setFloatArray2 = function (uniformName, array) {
  26102. this._valueCache[uniformName] = null;
  26103. this._engine.setFloatArray2(this.getUniform(uniformName), array);
  26104. return this;
  26105. };
  26106. Effect.prototype.setFloatArray3 = function (uniformName, array) {
  26107. this._valueCache[uniformName] = null;
  26108. this._engine.setFloatArray3(this.getUniform(uniformName), array);
  26109. return this;
  26110. };
  26111. Effect.prototype.setFloatArray4 = function (uniformName, array) {
  26112. this._valueCache[uniformName] = null;
  26113. this._engine.setFloatArray4(this.getUniform(uniformName), array);
  26114. return this;
  26115. };
  26116. Effect.prototype.setArray = function (uniformName, array) {
  26117. this._valueCache[uniformName] = null;
  26118. this._engine.setArray(this.getUniform(uniformName), array);
  26119. return this;
  26120. };
  26121. Effect.prototype.setArray2 = function (uniformName, array) {
  26122. this._valueCache[uniformName] = null;
  26123. this._engine.setArray2(this.getUniform(uniformName), array);
  26124. return this;
  26125. };
  26126. Effect.prototype.setArray3 = function (uniformName, array) {
  26127. this._valueCache[uniformName] = null;
  26128. this._engine.setArray3(this.getUniform(uniformName), array);
  26129. return this;
  26130. };
  26131. Effect.prototype.setArray4 = function (uniformName, array) {
  26132. this._valueCache[uniformName] = null;
  26133. this._engine.setArray4(this.getUniform(uniformName), array);
  26134. return this;
  26135. };
  26136. Effect.prototype.setMatrices = function (uniformName, matrices) {
  26137. this._valueCache[uniformName] = null;
  26138. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  26139. return this;
  26140. };
  26141. Effect.prototype.setMatrix = function (uniformName, matrix) {
  26142. if (this._cacheMatrix(uniformName, matrix)) {
  26143. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  26144. }
  26145. return this;
  26146. };
  26147. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  26148. this._valueCache[uniformName] = null;
  26149. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  26150. return this;
  26151. };
  26152. Effect.prototype.setMatrix2x2 = function (uniformName, matrix) {
  26153. this._valueCache[uniformName] = null;
  26154. this._engine.setMatrix2x2(this.getUniform(uniformName), matrix);
  26155. return this;
  26156. };
  26157. Effect.prototype.setFloat = function (uniformName, value) {
  26158. var cache = this._valueCache[uniformName];
  26159. if (cache !== undefined && cache === value)
  26160. return this;
  26161. this._valueCache[uniformName] = value;
  26162. this._engine.setFloat(this.getUniform(uniformName), value);
  26163. return this;
  26164. };
  26165. Effect.prototype.setBool = function (uniformName, bool) {
  26166. var cache = this._valueCache[uniformName];
  26167. if (cache !== undefined && cache === bool)
  26168. return this;
  26169. this._valueCache[uniformName] = bool;
  26170. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  26171. return this;
  26172. };
  26173. Effect.prototype.setVector2 = function (uniformName, vector2) {
  26174. if (this._cacheFloat2(uniformName, vector2.x, vector2.y)) {
  26175. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  26176. }
  26177. return this;
  26178. };
  26179. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  26180. if (this._cacheFloat2(uniformName, x, y)) {
  26181. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  26182. }
  26183. return this;
  26184. };
  26185. Effect.prototype.setVector3 = function (uniformName, vector3) {
  26186. if (this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z)) {
  26187. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  26188. }
  26189. return this;
  26190. };
  26191. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  26192. if (this._cacheFloat3(uniformName, x, y, z)) {
  26193. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  26194. }
  26195. return this;
  26196. };
  26197. Effect.prototype.setVector4 = function (uniformName, vector4) {
  26198. if (this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w)) {
  26199. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  26200. }
  26201. return this;
  26202. };
  26203. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  26204. if (this._cacheFloat4(uniformName, x, y, z, w)) {
  26205. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  26206. }
  26207. return this;
  26208. };
  26209. Effect.prototype.setColor3 = function (uniformName, color3) {
  26210. if (this._cacheFloat3(uniformName, color3.r, color3.g, color3.b)) {
  26211. this._engine.setColor3(this.getUniform(uniformName), color3);
  26212. }
  26213. return this;
  26214. };
  26215. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  26216. if (this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha)) {
  26217. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  26218. }
  26219. return this;
  26220. };
  26221. Effect.prototype._recombineShader = function (node) {
  26222. if (node.define) {
  26223. if (node.condition) {
  26224. var defineIndex = this.defines.indexOf("#define " + node.define);
  26225. if (defineIndex === -1) {
  26226. return null;
  26227. }
  26228. var nextComma = this.defines.indexOf("\n", defineIndex);
  26229. var defineValue = this.defines.substr(defineIndex + 7, nextComma - defineIndex - 7).replace(node.define, "").trim();
  26230. var condition = defineValue + node.condition;
  26231. if (!eval(condition)) {
  26232. return null;
  26233. }
  26234. }
  26235. else if (node.ndef) {
  26236. if (this.defines.indexOf("#define " + node.define) !== -1) {
  26237. return null;
  26238. }
  26239. }
  26240. else if (this.defines.indexOf("#define " + node.define) === -1) {
  26241. return null;
  26242. }
  26243. }
  26244. var result = "";
  26245. for (var index = 0; index < node.children.length; index++) {
  26246. var line = node.children[index];
  26247. if (line.children) {
  26248. var combined = this._recombineShader(line);
  26249. if (combined !== null) {
  26250. result += combined + "\r\n";
  26251. }
  26252. continue;
  26253. }
  26254. if (line.length > 0) {
  26255. result += line + "\r\n";
  26256. }
  26257. }
  26258. return result;
  26259. };
  26260. Effect.prototype._evaluateDefinesOnString = function (shaderString) {
  26261. var root = {
  26262. children: []
  26263. };
  26264. var currentNode = root;
  26265. var lines = shaderString.split("\n");
  26266. for (var index = 0; index < lines.length; index++) {
  26267. var line = lines[index].trim();
  26268. // #ifdef
  26269. var pos = line.indexOf("#ifdef ");
  26270. if (pos !== -1) {
  26271. var define = line.substr(pos + 7);
  26272. var newNode = {
  26273. condition: null,
  26274. ndef: false,
  26275. define: define,
  26276. children: [],
  26277. parent: currentNode
  26278. };
  26279. currentNode.children.push(newNode);
  26280. currentNode = newNode;
  26281. continue;
  26282. }
  26283. // #ifndef
  26284. var pos = line.indexOf("#ifndef ");
  26285. if (pos !== -1) {
  26286. var define = line.substr(pos + 8);
  26287. newNode = {
  26288. condition: null,
  26289. define: define,
  26290. ndef: true,
  26291. children: [],
  26292. parent: currentNode
  26293. };
  26294. currentNode.children.push(newNode);
  26295. currentNode = newNode;
  26296. continue;
  26297. }
  26298. // #if
  26299. var pos = line.indexOf("#if ");
  26300. if (pos !== -1) {
  26301. var define = line.substr(pos + 4).trim();
  26302. var conditionPos = define.indexOf(" ");
  26303. newNode = {
  26304. condition: define.substr(conditionPos + 1),
  26305. define: define.substr(0, conditionPos),
  26306. ndef: false,
  26307. children: [],
  26308. parent: currentNode
  26309. };
  26310. currentNode.children.push(newNode);
  26311. currentNode = newNode;
  26312. continue;
  26313. }
  26314. // #endif
  26315. pos = line.indexOf("#endif");
  26316. if (pos !== -1) {
  26317. currentNode = currentNode.parent;
  26318. continue;
  26319. }
  26320. currentNode.children.push(line);
  26321. }
  26322. // Recombine
  26323. return this._recombineShader(root);
  26324. };
  26325. return Effect;
  26326. }());
  26327. Effect._uniqueIdSeed = 0;
  26328. // Statics
  26329. Effect.ShadersStore = {};
  26330. Effect.IncludesShadersStore = {};
  26331. BABYLON.Effect = Effect;
  26332. })(BABYLON || (BABYLON = {}));
  26333. //# sourceMappingURL=babylon.effect.js.map
  26334. var BABYLON;
  26335. (function (BABYLON) {
  26336. var MaterialHelper = (function () {
  26337. function MaterialHelper() {
  26338. }
  26339. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, maxSimultaneousLights) {
  26340. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  26341. var lightIndex = 0;
  26342. var needNormals = false;
  26343. var needRebuild = false;
  26344. var needShadows = false;
  26345. var lightmapMode = false;
  26346. for (var index = 0; index < scene.lights.length; index++) {
  26347. var light = scene.lights[index];
  26348. if (!light.isEnabled()) {
  26349. continue;
  26350. }
  26351. // Excluded check
  26352. if (light._excludedMeshesIds.length > 0) {
  26353. for (var excludedIndex = 0; excludedIndex < light._excludedMeshesIds.length; excludedIndex++) {
  26354. var excludedMesh = scene.getMeshByID(light._excludedMeshesIds[excludedIndex]);
  26355. if (excludedMesh) {
  26356. light.excludedMeshes.push(excludedMesh);
  26357. }
  26358. }
  26359. light._excludedMeshesIds = [];
  26360. }
  26361. // Included check
  26362. if (light._includedOnlyMeshesIds.length > 0) {
  26363. for (var includedOnlyIndex = 0; includedOnlyIndex < light._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  26364. var includedOnlyMesh = scene.getMeshByID(light._includedOnlyMeshesIds[includedOnlyIndex]);
  26365. if (includedOnlyMesh) {
  26366. light.includedOnlyMeshes.push(includedOnlyMesh);
  26367. }
  26368. }
  26369. light._includedOnlyMeshesIds = [];
  26370. }
  26371. if (!light.canAffectMesh(mesh)) {
  26372. continue;
  26373. }
  26374. needNormals = true;
  26375. if (defines["LIGHT" + lightIndex] === undefined) {
  26376. needRebuild = true;
  26377. }
  26378. defines["LIGHT" + lightIndex] = true;
  26379. var type;
  26380. if (light instanceof BABYLON.SpotLight) {
  26381. type = "SPOTLIGHT" + lightIndex;
  26382. }
  26383. else if (light instanceof BABYLON.HemisphericLight) {
  26384. type = "HEMILIGHT" + lightIndex;
  26385. }
  26386. else if (light instanceof BABYLON.PointLight) {
  26387. type = "POINTLIGHT" + lightIndex;
  26388. }
  26389. else {
  26390. type = "DIRLIGHT" + lightIndex;
  26391. }
  26392. if (defines[type] === undefined) {
  26393. needRebuild = true;
  26394. }
  26395. defines[type] = true;
  26396. // Specular
  26397. if (!light.specular.equalsFloats(0, 0, 0) && defines["SPECULARTERM"] !== undefined) {
  26398. defines["SPECULARTERM"] = true;
  26399. }
  26400. // Shadows
  26401. if (scene.shadowsEnabled) {
  26402. var shadowGenerator = light.getShadowGenerator();
  26403. if (mesh && mesh.receiveShadows && shadowGenerator) {
  26404. if (defines["SHADOW" + lightIndex] === undefined) {
  26405. needRebuild = true;
  26406. }
  26407. defines["SHADOW" + lightIndex] = true;
  26408. defines["SHADOWS"] = true;
  26409. if (shadowGenerator.useVarianceShadowMap || shadowGenerator.useBlurVarianceShadowMap) {
  26410. if (defines["SHADOWVSM" + lightIndex] === undefined) {
  26411. needRebuild = true;
  26412. }
  26413. defines["SHADOWVSM" + lightIndex] = true;
  26414. }
  26415. if (shadowGenerator.usePoissonSampling) {
  26416. if (defines["SHADOWPCF" + lightIndex] === undefined) {
  26417. needRebuild = true;
  26418. }
  26419. defines["SHADOWPCF" + lightIndex] = true;
  26420. }
  26421. needShadows = true;
  26422. }
  26423. }
  26424. if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
  26425. lightmapMode = true;
  26426. if (defines["LIGHTMAPEXCLUDED" + lightIndex] === undefined) {
  26427. needRebuild = true;
  26428. }
  26429. if (defines["LIGHTMAPNOSPECULAR" + lightIndex] === undefined) {
  26430. needRebuild = true;
  26431. }
  26432. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  26433. if (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY) {
  26434. defines["LIGHTMAPNOSPECULAR" + lightIndex] = true;
  26435. }
  26436. }
  26437. lightIndex++;
  26438. if (lightIndex === maxSimultaneousLights)
  26439. break;
  26440. }
  26441. var caps = scene.getEngine().getCaps();
  26442. if (needShadows && caps.textureFloat && caps.textureFloatLinearFiltering && caps.textureFloatRender) {
  26443. if (defines["SHADOWFULLFLOAT"] === undefined) {
  26444. needRebuild = true;
  26445. }
  26446. defines["SHADOWFULLFLOAT"] = true;
  26447. }
  26448. if (defines["LIGHTMAPEXCLUDED"] === undefined) {
  26449. needRebuild = true;
  26450. }
  26451. if (lightmapMode) {
  26452. defines["LIGHTMAPEXCLUDED"] = true;
  26453. }
  26454. if (needRebuild) {
  26455. defines.rebuild();
  26456. }
  26457. return needNormals;
  26458. };
  26459. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsList, samplersList, defines, maxSimultaneousLights) {
  26460. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  26461. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  26462. if (!defines["LIGHT" + lightIndex]) {
  26463. break;
  26464. }
  26465. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex);
  26466. samplersList.push("shadowSampler" + lightIndex);
  26467. }
  26468. };
  26469. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights) {
  26470. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  26471. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  26472. if (!defines["LIGHT" + lightIndex]) {
  26473. break;
  26474. }
  26475. if (lightIndex > 0) {
  26476. fallbacks.addFallback(lightIndex, "LIGHT" + lightIndex);
  26477. }
  26478. if (defines["SHADOW" + lightIndex]) {
  26479. fallbacks.addFallback(0, "SHADOW" + lightIndex);
  26480. }
  26481. if (defines["SHADOWPCF" + lightIndex]) {
  26482. fallbacks.addFallback(0, "SHADOWPCF" + lightIndex);
  26483. }
  26484. if (defines["SHADOWVSM" + lightIndex]) {
  26485. fallbacks.addFallback(0, "SHADOWVSM" + lightIndex);
  26486. }
  26487. }
  26488. };
  26489. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  26490. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  26491. fallbacks.addCPUSkinningFallback(0, mesh);
  26492. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  26493. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  26494. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  26495. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  26496. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  26497. }
  26498. }
  26499. };
  26500. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  26501. if (defines["INSTANCES"]) {
  26502. attribs.push("world0");
  26503. attribs.push("world1");
  26504. attribs.push("world2");
  26505. attribs.push("world3");
  26506. }
  26507. };
  26508. // Bindings
  26509. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect, depthValuesAlreadySet) {
  26510. var shadowGenerator = light.getShadowGenerator();
  26511. if (mesh.receiveShadows && shadowGenerator) {
  26512. if (!light.needCube()) {
  26513. effect.setMatrix("lightMatrix" + lightIndex, shadowGenerator.getTransformMatrix());
  26514. }
  26515. else {
  26516. if (!depthValuesAlreadySet) {
  26517. depthValuesAlreadySet = true;
  26518. effect.setFloat2("depthValues", scene.activeCamera.minZ, scene.activeCamera.maxZ);
  26519. }
  26520. }
  26521. effect.setTexture("shadowSampler" + lightIndex, shadowGenerator.getShadowMapForRendering());
  26522. effect.setFloat3("shadowsInfo" + lightIndex, shadowGenerator.getDarkness(), shadowGenerator.blurScale / shadowGenerator.getShadowMap().getSize().width, shadowGenerator.bias);
  26523. }
  26524. return depthValuesAlreadySet;
  26525. };
  26526. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  26527. if (light instanceof BABYLON.PointLight) {
  26528. // Point Light
  26529. light.transferToEffect(effect, "vLightData" + lightIndex);
  26530. }
  26531. else if (light instanceof BABYLON.DirectionalLight) {
  26532. // Directional Light
  26533. light.transferToEffect(effect, "vLightData" + lightIndex);
  26534. }
  26535. else if (light instanceof BABYLON.SpotLight) {
  26536. // Spot Light
  26537. light.transferToEffect(effect, "vLightData" + lightIndex, "vLightDirection" + lightIndex);
  26538. }
  26539. else if (light instanceof BABYLON.HemisphericLight) {
  26540. // Hemispheric Light
  26541. light.transferToEffect(effect, "vLightData" + lightIndex, "vLightGround" + lightIndex);
  26542. }
  26543. };
  26544. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights) {
  26545. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  26546. var lightIndex = 0;
  26547. var depthValuesAlreadySet = false;
  26548. for (var index = 0; index < scene.lights.length; index++) {
  26549. var light = scene.lights[index];
  26550. if (!light.isEnabled()) {
  26551. continue;
  26552. }
  26553. if (!light.canAffectMesh(mesh)) {
  26554. continue;
  26555. }
  26556. MaterialHelper.BindLightProperties(light, effect, lightIndex);
  26557. light.diffuse.scaleToRef(light.intensity, BABYLON.Tmp.Color3[0]);
  26558. effect.setColor4("vLightDiffuse" + lightIndex, BABYLON.Tmp.Color3[0], light.range);
  26559. if (defines["SPECULARTERM"]) {
  26560. light.specular.scaleToRef(light.intensity, BABYLON.Tmp.Color3[1]);
  26561. effect.setColor3("vLightSpecular" + lightIndex, BABYLON.Tmp.Color3[1]);
  26562. }
  26563. // Shadows
  26564. if (scene.shadowsEnabled) {
  26565. depthValuesAlreadySet = this.BindLightShadow(light, scene, mesh, lightIndex, effect, depthValuesAlreadySet);
  26566. }
  26567. lightIndex++;
  26568. if (lightIndex === maxSimultaneousLights)
  26569. break;
  26570. }
  26571. };
  26572. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  26573. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  26574. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  26575. effect.setColor3("vFogColor", scene.fogColor);
  26576. }
  26577. };
  26578. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  26579. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  26580. var matrices = mesh.skeleton.getTransformMatrices(mesh);
  26581. if (matrices) {
  26582. effect.setMatrices("mBones", matrices);
  26583. }
  26584. }
  26585. };
  26586. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  26587. if (defines["LOGARITHMICDEPTH"]) {
  26588. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  26589. }
  26590. };
  26591. MaterialHelper.BindClipPlane = function (effect, scene) {
  26592. if (scene.clipPlane) {
  26593. var clipPlane = scene.clipPlane;
  26594. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  26595. }
  26596. };
  26597. return MaterialHelper;
  26598. }());
  26599. BABYLON.MaterialHelper = MaterialHelper;
  26600. })(BABYLON || (BABYLON = {}));
  26601. //# sourceMappingURL=babylon.materialHelper.js.map
  26602. var BABYLON;
  26603. (function (BABYLON) {
  26604. var FresnelParameters = (function () {
  26605. function FresnelParameters() {
  26606. this.isEnabled = true;
  26607. this.leftColor = BABYLON.Color3.White();
  26608. this.rightColor = BABYLON.Color3.Black();
  26609. this.bias = 0;
  26610. this.power = 1;
  26611. }
  26612. FresnelParameters.prototype.clone = function () {
  26613. var newFresnelParameters = new FresnelParameters();
  26614. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  26615. return newFresnelParameters;
  26616. };
  26617. FresnelParameters.prototype.serialize = function () {
  26618. var serializationObject = {};
  26619. serializationObject.isEnabled = this.isEnabled;
  26620. serializationObject.leftColor = this.leftColor;
  26621. serializationObject.rightColor = this.rightColor;
  26622. serializationObject.bias = this.bias;
  26623. serializationObject.power = this.power;
  26624. return serializationObject;
  26625. };
  26626. FresnelParameters.Parse = function (parsedFresnelParameters) {
  26627. var fresnelParameters = new FresnelParameters();
  26628. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  26629. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  26630. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  26631. fresnelParameters.bias = parsedFresnelParameters.bias;
  26632. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  26633. return fresnelParameters;
  26634. };
  26635. return FresnelParameters;
  26636. }());
  26637. BABYLON.FresnelParameters = FresnelParameters;
  26638. })(BABYLON || (BABYLON = {}));
  26639. //# sourceMappingURL=babylon.fresnelParameters.js.map
  26640. var BABYLON;
  26641. (function (BABYLON) {
  26642. var MaterialDefines = (function () {
  26643. function MaterialDefines() {
  26644. }
  26645. MaterialDefines.prototype.rebuild = function () {
  26646. if (this._keys) {
  26647. delete this._keys;
  26648. }
  26649. this._keys = Object.keys(this);
  26650. };
  26651. MaterialDefines.prototype.isEqual = function (other) {
  26652. if (this._keys.length !== other._keys.length) {
  26653. return false;
  26654. }
  26655. for (var index = 0; index < this._keys.length; index++) {
  26656. var prop = this._keys[index];
  26657. if (this[prop] !== other[prop]) {
  26658. return false;
  26659. }
  26660. }
  26661. return true;
  26662. };
  26663. MaterialDefines.prototype.cloneTo = function (other) {
  26664. if (this._keys.length !== other._keys.length) {
  26665. other._keys = this._keys.slice(0);
  26666. }
  26667. for (var index = 0; index < this._keys.length; index++) {
  26668. var prop = this._keys[index];
  26669. other[prop] = this[prop];
  26670. }
  26671. };
  26672. MaterialDefines.prototype.reset = function () {
  26673. for (var index = 0; index < this._keys.length; index++) {
  26674. var prop = this._keys[index];
  26675. if (typeof (this[prop]) === "number") {
  26676. this[prop] = 0;
  26677. }
  26678. else {
  26679. this[prop] = false;
  26680. }
  26681. }
  26682. };
  26683. MaterialDefines.prototype.toString = function () {
  26684. var result = "";
  26685. for (var index = 0; index < this._keys.length; index++) {
  26686. var prop = this._keys[index];
  26687. if (typeof (this[prop]) === "number") {
  26688. result += "#define " + prop + " " + this[prop] + "\n";
  26689. }
  26690. else if (this[prop]) {
  26691. result += "#define " + prop + "\n";
  26692. }
  26693. }
  26694. return result;
  26695. };
  26696. return MaterialDefines;
  26697. }());
  26698. BABYLON.MaterialDefines = MaterialDefines;
  26699. var Material = (function () {
  26700. function Material(name, scene, doNotAdd) {
  26701. this.checkReadyOnEveryCall = false;
  26702. this.checkReadyOnlyOnce = false;
  26703. this.state = "";
  26704. this.alpha = 1.0;
  26705. this.backFaceCulling = true;
  26706. this.doNotSerialize = false;
  26707. /**
  26708. * An event triggered when the material is disposed.
  26709. * @type {BABYLON.Observable}
  26710. */
  26711. this.onDisposeObservable = new BABYLON.Observable();
  26712. /**
  26713. * An event triggered when the material is bound.
  26714. * @type {BABYLON.Observable}
  26715. */
  26716. this.onBindObservable = new BABYLON.Observable();
  26717. /**
  26718. * An event triggered when the material is unbound.
  26719. * @type {BABYLON.Observable}
  26720. */
  26721. this.onUnBindObservable = new BABYLON.Observable();
  26722. this.alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  26723. this.disableDepthWrite = false;
  26724. this.fogEnabled = true;
  26725. this.pointSize = 1.0;
  26726. this.zOffset = 0;
  26727. this._wasPreviouslyReady = false;
  26728. this._fillMode = Material.TriangleFillMode;
  26729. this.name = name;
  26730. this.id = name;
  26731. this._scene = scene;
  26732. if (scene.useRightHandedSystem) {
  26733. this.sideOrientation = Material.ClockWiseSideOrientation;
  26734. }
  26735. else {
  26736. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  26737. }
  26738. if (!doNotAdd) {
  26739. scene.materials.push(this);
  26740. }
  26741. }
  26742. Object.defineProperty(Material, "TriangleFillMode", {
  26743. get: function () {
  26744. return Material._TriangleFillMode;
  26745. },
  26746. enumerable: true,
  26747. configurable: true
  26748. });
  26749. Object.defineProperty(Material, "WireFrameFillMode", {
  26750. get: function () {
  26751. return Material._WireFrameFillMode;
  26752. },
  26753. enumerable: true,
  26754. configurable: true
  26755. });
  26756. Object.defineProperty(Material, "PointFillMode", {
  26757. get: function () {
  26758. return Material._PointFillMode;
  26759. },
  26760. enumerable: true,
  26761. configurable: true
  26762. });
  26763. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  26764. get: function () {
  26765. return Material._ClockWiseSideOrientation;
  26766. },
  26767. enumerable: true,
  26768. configurable: true
  26769. });
  26770. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  26771. get: function () {
  26772. return Material._CounterClockWiseSideOrientation;
  26773. },
  26774. enumerable: true,
  26775. configurable: true
  26776. });
  26777. Object.defineProperty(Material.prototype, "onDispose", {
  26778. set: function (callback) {
  26779. if (this._onDisposeObserver) {
  26780. this.onDisposeObservable.remove(this._onDisposeObserver);
  26781. }
  26782. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  26783. },
  26784. enumerable: true,
  26785. configurable: true
  26786. });
  26787. Object.defineProperty(Material.prototype, "onBind", {
  26788. set: function (callback) {
  26789. if (this._onBindObserver) {
  26790. this.onBindObservable.remove(this._onBindObserver);
  26791. }
  26792. this._onBindObserver = this.onBindObservable.add(callback);
  26793. },
  26794. enumerable: true,
  26795. configurable: true
  26796. });
  26797. Object.defineProperty(Material.prototype, "wireframe", {
  26798. get: function () {
  26799. return this._fillMode === Material.WireFrameFillMode;
  26800. },
  26801. set: function (value) {
  26802. this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  26803. },
  26804. enumerable: true,
  26805. configurable: true
  26806. });
  26807. Object.defineProperty(Material.prototype, "pointsCloud", {
  26808. get: function () {
  26809. return this._fillMode === Material.PointFillMode;
  26810. },
  26811. set: function (value) {
  26812. this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  26813. },
  26814. enumerable: true,
  26815. configurable: true
  26816. });
  26817. Object.defineProperty(Material.prototype, "fillMode", {
  26818. get: function () {
  26819. return this._fillMode;
  26820. },
  26821. set: function (value) {
  26822. this._fillMode = value;
  26823. },
  26824. enumerable: true,
  26825. configurable: true
  26826. });
  26827. /**
  26828. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  26829. * subclasses should override adding information pertainent to themselves
  26830. */
  26831. Material.prototype.toString = function (fullDetails) {
  26832. var ret = "Name: " + this.name;
  26833. if (fullDetails) {
  26834. }
  26835. return ret;
  26836. };
  26837. Material.prototype.getClassName = function () {
  26838. return "Material";
  26839. };
  26840. Object.defineProperty(Material.prototype, "isFrozen", {
  26841. get: function () {
  26842. return this.checkReadyOnlyOnce;
  26843. },
  26844. enumerable: true,
  26845. configurable: true
  26846. });
  26847. Material.prototype.freeze = function () {
  26848. this.checkReadyOnlyOnce = true;
  26849. };
  26850. Material.prototype.unfreeze = function () {
  26851. this.checkReadyOnlyOnce = false;
  26852. };
  26853. Material.prototype.isReady = function (mesh, useInstances) {
  26854. return true;
  26855. };
  26856. Material.prototype.getEffect = function () {
  26857. return this._effect;
  26858. };
  26859. Material.prototype.getScene = function () {
  26860. return this._scene;
  26861. };
  26862. Material.prototype.needAlphaBlending = function () {
  26863. return (this.alpha < 1.0);
  26864. };
  26865. Material.prototype.needAlphaTesting = function () {
  26866. return false;
  26867. };
  26868. Material.prototype.getAlphaTestTexture = function () {
  26869. return null;
  26870. };
  26871. Material.prototype.markDirty = function () {
  26872. this._wasPreviouslyReady = false;
  26873. };
  26874. Material.prototype._preBind = function () {
  26875. var engine = this._scene.getEngine();
  26876. var reverse = this.sideOrientation === Material.ClockWiseSideOrientation;
  26877. engine.enableEffect(this._effect);
  26878. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  26879. };
  26880. Material.prototype.bind = function (world, mesh) {
  26881. this._scene._cachedMaterial = this;
  26882. this.onBindObservable.notifyObservers(mesh);
  26883. if (this.disableDepthWrite) {
  26884. var engine = this._scene.getEngine();
  26885. this._cachedDepthWriteState = engine.getDepthWrite();
  26886. engine.setDepthWrite(false);
  26887. }
  26888. };
  26889. Material.prototype.bindOnlyWorldMatrix = function (world) {
  26890. };
  26891. Material.prototype.unbind = function () {
  26892. this.onUnBindObservable.notifyObservers(this);
  26893. if (this.disableDepthWrite) {
  26894. var engine = this._scene.getEngine();
  26895. engine.setDepthWrite(this._cachedDepthWriteState);
  26896. }
  26897. };
  26898. Material.prototype.clone = function (name) {
  26899. return null;
  26900. };
  26901. Material.prototype.getBindedMeshes = function () {
  26902. var result = new Array();
  26903. for (var index = 0; index < this._scene.meshes.length; index++) {
  26904. var mesh = this._scene.meshes[index];
  26905. if (mesh.material === this) {
  26906. result.push(mesh);
  26907. }
  26908. }
  26909. return result;
  26910. };
  26911. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  26912. // Animations
  26913. this.getScene().stopAnimation(this);
  26914. // Remove from scene
  26915. var index = this._scene.materials.indexOf(this);
  26916. if (index >= 0) {
  26917. this._scene.materials.splice(index, 1);
  26918. }
  26919. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  26920. if (forceDisposeEffect && this._effect) {
  26921. this._scene.getEngine()._releaseEffect(this._effect);
  26922. this._effect = null;
  26923. }
  26924. // Remove from meshes
  26925. for (index = 0; index < this._scene.meshes.length; index++) {
  26926. var mesh = this._scene.meshes[index];
  26927. if (mesh.material === this) {
  26928. mesh.material = null;
  26929. }
  26930. }
  26931. // Callback
  26932. this.onDisposeObservable.notifyObservers(this);
  26933. this.onDisposeObservable.clear();
  26934. this.onBindObservable.clear();
  26935. this.onUnBindObservable.clear();
  26936. };
  26937. Material.prototype.serialize = function () {
  26938. return BABYLON.SerializationHelper.Serialize(this);
  26939. };
  26940. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  26941. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  26942. multiMaterial.id = parsedMultiMaterial.id;
  26943. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  26944. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  26945. var subMatId = parsedMultiMaterial.materials[matIndex];
  26946. if (subMatId) {
  26947. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  26948. }
  26949. else {
  26950. multiMaterial.subMaterials.push(null);
  26951. }
  26952. }
  26953. return multiMaterial;
  26954. };
  26955. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  26956. if (!parsedMaterial.customType) {
  26957. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  26958. }
  26959. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  26960. return materialType.Parse(parsedMaterial, scene, rootUrl);
  26961. ;
  26962. };
  26963. return Material;
  26964. }());
  26965. Material._TriangleFillMode = 0;
  26966. Material._WireFrameFillMode = 1;
  26967. Material._PointFillMode = 2;
  26968. Material._ClockWiseSideOrientation = 0;
  26969. Material._CounterClockWiseSideOrientation = 1;
  26970. __decorate([
  26971. BABYLON.serialize()
  26972. ], Material.prototype, "id", void 0);
  26973. __decorate([
  26974. BABYLON.serialize()
  26975. ], Material.prototype, "name", void 0);
  26976. __decorate([
  26977. BABYLON.serialize()
  26978. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  26979. __decorate([
  26980. BABYLON.serialize()
  26981. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  26982. __decorate([
  26983. BABYLON.serialize()
  26984. ], Material.prototype, "state", void 0);
  26985. __decorate([
  26986. BABYLON.serialize()
  26987. ], Material.prototype, "alpha", void 0);
  26988. __decorate([
  26989. BABYLON.serialize()
  26990. ], Material.prototype, "backFaceCulling", void 0);
  26991. __decorate([
  26992. BABYLON.serialize()
  26993. ], Material.prototype, "sideOrientation", void 0);
  26994. __decorate([
  26995. BABYLON.serialize()
  26996. ], Material.prototype, "alphaMode", void 0);
  26997. __decorate([
  26998. BABYLON.serialize()
  26999. ], Material.prototype, "disableDepthWrite", void 0);
  27000. __decorate([
  27001. BABYLON.serialize()
  27002. ], Material.prototype, "fogEnabled", void 0);
  27003. __decorate([
  27004. BABYLON.serialize()
  27005. ], Material.prototype, "pointSize", void 0);
  27006. __decorate([
  27007. BABYLON.serialize()
  27008. ], Material.prototype, "zOffset", void 0);
  27009. __decorate([
  27010. BABYLON.serialize()
  27011. ], Material.prototype, "wireframe", null);
  27012. __decorate([
  27013. BABYLON.serialize()
  27014. ], Material.prototype, "pointsCloud", null);
  27015. __decorate([
  27016. BABYLON.serialize()
  27017. ], Material.prototype, "fillMode", null);
  27018. BABYLON.Material = Material;
  27019. })(BABYLON || (BABYLON = {}));
  27020. //# sourceMappingURL=babylon.material.js.map
  27021. var BABYLON;
  27022. (function (BABYLON) {
  27023. var StandardMaterialDefines = (function (_super) {
  27024. __extends(StandardMaterialDefines, _super);
  27025. function StandardMaterialDefines() {
  27026. var _this = _super.call(this) || this;
  27027. _this.DIFFUSE = false;
  27028. _this.AMBIENT = false;
  27029. _this.OPACITY = false;
  27030. _this.OPACITYRGB = false;
  27031. _this.REFLECTION = false;
  27032. _this.EMISSIVE = false;
  27033. _this.SPECULAR = false;
  27034. _this.BUMP = false;
  27035. _this.PARALLAX = false;
  27036. _this.PARALLAXOCCLUSION = false;
  27037. _this.SPECULAROVERALPHA = false;
  27038. _this.CLIPPLANE = false;
  27039. _this.ALPHATEST = false;
  27040. _this.ALPHAFROMDIFFUSE = false;
  27041. _this.POINTSIZE = false;
  27042. _this.FOG = false;
  27043. _this.SPECULARTERM = false;
  27044. _this.DIFFUSEFRESNEL = false;
  27045. _this.OPACITYFRESNEL = false;
  27046. _this.REFLECTIONFRESNEL = false;
  27047. _this.REFRACTIONFRESNEL = false;
  27048. _this.EMISSIVEFRESNEL = false;
  27049. _this.FRESNEL = false;
  27050. _this.NORMAL = false;
  27051. _this.UV1 = false;
  27052. _this.UV2 = false;
  27053. _this.VERTEXCOLOR = false;
  27054. _this.VERTEXALPHA = false;
  27055. _this.NUM_BONE_INFLUENCERS = 0;
  27056. _this.BonesPerMesh = 0;
  27057. _this.INSTANCES = false;
  27058. _this.GLOSSINESS = false;
  27059. _this.ROUGHNESS = false;
  27060. _this.EMISSIVEASILLUMINATION = false;
  27061. _this.LINKEMISSIVEWITHDIFFUSE = false;
  27062. _this.REFLECTIONFRESNELFROMSPECULAR = false;
  27063. _this.LIGHTMAP = false;
  27064. _this.USELIGHTMAPASSHADOWMAP = false;
  27065. _this.REFLECTIONMAP_3D = false;
  27066. _this.REFLECTIONMAP_SPHERICAL = false;
  27067. _this.REFLECTIONMAP_PLANAR = false;
  27068. _this.REFLECTIONMAP_CUBIC = false;
  27069. _this.REFLECTIONMAP_PROJECTION = false;
  27070. _this.REFLECTIONMAP_SKYBOX = false;
  27071. _this.REFLECTIONMAP_EXPLICIT = false;
  27072. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  27073. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  27074. _this.INVERTCUBICMAP = false;
  27075. _this.LOGARITHMICDEPTH = false;
  27076. _this.REFRACTION = false;
  27077. _this.REFRACTIONMAP_3D = false;
  27078. _this.REFLECTIONOVERALPHA = false;
  27079. _this.INVERTNORMALMAPX = false;
  27080. _this.INVERTNORMALMAPY = false;
  27081. _this.SHADOWFULLFLOAT = false;
  27082. _this.CAMERACOLORGRADING = false;
  27083. _this.CAMERACOLORCURVES = false;
  27084. _this.rebuild();
  27085. return _this;
  27086. }
  27087. return StandardMaterialDefines;
  27088. }(BABYLON.MaterialDefines));
  27089. var StandardMaterial = (function (_super) {
  27090. __extends(StandardMaterial, _super);
  27091. function StandardMaterial(name, scene) {
  27092. var _this = _super.call(this, name, scene) || this;
  27093. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  27094. _this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  27095. _this.specularColor = new BABYLON.Color3(1, 1, 1);
  27096. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  27097. _this.specularPower = 64;
  27098. _this.useAlphaFromDiffuseTexture = false;
  27099. _this.useEmissiveAsIllumination = false;
  27100. _this.linkEmissiveWithDiffuse = false;
  27101. _this.useReflectionFresnelFromSpecular = false;
  27102. _this.useSpecularOverAlpha = false;
  27103. _this.useReflectionOverAlpha = false;
  27104. _this.disableLighting = false;
  27105. _this.useParallax = false;
  27106. _this.useParallaxOcclusion = false;
  27107. _this.parallaxScaleBias = 0.05;
  27108. _this.roughness = 0;
  27109. _this.indexOfRefraction = 0.98;
  27110. _this.invertRefractionY = true;
  27111. _this.useLightmapAsShadowmap = false;
  27112. _this.useGlossinessFromSpecularMapAlpha = false;
  27113. _this.maxSimultaneousLights = 4;
  27114. /**
  27115. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  27116. */
  27117. _this.invertNormalMapX = false;
  27118. /**
  27119. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  27120. */
  27121. _this.invertNormalMapY = false;
  27122. /**
  27123. * Color Grading 2D Lookup Texture.
  27124. * This allows special effects like sepia, black and white to sixties rendering style.
  27125. */
  27126. _this.cameraColorGradingTexture = null;
  27127. /**
  27128. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  27129. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  27130. * 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;
  27131. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  27132. */
  27133. _this.cameraColorCurves = null;
  27134. _this._renderTargets = new BABYLON.SmartArray(16);
  27135. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  27136. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  27137. _this._defines = new StandardMaterialDefines();
  27138. _this._cachedDefines = new StandardMaterialDefines();
  27139. _this._cachedDefines.BonesPerMesh = -1;
  27140. _this.getRenderTargetTextures = function () {
  27141. _this._renderTargets.reset();
  27142. if (_this.reflectionTexture && _this.reflectionTexture.isRenderTarget) {
  27143. _this._renderTargets.push(_this.reflectionTexture);
  27144. }
  27145. if (_this.refractionTexture && _this.refractionTexture.isRenderTarget) {
  27146. _this._renderTargets.push(_this.refractionTexture);
  27147. }
  27148. return _this._renderTargets;
  27149. };
  27150. return _this;
  27151. }
  27152. StandardMaterial.prototype.getClassName = function () {
  27153. return "StandardMaterial";
  27154. };
  27155. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  27156. get: function () {
  27157. return this._useLogarithmicDepth;
  27158. },
  27159. set: function (value) {
  27160. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  27161. },
  27162. enumerable: true,
  27163. configurable: true
  27164. });
  27165. StandardMaterial.prototype.needAlphaBlending = function () {
  27166. return (this.alpha < 1.0) || (this.opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled;
  27167. };
  27168. StandardMaterial.prototype.needAlphaTesting = function () {
  27169. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha;
  27170. };
  27171. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  27172. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha && this.useAlphaFromDiffuseTexture;
  27173. };
  27174. StandardMaterial.prototype.getAlphaTestTexture = function () {
  27175. return this.diffuseTexture;
  27176. };
  27177. // Methods
  27178. StandardMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  27179. if (!mesh) {
  27180. return true;
  27181. }
  27182. if (this._defines.INSTANCES !== useInstances) {
  27183. return false;
  27184. }
  27185. if (mesh._materialDefines && mesh._materialDefines.isEqual(this._defines)) {
  27186. return true;
  27187. }
  27188. return false;
  27189. };
  27190. StandardMaterial.prototype.isReady = function (mesh, useInstances) {
  27191. if (this.isFrozen) {
  27192. if (this._wasPreviouslyReady) {
  27193. return true;
  27194. }
  27195. }
  27196. var scene = this.getScene();
  27197. var engine = scene.getEngine();
  27198. var needUVs = false;
  27199. var needNormals = false;
  27200. this._defines.reset();
  27201. // Lights
  27202. if (scene.lightsEnabled && !this.disableLighting) {
  27203. needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, this._defines, this.maxSimultaneousLights);
  27204. }
  27205. if (!this.checkReadyOnEveryCall) {
  27206. if (this._renderId === scene.getRenderId()) {
  27207. if (this._checkCache(scene, mesh, useInstances)) {
  27208. return true;
  27209. }
  27210. }
  27211. }
  27212. // Textures
  27213. if (scene.texturesEnabled) {
  27214. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  27215. if (!this.diffuseTexture.isReady()) {
  27216. return false;
  27217. }
  27218. else {
  27219. needUVs = true;
  27220. this._defines.DIFFUSE = true;
  27221. }
  27222. }
  27223. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  27224. if (!this.ambientTexture.isReady()) {
  27225. return false;
  27226. }
  27227. else {
  27228. needUVs = true;
  27229. this._defines.AMBIENT = true;
  27230. }
  27231. }
  27232. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  27233. if (!this.opacityTexture.isReady()) {
  27234. return false;
  27235. }
  27236. else {
  27237. needUVs = true;
  27238. this._defines.OPACITY = true;
  27239. if (this.opacityTexture.getAlphaFromRGB) {
  27240. this._defines.OPACITYRGB = true;
  27241. }
  27242. }
  27243. }
  27244. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  27245. if (!this.reflectionTexture.isReady()) {
  27246. return false;
  27247. }
  27248. else {
  27249. needNormals = true;
  27250. this._defines.REFLECTION = true;
  27251. if (this.roughness > 0) {
  27252. this._defines.ROUGHNESS = true;
  27253. }
  27254. if (this.useReflectionOverAlpha) {
  27255. this._defines.REFLECTIONOVERALPHA = true;
  27256. }
  27257. if (this.reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  27258. this._defines.INVERTCUBICMAP = true;
  27259. }
  27260. this._defines.REFLECTIONMAP_3D = this.reflectionTexture.isCube;
  27261. switch (this.reflectionTexture.coordinatesMode) {
  27262. case BABYLON.Texture.CUBIC_MODE:
  27263. case BABYLON.Texture.INVCUBIC_MODE:
  27264. this._defines.REFLECTIONMAP_CUBIC = true;
  27265. break;
  27266. case BABYLON.Texture.EXPLICIT_MODE:
  27267. this._defines.REFLECTIONMAP_EXPLICIT = true;
  27268. break;
  27269. case BABYLON.Texture.PLANAR_MODE:
  27270. this._defines.REFLECTIONMAP_PLANAR = true;
  27271. break;
  27272. case BABYLON.Texture.PROJECTION_MODE:
  27273. this._defines.REFLECTIONMAP_PROJECTION = true;
  27274. break;
  27275. case BABYLON.Texture.SKYBOX_MODE:
  27276. this._defines.REFLECTIONMAP_SKYBOX = true;
  27277. break;
  27278. case BABYLON.Texture.SPHERICAL_MODE:
  27279. this._defines.REFLECTIONMAP_SPHERICAL = true;
  27280. break;
  27281. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  27282. this._defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  27283. break;
  27284. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  27285. this._defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  27286. break;
  27287. }
  27288. }
  27289. }
  27290. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  27291. if (!this.emissiveTexture.isReady()) {
  27292. return false;
  27293. }
  27294. else {
  27295. needUVs = true;
  27296. this._defines.EMISSIVE = true;
  27297. }
  27298. }
  27299. if (this.lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  27300. if (!this.lightmapTexture.isReady()) {
  27301. return false;
  27302. }
  27303. else {
  27304. needUVs = true;
  27305. this._defines.LIGHTMAP = true;
  27306. this._defines.USELIGHTMAPASSHADOWMAP = this.useLightmapAsShadowmap;
  27307. }
  27308. }
  27309. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  27310. if (!this.specularTexture.isReady()) {
  27311. return false;
  27312. }
  27313. else {
  27314. needUVs = true;
  27315. this._defines.SPECULAR = true;
  27316. this._defines.GLOSSINESS = this.useGlossinessFromSpecularMapAlpha;
  27317. }
  27318. }
  27319. if (scene.getEngine().getCaps().standardDerivatives && this.bumpTexture && StandardMaterial.BumpTextureEnabled) {
  27320. if (!this.bumpTexture.isReady()) {
  27321. return false;
  27322. }
  27323. else {
  27324. needUVs = true;
  27325. this._defines.BUMP = true;
  27326. if (this.useParallax) {
  27327. this._defines.PARALLAX = true;
  27328. if (this.useParallaxOcclusion) {
  27329. this._defines.PARALLAXOCCLUSION = true;
  27330. }
  27331. }
  27332. if (this.invertNormalMapX) {
  27333. this._defines.INVERTNORMALMAPX = true;
  27334. }
  27335. if (this.invertNormalMapY) {
  27336. this._defines.INVERTNORMALMAPY = true;
  27337. }
  27338. if (scene._mirroredCameraPosition) {
  27339. this._defines.INVERTNORMALMAPX = !this._defines.INVERTNORMALMAPX;
  27340. this._defines.INVERTNORMALMAPY = !this._defines.INVERTNORMALMAPY;
  27341. }
  27342. }
  27343. }
  27344. if (this.refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  27345. if (!this.refractionTexture.isReady()) {
  27346. return false;
  27347. }
  27348. else {
  27349. needUVs = true;
  27350. this._defines.REFRACTION = true;
  27351. this._defines.REFRACTIONMAP_3D = this.refractionTexture.isCube;
  27352. }
  27353. }
  27354. if (this.cameraColorGradingTexture && StandardMaterial.ColorGradingTextureEnabled) {
  27355. if (!this.cameraColorGradingTexture.isReady()) {
  27356. return false;
  27357. }
  27358. else {
  27359. this._defines.CAMERACOLORGRADING = true;
  27360. }
  27361. }
  27362. }
  27363. // Effect
  27364. if (scene.clipPlane) {
  27365. this._defines.CLIPPLANE = true;
  27366. }
  27367. if (engine.getAlphaTesting()) {
  27368. this._defines.ALPHATEST = true;
  27369. }
  27370. if (this._shouldUseAlphaFromDiffuseTexture()) {
  27371. this._defines.ALPHAFROMDIFFUSE = true;
  27372. }
  27373. if (this.useEmissiveAsIllumination) {
  27374. this._defines.EMISSIVEASILLUMINATION = true;
  27375. }
  27376. if (this.linkEmissiveWithDiffuse) {
  27377. this._defines.LINKEMISSIVEWITHDIFFUSE = true;
  27378. }
  27379. if (this.useLogarithmicDepth) {
  27380. this._defines.LOGARITHMICDEPTH = true;
  27381. }
  27382. if (this.cameraColorCurves) {
  27383. this._defines.CAMERACOLORCURVES = true;
  27384. }
  27385. // Point size
  27386. if (this.pointsCloud || scene.forcePointsCloud) {
  27387. this._defines.POINTSIZE = true;
  27388. }
  27389. // Fog
  27390. if (scene.fogEnabled && mesh && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  27391. this._defines.FOG = true;
  27392. }
  27393. if (StandardMaterial.FresnelEnabled) {
  27394. // Fresnel
  27395. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled ||
  27396. this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled ||
  27397. this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled ||
  27398. this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled ||
  27399. this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  27400. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  27401. this._defines.DIFFUSEFRESNEL = true;
  27402. }
  27403. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  27404. this._defines.OPACITYFRESNEL = true;
  27405. }
  27406. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  27407. this._defines.REFLECTIONFRESNEL = true;
  27408. if (this.useReflectionFresnelFromSpecular) {
  27409. this._defines.REFLECTIONFRESNELFROMSPECULAR = true;
  27410. }
  27411. }
  27412. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  27413. this._defines.REFRACTIONFRESNEL = true;
  27414. }
  27415. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  27416. this._defines.EMISSIVEFRESNEL = true;
  27417. }
  27418. needNormals = true;
  27419. this._defines.FRESNEL = true;
  27420. }
  27421. }
  27422. if (this._defines.SPECULARTERM && this.useSpecularOverAlpha) {
  27423. this._defines.SPECULAROVERALPHA = true;
  27424. }
  27425. // Attribs
  27426. if (mesh) {
  27427. if (needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  27428. this._defines.NORMAL = true;
  27429. }
  27430. if (needUVs) {
  27431. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  27432. this._defines.UV1 = true;
  27433. }
  27434. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  27435. this._defines.UV2 = true;
  27436. }
  27437. }
  27438. if (mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  27439. this._defines.VERTEXCOLOR = true;
  27440. if (mesh.hasVertexAlpha) {
  27441. this._defines.VERTEXALPHA = true;
  27442. }
  27443. }
  27444. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  27445. this._defines.NUM_BONE_INFLUENCERS = mesh.numBoneInfluencers;
  27446. this._defines.BonesPerMesh = (mesh.skeleton.bones.length + 1);
  27447. }
  27448. // Instances
  27449. if (useInstances) {
  27450. this._defines.INSTANCES = true;
  27451. }
  27452. }
  27453. // Get correct effect
  27454. if (!this._defines.isEqual(this._cachedDefines)) {
  27455. this._defines.cloneTo(this._cachedDefines);
  27456. scene.resetCachedMaterial();
  27457. // Fallbacks
  27458. var fallbacks = new BABYLON.EffectFallbacks();
  27459. if (this._defines.REFLECTION) {
  27460. fallbacks.addFallback(0, "REFLECTION");
  27461. }
  27462. if (this._defines.SPECULAR) {
  27463. fallbacks.addFallback(0, "SPECULAR");
  27464. }
  27465. if (this._defines.BUMP) {
  27466. fallbacks.addFallback(0, "BUMP");
  27467. }
  27468. if (this._defines.PARALLAX) {
  27469. fallbacks.addFallback(1, "PARALLAX");
  27470. }
  27471. if (this._defines.PARALLAXOCCLUSION) {
  27472. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  27473. }
  27474. if (this._defines.SPECULAROVERALPHA) {
  27475. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  27476. }
  27477. if (this._defines.FOG) {
  27478. fallbacks.addFallback(1, "FOG");
  27479. }
  27480. if (this._defines.POINTSIZE) {
  27481. fallbacks.addFallback(0, "POINTSIZE");
  27482. }
  27483. if (this._defines.LOGARITHMICDEPTH) {
  27484. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  27485. }
  27486. BABYLON.MaterialHelper.HandleFallbacksForShadows(this._defines, fallbacks, this.maxSimultaneousLights);
  27487. if (this._defines.SPECULARTERM) {
  27488. fallbacks.addFallback(0, "SPECULARTERM");
  27489. }
  27490. if (this._defines.DIFFUSEFRESNEL) {
  27491. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  27492. }
  27493. if (this._defines.OPACITYFRESNEL) {
  27494. fallbacks.addFallback(2, "OPACITYFRESNEL");
  27495. }
  27496. if (this._defines.REFLECTIONFRESNEL) {
  27497. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  27498. }
  27499. if (this._defines.EMISSIVEFRESNEL) {
  27500. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  27501. }
  27502. if (this._defines.FRESNEL) {
  27503. fallbacks.addFallback(4, "FRESNEL");
  27504. }
  27505. //Attributes
  27506. var attribs = [BABYLON.VertexBuffer.PositionKind];
  27507. if (this._defines.NORMAL) {
  27508. attribs.push(BABYLON.VertexBuffer.NormalKind);
  27509. }
  27510. if (this._defines.UV1) {
  27511. attribs.push(BABYLON.VertexBuffer.UVKind);
  27512. }
  27513. if (this._defines.UV2) {
  27514. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  27515. }
  27516. if (this._defines.VERTEXCOLOR) {
  27517. attribs.push(BABYLON.VertexBuffer.ColorKind);
  27518. }
  27519. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, this._defines, fallbacks);
  27520. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, this._defines);
  27521. var shaderName = "default";
  27522. var join = this._defines.toString();
  27523. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  27524. "vFogInfos", "vFogColor", "pointSize",
  27525. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  27526. "mBones",
  27527. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  27528. "depthValues",
  27529. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  27530. "logarithmicDepthConstant"
  27531. ];
  27532. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  27533. if (this._defines.CAMERACOLORCURVES) {
  27534. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  27535. }
  27536. if (this._defines.CAMERACOLORGRADING) {
  27537. BABYLON.ColorGradingTexture.PrepareUniformsAndSamplers(uniforms, samplers);
  27538. }
  27539. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList(uniforms, samplers, this._defines, this.maxSimultaneousLights);
  27540. this._effect = scene.getEngine().createEffect(shaderName, attribs, uniforms, samplers, join, fallbacks, this.onCompiled, this.onError, { maxSimultaneousLights: this.maxSimultaneousLights - 1 });
  27541. }
  27542. if (!this._effect.isReady()) {
  27543. return false;
  27544. }
  27545. this._renderId = scene.getRenderId();
  27546. this._wasPreviouslyReady = true;
  27547. if (mesh) {
  27548. if (!mesh._materialDefines) {
  27549. mesh._materialDefines = new StandardMaterialDefines();
  27550. }
  27551. this._defines.cloneTo(mesh._materialDefines);
  27552. }
  27553. return true;
  27554. };
  27555. StandardMaterial.prototype.unbind = function () {
  27556. if (this.reflectionTexture && this.reflectionTexture.isRenderTarget) {
  27557. this._effect.setTexture("reflection2DSampler", null);
  27558. }
  27559. if (this.refractionTexture && this.refractionTexture.isRenderTarget) {
  27560. this._effect.setTexture("refraction2DSampler", null);
  27561. }
  27562. _super.prototype.unbind.call(this);
  27563. };
  27564. StandardMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  27565. this._effect.setMatrix("world", world);
  27566. };
  27567. StandardMaterial.prototype.bind = function (world, mesh) {
  27568. var scene = this.getScene();
  27569. // Matrices
  27570. this.bindOnlyWorldMatrix(world);
  27571. // Bones
  27572. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  27573. if (scene.getCachedMaterial() !== this) {
  27574. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  27575. if (StandardMaterial.FresnelEnabled) {
  27576. // Fresnel
  27577. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  27578. this._effect.setColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  27579. this._effect.setColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  27580. }
  27581. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  27582. this._effect.setColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  27583. }
  27584. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  27585. this._effect.setColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  27586. this._effect.setColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  27587. }
  27588. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  27589. this._effect.setColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  27590. this._effect.setColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  27591. }
  27592. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  27593. this._effect.setColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  27594. this._effect.setColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  27595. }
  27596. }
  27597. // Textures
  27598. if (scene.texturesEnabled) {
  27599. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  27600. this._effect.setTexture("diffuseSampler", this.diffuseTexture);
  27601. this._effect.setFloat2("vDiffuseInfos", this.diffuseTexture.coordinatesIndex, this.diffuseTexture.level);
  27602. this._effect.setMatrix("diffuseMatrix", this.diffuseTexture.getTextureMatrix());
  27603. }
  27604. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  27605. this._effect.setTexture("ambientSampler", this.ambientTexture);
  27606. this._effect.setFloat2("vAmbientInfos", this.ambientTexture.coordinatesIndex, this.ambientTexture.level);
  27607. this._effect.setMatrix("ambientMatrix", this.ambientTexture.getTextureMatrix());
  27608. }
  27609. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  27610. this._effect.setTexture("opacitySampler", this.opacityTexture);
  27611. this._effect.setFloat2("vOpacityInfos", this.opacityTexture.coordinatesIndex, this.opacityTexture.level);
  27612. this._effect.setMatrix("opacityMatrix", this.opacityTexture.getTextureMatrix());
  27613. }
  27614. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  27615. if (this.reflectionTexture.isCube) {
  27616. this._effect.setTexture("reflectionCubeSampler", this.reflectionTexture);
  27617. }
  27618. else {
  27619. this._effect.setTexture("reflection2DSampler", this.reflectionTexture);
  27620. }
  27621. this._effect.setMatrix("reflectionMatrix", this.reflectionTexture.getReflectionTextureMatrix());
  27622. this._effect.setFloat2("vReflectionInfos", this.reflectionTexture.level, this.roughness);
  27623. }
  27624. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  27625. this._effect.setTexture("emissiveSampler", this.emissiveTexture);
  27626. this._effect.setFloat2("vEmissiveInfos", this.emissiveTexture.coordinatesIndex, this.emissiveTexture.level);
  27627. this._effect.setMatrix("emissiveMatrix", this.emissiveTexture.getTextureMatrix());
  27628. }
  27629. if (this.lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  27630. this._effect.setTexture("lightmapSampler", this.lightmapTexture);
  27631. this._effect.setFloat2("vLightmapInfos", this.lightmapTexture.coordinatesIndex, this.lightmapTexture.level);
  27632. this._effect.setMatrix("lightmapMatrix", this.lightmapTexture.getTextureMatrix());
  27633. }
  27634. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  27635. this._effect.setTexture("specularSampler", this.specularTexture);
  27636. this._effect.setFloat2("vSpecularInfos", this.specularTexture.coordinatesIndex, this.specularTexture.level);
  27637. this._effect.setMatrix("specularMatrix", this.specularTexture.getTextureMatrix());
  27638. }
  27639. if (this.bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  27640. this._effect.setTexture("bumpSampler", this.bumpTexture);
  27641. this._effect.setFloat3("vBumpInfos", this.bumpTexture.coordinatesIndex, 1.0 / this.bumpTexture.level, this.parallaxScaleBias);
  27642. this._effect.setMatrix("bumpMatrix", this.bumpTexture.getTextureMatrix());
  27643. }
  27644. if (this.refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  27645. var depth = 1.0;
  27646. if (this.refractionTexture.isCube) {
  27647. this._effect.setTexture("refractionCubeSampler", this.refractionTexture);
  27648. }
  27649. else {
  27650. this._effect.setTexture("refraction2DSampler", this.refractionTexture);
  27651. this._effect.setMatrix("refractionMatrix", this.refractionTexture.getReflectionTextureMatrix());
  27652. if (this.refractionTexture.depth) {
  27653. depth = this.refractionTexture.depth;
  27654. }
  27655. }
  27656. this._effect.setFloat4("vRefractionInfos", this.refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  27657. }
  27658. if (this.cameraColorGradingTexture && StandardMaterial.ColorGradingTextureEnabled) {
  27659. BABYLON.ColorGradingTexture.Bind(this.cameraColorGradingTexture, this._effect);
  27660. }
  27661. }
  27662. // Clip plane
  27663. BABYLON.MaterialHelper.BindClipPlane(this._effect, scene);
  27664. // Point size
  27665. if (this.pointsCloud) {
  27666. this._effect.setFloat("pointSize", this.pointSize);
  27667. }
  27668. // Colors
  27669. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  27670. this._effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.position);
  27671. this._effect.setColor3("vAmbientColor", this._globalAmbientColor);
  27672. if (this._defines.SPECULARTERM) {
  27673. this._effect.setColor4("vSpecularColor", this.specularColor, this.specularPower);
  27674. }
  27675. this._effect.setColor3("vEmissiveColor", this.emissiveColor);
  27676. }
  27677. if (scene.getCachedMaterial() !== this || !this.isFrozen) {
  27678. // Diffuse
  27679. this._effect.setColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  27680. // Lights
  27681. if (scene.lightsEnabled && !this.disableLighting) {
  27682. BABYLON.MaterialHelper.BindLights(scene, mesh, this._effect, this._defines, this.maxSimultaneousLights);
  27683. }
  27684. // View
  27685. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this.reflectionTexture || this.refractionTexture) {
  27686. this._effect.setMatrix("view", scene.getViewMatrix());
  27687. }
  27688. // Fog
  27689. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._effect);
  27690. // Log. depth
  27691. BABYLON.MaterialHelper.BindLogDepth(this._defines, this._effect, scene);
  27692. // Color Curves
  27693. if (this.cameraColorCurves) {
  27694. BABYLON.ColorCurves.Bind(this.cameraColorCurves, this._effect);
  27695. }
  27696. }
  27697. _super.prototype.bind.call(this, world, mesh);
  27698. };
  27699. StandardMaterial.prototype.getAnimatables = function () {
  27700. var results = [];
  27701. if (this.diffuseTexture && this.diffuseTexture.animations && this.diffuseTexture.animations.length > 0) {
  27702. results.push(this.diffuseTexture);
  27703. }
  27704. if (this.ambientTexture && this.ambientTexture.animations && this.ambientTexture.animations.length > 0) {
  27705. results.push(this.ambientTexture);
  27706. }
  27707. if (this.opacityTexture && this.opacityTexture.animations && this.opacityTexture.animations.length > 0) {
  27708. results.push(this.opacityTexture);
  27709. }
  27710. if (this.reflectionTexture && this.reflectionTexture.animations && this.reflectionTexture.animations.length > 0) {
  27711. results.push(this.reflectionTexture);
  27712. }
  27713. if (this.emissiveTexture && this.emissiveTexture.animations && this.emissiveTexture.animations.length > 0) {
  27714. results.push(this.emissiveTexture);
  27715. }
  27716. if (this.specularTexture && this.specularTexture.animations && this.specularTexture.animations.length > 0) {
  27717. results.push(this.specularTexture);
  27718. }
  27719. if (this.bumpTexture && this.bumpTexture.animations && this.bumpTexture.animations.length > 0) {
  27720. results.push(this.bumpTexture);
  27721. }
  27722. if (this.lightmapTexture && this.lightmapTexture.animations && this.lightmapTexture.animations.length > 0) {
  27723. results.push(this.lightmapTexture);
  27724. }
  27725. if (this.refractionTexture && this.refractionTexture.animations && this.refractionTexture.animations.length > 0) {
  27726. results.push(this.refractionTexture);
  27727. }
  27728. if (this.cameraColorGradingTexture && this.cameraColorGradingTexture.animations && this.cameraColorGradingTexture.animations.length > 0) {
  27729. results.push(this.cameraColorGradingTexture);
  27730. }
  27731. return results;
  27732. };
  27733. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  27734. if (forceDisposeTextures) {
  27735. if (this.diffuseTexture) {
  27736. this.diffuseTexture.dispose();
  27737. }
  27738. if (this.ambientTexture) {
  27739. this.ambientTexture.dispose();
  27740. }
  27741. if (this.opacityTexture) {
  27742. this.opacityTexture.dispose();
  27743. }
  27744. if (this.reflectionTexture) {
  27745. this.reflectionTexture.dispose();
  27746. }
  27747. if (this.emissiveTexture) {
  27748. this.emissiveTexture.dispose();
  27749. }
  27750. if (this.specularTexture) {
  27751. this.specularTexture.dispose();
  27752. }
  27753. if (this.bumpTexture) {
  27754. this.bumpTexture.dispose();
  27755. }
  27756. if (this.lightmapTexture) {
  27757. this.lightmapTexture.dispose();
  27758. }
  27759. if (this.refractionTexture) {
  27760. this.refractionTexture.dispose();
  27761. }
  27762. if (this.cameraColorGradingTexture) {
  27763. this.cameraColorGradingTexture.dispose();
  27764. }
  27765. }
  27766. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  27767. };
  27768. StandardMaterial.prototype.clone = function (name) {
  27769. var _this = this;
  27770. return BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  27771. };
  27772. StandardMaterial.prototype.serialize = function () {
  27773. return BABYLON.SerializationHelper.Serialize(this);
  27774. };
  27775. // Statics
  27776. StandardMaterial.Parse = function (source, scene, rootUrl) {
  27777. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  27778. };
  27779. return StandardMaterial;
  27780. }(BABYLON.Material));
  27781. // Flags used to enable or disable a type of texture for all Standard Materials
  27782. StandardMaterial.DiffuseTextureEnabled = true;
  27783. StandardMaterial.AmbientTextureEnabled = true;
  27784. StandardMaterial.OpacityTextureEnabled = true;
  27785. StandardMaterial.ReflectionTextureEnabled = true;
  27786. StandardMaterial.EmissiveTextureEnabled = true;
  27787. StandardMaterial.SpecularTextureEnabled = true;
  27788. StandardMaterial.BumpTextureEnabled = true;
  27789. StandardMaterial.FresnelEnabled = true;
  27790. StandardMaterial.LightmapTextureEnabled = true;
  27791. StandardMaterial.RefractionTextureEnabled = true;
  27792. StandardMaterial.ColorGradingTextureEnabled = true;
  27793. __decorate([
  27794. BABYLON.serializeAsTexture()
  27795. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  27796. __decorate([
  27797. BABYLON.serializeAsTexture()
  27798. ], StandardMaterial.prototype, "ambientTexture", void 0);
  27799. __decorate([
  27800. BABYLON.serializeAsTexture()
  27801. ], StandardMaterial.prototype, "opacityTexture", void 0);
  27802. __decorate([
  27803. BABYLON.serializeAsTexture()
  27804. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  27805. __decorate([
  27806. BABYLON.serializeAsTexture()
  27807. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  27808. __decorate([
  27809. BABYLON.serializeAsTexture()
  27810. ], StandardMaterial.prototype, "specularTexture", void 0);
  27811. __decorate([
  27812. BABYLON.serializeAsTexture()
  27813. ], StandardMaterial.prototype, "bumpTexture", void 0);
  27814. __decorate([
  27815. BABYLON.serializeAsTexture()
  27816. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  27817. __decorate([
  27818. BABYLON.serializeAsTexture()
  27819. ], StandardMaterial.prototype, "refractionTexture", void 0);
  27820. __decorate([
  27821. BABYLON.serializeAsColor3("ambient")
  27822. ], StandardMaterial.prototype, "ambientColor", void 0);
  27823. __decorate([
  27824. BABYLON.serializeAsColor3("diffuse")
  27825. ], StandardMaterial.prototype, "diffuseColor", void 0);
  27826. __decorate([
  27827. BABYLON.serializeAsColor3("specular")
  27828. ], StandardMaterial.prototype, "specularColor", void 0);
  27829. __decorate([
  27830. BABYLON.serializeAsColor3("emissive")
  27831. ], StandardMaterial.prototype, "emissiveColor", void 0);
  27832. __decorate([
  27833. BABYLON.serialize()
  27834. ], StandardMaterial.prototype, "specularPower", void 0);
  27835. __decorate([
  27836. BABYLON.serialize()
  27837. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  27838. __decorate([
  27839. BABYLON.serialize()
  27840. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  27841. __decorate([
  27842. BABYLON.serialize()
  27843. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  27844. __decorate([
  27845. BABYLON.serialize()
  27846. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  27847. __decorate([
  27848. BABYLON.serialize()
  27849. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  27850. __decorate([
  27851. BABYLON.serialize()
  27852. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  27853. __decorate([
  27854. BABYLON.serialize()
  27855. ], StandardMaterial.prototype, "disableLighting", void 0);
  27856. __decorate([
  27857. BABYLON.serialize()
  27858. ], StandardMaterial.prototype, "useParallax", void 0);
  27859. __decorate([
  27860. BABYLON.serialize()
  27861. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  27862. __decorate([
  27863. BABYLON.serialize()
  27864. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  27865. __decorate([
  27866. BABYLON.serialize()
  27867. ], StandardMaterial.prototype, "roughness", void 0);
  27868. __decorate([
  27869. BABYLON.serialize()
  27870. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  27871. __decorate([
  27872. BABYLON.serialize()
  27873. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  27874. __decorate([
  27875. BABYLON.serialize()
  27876. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  27877. __decorate([
  27878. BABYLON.serializeAsFresnelParameters()
  27879. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  27880. __decorate([
  27881. BABYLON.serializeAsFresnelParameters()
  27882. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  27883. __decorate([
  27884. BABYLON.serializeAsFresnelParameters()
  27885. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  27886. __decorate([
  27887. BABYLON.serializeAsFresnelParameters()
  27888. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  27889. __decorate([
  27890. BABYLON.serializeAsFresnelParameters()
  27891. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  27892. __decorate([
  27893. BABYLON.serialize()
  27894. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  27895. __decorate([
  27896. BABYLON.serialize()
  27897. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  27898. __decorate([
  27899. BABYLON.serialize()
  27900. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  27901. __decorate([
  27902. BABYLON.serialize()
  27903. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  27904. __decorate([
  27905. BABYLON.serializeAsTexture()
  27906. ], StandardMaterial.prototype, "cameraColorGradingTexture", void 0);
  27907. __decorate([
  27908. BABYLON.serializeAsColorCurves()
  27909. ], StandardMaterial.prototype, "cameraColorCurves", void 0);
  27910. __decorate([
  27911. BABYLON.serialize()
  27912. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  27913. BABYLON.StandardMaterial = StandardMaterial;
  27914. })(BABYLON || (BABYLON = {}));
  27915. //# sourceMappingURL=babylon.standardMaterial.js.map
  27916. var BABYLON;
  27917. (function (BABYLON) {
  27918. var MultiMaterial = (function (_super) {
  27919. __extends(MultiMaterial, _super);
  27920. function MultiMaterial(name, scene) {
  27921. var _this = _super.call(this, name, scene, true) || this;
  27922. _this.subMaterials = new Array();
  27923. scene.multiMaterials.push(_this);
  27924. return _this;
  27925. }
  27926. // Properties
  27927. MultiMaterial.prototype.getSubMaterial = function (index) {
  27928. if (index < 0 || index >= this.subMaterials.length) {
  27929. return this.getScene().defaultMaterial;
  27930. }
  27931. return this.subMaterials[index];
  27932. };
  27933. // Methods
  27934. MultiMaterial.prototype.getClassName = function () {
  27935. return "MultiMaterial";
  27936. };
  27937. MultiMaterial.prototype.isReady = function (mesh) {
  27938. for (var index = 0; index < this.subMaterials.length; index++) {
  27939. var subMaterial = this.subMaterials[index];
  27940. if (subMaterial) {
  27941. if (!this.subMaterials[index].isReady(mesh)) {
  27942. return false;
  27943. }
  27944. }
  27945. }
  27946. return true;
  27947. };
  27948. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  27949. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  27950. for (var index = 0; index < this.subMaterials.length; index++) {
  27951. var subMaterial = null;
  27952. if (cloneChildren) {
  27953. subMaterial = this.subMaterials[index].clone(name + "-" + this.subMaterials[index].name);
  27954. }
  27955. else {
  27956. subMaterial = this.subMaterials[index];
  27957. }
  27958. newMultiMaterial.subMaterials.push(subMaterial);
  27959. }
  27960. return newMultiMaterial;
  27961. };
  27962. MultiMaterial.prototype.serialize = function () {
  27963. var serializationObject = {};
  27964. serializationObject.name = this.name;
  27965. serializationObject.id = this.id;
  27966. serializationObject.tags = BABYLON.Tags.GetTags(this);
  27967. serializationObject.materials = [];
  27968. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  27969. var subMat = this.subMaterials[matIndex];
  27970. if (subMat) {
  27971. serializationObject.materials.push(subMat.id);
  27972. }
  27973. else {
  27974. serializationObject.materials.push(null);
  27975. }
  27976. }
  27977. return serializationObject;
  27978. };
  27979. return MultiMaterial;
  27980. }(BABYLON.Material));
  27981. BABYLON.MultiMaterial = MultiMaterial;
  27982. })(BABYLON || (BABYLON = {}));
  27983. //# sourceMappingURL=babylon.multiMaterial.js.map
  27984. var BABYLON;
  27985. (function (BABYLON) {
  27986. var SceneLoader = (function () {
  27987. function SceneLoader() {
  27988. }
  27989. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  27990. get: function () {
  27991. return 0;
  27992. },
  27993. enumerable: true,
  27994. configurable: true
  27995. });
  27996. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  27997. get: function () {
  27998. return 1;
  27999. },
  28000. enumerable: true,
  28001. configurable: true
  28002. });
  28003. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  28004. get: function () {
  28005. return 2;
  28006. },
  28007. enumerable: true,
  28008. configurable: true
  28009. });
  28010. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  28011. get: function () {
  28012. return 3;
  28013. },
  28014. enumerable: true,
  28015. configurable: true
  28016. });
  28017. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  28018. get: function () {
  28019. return SceneLoader._ForceFullSceneLoadingForIncremental;
  28020. },
  28021. set: function (value) {
  28022. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  28023. },
  28024. enumerable: true,
  28025. configurable: true
  28026. });
  28027. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  28028. get: function () {
  28029. return SceneLoader._ShowLoadingScreen;
  28030. },
  28031. set: function (value) {
  28032. SceneLoader._ShowLoadingScreen = value;
  28033. },
  28034. enumerable: true,
  28035. configurable: true
  28036. });
  28037. Object.defineProperty(SceneLoader, "loggingLevel", {
  28038. get: function () {
  28039. return SceneLoader._loggingLevel;
  28040. },
  28041. set: function (value) {
  28042. SceneLoader._loggingLevel = value;
  28043. },
  28044. enumerable: true,
  28045. configurable: true
  28046. });
  28047. SceneLoader._getDefaultPlugin = function () {
  28048. return SceneLoader._registeredPlugins[".babylon"];
  28049. };
  28050. SceneLoader._getPluginForExtension = function (extension) {
  28051. var registeredPlugin = SceneLoader._registeredPlugins[extension];
  28052. if (registeredPlugin) {
  28053. return registeredPlugin;
  28054. }
  28055. return SceneLoader._getDefaultPlugin();
  28056. };
  28057. SceneLoader._getPluginForFilename = function (sceneFilename) {
  28058. if (sceneFilename.name) {
  28059. sceneFilename = sceneFilename.name;
  28060. }
  28061. var dotPosition = sceneFilename.lastIndexOf(".");
  28062. var queryStringPosition = sceneFilename.indexOf("?");
  28063. if (queryStringPosition === -1) {
  28064. queryStringPosition = sceneFilename.length;
  28065. }
  28066. var extension = sceneFilename.substring(dotPosition, queryStringPosition).toLowerCase();
  28067. return SceneLoader._getPluginForExtension(extension);
  28068. };
  28069. // use babylon file loader directly if sceneFilename is prefixed with "data:"
  28070. SceneLoader._getDirectLoad = function (sceneFilename) {
  28071. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  28072. return sceneFilename.substr(5);
  28073. }
  28074. return null;
  28075. };
  28076. // Public functions
  28077. SceneLoader.GetPluginForExtension = function (extension) {
  28078. return SceneLoader._getPluginForExtension(extension).plugin;
  28079. };
  28080. SceneLoader.RegisterPlugin = function (plugin) {
  28081. if (typeof plugin.extensions === "string") {
  28082. var extension = plugin.extensions;
  28083. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  28084. plugin: plugin,
  28085. isBinary: false
  28086. };
  28087. }
  28088. else {
  28089. var extensions = plugin.extensions;
  28090. Object.keys(extensions).forEach(function (extension) {
  28091. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  28092. plugin: plugin,
  28093. isBinary: extensions[extension].isBinary
  28094. };
  28095. });
  28096. }
  28097. };
  28098. SceneLoader.ImportMesh = function (meshesNames, rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  28099. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  28100. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  28101. return;
  28102. }
  28103. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  28104. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  28105. return;
  28106. }
  28107. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  28108. var loadingToken = {};
  28109. scene._addPendingData(loadingToken);
  28110. var manifestChecked = function (success) {
  28111. scene.database = database;
  28112. var registeredPlugin = directLoad ? SceneLoader._getDefaultPlugin() : SceneLoader._getPluginForFilename(sceneFilename);
  28113. var plugin = registeredPlugin.plugin;
  28114. var useArrayBuffer = registeredPlugin.isBinary;
  28115. var importMeshFromData = function (data) {
  28116. var meshes = [];
  28117. var particleSystems = [];
  28118. var skeletons = [];
  28119. try {
  28120. if (plugin.importMesh) {
  28121. var syncedPlugin = plugin;
  28122. if (!syncedPlugin.importMesh(meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons)) {
  28123. if (onerror) {
  28124. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename);
  28125. }
  28126. scene._removePendingData(loadingToken);
  28127. return;
  28128. }
  28129. if (onsuccess) {
  28130. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  28131. onsuccess(meshes, particleSystems, skeletons);
  28132. scene._removePendingData(loadingToken);
  28133. }
  28134. }
  28135. else {
  28136. var asyncedPlugin = plugin;
  28137. asyncedPlugin.importMeshAsync(meshesNames, scene, data, rootUrl, function (meshes, particleSystems, skeletons) {
  28138. if (onsuccess) {
  28139. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  28140. onsuccess(meshes, particleSystems, skeletons);
  28141. scene._removePendingData(loadingToken);
  28142. }
  28143. }, function () {
  28144. if (onerror) {
  28145. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename);
  28146. }
  28147. scene._removePendingData(loadingToken);
  28148. });
  28149. }
  28150. }
  28151. catch (e) {
  28152. if (onerror) {
  28153. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename, e);
  28154. }
  28155. scene._removePendingData(loadingToken);
  28156. }
  28157. };
  28158. if (directLoad) {
  28159. importMeshFromData(directLoad);
  28160. return;
  28161. }
  28162. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, function (data) {
  28163. importMeshFromData(data);
  28164. }, progressCallBack, database, useArrayBuffer);
  28165. };
  28166. if (scene.getEngine().enableOfflineSupport && !directLoad) {
  28167. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  28168. var database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  28169. }
  28170. else {
  28171. // If the scene is a data stream or offline support is not enabled, it's a direct load
  28172. manifestChecked(true);
  28173. }
  28174. };
  28175. /**
  28176. * Load a scene
  28177. * @param rootUrl a string that defines the root url for scene and resources
  28178. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  28179. * @param engine is the instance of BABYLON.Engine to use to create the scene
  28180. */
  28181. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onsuccess, progressCallBack, onerror) {
  28182. SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onsuccess, progressCallBack, onerror);
  28183. };
  28184. /**
  28185. * Append a scene
  28186. * @param rootUrl a string that defines the root url for scene and resources
  28187. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  28188. * @param scene is the instance of BABYLON.Scene to append to
  28189. */
  28190. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  28191. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  28192. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  28193. return;
  28194. }
  28195. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  28196. var registeredPlugin = directLoad ? SceneLoader._getDefaultPlugin() : SceneLoader._getPluginForFilename(sceneFilename);
  28197. var plugin = registeredPlugin.plugin;
  28198. var useArrayBuffer = registeredPlugin.isBinary;
  28199. var database;
  28200. var loadingToken = {};
  28201. scene._addPendingData(loadingToken);
  28202. if (SceneLoader.ShowLoadingScreen) {
  28203. scene.getEngine().displayLoadingUI();
  28204. }
  28205. var loadSceneFromData = function (data) {
  28206. scene.database = database;
  28207. if (plugin.load) {
  28208. var syncedPlugin = plugin;
  28209. if (!syncedPlugin.load(scene, data, rootUrl)) {
  28210. if (onerror) {
  28211. onerror(scene);
  28212. }
  28213. scene._removePendingData(loadingToken);
  28214. scene.getEngine().hideLoadingUI();
  28215. return;
  28216. }
  28217. if (onsuccess) {
  28218. onsuccess(scene);
  28219. }
  28220. scene._removePendingData(loadingToken);
  28221. }
  28222. else {
  28223. var asyncedPlugin = plugin;
  28224. asyncedPlugin.loadAsync(scene, data, rootUrl, function () {
  28225. if (onsuccess) {
  28226. onsuccess(scene);
  28227. }
  28228. scene._removePendingData(loadingToken);
  28229. }, function () {
  28230. if (onerror) {
  28231. onerror(scene);
  28232. }
  28233. scene._removePendingData(loadingToken);
  28234. scene.getEngine().hideLoadingUI();
  28235. });
  28236. }
  28237. if (SceneLoader.ShowLoadingScreen) {
  28238. scene.executeWhenReady(function () {
  28239. scene.getEngine().hideLoadingUI();
  28240. });
  28241. }
  28242. };
  28243. var manifestChecked = function (success) {
  28244. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, loadSceneFromData, progressCallBack, database, useArrayBuffer);
  28245. };
  28246. if (directLoad) {
  28247. loadSceneFromData(directLoad);
  28248. return;
  28249. }
  28250. if (rootUrl.indexOf("file:") === -1) {
  28251. if (scene.getEngine().enableOfflineSupport) {
  28252. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  28253. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  28254. }
  28255. else {
  28256. manifestChecked(true);
  28257. }
  28258. }
  28259. else {
  28260. BABYLON.Tools.ReadFile(sceneFilename, loadSceneFromData, progressCallBack, useArrayBuffer);
  28261. }
  28262. };
  28263. return SceneLoader;
  28264. }());
  28265. // Flags
  28266. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  28267. SceneLoader._ShowLoadingScreen = true;
  28268. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  28269. // Members
  28270. SceneLoader._registeredPlugins = {};
  28271. BABYLON.SceneLoader = SceneLoader;
  28272. ;
  28273. })(BABYLON || (BABYLON = {}));
  28274. //# sourceMappingURL=babylon.sceneLoader.js.map
  28275. var BABYLON;
  28276. (function (BABYLON) {
  28277. var Internals;
  28278. (function (Internals) {
  28279. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  28280. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  28281. var parsedMaterial = parsedData.materials[index];
  28282. if (parsedMaterial.id === id) {
  28283. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  28284. }
  28285. }
  28286. return null;
  28287. };
  28288. var isDescendantOf = function (mesh, names, hierarchyIds) {
  28289. names = (names instanceof Array) ? names : [names];
  28290. for (var i in names) {
  28291. if (mesh.name === names[i]) {
  28292. hierarchyIds.push(mesh.id);
  28293. return true;
  28294. }
  28295. }
  28296. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  28297. hierarchyIds.push(mesh.id);
  28298. return true;
  28299. }
  28300. return false;
  28301. };
  28302. var logOperation = function (operation, producer) {
  28303. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  28304. };
  28305. BABYLON.SceneLoader.RegisterPlugin({
  28306. extensions: ".babylon",
  28307. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
  28308. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  28309. // when SceneLoader.debugLogging = true (default), or exception encountered.
  28310. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  28311. // and avoid problems with multiple concurrent .babylon loads.
  28312. var log = "importMesh has failed JSON parse";
  28313. try {
  28314. var parsedData = JSON.parse(data);
  28315. log = "";
  28316. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  28317. var loadedSkeletonsIds = [];
  28318. var loadedMaterialsIds = [];
  28319. var hierarchyIds = [];
  28320. var index;
  28321. var cache;
  28322. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  28323. var parsedMesh = parsedData.meshes[index];
  28324. if (!meshesNames || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  28325. if (meshesNames instanceof Array) {
  28326. // Remove found mesh name from list.
  28327. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  28328. }
  28329. //Geometry?
  28330. if (parsedMesh.geometryId) {
  28331. //does the file contain geometries?
  28332. if (parsedData.geometries) {
  28333. //find the correct geometry and add it to the scene
  28334. var found = false;
  28335. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  28336. if (found || !parsedData.geometries[geometryType] || !(parsedData.geometries[geometryType] instanceof Array)) {
  28337. return;
  28338. }
  28339. else {
  28340. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  28341. if (parsedGeometryData.id === parsedMesh.geometryId) {
  28342. switch (geometryType) {
  28343. case "boxes":
  28344. BABYLON.Geometry.Primitives.Box.Parse(parsedGeometryData, scene);
  28345. break;
  28346. case "spheres":
  28347. BABYLON.Geometry.Primitives.Sphere.Parse(parsedGeometryData, scene);
  28348. break;
  28349. case "cylinders":
  28350. BABYLON.Geometry.Primitives.Cylinder.Parse(parsedGeometryData, scene);
  28351. break;
  28352. case "toruses":
  28353. BABYLON.Geometry.Primitives.Torus.Parse(parsedGeometryData, scene);
  28354. break;
  28355. case "grounds":
  28356. BABYLON.Geometry.Primitives.Ground.Parse(parsedGeometryData, scene);
  28357. break;
  28358. case "planes":
  28359. BABYLON.Geometry.Primitives.Plane.Parse(parsedGeometryData, scene);
  28360. break;
  28361. case "torusKnots":
  28362. BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedGeometryData, scene);
  28363. break;
  28364. case "vertexData":
  28365. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  28366. break;
  28367. }
  28368. found = true;
  28369. }
  28370. });
  28371. }
  28372. });
  28373. if (!found) {
  28374. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  28375. }
  28376. }
  28377. }
  28378. // Material ?
  28379. if (parsedMesh.materialId) {
  28380. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  28381. if (!materialFound && parsedData.multiMaterials) {
  28382. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  28383. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  28384. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  28385. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  28386. var subMatId = parsedMultiMaterial.materials[matIndex];
  28387. loadedMaterialsIds.push(subMatId);
  28388. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  28389. log += "\n\tMaterial " + mat.toString(fullDetails);
  28390. }
  28391. loadedMaterialsIds.push(parsedMultiMaterial.id);
  28392. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  28393. materialFound = true;
  28394. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  28395. break;
  28396. }
  28397. }
  28398. }
  28399. if (!materialFound) {
  28400. loadedMaterialsIds.push(parsedMesh.materialId);
  28401. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  28402. if (!mat) {
  28403. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  28404. }
  28405. else {
  28406. log += "\n\tMaterial " + mat.toString(fullDetails);
  28407. }
  28408. }
  28409. }
  28410. // Skeleton ?
  28411. if (parsedMesh.skeletonId > -1 && scene.skeletons) {
  28412. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  28413. if (!skeletonAlreadyLoaded) {
  28414. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  28415. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  28416. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  28417. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  28418. skeletons.push(skeleton);
  28419. loadedSkeletonsIds.push(parsedSkeleton.id);
  28420. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  28421. }
  28422. }
  28423. }
  28424. }
  28425. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  28426. meshes.push(mesh);
  28427. log += "\n\tMesh " + mesh.toString(fullDetails);
  28428. }
  28429. }
  28430. // Connecting parents
  28431. var currentMesh;
  28432. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  28433. currentMesh = scene.meshes[index];
  28434. if (currentMesh._waitingParentId) {
  28435. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  28436. currentMesh._waitingParentId = undefined;
  28437. }
  28438. }
  28439. // freeze and compute world matrix application
  28440. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  28441. currentMesh = scene.meshes[index];
  28442. if (currentMesh._waitingFreezeWorldMatrix) {
  28443. currentMesh.freezeWorldMatrix();
  28444. currentMesh._waitingFreezeWorldMatrix = undefined;
  28445. }
  28446. else {
  28447. currentMesh.computeWorldMatrix(true);
  28448. }
  28449. }
  28450. // Particles
  28451. if (parsedData.particleSystems) {
  28452. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  28453. var parsedParticleSystem = parsedData.particleSystems[index];
  28454. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  28455. particleSystems.push(BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl));
  28456. }
  28457. }
  28458. }
  28459. return true;
  28460. }
  28461. catch (err) {
  28462. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log);
  28463. log = null;
  28464. throw err;
  28465. }
  28466. finally {
  28467. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  28468. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  28469. }
  28470. }
  28471. },
  28472. load: function (scene, data, rootUrl) {
  28473. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  28474. // when SceneLoader.debugLogging = true (default), or exception encountered.
  28475. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  28476. // and avoid problems with multiple concurrent .babylon loads.
  28477. var log = "importScene has failed JSON parse";
  28478. try {
  28479. var parsedData = JSON.parse(data);
  28480. log = "";
  28481. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  28482. // Scene
  28483. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  28484. scene.autoClear = parsedData.autoClear;
  28485. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  28486. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  28487. if (parsedData.gravity) {
  28488. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  28489. }
  28490. // Fog
  28491. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  28492. scene.fogMode = parsedData.fogMode;
  28493. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  28494. scene.fogStart = parsedData.fogStart;
  28495. scene.fogEnd = parsedData.fogEnd;
  28496. scene.fogDensity = parsedData.fogDensity;
  28497. log += "\tFog mode for scene: ";
  28498. switch (scene.fogMode) {
  28499. // getters not compiling, so using hardcoded
  28500. case 1:
  28501. log += "exp\n";
  28502. break;
  28503. case 2:
  28504. log += "exp2\n";
  28505. break;
  28506. case 3:
  28507. log += "linear\n";
  28508. break;
  28509. }
  28510. }
  28511. //Physics
  28512. if (parsedData.physicsEnabled) {
  28513. var physicsPlugin;
  28514. if (parsedData.physicsEngine === "cannon") {
  28515. physicsPlugin = new BABYLON.CannonJSPlugin();
  28516. }
  28517. else if (parsedData.physicsEngine === "oimo") {
  28518. physicsPlugin = new BABYLON.OimoJSPlugin();
  28519. }
  28520. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  28521. //else - default engine, which is currently oimo
  28522. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  28523. scene.enablePhysics(physicsGravity, physicsPlugin);
  28524. }
  28525. // Metadata
  28526. if (parsedData.metadata !== undefined) {
  28527. scene.metadata = parsedData.metadata;
  28528. }
  28529. //collisions, if defined. otherwise, default is true
  28530. if (parsedData.collisionsEnabled != undefined) {
  28531. scene.collisionsEnabled = parsedData.collisionsEnabled;
  28532. }
  28533. scene.workerCollisions = !!parsedData.workerCollisions;
  28534. var index;
  28535. var cache;
  28536. // Lights
  28537. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  28538. var parsedLight = parsedData.lights[index];
  28539. var light = BABYLON.Light.Parse(parsedLight, scene);
  28540. log += (index === 0 ? "\n\tLights:" : "");
  28541. log += "\n\t\t" + light.toString(fullDetails);
  28542. }
  28543. // Animations
  28544. if (parsedData.animations) {
  28545. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  28546. var parsedAnimation = parsedData.animations[index];
  28547. var animation = BABYLON.Animation.Parse(parsedAnimation);
  28548. scene.animations.push(animation);
  28549. log += (index === 0 ? "\n\tAnimations:" : "");
  28550. log += "\n\t\t" + animation.toString(fullDetails);
  28551. }
  28552. }
  28553. if (parsedData.autoAnimate) {
  28554. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  28555. }
  28556. // Materials
  28557. if (parsedData.materials) {
  28558. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  28559. var parsedMaterial = parsedData.materials[index];
  28560. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  28561. log += (index === 0 ? "\n\tMaterials:" : "");
  28562. log += "\n\t\t" + mat.toString(fullDetails);
  28563. }
  28564. }
  28565. if (parsedData.multiMaterials) {
  28566. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  28567. var parsedMultiMaterial = parsedData.multiMaterials[index];
  28568. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  28569. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  28570. log += "\n\t\t" + mmat.toString(fullDetails);
  28571. }
  28572. }
  28573. // Skeletons
  28574. if (parsedData.skeletons) {
  28575. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  28576. var parsedSkeleton = parsedData.skeletons[index];
  28577. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  28578. log += (index === 0 ? "\n\tSkeletons:" : "");
  28579. log += "\n\t\t" + skeleton.toString(fullDetails);
  28580. }
  28581. }
  28582. // Geometries
  28583. var geometries = parsedData.geometries;
  28584. if (geometries) {
  28585. // Boxes
  28586. var boxes = geometries.boxes;
  28587. if (boxes) {
  28588. for (index = 0, cache = boxes.length; index < cache; index++) {
  28589. var parsedBox = boxes[index];
  28590. BABYLON.Geometry.Primitives.Box.Parse(parsedBox, scene);
  28591. }
  28592. }
  28593. // Spheres
  28594. var spheres = geometries.spheres;
  28595. if (spheres) {
  28596. for (index = 0, cache = spheres.length; index < cache; index++) {
  28597. var parsedSphere = spheres[index];
  28598. BABYLON.Geometry.Primitives.Sphere.Parse(parsedSphere, scene);
  28599. }
  28600. }
  28601. // Cylinders
  28602. var cylinders = geometries.cylinders;
  28603. if (cylinders) {
  28604. for (index = 0, cache = cylinders.length; index < cache; index++) {
  28605. var parsedCylinder = cylinders[index];
  28606. BABYLON.Geometry.Primitives.Cylinder.Parse(parsedCylinder, scene);
  28607. }
  28608. }
  28609. // Toruses
  28610. var toruses = geometries.toruses;
  28611. if (toruses) {
  28612. for (index = 0, cache = toruses.length; index < cache; index++) {
  28613. var parsedTorus = toruses[index];
  28614. BABYLON.Geometry.Primitives.Torus.Parse(parsedTorus, scene);
  28615. }
  28616. }
  28617. // Grounds
  28618. var grounds = geometries.grounds;
  28619. if (grounds) {
  28620. for (index = 0, cache = grounds.length; index < cache; index++) {
  28621. var parsedGround = grounds[index];
  28622. BABYLON.Geometry.Primitives.Ground.Parse(parsedGround, scene);
  28623. }
  28624. }
  28625. // Planes
  28626. var planes = geometries.planes;
  28627. if (planes) {
  28628. for (index = 0, cache = planes.length; index < cache; index++) {
  28629. var parsedPlane = planes[index];
  28630. BABYLON.Geometry.Primitives.Plane.Parse(parsedPlane, scene);
  28631. }
  28632. }
  28633. // TorusKnots
  28634. var torusKnots = geometries.torusKnots;
  28635. if (torusKnots) {
  28636. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  28637. var parsedTorusKnot = torusKnots[index];
  28638. BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedTorusKnot, scene);
  28639. }
  28640. }
  28641. // VertexData
  28642. var vertexData = geometries.vertexData;
  28643. if (vertexData) {
  28644. for (index = 0, cache = vertexData.length; index < cache; index++) {
  28645. var parsedVertexData = vertexData[index];
  28646. BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl);
  28647. }
  28648. }
  28649. }
  28650. // Meshes
  28651. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  28652. var parsedMesh = parsedData.meshes[index];
  28653. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  28654. log += (index === 0 ? "\n\tMeshes:" : "");
  28655. log += "\n\t\t" + mesh.toString(fullDetails);
  28656. }
  28657. // Cameras
  28658. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  28659. var parsedCamera = parsedData.cameras[index];
  28660. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  28661. log += (index === 0 ? "\n\tCameras:" : "");
  28662. log += "\n\t\t" + camera.toString(fullDetails);
  28663. }
  28664. if (parsedData.activeCameraID) {
  28665. scene.setActiveCameraByID(parsedData.activeCameraID);
  28666. }
  28667. // Browsing all the graph to connect the dots
  28668. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  28669. var camera = scene.cameras[index];
  28670. if (camera._waitingParentId) {
  28671. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  28672. camera._waitingParentId = undefined;
  28673. }
  28674. }
  28675. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  28676. var light = scene.lights[index];
  28677. if (light._waitingParentId) {
  28678. light.parent = scene.getLastEntryByID(light._waitingParentId);
  28679. light._waitingParentId = undefined;
  28680. }
  28681. }
  28682. // Sounds
  28683. var loadedSounds = [];
  28684. var loadedSound;
  28685. if (BABYLON.AudioEngine && parsedData.sounds) {
  28686. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  28687. var parsedSound = parsedData.sounds[index];
  28688. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  28689. if (!parsedSound.url)
  28690. parsedSound.url = parsedSound.name;
  28691. if (!loadedSounds[parsedSound.url]) {
  28692. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  28693. loadedSounds[parsedSound.url] = loadedSound;
  28694. }
  28695. else {
  28696. BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]);
  28697. }
  28698. }
  28699. else {
  28700. var emptySound = new BABYLON.Sound(parsedSound.name, null, scene);
  28701. }
  28702. }
  28703. }
  28704. loadedSounds = [];
  28705. // Connect parents & children and parse actions
  28706. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  28707. var mesh = scene.meshes[index];
  28708. if (mesh._waitingParentId) {
  28709. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  28710. mesh._waitingParentId = undefined;
  28711. }
  28712. if (mesh._waitingActions) {
  28713. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  28714. mesh._waitingActions = undefined;
  28715. }
  28716. }
  28717. // freeze world matrix application
  28718. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  28719. var currentMesh = scene.meshes[index];
  28720. if (currentMesh._waitingFreezeWorldMatrix) {
  28721. currentMesh.freezeWorldMatrix();
  28722. currentMesh._waitingFreezeWorldMatrix = undefined;
  28723. }
  28724. else {
  28725. currentMesh.computeWorldMatrix(true);
  28726. }
  28727. }
  28728. // Particles Systems
  28729. if (parsedData.particleSystems) {
  28730. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  28731. var parsedParticleSystem = parsedData.particleSystems[index];
  28732. BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  28733. }
  28734. }
  28735. // Lens flares
  28736. if (parsedData.lensFlareSystems) {
  28737. for (index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  28738. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  28739. BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  28740. }
  28741. }
  28742. // Shadows
  28743. if (parsedData.shadowGenerators) {
  28744. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  28745. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  28746. BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  28747. }
  28748. }
  28749. // Actions (scene)
  28750. if (parsedData.actions) {
  28751. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  28752. }
  28753. // Finish
  28754. return true;
  28755. }
  28756. catch (err) {
  28757. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log);
  28758. log = null;
  28759. throw err;
  28760. }
  28761. finally {
  28762. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  28763. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  28764. }
  28765. }
  28766. }
  28767. });
  28768. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  28769. })(BABYLON || (BABYLON = {}));
  28770. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  28771. var BABYLON;
  28772. (function (BABYLON) {
  28773. var SpriteManager = (function () {
  28774. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  28775. if (epsilon === void 0) { epsilon = 0.01; }
  28776. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  28777. this.name = name;
  28778. this.sprites = new Array();
  28779. this.renderingGroupId = 0;
  28780. this.layerMask = 0x0FFFFFFF;
  28781. this.fogEnabled = true;
  28782. this.isPickable = false;
  28783. /**
  28784. * An event triggered when the manager is disposed.
  28785. * @type {BABYLON.Observable}
  28786. */
  28787. this.onDisposeObservable = new BABYLON.Observable();
  28788. this._vertexBuffers = {};
  28789. this._capacity = capacity;
  28790. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  28791. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  28792. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  28793. if (cellSize.width && cellSize.height) {
  28794. this.cellWidth = cellSize.width;
  28795. this.cellHeight = cellSize.height;
  28796. }
  28797. else if (cellSize !== undefined) {
  28798. this.cellWidth = cellSize;
  28799. this.cellHeight = cellSize;
  28800. }
  28801. else {
  28802. return;
  28803. }
  28804. this._epsilon = epsilon;
  28805. this._scene = scene;
  28806. this._scene.spriteManagers.push(this);
  28807. var indices = [];
  28808. var index = 0;
  28809. for (var count = 0; count < capacity; count++) {
  28810. indices.push(index);
  28811. indices.push(index + 1);
  28812. indices.push(index + 2);
  28813. indices.push(index);
  28814. indices.push(index + 2);
  28815. indices.push(index + 3);
  28816. index += 4;
  28817. }
  28818. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  28819. // VBO
  28820. // 16 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color r, color g, color b, color a)
  28821. this._vertexData = new Float32Array(capacity * 16 * 4);
  28822. this._buffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 16);
  28823. var positions = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 4);
  28824. var options = this._buffer.createVertexBuffer("options", 4, 4);
  28825. var cellInfo = this._buffer.createVertexBuffer("cellInfo", 8, 4);
  28826. var colors = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 12, 4);
  28827. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  28828. this._vertexBuffers["options"] = options;
  28829. this._vertexBuffers["cellInfo"] = cellInfo;
  28830. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  28831. // Effects
  28832. this._effectBase = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  28833. this._effectFog = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  28834. }
  28835. Object.defineProperty(SpriteManager.prototype, "onDispose", {
  28836. set: function (callback) {
  28837. if (this._onDisposeObserver) {
  28838. this.onDisposeObservable.remove(this._onDisposeObserver);
  28839. }
  28840. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  28841. },
  28842. enumerable: true,
  28843. configurable: true
  28844. });
  28845. Object.defineProperty(SpriteManager.prototype, "texture", {
  28846. get: function () {
  28847. return this._spriteTexture;
  28848. },
  28849. set: function (value) {
  28850. this._spriteTexture = value;
  28851. },
  28852. enumerable: true,
  28853. configurable: true
  28854. });
  28855. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  28856. var arrayOffset = index * 16;
  28857. if (offsetX === 0)
  28858. offsetX = this._epsilon;
  28859. else if (offsetX === 1)
  28860. offsetX = 1 - this._epsilon;
  28861. if (offsetY === 0)
  28862. offsetY = this._epsilon;
  28863. else if (offsetY === 1)
  28864. offsetY = 1 - this._epsilon;
  28865. this._vertexData[arrayOffset] = sprite.position.x;
  28866. this._vertexData[arrayOffset + 1] = sprite.position.y;
  28867. this._vertexData[arrayOffset + 2] = sprite.position.z;
  28868. this._vertexData[arrayOffset + 3] = sprite.angle;
  28869. this._vertexData[arrayOffset + 4] = sprite.width;
  28870. this._vertexData[arrayOffset + 5] = sprite.height;
  28871. this._vertexData[arrayOffset + 6] = offsetX;
  28872. this._vertexData[arrayOffset + 7] = offsetY;
  28873. this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  28874. this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  28875. var offset = (sprite.cellIndex / rowSize) >> 0;
  28876. this._vertexData[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  28877. this._vertexData[arrayOffset + 11] = offset;
  28878. // Color
  28879. this._vertexData[arrayOffset + 12] = sprite.color.r;
  28880. this._vertexData[arrayOffset + 13] = sprite.color.g;
  28881. this._vertexData[arrayOffset + 14] = sprite.color.b;
  28882. this._vertexData[arrayOffset + 15] = sprite.color.a;
  28883. };
  28884. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  28885. var count = Math.min(this._capacity, this.sprites.length);
  28886. var min = BABYLON.Vector3.Zero();
  28887. var max = BABYLON.Vector3.Zero();
  28888. var distance = Number.MAX_VALUE;
  28889. var currentSprite;
  28890. var cameraSpacePosition = BABYLON.Vector3.Zero();
  28891. var cameraView = camera.getViewMatrix();
  28892. for (var index = 0; index < count; index++) {
  28893. var sprite = this.sprites[index];
  28894. if (!sprite) {
  28895. continue;
  28896. }
  28897. if (predicate) {
  28898. if (!predicate(sprite)) {
  28899. continue;
  28900. }
  28901. }
  28902. else if (!sprite.isPickable) {
  28903. continue;
  28904. }
  28905. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  28906. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  28907. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  28908. if (ray.intersectsBoxMinMax(min, max)) {
  28909. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  28910. if (distance > currentDistance) {
  28911. distance = currentDistance;
  28912. currentSprite = sprite;
  28913. if (fastCheck) {
  28914. break;
  28915. }
  28916. }
  28917. }
  28918. }
  28919. if (currentSprite) {
  28920. var result = new BABYLON.PickingInfo();
  28921. result.hit = true;
  28922. result.pickedSprite = currentSprite;
  28923. result.distance = distance;
  28924. return result;
  28925. }
  28926. return null;
  28927. };
  28928. SpriteManager.prototype.render = function () {
  28929. // Check
  28930. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  28931. return;
  28932. var engine = this._scene.getEngine();
  28933. var baseSize = this._spriteTexture.getBaseSize();
  28934. // Sprites
  28935. var deltaTime = engine.getDeltaTime();
  28936. var max = Math.min(this._capacity, this.sprites.length);
  28937. var rowSize = baseSize.width / this.cellWidth;
  28938. var offset = 0;
  28939. for (var index = 0; index < max; index++) {
  28940. var sprite = this.sprites[index];
  28941. if (!sprite) {
  28942. continue;
  28943. }
  28944. sprite._animate(deltaTime);
  28945. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  28946. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  28947. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  28948. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  28949. }
  28950. this._buffer.update(this._vertexData);
  28951. // Render
  28952. var effect = this._effectBase;
  28953. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  28954. effect = this._effectFog;
  28955. }
  28956. engine.enableEffect(effect);
  28957. var viewMatrix = this._scene.getViewMatrix();
  28958. effect.setTexture("diffuseSampler", this._spriteTexture);
  28959. effect.setMatrix("view", viewMatrix);
  28960. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  28961. effect.setFloat2("textureInfos", this.cellWidth / baseSize.width, this.cellHeight / baseSize.height);
  28962. // Fog
  28963. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  28964. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  28965. effect.setColor3("vFogColor", this._scene.fogColor);
  28966. }
  28967. // VBOs
  28968. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  28969. // Draw order
  28970. engine.setDepthFunctionToLessOrEqual();
  28971. effect.setBool("alphaTest", true);
  28972. engine.setColorWrite(false);
  28973. engine.draw(true, 0, max * 6);
  28974. engine.setColorWrite(true);
  28975. effect.setBool("alphaTest", false);
  28976. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  28977. engine.draw(true, 0, max * 6);
  28978. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  28979. };
  28980. SpriteManager.prototype.dispose = function () {
  28981. if (this._buffer) {
  28982. this._buffer.dispose();
  28983. this._buffer = null;
  28984. }
  28985. if (this._indexBuffer) {
  28986. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  28987. this._indexBuffer = null;
  28988. }
  28989. if (this._spriteTexture) {
  28990. this._spriteTexture.dispose();
  28991. this._spriteTexture = null;
  28992. }
  28993. // Remove from scene
  28994. var index = this._scene.spriteManagers.indexOf(this);
  28995. this._scene.spriteManagers.splice(index, 1);
  28996. // Callback
  28997. this.onDisposeObservable.notifyObservers(this);
  28998. this.onDisposeObservable.clear();
  28999. };
  29000. return SpriteManager;
  29001. }());
  29002. BABYLON.SpriteManager = SpriteManager;
  29003. })(BABYLON || (BABYLON = {}));
  29004. //# sourceMappingURL=babylon.spriteManager.js.map
  29005. var BABYLON;
  29006. (function (BABYLON) {
  29007. var Sprite = (function () {
  29008. function Sprite(name, manager) {
  29009. this.name = name;
  29010. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  29011. this.width = 1.0;
  29012. this.height = 1.0;
  29013. this.angle = 0;
  29014. this.cellIndex = 0;
  29015. this.invertU = 0;
  29016. this.invertV = 0;
  29017. this.animations = new Array();
  29018. this.isPickable = false;
  29019. this._animationStarted = false;
  29020. this._loopAnimation = false;
  29021. this._fromIndex = 0;
  29022. this._toIndex = 0;
  29023. this._delay = 0;
  29024. this._direction = 1;
  29025. this._frameCount = 0;
  29026. this._time = 0;
  29027. this._manager = manager;
  29028. this._manager.sprites.push(this);
  29029. this.position = BABYLON.Vector3.Zero();
  29030. }
  29031. Object.defineProperty(Sprite.prototype, "size", {
  29032. get: function () {
  29033. return this.width;
  29034. },
  29035. set: function (value) {
  29036. this.width = value;
  29037. this.height = value;
  29038. },
  29039. enumerable: true,
  29040. configurable: true
  29041. });
  29042. Sprite.prototype.playAnimation = function (from, to, loop, delay, onAnimationEnd) {
  29043. this._fromIndex = from;
  29044. this._toIndex = to;
  29045. this._loopAnimation = loop;
  29046. this._delay = delay;
  29047. this._animationStarted = true;
  29048. this._direction = from < to ? 1 : -1;
  29049. this.cellIndex = from;
  29050. this._time = 0;
  29051. this._onAnimationEnd = onAnimationEnd;
  29052. };
  29053. Sprite.prototype.stopAnimation = function () {
  29054. this._animationStarted = false;
  29055. };
  29056. Sprite.prototype._animate = function (deltaTime) {
  29057. if (!this._animationStarted)
  29058. return;
  29059. this._time += deltaTime;
  29060. if (this._time > this._delay) {
  29061. this._time = this._time % this._delay;
  29062. this.cellIndex += this._direction;
  29063. if (this.cellIndex === this._toIndex) {
  29064. if (this._loopAnimation) {
  29065. this.cellIndex = this._fromIndex;
  29066. }
  29067. else {
  29068. this._animationStarted = false;
  29069. if (this._onAnimationEnd) {
  29070. this._onAnimationEnd();
  29071. }
  29072. if (this.disposeWhenFinishedAnimating) {
  29073. this.dispose();
  29074. }
  29075. }
  29076. }
  29077. }
  29078. };
  29079. Sprite.prototype.dispose = function () {
  29080. for (var i = 0; i < this._manager.sprites.length; i++) {
  29081. if (this._manager.sprites[i] == this) {
  29082. this._manager.sprites.splice(i, 1);
  29083. }
  29084. }
  29085. };
  29086. return Sprite;
  29087. }());
  29088. BABYLON.Sprite = Sprite;
  29089. })(BABYLON || (BABYLON = {}));
  29090. //# sourceMappingURL=babylon.sprite.js.map
  29091. var BABYLON;
  29092. (function (BABYLON) {
  29093. var Layer = (function () {
  29094. function Layer(name, imgUrl, scene, isBackground, color) {
  29095. this.name = name;
  29096. this.scale = new BABYLON.Vector2(1, 1);
  29097. this.offset = new BABYLON.Vector2(0, 0);
  29098. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  29099. this._vertexBuffers = {};
  29100. // Events
  29101. /**
  29102. * An event triggered when the layer is disposed.
  29103. * @type {BABYLON.Observable}
  29104. */
  29105. this.onDisposeObservable = new BABYLON.Observable();
  29106. /**
  29107. * An event triggered before rendering the scene
  29108. * @type {BABYLON.Observable}
  29109. */
  29110. this.onBeforeRenderObservable = new BABYLON.Observable();
  29111. /**
  29112. * An event triggered after rendering the scene
  29113. * @type {BABYLON.Observable}
  29114. */
  29115. this.onAfterRenderObservable = new BABYLON.Observable();
  29116. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  29117. this.isBackground = isBackground === undefined ? true : isBackground;
  29118. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  29119. this._scene = scene;
  29120. this._scene.layers.push(this);
  29121. var engine = scene.getEngine();
  29122. // VBO
  29123. var vertices = [];
  29124. vertices.push(1, 1);
  29125. vertices.push(-1, 1);
  29126. vertices.push(-1, -1);
  29127. vertices.push(1, -1);
  29128. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  29129. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  29130. // Indices
  29131. var indices = [];
  29132. indices.push(0);
  29133. indices.push(1);
  29134. indices.push(2);
  29135. indices.push(0);
  29136. indices.push(2);
  29137. indices.push(3);
  29138. this._indexBuffer = engine.createIndexBuffer(indices);
  29139. // Effects
  29140. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  29141. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  29142. }
  29143. Object.defineProperty(Layer.prototype, "onDispose", {
  29144. set: function (callback) {
  29145. if (this._onDisposeObserver) {
  29146. this.onDisposeObservable.remove(this._onDisposeObserver);
  29147. }
  29148. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  29149. },
  29150. enumerable: true,
  29151. configurable: true
  29152. });
  29153. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  29154. set: function (callback) {
  29155. if (this._onBeforeRenderObserver) {
  29156. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  29157. }
  29158. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  29159. },
  29160. enumerable: true,
  29161. configurable: true
  29162. });
  29163. Object.defineProperty(Layer.prototype, "onAfterRender", {
  29164. set: function (callback) {
  29165. if (this._onAfterRenderObserver) {
  29166. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  29167. }
  29168. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  29169. },
  29170. enumerable: true,
  29171. configurable: true
  29172. });
  29173. Layer.prototype.render = function () {
  29174. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  29175. // Check
  29176. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  29177. return;
  29178. var engine = this._scene.getEngine();
  29179. this.onBeforeRenderObservable.notifyObservers(this);
  29180. // Render
  29181. engine.enableEffect(currentEffect);
  29182. engine.setState(false);
  29183. // Texture
  29184. currentEffect.setTexture("textureSampler", this.texture);
  29185. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  29186. // Color
  29187. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  29188. // Scale / offset
  29189. currentEffect.setVector2("offset", this.offset);
  29190. currentEffect.setVector2("scale", this.scale);
  29191. // VBOs
  29192. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  29193. // Draw order
  29194. if (!this.alphaTest) {
  29195. engine.setAlphaMode(this.alphaBlendingMode);
  29196. engine.draw(true, 0, 6);
  29197. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  29198. }
  29199. else {
  29200. engine.draw(true, 0, 6);
  29201. }
  29202. this.onAfterRenderObservable.notifyObservers(this);
  29203. };
  29204. Layer.prototype.dispose = function () {
  29205. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  29206. if (vertexBuffer) {
  29207. vertexBuffer.dispose();
  29208. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  29209. }
  29210. if (this._indexBuffer) {
  29211. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  29212. this._indexBuffer = null;
  29213. }
  29214. if (this.texture) {
  29215. this.texture.dispose();
  29216. this.texture = null;
  29217. }
  29218. // Remove from scene
  29219. var index = this._scene.layers.indexOf(this);
  29220. this._scene.layers.splice(index, 1);
  29221. // Callback
  29222. this.onDisposeObservable.notifyObservers(this);
  29223. this.onDisposeObservable.clear();
  29224. this.onAfterRenderObservable.clear();
  29225. this.onBeforeRenderObservable.clear();
  29226. };
  29227. return Layer;
  29228. }());
  29229. BABYLON.Layer = Layer;
  29230. })(BABYLON || (BABYLON = {}));
  29231. //# sourceMappingURL=babylon.layer.js.map
  29232. var BABYLON;
  29233. (function (BABYLON) {
  29234. var Particle = (function () {
  29235. function Particle() {
  29236. this.position = BABYLON.Vector3.Zero();
  29237. this.direction = BABYLON.Vector3.Zero();
  29238. this.color = new BABYLON.Color4(0, 0, 0, 0);
  29239. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  29240. this.lifeTime = 1.0;
  29241. this.age = 0;
  29242. this.size = 0;
  29243. this.angle = 0;
  29244. this.angularSpeed = 0;
  29245. }
  29246. Particle.prototype.copyTo = function (other) {
  29247. other.position.copyFrom(this.position);
  29248. other.direction.copyFrom(this.direction);
  29249. other.color.copyFrom(this.color);
  29250. other.colorStep.copyFrom(this.colorStep);
  29251. other.lifeTime = this.lifeTime;
  29252. other.age = this.age;
  29253. other.size = this.size;
  29254. other.angle = this.angle;
  29255. other.angularSpeed = this.angularSpeed;
  29256. };
  29257. return Particle;
  29258. }());
  29259. BABYLON.Particle = Particle;
  29260. })(BABYLON || (BABYLON = {}));
  29261. //# sourceMappingURL=babylon.particle.js.map
  29262. var BABYLON;
  29263. (function (BABYLON) {
  29264. var randomNumber = function (min, max) {
  29265. if (min === max) {
  29266. return (min);
  29267. }
  29268. var random = Math.random();
  29269. return ((random * (max - min)) + min);
  29270. };
  29271. var ParticleSystem = (function () {
  29272. function ParticleSystem(name, capacity, scene, customEffect) {
  29273. var _this = this;
  29274. this.name = name;
  29275. // Members
  29276. this.animations = [];
  29277. this.renderingGroupId = 0;
  29278. this.emitter = null;
  29279. this.emitRate = 10;
  29280. this.manualEmitCount = -1;
  29281. this.updateSpeed = 0.01;
  29282. this.targetStopDuration = 0;
  29283. this.disposeOnStop = false;
  29284. this.minEmitPower = 1;
  29285. this.maxEmitPower = 1;
  29286. this.minLifeTime = 1;
  29287. this.maxLifeTime = 1;
  29288. this.minSize = 1;
  29289. this.maxSize = 1;
  29290. this.minAngularSpeed = 0;
  29291. this.maxAngularSpeed = 0;
  29292. this.layerMask = 0x0FFFFFFF;
  29293. this.customShader = null;
  29294. this.preventAutoStart = false;
  29295. /**
  29296. * An event triggered when the system is disposed.
  29297. * @type {BABYLON.Observable}
  29298. */
  29299. this.onDisposeObservable = new BABYLON.Observable();
  29300. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  29301. this.forceDepthWrite = false;
  29302. this.gravity = BABYLON.Vector3.Zero();
  29303. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  29304. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  29305. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  29306. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  29307. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  29308. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  29309. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  29310. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  29311. this.particles = new Array();
  29312. this._stockParticles = new Array();
  29313. this._newPartsExcess = 0;
  29314. this._vertexBuffers = {};
  29315. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  29316. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  29317. this._scaledDirection = BABYLON.Vector3.Zero();
  29318. this._scaledGravity = BABYLON.Vector3.Zero();
  29319. this._currentRenderId = -1;
  29320. this._started = false;
  29321. this._stopped = false;
  29322. this._actualFrame = 0;
  29323. this.id = name;
  29324. this._capacity = capacity;
  29325. this._scene = scene;
  29326. this._customEffect = customEffect;
  29327. scene.particleSystems.push(this);
  29328. var indices = [];
  29329. var index = 0;
  29330. for (var count = 0; count < capacity; count++) {
  29331. indices.push(index);
  29332. indices.push(index + 1);
  29333. indices.push(index + 2);
  29334. indices.push(index);
  29335. indices.push(index + 2);
  29336. indices.push(index + 3);
  29337. index += 4;
  29338. }
  29339. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  29340. // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY) + 1 filler
  29341. this._vertexData = new Float32Array(capacity * 11 * 4);
  29342. this._vertexBuffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 11);
  29343. var positions = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 3);
  29344. var colors = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 3, 4);
  29345. var options = this._vertexBuffer.createVertexBuffer("options", 7, 4);
  29346. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  29347. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  29348. this._vertexBuffers["options"] = options;
  29349. // Default behaviors
  29350. this.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  29351. var randX = randomNumber(_this.direction1.x, _this.direction2.x);
  29352. var randY = randomNumber(_this.direction1.y, _this.direction2.y);
  29353. var randZ = randomNumber(_this.direction1.z, _this.direction2.z);
  29354. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  29355. };
  29356. this.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  29357. var randX = randomNumber(_this.minEmitBox.x, _this.maxEmitBox.x);
  29358. var randY = randomNumber(_this.minEmitBox.y, _this.maxEmitBox.y);
  29359. var randZ = randomNumber(_this.minEmitBox.z, _this.maxEmitBox.z);
  29360. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  29361. };
  29362. this.updateFunction = function (particles) {
  29363. for (var index = 0; index < particles.length; index++) {
  29364. var particle = particles[index];
  29365. particle.age += _this._scaledUpdateSpeed;
  29366. if (particle.age >= particle.lifeTime) {
  29367. _this.recycleParticle(particle);
  29368. index--;
  29369. continue;
  29370. }
  29371. else {
  29372. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  29373. particle.color.addInPlace(_this._scaledColorStep);
  29374. if (particle.color.a < 0)
  29375. particle.color.a = 0;
  29376. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  29377. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  29378. particle.position.addInPlace(_this._scaledDirection);
  29379. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  29380. particle.direction.addInPlace(_this._scaledGravity);
  29381. }
  29382. }
  29383. };
  29384. }
  29385. Object.defineProperty(ParticleSystem.prototype, "onDispose", {
  29386. set: function (callback) {
  29387. if (this._onDisposeObserver) {
  29388. this.onDisposeObservable.remove(this._onDisposeObserver);
  29389. }
  29390. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  29391. },
  29392. enumerable: true,
  29393. configurable: true
  29394. });
  29395. ParticleSystem.prototype.recycleParticle = function (particle) {
  29396. var lastParticle = this.particles.pop();
  29397. if (lastParticle !== particle) {
  29398. lastParticle.copyTo(particle);
  29399. this._stockParticles.push(lastParticle);
  29400. }
  29401. };
  29402. ParticleSystem.prototype.getCapacity = function () {
  29403. return this._capacity;
  29404. };
  29405. ParticleSystem.prototype.isAlive = function () {
  29406. return this._alive;
  29407. };
  29408. ParticleSystem.prototype.isStarted = function () {
  29409. return this._started;
  29410. };
  29411. ParticleSystem.prototype.start = function () {
  29412. this._started = true;
  29413. this._stopped = false;
  29414. this._actualFrame = 0;
  29415. };
  29416. ParticleSystem.prototype.stop = function () {
  29417. this._stopped = true;
  29418. };
  29419. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  29420. var offset = index * 11;
  29421. this._vertexData[offset] = particle.position.x;
  29422. this._vertexData[offset + 1] = particle.position.y;
  29423. this._vertexData[offset + 2] = particle.position.z;
  29424. this._vertexData[offset + 3] = particle.color.r;
  29425. this._vertexData[offset + 4] = particle.color.g;
  29426. this._vertexData[offset + 5] = particle.color.b;
  29427. this._vertexData[offset + 6] = particle.color.a;
  29428. this._vertexData[offset + 7] = particle.angle;
  29429. this._vertexData[offset + 8] = particle.size;
  29430. this._vertexData[offset + 9] = offsetX;
  29431. this._vertexData[offset + 10] = offsetY;
  29432. };
  29433. ParticleSystem.prototype._update = function (newParticles) {
  29434. // Update current
  29435. this._alive = this.particles.length > 0;
  29436. this.updateFunction(this.particles);
  29437. // Add new ones
  29438. var worldMatrix;
  29439. if (this.emitter.position) {
  29440. worldMatrix = this.emitter.getWorldMatrix();
  29441. }
  29442. else {
  29443. worldMatrix = BABYLON.Matrix.Translation(this.emitter.x, this.emitter.y, this.emitter.z);
  29444. }
  29445. var particle;
  29446. for (var index = 0; index < newParticles; index++) {
  29447. if (this.particles.length === this._capacity) {
  29448. break;
  29449. }
  29450. if (this._stockParticles.length !== 0) {
  29451. particle = this._stockParticles.pop();
  29452. particle.age = 0;
  29453. }
  29454. else {
  29455. particle = new BABYLON.Particle();
  29456. }
  29457. this.particles.push(particle);
  29458. var emitPower = randomNumber(this.minEmitPower, this.maxEmitPower);
  29459. this.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  29460. particle.lifeTime = randomNumber(this.minLifeTime, this.maxLifeTime);
  29461. particle.size = randomNumber(this.minSize, this.maxSize);
  29462. particle.angularSpeed = randomNumber(this.minAngularSpeed, this.maxAngularSpeed);
  29463. this.startPositionFunction(worldMatrix, particle.position, particle);
  29464. var step = randomNumber(0, 1.0);
  29465. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  29466. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  29467. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  29468. }
  29469. };
  29470. ParticleSystem.prototype._getEffect = function () {
  29471. if (this._customEffect) {
  29472. return this._customEffect;
  29473. }
  29474. ;
  29475. var defines = [];
  29476. if (this._scene.clipPlane) {
  29477. defines.push("#define CLIPPLANE");
  29478. }
  29479. // Effect
  29480. var join = defines.join("\n");
  29481. if (this._cachedDefines !== join) {
  29482. this._cachedDefines = join;
  29483. this._effect = this._scene.getEngine().createEffect("particles", [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options"], ["invView", "view", "projection", "vClipPlane", "textureMask"], ["diffuseSampler"], join);
  29484. }
  29485. return this._effect;
  29486. };
  29487. ParticleSystem.prototype.animate = function () {
  29488. if (!this._started)
  29489. return;
  29490. var effect = this._getEffect();
  29491. // Check
  29492. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  29493. return;
  29494. if (this._currentRenderId === this._scene.getRenderId()) {
  29495. return;
  29496. }
  29497. this._currentRenderId = this._scene.getRenderId();
  29498. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  29499. // determine the number of particles we need to create
  29500. var newParticles;
  29501. if (this.manualEmitCount > -1) {
  29502. newParticles = this.manualEmitCount;
  29503. this._newPartsExcess = 0;
  29504. this.manualEmitCount = 0;
  29505. }
  29506. else {
  29507. newParticles = ((this.emitRate * this._scaledUpdateSpeed) >> 0);
  29508. this._newPartsExcess += this.emitRate * this._scaledUpdateSpeed - newParticles;
  29509. }
  29510. if (this._newPartsExcess > 1.0) {
  29511. newParticles += this._newPartsExcess >> 0;
  29512. this._newPartsExcess -= this._newPartsExcess >> 0;
  29513. }
  29514. this._alive = false;
  29515. if (!this._stopped) {
  29516. this._actualFrame += this._scaledUpdateSpeed;
  29517. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  29518. this.stop();
  29519. }
  29520. else {
  29521. newParticles = 0;
  29522. }
  29523. this._update(newParticles);
  29524. // Stopped?
  29525. if (this._stopped) {
  29526. if (!this._alive) {
  29527. this._started = false;
  29528. if (this.disposeOnStop) {
  29529. this._scene._toBeDisposed.push(this);
  29530. }
  29531. }
  29532. }
  29533. // Update VBO
  29534. var offset = 0;
  29535. for (var index = 0; index < this.particles.length; index++) {
  29536. var particle = this.particles[index];
  29537. this._appendParticleVertex(offset++, particle, 0, 0);
  29538. this._appendParticleVertex(offset++, particle, 1, 0);
  29539. this._appendParticleVertex(offset++, particle, 1, 1);
  29540. this._appendParticleVertex(offset++, particle, 0, 1);
  29541. }
  29542. this._vertexBuffer.update(this._vertexData);
  29543. };
  29544. ParticleSystem.prototype.render = function () {
  29545. var effect = this._getEffect();
  29546. // Check
  29547. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this.particles.length)
  29548. return 0;
  29549. var engine = this._scene.getEngine();
  29550. // Render
  29551. engine.enableEffect(effect);
  29552. engine.setState(false);
  29553. var viewMatrix = this._scene.getViewMatrix();
  29554. effect.setTexture("diffuseSampler", this.particleTexture);
  29555. effect.setMatrix("view", viewMatrix);
  29556. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  29557. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  29558. if (this._scene.clipPlane) {
  29559. var clipPlane = this._scene.clipPlane;
  29560. var invView = viewMatrix.clone();
  29561. invView.invert();
  29562. effect.setMatrix("invView", invView);
  29563. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  29564. }
  29565. // VBOs
  29566. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  29567. // Draw order
  29568. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  29569. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  29570. }
  29571. else {
  29572. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  29573. }
  29574. if (this.forceDepthWrite) {
  29575. engine.setDepthWrite(true);
  29576. }
  29577. engine.draw(true, 0, this.particles.length * 6);
  29578. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  29579. return this.particles.length;
  29580. };
  29581. ParticleSystem.prototype.dispose = function () {
  29582. if (this._vertexBuffer) {
  29583. this._vertexBuffer.dispose();
  29584. this._vertexBuffer = null;
  29585. }
  29586. if (this._indexBuffer) {
  29587. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  29588. this._indexBuffer = null;
  29589. }
  29590. if (this.particleTexture) {
  29591. this.particleTexture.dispose();
  29592. this.particleTexture = null;
  29593. }
  29594. // Remove from scene
  29595. var index = this._scene.particleSystems.indexOf(this);
  29596. this._scene.particleSystems.splice(index, 1);
  29597. // Callback
  29598. this.onDisposeObservable.notifyObservers(this);
  29599. this.onDisposeObservable.clear();
  29600. };
  29601. // Clone
  29602. ParticleSystem.prototype.clone = function (name, newEmitter) {
  29603. var custom = null;
  29604. var program = null;
  29605. if (this.customShader != null) {
  29606. program = this.customShader;
  29607. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  29608. custom = this._scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  29609. }
  29610. var result = new ParticleSystem(name, this._capacity, this._scene, custom);
  29611. result.customShader = program;
  29612. BABYLON.Tools.DeepCopy(this, result, ["particles", "customShader"]);
  29613. if (newEmitter === undefined) {
  29614. newEmitter = this.emitter;
  29615. }
  29616. result.emitter = newEmitter;
  29617. if (this.particleTexture) {
  29618. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  29619. }
  29620. if (!this.preventAutoStart) {
  29621. result.start();
  29622. }
  29623. return result;
  29624. };
  29625. ParticleSystem.prototype.serialize = function () {
  29626. var serializationObject = {};
  29627. serializationObject.name = this.name;
  29628. serializationObject.id = this.id;
  29629. // Emitter
  29630. if (this.emitter.position) {
  29631. serializationObject.emitterId = this.emitter.id;
  29632. }
  29633. else {
  29634. serializationObject.emitter = this.emitter.asArray();
  29635. }
  29636. serializationObject.capacity = this.getCapacity();
  29637. if (this.particleTexture) {
  29638. serializationObject.textureName = this.particleTexture.name;
  29639. }
  29640. // Animations
  29641. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  29642. // Particle system
  29643. serializationObject.minAngularSpeed = this.minAngularSpeed;
  29644. serializationObject.maxAngularSpeed = this.maxAngularSpeed;
  29645. serializationObject.minSize = this.minSize;
  29646. serializationObject.maxSize = this.maxSize;
  29647. serializationObject.minEmitPower = this.minEmitPower;
  29648. serializationObject.maxEmitPower = this.maxEmitPower;
  29649. serializationObject.minLifeTime = this.minLifeTime;
  29650. serializationObject.maxLifeTime = this.maxLifeTime;
  29651. serializationObject.emitRate = this.emitRate;
  29652. serializationObject.minEmitBox = this.minEmitBox.asArray();
  29653. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  29654. serializationObject.gravity = this.gravity.asArray();
  29655. serializationObject.direction1 = this.direction1.asArray();
  29656. serializationObject.direction2 = this.direction2.asArray();
  29657. serializationObject.color1 = this.color1.asArray();
  29658. serializationObject.color2 = this.color2.asArray();
  29659. serializationObject.colorDead = this.colorDead.asArray();
  29660. serializationObject.updateSpeed = this.updateSpeed;
  29661. serializationObject.targetStopDuration = this.targetStopDuration;
  29662. serializationObject.textureMask = this.textureMask.asArray();
  29663. serializationObject.blendMode = this.blendMode;
  29664. serializationObject.customShader = this.customShader;
  29665. serializationObject.preventAutoStart = this.preventAutoStart;
  29666. return serializationObject;
  29667. };
  29668. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  29669. var name = parsedParticleSystem.name;
  29670. var custom = null;
  29671. var program = null;
  29672. if (parsedParticleSystem.customShader) {
  29673. program = parsedParticleSystem.customShader;
  29674. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  29675. custom = scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  29676. }
  29677. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene, custom);
  29678. particleSystem.customShader = program;
  29679. if (parsedParticleSystem.id) {
  29680. particleSystem.id = parsedParticleSystem.id;
  29681. }
  29682. // Auto start
  29683. if (parsedParticleSystem.preventAutoStart) {
  29684. particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;
  29685. }
  29686. // Texture
  29687. if (parsedParticleSystem.textureName) {
  29688. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  29689. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  29690. }
  29691. // Emitter
  29692. if (parsedParticleSystem.emitterId) {
  29693. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  29694. }
  29695. else {
  29696. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  29697. }
  29698. // Animations
  29699. if (parsedParticleSystem.animations) {
  29700. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  29701. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  29702. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  29703. }
  29704. }
  29705. if (parsedParticleSystem.autoAnimate) {
  29706. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  29707. }
  29708. // Particle system
  29709. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  29710. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  29711. particleSystem.minSize = parsedParticleSystem.minSize;
  29712. particleSystem.maxSize = parsedParticleSystem.maxSize;
  29713. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  29714. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  29715. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  29716. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  29717. particleSystem.emitRate = parsedParticleSystem.emitRate;
  29718. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  29719. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  29720. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  29721. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  29722. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  29723. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  29724. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  29725. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  29726. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  29727. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  29728. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  29729. particleSystem.blendMode = parsedParticleSystem.blendMode;
  29730. if (!particleSystem.preventAutoStart) {
  29731. particleSystem.start();
  29732. }
  29733. return particleSystem;
  29734. };
  29735. return ParticleSystem;
  29736. }());
  29737. // Statics
  29738. ParticleSystem.BLENDMODE_ONEONE = 0;
  29739. ParticleSystem.BLENDMODE_STANDARD = 1;
  29740. BABYLON.ParticleSystem = ParticleSystem;
  29741. })(BABYLON || (BABYLON = {}));
  29742. //# sourceMappingURL=babylon.particleSystem.js.map
  29743. var BABYLON;
  29744. (function (BABYLON) {
  29745. var AnimationRange = (function () {
  29746. function AnimationRange(name, from, to) {
  29747. this.name = name;
  29748. this.from = from;
  29749. this.to = to;
  29750. }
  29751. AnimationRange.prototype.clone = function () {
  29752. return new AnimationRange(this.name, this.from, this.to);
  29753. };
  29754. return AnimationRange;
  29755. }());
  29756. BABYLON.AnimationRange = AnimationRange;
  29757. /**
  29758. * Composed of a frame, and an action function
  29759. */
  29760. var AnimationEvent = (function () {
  29761. function AnimationEvent(frame, action, onlyOnce) {
  29762. this.frame = frame;
  29763. this.action = action;
  29764. this.onlyOnce = onlyOnce;
  29765. this.isDone = false;
  29766. }
  29767. return AnimationEvent;
  29768. }());
  29769. BABYLON.AnimationEvent = AnimationEvent;
  29770. var PathCursor = (function () {
  29771. function PathCursor(path) {
  29772. this.path = path;
  29773. this._onchange = new Array();
  29774. this.value = 0;
  29775. this.animations = new Array();
  29776. }
  29777. PathCursor.prototype.getPoint = function () {
  29778. var point = this.path.getPointAtLengthPosition(this.value);
  29779. return new BABYLON.Vector3(point.x, 0, point.y);
  29780. };
  29781. PathCursor.prototype.moveAhead = function (step) {
  29782. if (step === void 0) { step = 0.002; }
  29783. this.move(step);
  29784. return this;
  29785. };
  29786. PathCursor.prototype.moveBack = function (step) {
  29787. if (step === void 0) { step = 0.002; }
  29788. this.move(-step);
  29789. return this;
  29790. };
  29791. PathCursor.prototype.move = function (step) {
  29792. if (Math.abs(step) > 1) {
  29793. throw "step size should be less than 1.";
  29794. }
  29795. this.value += step;
  29796. this.ensureLimits();
  29797. this.raiseOnChange();
  29798. return this;
  29799. };
  29800. PathCursor.prototype.ensureLimits = function () {
  29801. while (this.value > 1) {
  29802. this.value -= 1;
  29803. }
  29804. while (this.value < 0) {
  29805. this.value += 1;
  29806. }
  29807. return this;
  29808. };
  29809. // used by animation engine
  29810. PathCursor.prototype.markAsDirty = function (propertyName) {
  29811. this.ensureLimits();
  29812. this.raiseOnChange();
  29813. return this;
  29814. };
  29815. PathCursor.prototype.raiseOnChange = function () {
  29816. var _this = this;
  29817. this._onchange.forEach(function (f) { return f(_this); });
  29818. return this;
  29819. };
  29820. PathCursor.prototype.onchange = function (f) {
  29821. this._onchange.push(f);
  29822. return this;
  29823. };
  29824. return PathCursor;
  29825. }());
  29826. BABYLON.PathCursor = PathCursor;
  29827. var Animation = (function () {
  29828. function Animation(name, targetProperty, framePerSecond, dataType, loopMode, enableBlending) {
  29829. this.name = name;
  29830. this.targetProperty = targetProperty;
  29831. this.framePerSecond = framePerSecond;
  29832. this.dataType = dataType;
  29833. this.loopMode = loopMode;
  29834. this.enableBlending = enableBlending;
  29835. this._offsetsCache = {};
  29836. this._highLimitsCache = {};
  29837. this._stopped = false;
  29838. this._blendingFactor = 0;
  29839. // The set of event that will be linked to this animation
  29840. this._events = new Array();
  29841. this.allowMatricesInterpolation = false;
  29842. this.blendingSpeed = 0.01;
  29843. this._ranges = {};
  29844. this.targetPropertyPath = targetProperty.split(".");
  29845. this.dataType = dataType;
  29846. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  29847. }
  29848. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  29849. var dataType = undefined;
  29850. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  29851. dataType = Animation.ANIMATIONTYPE_FLOAT;
  29852. }
  29853. else if (from instanceof BABYLON.Quaternion) {
  29854. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  29855. }
  29856. else if (from instanceof BABYLON.Vector3) {
  29857. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  29858. }
  29859. else if (from instanceof BABYLON.Vector2) {
  29860. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  29861. }
  29862. else if (from instanceof BABYLON.Color3) {
  29863. dataType = Animation.ANIMATIONTYPE_COLOR3;
  29864. }
  29865. else if (from instanceof BABYLON.Size) {
  29866. dataType = Animation.ANIMATIONTYPE_SIZE;
  29867. }
  29868. if (dataType == undefined) {
  29869. return null;
  29870. }
  29871. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  29872. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  29873. animation.setKeys(keys);
  29874. if (easingFunction !== undefined) {
  29875. animation.setEasingFunction(easingFunction);
  29876. }
  29877. return animation;
  29878. };
  29879. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  29880. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  29881. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  29882. };
  29883. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  29884. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  29885. node.animations.push(animation);
  29886. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  29887. };
  29888. // Methods
  29889. /**
  29890. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  29891. */
  29892. Animation.prototype.toString = function (fullDetails) {
  29893. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  29894. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  29895. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  29896. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  29897. if (fullDetails) {
  29898. ret += ", Ranges: {";
  29899. var first = true;
  29900. for (var name in this._ranges) {
  29901. if (first) {
  29902. ret += ", ";
  29903. first = false;
  29904. }
  29905. ret += name;
  29906. }
  29907. ret += "}";
  29908. }
  29909. return ret;
  29910. };
  29911. /**
  29912. * Add an event to this animation.
  29913. */
  29914. Animation.prototype.addEvent = function (event) {
  29915. this._events.push(event);
  29916. };
  29917. /**
  29918. * Remove all events found at the given frame
  29919. * @param frame
  29920. */
  29921. Animation.prototype.removeEvents = function (frame) {
  29922. for (var index = 0; index < this._events.length; index++) {
  29923. if (this._events[index].frame === frame) {
  29924. this._events.splice(index, 1);
  29925. index--;
  29926. }
  29927. }
  29928. };
  29929. Animation.prototype.createRange = function (name, from, to) {
  29930. // check name not already in use; could happen for bones after serialized
  29931. if (!this._ranges[name]) {
  29932. this._ranges[name] = new AnimationRange(name, from, to);
  29933. }
  29934. };
  29935. Animation.prototype.deleteRange = function (name, deleteFrames) {
  29936. if (deleteFrames === void 0) { deleteFrames = true; }
  29937. if (this._ranges[name]) {
  29938. if (deleteFrames) {
  29939. var from = this._ranges[name].from;
  29940. var to = this._ranges[name].to;
  29941. // this loop MUST go high to low for multiple splices to work
  29942. for (var key = this._keys.length - 1; key >= 0; key--) {
  29943. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  29944. this._keys.splice(key, 1);
  29945. }
  29946. }
  29947. }
  29948. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  29949. }
  29950. };
  29951. Animation.prototype.getRange = function (name) {
  29952. return this._ranges[name];
  29953. };
  29954. Animation.prototype.reset = function () {
  29955. this._offsetsCache = {};
  29956. this._highLimitsCache = {};
  29957. this.currentFrame = 0;
  29958. this._blendingFactor = 0;
  29959. this._originalBlendValue = null;
  29960. };
  29961. Animation.prototype.isStopped = function () {
  29962. return this._stopped;
  29963. };
  29964. Animation.prototype.getKeys = function () {
  29965. return this._keys;
  29966. };
  29967. Animation.prototype.getHighestFrame = function () {
  29968. var ret = 0;
  29969. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  29970. if (ret < this._keys[key].frame) {
  29971. ret = this._keys[key].frame;
  29972. }
  29973. }
  29974. return ret;
  29975. };
  29976. Animation.prototype.getEasingFunction = function () {
  29977. return this._easingFunction;
  29978. };
  29979. Animation.prototype.setEasingFunction = function (easingFunction) {
  29980. this._easingFunction = easingFunction;
  29981. };
  29982. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  29983. return startValue + (endValue - startValue) * gradient;
  29984. };
  29985. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  29986. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  29987. };
  29988. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  29989. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  29990. };
  29991. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  29992. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  29993. };
  29994. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  29995. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  29996. };
  29997. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  29998. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  29999. };
  30000. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  30001. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  30002. };
  30003. Animation.prototype.clone = function () {
  30004. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  30005. clone.enableBlending = this.enableBlending;
  30006. clone.blendingSpeed = this.blendingSpeed;
  30007. if (this._keys) {
  30008. clone.setKeys(this._keys);
  30009. }
  30010. if (this._ranges) {
  30011. clone._ranges = {};
  30012. for (var name in this._ranges) {
  30013. clone._ranges[name] = this._ranges[name].clone();
  30014. }
  30015. }
  30016. return clone;
  30017. };
  30018. Animation.prototype.setKeys = function (values) {
  30019. this._keys = values.slice(0);
  30020. this._offsetsCache = {};
  30021. this._highLimitsCache = {};
  30022. };
  30023. Animation.prototype._getKeyValue = function (value) {
  30024. if (typeof value === "function") {
  30025. return value();
  30026. }
  30027. return value;
  30028. };
  30029. Animation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  30030. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  30031. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  30032. }
  30033. this.currentFrame = currentFrame;
  30034. // Try to get a hash to find the right key
  30035. var startKey = 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));
  30036. if (this._keys[startKey].frame >= currentFrame) {
  30037. while (startKey - 1 >= 0 && this._keys[startKey].frame >= currentFrame) {
  30038. startKey--;
  30039. }
  30040. }
  30041. for (var key = startKey; key < this._keys.length; key++) {
  30042. if (this._keys[key + 1].frame >= currentFrame) {
  30043. var startValue = this._getKeyValue(this._keys[key].value);
  30044. var endValue = this._getKeyValue(this._keys[key + 1].value);
  30045. // gradient : percent of currentFrame between the frame inf and the frame sup
  30046. var gradient = (currentFrame - this._keys[key].frame) / (this._keys[key + 1].frame - this._keys[key].frame);
  30047. // check for easingFunction and correction of gradient
  30048. if (this._easingFunction != null) {
  30049. gradient = this._easingFunction.ease(gradient);
  30050. }
  30051. switch (this.dataType) {
  30052. // Float
  30053. case Animation.ANIMATIONTYPE_FLOAT:
  30054. switch (loopMode) {
  30055. case Animation.ANIMATIONLOOPMODE_CYCLE:
  30056. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  30057. return this.floatInterpolateFunction(startValue, endValue, gradient);
  30058. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  30059. return offsetValue * repeatCount + this.floatInterpolateFunction(startValue, endValue, gradient);
  30060. }
  30061. break;
  30062. // Quaternion
  30063. case Animation.ANIMATIONTYPE_QUATERNION:
  30064. var quaternion = null;
  30065. switch (loopMode) {
  30066. case Animation.ANIMATIONLOOPMODE_CYCLE:
  30067. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  30068. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient);
  30069. break;
  30070. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  30071. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  30072. break;
  30073. }
  30074. return quaternion;
  30075. // Vector3
  30076. case Animation.ANIMATIONTYPE_VECTOR3:
  30077. switch (loopMode) {
  30078. case Animation.ANIMATIONLOOPMODE_CYCLE:
  30079. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  30080. return this.vector3InterpolateFunction(startValue, endValue, gradient);
  30081. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  30082. return this.vector3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  30083. }
  30084. // Vector2
  30085. case Animation.ANIMATIONTYPE_VECTOR2:
  30086. switch (loopMode) {
  30087. case Animation.ANIMATIONLOOPMODE_CYCLE:
  30088. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  30089. return this.vector2InterpolateFunction(startValue, endValue, gradient);
  30090. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  30091. return this.vector2InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  30092. }
  30093. // Size
  30094. case Animation.ANIMATIONTYPE_SIZE:
  30095. switch (loopMode) {
  30096. case Animation.ANIMATIONLOOPMODE_CYCLE:
  30097. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  30098. return this.sizeInterpolateFunction(startValue, endValue, gradient);
  30099. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  30100. return this.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  30101. }
  30102. // Color3
  30103. case Animation.ANIMATIONTYPE_COLOR3:
  30104. switch (loopMode) {
  30105. case Animation.ANIMATIONLOOPMODE_CYCLE:
  30106. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  30107. return this.color3InterpolateFunction(startValue, endValue, gradient);
  30108. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  30109. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  30110. }
  30111. // Matrix
  30112. case Animation.ANIMATIONTYPE_MATRIX:
  30113. switch (loopMode) {
  30114. case Animation.ANIMATIONLOOPMODE_CYCLE:
  30115. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  30116. if (this.allowMatricesInterpolation) {
  30117. return this.matrixInterpolateFunction(startValue, endValue, gradient);
  30118. }
  30119. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  30120. return startValue;
  30121. }
  30122. default:
  30123. break;
  30124. }
  30125. break;
  30126. }
  30127. }
  30128. return this._getKeyValue(this._keys[this._keys.length - 1].value);
  30129. };
  30130. Animation.prototype.setValue = function (currentValue, blend) {
  30131. if (blend === void 0) { blend = false; }
  30132. // Set value
  30133. var path;
  30134. var destination;
  30135. if (this.targetPropertyPath.length > 1) {
  30136. var property = this._target[this.targetPropertyPath[0]];
  30137. for (var index = 1; index < this.targetPropertyPath.length - 1; index++) {
  30138. property = property[this.targetPropertyPath[index]];
  30139. }
  30140. path = this.targetPropertyPath[this.targetPropertyPath.length - 1];
  30141. destination = property;
  30142. }
  30143. else {
  30144. path = this.targetPropertyPath[0];
  30145. destination = this._target;
  30146. }
  30147. // Blending
  30148. if (this.enableBlending && this._blendingFactor <= 1.0) {
  30149. if (!this._originalBlendValue) {
  30150. if (destination[path].clone) {
  30151. this._originalBlendValue = destination[path].clone();
  30152. }
  30153. else {
  30154. this._originalBlendValue = destination[path];
  30155. }
  30156. }
  30157. if (this._originalBlendValue.prototype) {
  30158. if (this._originalBlendValue.prototype.Lerp) {
  30159. destination[path] = this._originalBlendValue.construtor.prototype.Lerp(currentValue, this._originalBlendValue, this._blendingFactor);
  30160. }
  30161. else {
  30162. destination[path] = currentValue;
  30163. }
  30164. }
  30165. else if (this._originalBlendValue.m) {
  30166. destination[path] = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  30167. }
  30168. else {
  30169. destination[path] = this._originalBlendValue * (1.0 - this._blendingFactor) + this._blendingFactor * currentValue;
  30170. }
  30171. this._blendingFactor += this.blendingSpeed;
  30172. }
  30173. else {
  30174. destination[path] = currentValue;
  30175. }
  30176. if (this._target.markAsDirty) {
  30177. this._target.markAsDirty(this.targetProperty);
  30178. }
  30179. };
  30180. Animation.prototype.goToFrame = function (frame) {
  30181. if (frame < this._keys[0].frame) {
  30182. frame = this._keys[0].frame;
  30183. }
  30184. else if (frame > this._keys[this._keys.length - 1].frame) {
  30185. frame = this._keys[this._keys.length - 1].frame;
  30186. }
  30187. var currentValue = this._interpolate(frame, 0, this.loopMode);
  30188. this.setValue(currentValue);
  30189. };
  30190. Animation.prototype.animate = function (delay, from, to, loop, speedRatio, blend) {
  30191. if (blend === void 0) { blend = false; }
  30192. if (!this.targetPropertyPath || this.targetPropertyPath.length < 1) {
  30193. this._stopped = true;
  30194. return false;
  30195. }
  30196. var returnValue = true;
  30197. // Adding a start key at frame 0 if missing
  30198. if (this._keys[0].frame !== 0) {
  30199. var newKey = { frame: 0, value: this._keys[0].value };
  30200. this._keys.splice(0, 0, newKey);
  30201. }
  30202. // Check limits
  30203. if (from < this._keys[0].frame || from > this._keys[this._keys.length - 1].frame) {
  30204. from = this._keys[0].frame;
  30205. }
  30206. if (to < this._keys[0].frame || to > this._keys[this._keys.length - 1].frame) {
  30207. to = this._keys[this._keys.length - 1].frame;
  30208. }
  30209. //to and from cannot be the same key
  30210. if (from === to) {
  30211. from++;
  30212. }
  30213. // Compute ratio
  30214. var range = to - from;
  30215. var offsetValue;
  30216. // ratio represents the frame delta between from and to
  30217. var ratio = delay * (this.framePerSecond * speedRatio) / 1000.0;
  30218. var highLimitValue = 0;
  30219. if (ratio > range && !loop) {
  30220. returnValue = false;
  30221. highLimitValue = this._getKeyValue(this._keys[this._keys.length - 1].value);
  30222. }
  30223. else {
  30224. // Get max value if required
  30225. if (this.loopMode !== Animation.ANIMATIONLOOPMODE_CYCLE) {
  30226. var keyOffset = to.toString() + from.toString();
  30227. if (!this._offsetsCache[keyOffset]) {
  30228. var fromValue = this._interpolate(from, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  30229. var toValue = this._interpolate(to, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  30230. switch (this.dataType) {
  30231. // Float
  30232. case Animation.ANIMATIONTYPE_FLOAT:
  30233. this._offsetsCache[keyOffset] = toValue - fromValue;
  30234. break;
  30235. // Quaternion
  30236. case Animation.ANIMATIONTYPE_QUATERNION:
  30237. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  30238. break;
  30239. // Vector3
  30240. case Animation.ANIMATIONTYPE_VECTOR3:
  30241. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  30242. // Vector2
  30243. case Animation.ANIMATIONTYPE_VECTOR2:
  30244. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  30245. // Size
  30246. case Animation.ANIMATIONTYPE_SIZE:
  30247. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  30248. // Color3
  30249. case Animation.ANIMATIONTYPE_COLOR3:
  30250. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  30251. default:
  30252. break;
  30253. }
  30254. this._highLimitsCache[keyOffset] = toValue;
  30255. }
  30256. highLimitValue = this._highLimitsCache[keyOffset];
  30257. offsetValue = this._offsetsCache[keyOffset];
  30258. }
  30259. }
  30260. if (offsetValue === undefined) {
  30261. switch (this.dataType) {
  30262. // Float
  30263. case Animation.ANIMATIONTYPE_FLOAT:
  30264. offsetValue = 0;
  30265. break;
  30266. // Quaternion
  30267. case Animation.ANIMATIONTYPE_QUATERNION:
  30268. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  30269. break;
  30270. // Vector3
  30271. case Animation.ANIMATIONTYPE_VECTOR3:
  30272. offsetValue = BABYLON.Vector3.Zero();
  30273. break;
  30274. // Vector2
  30275. case Animation.ANIMATIONTYPE_VECTOR2:
  30276. offsetValue = BABYLON.Vector2.Zero();
  30277. break;
  30278. // Size
  30279. case Animation.ANIMATIONTYPE_SIZE:
  30280. offsetValue = BABYLON.Size.Zero();
  30281. break;
  30282. // Color3
  30283. case Animation.ANIMATIONTYPE_COLOR3:
  30284. offsetValue = BABYLON.Color3.Black();
  30285. }
  30286. }
  30287. // Compute value
  30288. var repeatCount = (ratio / range) >> 0;
  30289. var currentFrame = returnValue ? from + ratio % range : to;
  30290. var currentValue = this._interpolate(currentFrame, repeatCount, this.loopMode, offsetValue, highLimitValue);
  30291. // Set value
  30292. this.setValue(currentValue);
  30293. // Check events
  30294. for (var index = 0; index < this._events.length; index++) {
  30295. if (currentFrame >= this._events[index].frame) {
  30296. var event = this._events[index];
  30297. if (!event.isDone) {
  30298. // If event should be done only once, remove it.
  30299. if (event.onlyOnce) {
  30300. this._events.splice(index, 1);
  30301. index--;
  30302. }
  30303. event.isDone = true;
  30304. event.action();
  30305. } // Don't do anything if the event has already be done.
  30306. }
  30307. else if (this._events[index].isDone && !this._events[index].onlyOnce) {
  30308. // reset event, the animation is looping
  30309. this._events[index].isDone = false;
  30310. }
  30311. }
  30312. if (!returnValue) {
  30313. this._stopped = true;
  30314. }
  30315. return returnValue;
  30316. };
  30317. Animation.prototype.serialize = function () {
  30318. var serializationObject = {};
  30319. serializationObject.name = this.name;
  30320. serializationObject.property = this.targetProperty;
  30321. serializationObject.framePerSecond = this.framePerSecond;
  30322. serializationObject.dataType = this.dataType;
  30323. serializationObject.loopBehavior = this.loopMode;
  30324. serializationObject.enableBlending = this.enableBlending;
  30325. serializationObject.blendingSpeed = this.blendingSpeed;
  30326. var dataType = this.dataType;
  30327. serializationObject.keys = [];
  30328. var keys = this.getKeys();
  30329. for (var index = 0; index < keys.length; index++) {
  30330. var animationKey = keys[index];
  30331. var key = {};
  30332. key.frame = animationKey.frame;
  30333. switch (dataType) {
  30334. case Animation.ANIMATIONTYPE_FLOAT:
  30335. key.values = [animationKey.value];
  30336. break;
  30337. case Animation.ANIMATIONTYPE_QUATERNION:
  30338. case Animation.ANIMATIONTYPE_MATRIX:
  30339. case Animation.ANIMATIONTYPE_VECTOR3:
  30340. case Animation.ANIMATIONTYPE_COLOR3:
  30341. key.values = animationKey.value.asArray();
  30342. break;
  30343. }
  30344. serializationObject.keys.push(key);
  30345. }
  30346. serializationObject.ranges = [];
  30347. for (var name in this._ranges) {
  30348. var range = {};
  30349. range.name = name;
  30350. range.from = this._ranges[name].from;
  30351. range.to = this._ranges[name].to;
  30352. serializationObject.ranges.push(range);
  30353. }
  30354. return serializationObject;
  30355. };
  30356. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  30357. get: function () {
  30358. return Animation._ANIMATIONTYPE_FLOAT;
  30359. },
  30360. enumerable: true,
  30361. configurable: true
  30362. });
  30363. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  30364. get: function () {
  30365. return Animation._ANIMATIONTYPE_VECTOR3;
  30366. },
  30367. enumerable: true,
  30368. configurable: true
  30369. });
  30370. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  30371. get: function () {
  30372. return Animation._ANIMATIONTYPE_VECTOR2;
  30373. },
  30374. enumerable: true,
  30375. configurable: true
  30376. });
  30377. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  30378. get: function () {
  30379. return Animation._ANIMATIONTYPE_SIZE;
  30380. },
  30381. enumerable: true,
  30382. configurable: true
  30383. });
  30384. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  30385. get: function () {
  30386. return Animation._ANIMATIONTYPE_QUATERNION;
  30387. },
  30388. enumerable: true,
  30389. configurable: true
  30390. });
  30391. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  30392. get: function () {
  30393. return Animation._ANIMATIONTYPE_MATRIX;
  30394. },
  30395. enumerable: true,
  30396. configurable: true
  30397. });
  30398. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  30399. get: function () {
  30400. return Animation._ANIMATIONTYPE_COLOR3;
  30401. },
  30402. enumerable: true,
  30403. configurable: true
  30404. });
  30405. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  30406. get: function () {
  30407. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  30408. },
  30409. enumerable: true,
  30410. configurable: true
  30411. });
  30412. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  30413. get: function () {
  30414. return Animation._ANIMATIONLOOPMODE_CYCLE;
  30415. },
  30416. enumerable: true,
  30417. configurable: true
  30418. });
  30419. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  30420. get: function () {
  30421. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  30422. },
  30423. enumerable: true,
  30424. configurable: true
  30425. });
  30426. Animation.Parse = function (parsedAnimation) {
  30427. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  30428. var dataType = parsedAnimation.dataType;
  30429. var keys = [];
  30430. var data;
  30431. var index;
  30432. if (parsedAnimation.enableBlending) {
  30433. animation.enableBlending = parsedAnimation.enableBlending;
  30434. }
  30435. if (parsedAnimation.blendingSpeed) {
  30436. animation.blendingSpeed = parsedAnimation.blendingSpeed;
  30437. }
  30438. for (index = 0; index < parsedAnimation.keys.length; index++) {
  30439. var key = parsedAnimation.keys[index];
  30440. switch (dataType) {
  30441. case Animation.ANIMATIONTYPE_FLOAT:
  30442. data = key.values[0];
  30443. break;
  30444. case Animation.ANIMATIONTYPE_QUATERNION:
  30445. data = BABYLON.Quaternion.FromArray(key.values);
  30446. break;
  30447. case Animation.ANIMATIONTYPE_MATRIX:
  30448. data = BABYLON.Matrix.FromArray(key.values);
  30449. break;
  30450. case Animation.ANIMATIONTYPE_COLOR3:
  30451. data = BABYLON.Color3.FromArray(key.values);
  30452. break;
  30453. case Animation.ANIMATIONTYPE_VECTOR3:
  30454. default:
  30455. data = BABYLON.Vector3.FromArray(key.values);
  30456. break;
  30457. }
  30458. keys.push({
  30459. frame: key.frame,
  30460. value: data
  30461. });
  30462. }
  30463. animation.setKeys(keys);
  30464. if (parsedAnimation.ranges) {
  30465. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  30466. data = parsedAnimation.ranges[index];
  30467. animation.createRange(data.name, data.from, data.to);
  30468. }
  30469. }
  30470. return animation;
  30471. };
  30472. Animation.AppendSerializedAnimations = function (source, destination) {
  30473. if (source.animations) {
  30474. destination.animations = [];
  30475. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  30476. var animation = source.animations[animationIndex];
  30477. destination.animations.push(animation.serialize());
  30478. }
  30479. }
  30480. };
  30481. return Animation;
  30482. }());
  30483. // Statics
  30484. Animation._ANIMATIONTYPE_FLOAT = 0;
  30485. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  30486. Animation._ANIMATIONTYPE_QUATERNION = 2;
  30487. Animation._ANIMATIONTYPE_MATRIX = 3;
  30488. Animation._ANIMATIONTYPE_COLOR3 = 4;
  30489. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  30490. Animation._ANIMATIONTYPE_SIZE = 6;
  30491. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  30492. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  30493. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  30494. BABYLON.Animation = Animation;
  30495. })(BABYLON || (BABYLON = {}));
  30496. //# sourceMappingURL=babylon.animation.js.map
  30497. var BABYLON;
  30498. (function (BABYLON) {
  30499. var Animatable = (function () {
  30500. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  30501. if (fromFrame === void 0) { fromFrame = 0; }
  30502. if (toFrame === void 0) { toFrame = 100; }
  30503. if (loopAnimation === void 0) { loopAnimation = false; }
  30504. if (speedRatio === void 0) { speedRatio = 1.0; }
  30505. this.target = target;
  30506. this.fromFrame = fromFrame;
  30507. this.toFrame = toFrame;
  30508. this.loopAnimation = loopAnimation;
  30509. this.speedRatio = speedRatio;
  30510. this.onAnimationEnd = onAnimationEnd;
  30511. this._animations = new Array();
  30512. this._paused = false;
  30513. this.animationStarted = false;
  30514. if (animations) {
  30515. this.appendAnimations(target, animations);
  30516. }
  30517. this._scene = scene;
  30518. scene._activeAnimatables.push(this);
  30519. }
  30520. // Methods
  30521. Animatable.prototype.getAnimations = function () {
  30522. return this._animations;
  30523. };
  30524. Animatable.prototype.appendAnimations = function (target, animations) {
  30525. for (var index = 0; index < animations.length; index++) {
  30526. var animation = animations[index];
  30527. animation._target = target;
  30528. this._animations.push(animation);
  30529. }
  30530. };
  30531. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  30532. var animations = this._animations;
  30533. for (var index = 0; index < animations.length; index++) {
  30534. if (animations[index].targetProperty === property) {
  30535. return animations[index];
  30536. }
  30537. }
  30538. return null;
  30539. };
  30540. Animatable.prototype.reset = function () {
  30541. var animations = this._animations;
  30542. for (var index = 0; index < animations.length; index++) {
  30543. animations[index].reset();
  30544. }
  30545. this._localDelayOffset = null;
  30546. this._pausedDelay = null;
  30547. };
  30548. Animatable.prototype.enableBlending = function (blendingSpeed) {
  30549. var animations = this._animations;
  30550. for (var index = 0; index < animations.length; index++) {
  30551. animations[index].enableBlending = true;
  30552. animations[index].blendingSpeed = blendingSpeed;
  30553. }
  30554. };
  30555. Animatable.prototype.disableBlending = function () {
  30556. var animations = this._animations;
  30557. for (var index = 0; index < animations.length; index++) {
  30558. animations[index].enableBlending = false;
  30559. }
  30560. };
  30561. Animatable.prototype.goToFrame = function (frame) {
  30562. var animations = this._animations;
  30563. if (animations[0]) {
  30564. var fps = animations[0].framePerSecond;
  30565. var currentFrame = animations[0].currentFrame;
  30566. var adjustTime = frame - currentFrame;
  30567. var delay = adjustTime * 1000 / fps;
  30568. this._localDelayOffset -= delay;
  30569. }
  30570. for (var index = 0; index < animations.length; index++) {
  30571. animations[index].goToFrame(frame);
  30572. }
  30573. };
  30574. Animatable.prototype.pause = function () {
  30575. if (this._paused) {
  30576. return;
  30577. }
  30578. this._paused = true;
  30579. };
  30580. Animatable.prototype.restart = function () {
  30581. this._paused = false;
  30582. };
  30583. Animatable.prototype.stop = function (animationName) {
  30584. if (animationName) {
  30585. var idx = this._scene._activeAnimatables.indexOf(this);
  30586. if (idx > -1) {
  30587. var animations = this._animations;
  30588. var numberOfAnimationsStopped = 0;
  30589. for (var index = animations.length - 1; index >= 0; index--) {
  30590. if (typeof animationName === "string" && animations[index].name != animationName) {
  30591. continue;
  30592. }
  30593. animations[index].reset();
  30594. animations.splice(index, 1);
  30595. numberOfAnimationsStopped++;
  30596. }
  30597. if (animations.length == numberOfAnimationsStopped) {
  30598. this._scene._activeAnimatables.splice(idx, 1);
  30599. if (this.onAnimationEnd) {
  30600. this.onAnimationEnd();
  30601. }
  30602. }
  30603. }
  30604. }
  30605. else {
  30606. var index = this._scene._activeAnimatables.indexOf(this);
  30607. if (index > -1) {
  30608. this._scene._activeAnimatables.splice(index, 1);
  30609. var animations = this._animations;
  30610. for (var index = 0; index < animations.length; index++) {
  30611. animations[index].reset();
  30612. }
  30613. if (this.onAnimationEnd) {
  30614. this.onAnimationEnd();
  30615. }
  30616. }
  30617. }
  30618. };
  30619. Animatable.prototype._animate = function (delay) {
  30620. if (this._paused) {
  30621. this.animationStarted = false;
  30622. if (!this._pausedDelay) {
  30623. this._pausedDelay = delay;
  30624. }
  30625. return true;
  30626. }
  30627. if (!this._localDelayOffset) {
  30628. this._localDelayOffset = delay;
  30629. }
  30630. else if (this._pausedDelay) {
  30631. this._localDelayOffset += delay - this._pausedDelay;
  30632. this._pausedDelay = null;
  30633. }
  30634. // Animating
  30635. var running = false;
  30636. var animations = this._animations;
  30637. var index;
  30638. for (index = 0; index < animations.length; index++) {
  30639. var animation = animations[index];
  30640. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this.speedRatio);
  30641. running = running || isRunning;
  30642. }
  30643. this.animationStarted = running;
  30644. if (!running) {
  30645. // Remove from active animatables
  30646. index = this._scene._activeAnimatables.indexOf(this);
  30647. this._scene._activeAnimatables.splice(index, 1);
  30648. }
  30649. if (!running && this.onAnimationEnd) {
  30650. this.onAnimationEnd();
  30651. this.onAnimationEnd = null;
  30652. }
  30653. return running;
  30654. };
  30655. return Animatable;
  30656. }());
  30657. BABYLON.Animatable = Animatable;
  30658. })(BABYLON || (BABYLON = {}));
  30659. //# sourceMappingURL=babylon.animatable.js.map
  30660. var BABYLON;
  30661. (function (BABYLON) {
  30662. var EasingFunction = (function () {
  30663. function EasingFunction() {
  30664. // Properties
  30665. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  30666. }
  30667. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  30668. get: function () {
  30669. return EasingFunction._EASINGMODE_EASEIN;
  30670. },
  30671. enumerable: true,
  30672. configurable: true
  30673. });
  30674. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  30675. get: function () {
  30676. return EasingFunction._EASINGMODE_EASEOUT;
  30677. },
  30678. enumerable: true,
  30679. configurable: true
  30680. });
  30681. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  30682. get: function () {
  30683. return EasingFunction._EASINGMODE_EASEINOUT;
  30684. },
  30685. enumerable: true,
  30686. configurable: true
  30687. });
  30688. EasingFunction.prototype.setEasingMode = function (easingMode) {
  30689. var n = Math.min(Math.max(easingMode, 0), 2);
  30690. this._easingMode = n;
  30691. };
  30692. EasingFunction.prototype.getEasingMode = function () {
  30693. return this._easingMode;
  30694. };
  30695. EasingFunction.prototype.easeInCore = function (gradient) {
  30696. throw new Error('You must implement this method');
  30697. };
  30698. EasingFunction.prototype.ease = function (gradient) {
  30699. switch (this._easingMode) {
  30700. case EasingFunction.EASINGMODE_EASEIN:
  30701. return this.easeInCore(gradient);
  30702. case EasingFunction.EASINGMODE_EASEOUT:
  30703. return (1 - this.easeInCore(1 - gradient));
  30704. }
  30705. if (gradient >= 0.5) {
  30706. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  30707. }
  30708. return (this.easeInCore(gradient * 2) * 0.5);
  30709. };
  30710. return EasingFunction;
  30711. }());
  30712. //Statics
  30713. EasingFunction._EASINGMODE_EASEIN = 0;
  30714. EasingFunction._EASINGMODE_EASEOUT = 1;
  30715. EasingFunction._EASINGMODE_EASEINOUT = 2;
  30716. BABYLON.EasingFunction = EasingFunction;
  30717. var CircleEase = (function (_super) {
  30718. __extends(CircleEase, _super);
  30719. function CircleEase() {
  30720. return _super.apply(this, arguments) || this;
  30721. }
  30722. CircleEase.prototype.easeInCore = function (gradient) {
  30723. gradient = Math.max(0, Math.min(1, gradient));
  30724. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  30725. };
  30726. return CircleEase;
  30727. }(EasingFunction));
  30728. BABYLON.CircleEase = CircleEase;
  30729. var BackEase = (function (_super) {
  30730. __extends(BackEase, _super);
  30731. function BackEase(amplitude) {
  30732. if (amplitude === void 0) { amplitude = 1; }
  30733. var _this = _super.call(this) || this;
  30734. _this.amplitude = amplitude;
  30735. return _this;
  30736. }
  30737. BackEase.prototype.easeInCore = function (gradient) {
  30738. var num = Math.max(0, this.amplitude);
  30739. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  30740. };
  30741. return BackEase;
  30742. }(EasingFunction));
  30743. BABYLON.BackEase = BackEase;
  30744. var BounceEase = (function (_super) {
  30745. __extends(BounceEase, _super);
  30746. function BounceEase(bounces, bounciness) {
  30747. if (bounces === void 0) { bounces = 3; }
  30748. if (bounciness === void 0) { bounciness = 2; }
  30749. var _this = _super.call(this) || this;
  30750. _this.bounces = bounces;
  30751. _this.bounciness = bounciness;
  30752. return _this;
  30753. }
  30754. BounceEase.prototype.easeInCore = function (gradient) {
  30755. var y = Math.max(0.0, this.bounces);
  30756. var bounciness = this.bounciness;
  30757. if (bounciness <= 1.0) {
  30758. bounciness = 1.001;
  30759. }
  30760. var num9 = Math.pow(bounciness, y);
  30761. var num5 = 1.0 - bounciness;
  30762. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  30763. var num15 = gradient * num4;
  30764. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  30765. var num3 = Math.floor(num65);
  30766. var num13 = num3 + 1.0;
  30767. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  30768. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  30769. var num7 = (num8 + num12) * 0.5;
  30770. var num6 = gradient - num7;
  30771. var num2 = num7 - num8;
  30772. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  30773. };
  30774. return BounceEase;
  30775. }(EasingFunction));
  30776. BABYLON.BounceEase = BounceEase;
  30777. var CubicEase = (function (_super) {
  30778. __extends(CubicEase, _super);
  30779. function CubicEase() {
  30780. return _super.apply(this, arguments) || this;
  30781. }
  30782. CubicEase.prototype.easeInCore = function (gradient) {
  30783. return (gradient * gradient * gradient);
  30784. };
  30785. return CubicEase;
  30786. }(EasingFunction));
  30787. BABYLON.CubicEase = CubicEase;
  30788. var ElasticEase = (function (_super) {
  30789. __extends(ElasticEase, _super);
  30790. function ElasticEase(oscillations, springiness) {
  30791. if (oscillations === void 0) { oscillations = 3; }
  30792. if (springiness === void 0) { springiness = 3; }
  30793. var _this = _super.call(this) || this;
  30794. _this.oscillations = oscillations;
  30795. _this.springiness = springiness;
  30796. return _this;
  30797. }
  30798. ElasticEase.prototype.easeInCore = function (gradient) {
  30799. var num2;
  30800. var num3 = Math.max(0.0, this.oscillations);
  30801. var num = Math.max(0.0, this.springiness);
  30802. if (num == 0) {
  30803. num2 = gradient;
  30804. }
  30805. else {
  30806. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  30807. }
  30808. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  30809. };
  30810. return ElasticEase;
  30811. }(EasingFunction));
  30812. BABYLON.ElasticEase = ElasticEase;
  30813. var ExponentialEase = (function (_super) {
  30814. __extends(ExponentialEase, _super);
  30815. function ExponentialEase(exponent) {
  30816. if (exponent === void 0) { exponent = 2; }
  30817. var _this = _super.call(this) || this;
  30818. _this.exponent = exponent;
  30819. return _this;
  30820. }
  30821. ExponentialEase.prototype.easeInCore = function (gradient) {
  30822. if (this.exponent <= 0) {
  30823. return gradient;
  30824. }
  30825. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  30826. };
  30827. return ExponentialEase;
  30828. }(EasingFunction));
  30829. BABYLON.ExponentialEase = ExponentialEase;
  30830. var PowerEase = (function (_super) {
  30831. __extends(PowerEase, _super);
  30832. function PowerEase(power) {
  30833. if (power === void 0) { power = 2; }
  30834. var _this = _super.call(this) || this;
  30835. _this.power = power;
  30836. return _this;
  30837. }
  30838. PowerEase.prototype.easeInCore = function (gradient) {
  30839. var y = Math.max(0.0, this.power);
  30840. return Math.pow(gradient, y);
  30841. };
  30842. return PowerEase;
  30843. }(EasingFunction));
  30844. BABYLON.PowerEase = PowerEase;
  30845. var QuadraticEase = (function (_super) {
  30846. __extends(QuadraticEase, _super);
  30847. function QuadraticEase() {
  30848. return _super.apply(this, arguments) || this;
  30849. }
  30850. QuadraticEase.prototype.easeInCore = function (gradient) {
  30851. return (gradient * gradient);
  30852. };
  30853. return QuadraticEase;
  30854. }(EasingFunction));
  30855. BABYLON.QuadraticEase = QuadraticEase;
  30856. var QuarticEase = (function (_super) {
  30857. __extends(QuarticEase, _super);
  30858. function QuarticEase() {
  30859. return _super.apply(this, arguments) || this;
  30860. }
  30861. QuarticEase.prototype.easeInCore = function (gradient) {
  30862. return (gradient * gradient * gradient * gradient);
  30863. };
  30864. return QuarticEase;
  30865. }(EasingFunction));
  30866. BABYLON.QuarticEase = QuarticEase;
  30867. var QuinticEase = (function (_super) {
  30868. __extends(QuinticEase, _super);
  30869. function QuinticEase() {
  30870. return _super.apply(this, arguments) || this;
  30871. }
  30872. QuinticEase.prototype.easeInCore = function (gradient) {
  30873. return (gradient * gradient * gradient * gradient * gradient);
  30874. };
  30875. return QuinticEase;
  30876. }(EasingFunction));
  30877. BABYLON.QuinticEase = QuinticEase;
  30878. var SineEase = (function (_super) {
  30879. __extends(SineEase, _super);
  30880. function SineEase() {
  30881. return _super.apply(this, arguments) || this;
  30882. }
  30883. SineEase.prototype.easeInCore = function (gradient) {
  30884. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  30885. };
  30886. return SineEase;
  30887. }(EasingFunction));
  30888. BABYLON.SineEase = SineEase;
  30889. var BezierCurveEase = (function (_super) {
  30890. __extends(BezierCurveEase, _super);
  30891. function BezierCurveEase(x1, y1, x2, y2) {
  30892. if (x1 === void 0) { x1 = 0; }
  30893. if (y1 === void 0) { y1 = 0; }
  30894. if (x2 === void 0) { x2 = 1; }
  30895. if (y2 === void 0) { y2 = 1; }
  30896. var _this = _super.call(this) || this;
  30897. _this.x1 = x1;
  30898. _this.y1 = y1;
  30899. _this.x2 = x2;
  30900. _this.y2 = y2;
  30901. return _this;
  30902. }
  30903. BezierCurveEase.prototype.easeInCore = function (gradient) {
  30904. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  30905. };
  30906. return BezierCurveEase;
  30907. }(EasingFunction));
  30908. BABYLON.BezierCurveEase = BezierCurveEase;
  30909. })(BABYLON || (BABYLON = {}));
  30910. //# sourceMappingURL=babylon.easing.js.map
  30911. var BABYLON;
  30912. (function (BABYLON) {
  30913. var Bone = (function (_super) {
  30914. __extends(Bone, _super);
  30915. function Bone(name, skeleton, parentBone, matrix, restPose) {
  30916. var _this = _super.call(this, name, skeleton.getScene()) || this;
  30917. _this.name = name;
  30918. _this.children = new Array();
  30919. _this.animations = new Array();
  30920. _this._worldTransform = new BABYLON.Matrix();
  30921. _this._absoluteTransform = new BABYLON.Matrix();
  30922. _this._invertedAbsoluteTransform = new BABYLON.Matrix();
  30923. _this._scaleMatrix = BABYLON.Matrix.Identity();
  30924. _this._scaleVector = new BABYLON.Vector3(1, 1, 1);
  30925. _this._negateScaleChildren = new BABYLON.Vector3(1, 1, 1);
  30926. _this._scalingDeterminant = 1;
  30927. _this._syncScaleVector = function () {
  30928. var lm = this.getLocalMatrix();
  30929. var xsq = (lm.m[0] * lm.m[0] + lm.m[1] * lm.m[1] + lm.m[2] * lm.m[2]);
  30930. var ysq = (lm.m[4] * lm.m[4] + lm.m[5] * lm.m[5] + lm.m[6] * lm.m[6]);
  30931. var zsq = (lm.m[8] * lm.m[8] + lm.m[9] * lm.m[9] + lm.m[10] * lm.m[10]);
  30932. var xs = lm.m[0] * lm.m[1] * lm.m[2] * lm.m[3] < 0 ? -1 : 1;
  30933. var ys = lm.m[4] * lm.m[5] * lm.m[6] * lm.m[7] < 0 ? -1 : 1;
  30934. var zs = lm.m[8] * lm.m[9] * lm.m[10] * lm.m[11] < 0 ? -1 : 1;
  30935. this._scaleVector.x = xs * Math.sqrt(xsq);
  30936. this._scaleVector.y = ys * Math.sqrt(ysq);
  30937. this._scaleVector.z = zs * Math.sqrt(zsq);
  30938. if (this._parent) {
  30939. this._scaleVector.x /= this._parent._negateScaleChildren.x;
  30940. this._scaleVector.y /= this._parent._negateScaleChildren.y;
  30941. this._scaleVector.z /= this._parent._negateScaleChildren.z;
  30942. }
  30943. 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);
  30944. };
  30945. _this._skeleton = skeleton;
  30946. _this._matrix = matrix;
  30947. _this._baseMatrix = matrix;
  30948. _this._restPose = restPose ? restPose : matrix.clone();
  30949. skeleton.bones.push(_this);
  30950. if (parentBone) {
  30951. _this._parent = parentBone;
  30952. parentBone.children.push(_this);
  30953. }
  30954. else {
  30955. _this._parent = null;
  30956. }
  30957. _this._updateDifferenceMatrix();
  30958. if (_this.getAbsoluteTransform().determinant() < 0) {
  30959. _this._scalingDeterminant *= -1;
  30960. }
  30961. return _this;
  30962. }
  30963. // Members
  30964. Bone.prototype.getParent = function () {
  30965. return this._parent;
  30966. };
  30967. Bone.prototype.getLocalMatrix = function () {
  30968. return this._matrix;
  30969. };
  30970. Bone.prototype.getBaseMatrix = function () {
  30971. return this._baseMatrix;
  30972. };
  30973. Bone.prototype.getRestPose = function () {
  30974. return this._restPose;
  30975. };
  30976. Bone.prototype.returnToRest = function () {
  30977. this.updateMatrix(this._restPose.clone());
  30978. };
  30979. Bone.prototype.getWorldMatrix = function () {
  30980. return this._worldTransform;
  30981. };
  30982. Bone.prototype.getInvertedAbsoluteTransform = function () {
  30983. return this._invertedAbsoluteTransform;
  30984. };
  30985. Bone.prototype.getAbsoluteTransform = function () {
  30986. return this._absoluteTransform;
  30987. };
  30988. // Methods
  30989. Bone.prototype.updateMatrix = function (matrix, updateDifferenceMatrix) {
  30990. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  30991. this._baseMatrix = matrix.clone();
  30992. this._matrix = matrix.clone();
  30993. this._skeleton._markAsDirty();
  30994. if (updateDifferenceMatrix) {
  30995. this._updateDifferenceMatrix();
  30996. }
  30997. };
  30998. Bone.prototype._updateDifferenceMatrix = function (rootMatrix) {
  30999. if (!rootMatrix) {
  31000. rootMatrix = this._baseMatrix;
  31001. }
  31002. if (this._parent) {
  31003. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  31004. }
  31005. else {
  31006. this._absoluteTransform.copyFrom(rootMatrix);
  31007. }
  31008. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  31009. for (var index = 0; index < this.children.length; index++) {
  31010. this.children[index]._updateDifferenceMatrix();
  31011. }
  31012. };
  31013. Bone.prototype.markAsDirty = function () {
  31014. this._currentRenderId++;
  31015. this._skeleton._markAsDirty();
  31016. };
  31017. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) {
  31018. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  31019. if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; }
  31020. // all animation may be coming from a library skeleton, so may need to create animation
  31021. if (this.animations.length === 0) {
  31022. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  31023. this.animations[0].setKeys([]);
  31024. }
  31025. // get animation info / verify there is such a range from the source bone
  31026. var sourceRange = source.animations[0].getRange(rangeName);
  31027. if (!sourceRange) {
  31028. return false;
  31029. }
  31030. var from = sourceRange.from;
  31031. var to = sourceRange.to;
  31032. var sourceKeys = source.animations[0].getKeys();
  31033. // rescaling prep
  31034. var sourceBoneLength = source.length;
  31035. var sourceParent = source.getParent();
  31036. var parent = this.getParent();
  31037. var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  31038. var parentRatio = parentScalingReqd ? parent.length / sourceParent.length : null;
  31039. var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);
  31040. var destKeys = this.animations[0].getKeys();
  31041. // loop vars declaration
  31042. var orig;
  31043. var origTranslation;
  31044. var mat;
  31045. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  31046. orig = sourceKeys[key];
  31047. if (orig.frame >= from && orig.frame <= to) {
  31048. if (rescaleAsRequired) {
  31049. mat = orig.value.clone();
  31050. // scale based on parent ratio, when bone has parent
  31051. if (parentScalingReqd) {
  31052. origTranslation = mat.getTranslation();
  31053. mat.setTranslation(origTranslation.scaleInPlace(parentRatio));
  31054. }
  31055. else if (dimensionsScalingReqd) {
  31056. origTranslation = mat.getTranslation();
  31057. mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));
  31058. }
  31059. else {
  31060. mat = orig.value;
  31061. }
  31062. }
  31063. else {
  31064. mat = orig.value;
  31065. }
  31066. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  31067. }
  31068. }
  31069. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  31070. return true;
  31071. };
  31072. Bone.prototype.translate = function (vec, space, mesh) {
  31073. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  31074. var lm = this.getLocalMatrix();
  31075. if (space == BABYLON.Space.LOCAL) {
  31076. lm.m[12] += vec.x;
  31077. lm.m[13] += vec.y;
  31078. lm.m[14] += vec.z;
  31079. }
  31080. else {
  31081. this._skeleton.computeAbsoluteTransforms();
  31082. var tmat = BABYLON.Tmp.Matrix[0];
  31083. var tvec = BABYLON.Tmp.Vector3[0];
  31084. if (mesh) {
  31085. tmat.copyFrom(this._parent.getAbsoluteTransform());
  31086. tmat.multiplyToRef(mesh.getWorldMatrix(), tmat);
  31087. }
  31088. else {
  31089. tmat.copyFrom(this._parent.getAbsoluteTransform());
  31090. }
  31091. tmat.m[12] = 0;
  31092. tmat.m[13] = 0;
  31093. tmat.m[14] = 0;
  31094. tmat.invert();
  31095. BABYLON.Vector3.TransformCoordinatesToRef(vec, tmat, tvec);
  31096. lm.m[12] += tvec.x;
  31097. lm.m[13] += tvec.y;
  31098. lm.m[14] += tvec.z;
  31099. }
  31100. this.markAsDirty();
  31101. };
  31102. Bone.prototype.setPosition = function (position, space, mesh) {
  31103. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  31104. var lm = this.getLocalMatrix();
  31105. if (space == BABYLON.Space.LOCAL) {
  31106. lm.m[12] = position.x;
  31107. lm.m[13] = position.y;
  31108. lm.m[14] = position.z;
  31109. }
  31110. else {
  31111. this._skeleton.computeAbsoluteTransforms();
  31112. var tmat = BABYLON.Tmp.Matrix[0];
  31113. var vec = BABYLON.Tmp.Vector3[0];
  31114. if (mesh) {
  31115. tmat.copyFrom(this._parent.getAbsoluteTransform());
  31116. tmat.multiplyToRef(mesh.getWorldMatrix(), tmat);
  31117. }
  31118. else {
  31119. tmat.copyFrom(this._parent.getAbsoluteTransform());
  31120. }
  31121. tmat.invert();
  31122. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, vec);
  31123. lm.m[12] = vec.x;
  31124. lm.m[13] = vec.y;
  31125. lm.m[14] = vec.z;
  31126. }
  31127. this.markAsDirty();
  31128. };
  31129. Bone.prototype.setAbsolutePosition = function (position, mesh) {
  31130. this.setPosition(position, BABYLON.Space.WORLD, mesh);
  31131. };
  31132. Bone.prototype.setScale = function (x, y, z, scaleChildren) {
  31133. if (scaleChildren === void 0) { scaleChildren = false; }
  31134. if (this.animations[0] && !this.animations[0].isStopped()) {
  31135. if (!scaleChildren) {
  31136. this._negateScaleChildren.x = 1 / x;
  31137. this._negateScaleChildren.y = 1 / y;
  31138. this._negateScaleChildren.z = 1 / z;
  31139. }
  31140. this._syncScaleVector();
  31141. }
  31142. this.scale(x / this._scaleVector.x, y / this._scaleVector.y, z / this._scaleVector.z, scaleChildren);
  31143. };
  31144. Bone.prototype.scale = function (x, y, z, scaleChildren) {
  31145. if (scaleChildren === void 0) { scaleChildren = false; }
  31146. var locMat = this.getLocalMatrix();
  31147. var origLocMat = BABYLON.Tmp.Matrix[0];
  31148. origLocMat.copyFrom(locMat);
  31149. var origLocMatInv = BABYLON.Tmp.Matrix[1];
  31150. origLocMatInv.copyFrom(origLocMat);
  31151. origLocMatInv.invert();
  31152. var scaleMat = BABYLON.Tmp.Matrix[2];
  31153. BABYLON.Matrix.FromValuesToRef(x, 0, 0, 0, 0, y, 0, 0, 0, 0, z, 0, 0, 0, 0, 1, scaleMat);
  31154. this._scaleMatrix.multiplyToRef(scaleMat, this._scaleMatrix);
  31155. this._scaleVector.x *= x;
  31156. this._scaleVector.y *= y;
  31157. this._scaleVector.z *= z;
  31158. locMat.multiplyToRef(origLocMatInv, locMat);
  31159. locMat.multiplyToRef(scaleMat, locMat);
  31160. locMat.multiplyToRef(origLocMat, locMat);
  31161. var parent = this.getParent();
  31162. if (parent) {
  31163. locMat.multiplyToRef(parent.getAbsoluteTransform(), this.getAbsoluteTransform());
  31164. }
  31165. else {
  31166. this.getAbsoluteTransform().copyFrom(locMat);
  31167. }
  31168. var len = this.children.length;
  31169. scaleMat.invert();
  31170. for (var i = 0; i < len; i++) {
  31171. var child = this.children[i];
  31172. var cm = child.getLocalMatrix();
  31173. cm.multiplyToRef(scaleMat, cm);
  31174. var lm = child.getLocalMatrix();
  31175. lm.m[12] *= x;
  31176. lm.m[13] *= y;
  31177. lm.m[14] *= z;
  31178. }
  31179. this.computeAbsoluteTransforms();
  31180. if (scaleChildren) {
  31181. for (var i = 0; i < len; i++) {
  31182. this.children[i].scale(x, y, z, scaleChildren);
  31183. }
  31184. }
  31185. this.markAsDirty();
  31186. };
  31187. Bone.prototype.setYawPitchRoll = function (yaw, pitch, roll, space, mesh) {
  31188. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  31189. var rotMat = BABYLON.Tmp.Matrix[0];
  31190. BABYLON.Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, rotMat);
  31191. var rotMatInv = BABYLON.Tmp.Matrix[1];
  31192. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  31193. rotMatInv.multiplyToRef(rotMat, rotMat);
  31194. this._rotateWithMatrix(rotMat, space, mesh);
  31195. };
  31196. Bone.prototype.rotate = function (axis, amount, space, mesh) {
  31197. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  31198. var rmat = BABYLON.Tmp.Matrix[0];
  31199. rmat.m[12] = 0;
  31200. rmat.m[13] = 0;
  31201. rmat.m[14] = 0;
  31202. BABYLON.Matrix.RotationAxisToRef(axis, amount, rmat);
  31203. this._rotateWithMatrix(rmat, space, mesh);
  31204. };
  31205. Bone.prototype.setAxisAngle = function (axis, angle, space, mesh) {
  31206. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  31207. var rotMat = BABYLON.Tmp.Matrix[0];
  31208. BABYLON.Matrix.RotationAxisToRef(axis, angle, rotMat);
  31209. var rotMatInv = BABYLON.Tmp.Matrix[1];
  31210. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  31211. rotMatInv.multiplyToRef(rotMat, rotMat);
  31212. this._rotateWithMatrix(rotMat, space, mesh);
  31213. };
  31214. Bone.prototype.setRotation = function (rotation, space, mesh) {
  31215. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  31216. this.setYawPitchRoll(rotation.y, rotation.x, rotation.z, space, mesh);
  31217. };
  31218. Bone.prototype.setRotationQuaternion = function (quat, space, mesh) {
  31219. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  31220. var rotMatInv = BABYLON.Tmp.Matrix[0];
  31221. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  31222. var rotMat = BABYLON.Tmp.Matrix[1];
  31223. BABYLON.Matrix.FromQuaternionToRef(quat, rotMat);
  31224. rotMatInv.multiplyToRef(rotMat, rotMat);
  31225. this._rotateWithMatrix(rotMat, space, mesh);
  31226. };
  31227. Bone.prototype.setRotationMatrix = function (rotMat, space, mesh) {
  31228. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  31229. var rotMatInv = BABYLON.Tmp.Matrix[0];
  31230. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  31231. var rotMat2 = BABYLON.Tmp.Matrix[1];
  31232. rotMat2.copyFrom(rotMat);
  31233. rotMatInv.multiplyToRef(rotMat, rotMat2);
  31234. this._rotateWithMatrix(rotMat2, space, mesh);
  31235. };
  31236. Bone.prototype._rotateWithMatrix = function (rmat, space, mesh) {
  31237. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  31238. var lmat = this.getLocalMatrix();
  31239. var lx = lmat.m[12];
  31240. var ly = lmat.m[13];
  31241. var lz = lmat.m[14];
  31242. var parent = this.getParent();
  31243. var parentScale = BABYLON.Tmp.Matrix[3];
  31244. var parentScaleInv = BABYLON.Tmp.Matrix[4];
  31245. if (parent) {
  31246. if (space == BABYLON.Space.WORLD) {
  31247. if (mesh) {
  31248. parentScale.copyFrom(mesh.getWorldMatrix());
  31249. parent.getAbsoluteTransform().multiplyToRef(parentScale, parentScale);
  31250. }
  31251. else {
  31252. parentScale.copyFrom(parent.getAbsoluteTransform());
  31253. }
  31254. }
  31255. else {
  31256. parentScale = parent._scaleMatrix;
  31257. }
  31258. parentScaleInv.copyFrom(parentScale);
  31259. parentScaleInv.invert();
  31260. lmat.multiplyToRef(parentScale, lmat);
  31261. lmat.multiplyToRef(rmat, lmat);
  31262. lmat.multiplyToRef(parentScaleInv, lmat);
  31263. }
  31264. else {
  31265. if (space == BABYLON.Space.WORLD && mesh) {
  31266. parentScale.copyFrom(mesh.getWorldMatrix());
  31267. parentScaleInv.copyFrom(parentScale);
  31268. parentScaleInv.invert();
  31269. lmat.multiplyToRef(parentScale, lmat);
  31270. lmat.multiplyToRef(rmat, lmat);
  31271. lmat.multiplyToRef(parentScaleInv, lmat);
  31272. }
  31273. else {
  31274. lmat.multiplyToRef(rmat, lmat);
  31275. }
  31276. }
  31277. lmat.m[12] = lx;
  31278. lmat.m[13] = ly;
  31279. lmat.m[14] = lz;
  31280. this.computeAbsoluteTransforms();
  31281. this.markAsDirty();
  31282. };
  31283. Bone.prototype._getNegativeRotationToRef = function (rotMatInv, space, mesh) {
  31284. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  31285. if (space == BABYLON.Space.WORLD) {
  31286. var scaleMatrix = BABYLON.Tmp.Matrix[2];
  31287. scaleMatrix.copyFrom(this._scaleMatrix);
  31288. rotMatInv.copyFrom(this.getAbsoluteTransform());
  31289. if (mesh) {
  31290. rotMatInv.multiplyToRef(mesh.getWorldMatrix(), rotMatInv);
  31291. var meshScale = BABYLON.Tmp.Matrix[3];
  31292. BABYLON.Matrix.ScalingToRef(mesh.scaling.x, mesh.scaling.y, mesh.scaling.z, meshScale);
  31293. scaleMatrix.multiplyToRef(meshScale, scaleMatrix);
  31294. }
  31295. rotMatInv.invert();
  31296. scaleMatrix.m[0] *= this._scalingDeterminant;
  31297. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  31298. }
  31299. else {
  31300. rotMatInv.copyFrom(this.getLocalMatrix());
  31301. rotMatInv.invert();
  31302. var scaleMatrix = BABYLON.Tmp.Matrix[2];
  31303. scaleMatrix.copyFrom(this._scaleMatrix);
  31304. if (this._parent) {
  31305. var pscaleMatrix = BABYLON.Tmp.Matrix[3];
  31306. pscaleMatrix.copyFrom(this._parent._scaleMatrix);
  31307. pscaleMatrix.invert();
  31308. pscaleMatrix.multiplyToRef(rotMatInv, rotMatInv);
  31309. }
  31310. else {
  31311. scaleMatrix.m[0] *= this._scalingDeterminant;
  31312. }
  31313. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  31314. }
  31315. };
  31316. Bone.prototype.getScale = function () {
  31317. return this._scaleVector.clone();
  31318. };
  31319. Bone.prototype.getScaleToRef = function (result) {
  31320. result.copyFrom(this._scaleVector);
  31321. };
  31322. Bone.prototype.getPosition = function (space, mesh) {
  31323. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  31324. var pos = BABYLON.Vector3.Zero();
  31325. this.getPositionToRef(space, mesh, pos);
  31326. return pos;
  31327. };
  31328. Bone.prototype.getPositionToRef = function (space, mesh, result) {
  31329. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  31330. if (space == BABYLON.Space.LOCAL) {
  31331. var lm = this.getLocalMatrix();
  31332. result.x = lm.m[12];
  31333. result.y = lm.m[13];
  31334. result.z = lm.m[14];
  31335. }
  31336. else {
  31337. this._skeleton.computeAbsoluteTransforms();
  31338. var tmat = BABYLON.Tmp.Matrix[0];
  31339. if (mesh) {
  31340. tmat.copyFrom(this.getAbsoluteTransform());
  31341. tmat.multiplyToRef(mesh.getWorldMatrix(), tmat);
  31342. }
  31343. else {
  31344. tmat = this.getAbsoluteTransform();
  31345. }
  31346. result.x = tmat.m[12];
  31347. result.y = tmat.m[13];
  31348. result.z = tmat.m[14];
  31349. }
  31350. };
  31351. Bone.prototype.getAbsolutePosition = function (mesh) {
  31352. var pos = BABYLON.Vector3.Zero();
  31353. this.getPositionToRef(BABYLON.Space.WORLD, mesh, pos);
  31354. return pos;
  31355. };
  31356. Bone.prototype.getAbsolutePositionToRef = function (mesh, result) {
  31357. this.getPositionToRef(BABYLON.Space.WORLD, mesh, result);
  31358. };
  31359. Bone.prototype.computeAbsoluteTransforms = function () {
  31360. if (this._parent) {
  31361. this._matrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  31362. }
  31363. else {
  31364. this._absoluteTransform.copyFrom(this._matrix);
  31365. var poseMatrix = this._skeleton.getPoseMatrix();
  31366. if (poseMatrix) {
  31367. this._absoluteTransform.multiplyToRef(poseMatrix, this._absoluteTransform);
  31368. }
  31369. }
  31370. var children = this.children;
  31371. var len = children.length;
  31372. for (var i = 0; i < len; i++) {
  31373. children[i].computeAbsoluteTransforms();
  31374. }
  31375. };
  31376. Bone.prototype.getDirection = function (localAxis, mesh) {
  31377. var result = BABYLON.Vector3.Zero();
  31378. this.getDirectionToRef(localAxis, mesh, result);
  31379. return result;
  31380. };
  31381. Bone.prototype.getDirectionToRef = function (localAxis, mesh, result) {
  31382. this._skeleton.computeAbsoluteTransforms();
  31383. var mat = BABYLON.Tmp.Matrix[0];
  31384. mat.copyFrom(this.getAbsoluteTransform());
  31385. if (mesh) {
  31386. mat.multiplyToRef(mesh.getWorldMatrix(), mat);
  31387. }
  31388. BABYLON.Vector3.TransformNormalToRef(localAxis, mat, result);
  31389. result.normalize();
  31390. };
  31391. Bone.prototype.getRotation = function (space, mesh) {
  31392. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  31393. var result = BABYLON.Vector3.Zero();
  31394. this.getRotationToRef(space, mesh, result);
  31395. return result;
  31396. };
  31397. Bone.prototype.getRotationToRef = function (space, mesh, result) {
  31398. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  31399. var quat = BABYLON.Tmp.Quaternion[0];
  31400. this.getRotationQuaternionToRef(space, mesh, quat);
  31401. quat.toEulerAnglesToRef(result);
  31402. };
  31403. Bone.prototype.getRotationQuaternion = function (space, mesh) {
  31404. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  31405. var result = BABYLON.Quaternion.Identity();
  31406. this.getRotationQuaternionToRef(space, mesh, result);
  31407. return result;
  31408. };
  31409. Bone.prototype.getRotationQuaternionToRef = function (space, mesh, result) {
  31410. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  31411. if (space == BABYLON.Space.LOCAL) {
  31412. this.getLocalMatrix().decompose(BABYLON.Tmp.Vector3[0], result, BABYLON.Tmp.Vector3[1]);
  31413. }
  31414. else {
  31415. var mat = BABYLON.Tmp.Matrix[0];
  31416. var amat = this.getAbsoluteTransform();
  31417. if (mesh) {
  31418. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  31419. }
  31420. else {
  31421. mat.copyFrom(amat);
  31422. }
  31423. mat.m[0] *= this._scalingDeterminant;
  31424. mat.m[1] *= this._scalingDeterminant;
  31425. mat.m[2] *= this._scalingDeterminant;
  31426. mat.decompose(BABYLON.Tmp.Vector3[0], result, BABYLON.Tmp.Vector3[1]);
  31427. }
  31428. };
  31429. Bone.prototype.getRotationMatrix = function (space, mesh) {
  31430. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  31431. var result = BABYLON.Matrix.Identity();
  31432. this.getRotationMatrixToRef(space, mesh, result);
  31433. return result;
  31434. };
  31435. Bone.prototype.getRotationMatrixToRef = function (space, mesh, result) {
  31436. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  31437. if (space == BABYLON.Space.LOCAL) {
  31438. this.getLocalMatrix().getRotationMatrixToRef(result);
  31439. }
  31440. else {
  31441. var mat = BABYLON.Tmp.Matrix[0];
  31442. var amat = this.getAbsoluteTransform();
  31443. if (mesh) {
  31444. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  31445. }
  31446. else {
  31447. mat.copyFrom(amat);
  31448. }
  31449. mat.m[0] *= this._scalingDeterminant;
  31450. mat.m[1] *= this._scalingDeterminant;
  31451. mat.m[2] *= this._scalingDeterminant;
  31452. mat.getRotationMatrixToRef(result);
  31453. }
  31454. };
  31455. Bone.prototype.getAbsolutePositionFromLocal = function (position, mesh) {
  31456. var result = BABYLON.Vector3.Zero();
  31457. this.getAbsolutePositionFromLocalToRef(position, mesh, result);
  31458. return result;
  31459. };
  31460. Bone.prototype.getAbsolutePositionFromLocalToRef = function (position, mesh, result) {
  31461. this._skeleton.computeAbsoluteTransforms();
  31462. var tmat = BABYLON.Tmp.Matrix[0];
  31463. if (mesh) {
  31464. tmat.copyFrom(this.getAbsoluteTransform());
  31465. tmat.multiplyToRef(mesh.getWorldMatrix(), tmat);
  31466. }
  31467. else {
  31468. tmat = this.getAbsoluteTransform();
  31469. }
  31470. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  31471. };
  31472. Bone.prototype.getLocalPositionFromAbsolute = function (position, mesh) {
  31473. var result = BABYLON.Vector3.Zero();
  31474. this.getLocalPositionFromAbsoluteToRef(position, mesh, result);
  31475. return result;
  31476. };
  31477. Bone.prototype.getLocalPositionFromAbsoluteToRef = function (position, mesh, result) {
  31478. this._skeleton.computeAbsoluteTransforms();
  31479. var tmat = BABYLON.Tmp.Matrix[0];
  31480. tmat.copyFrom(this.getAbsoluteTransform());
  31481. if (mesh) {
  31482. tmat.multiplyToRef(mesh.getWorldMatrix(), tmat);
  31483. }
  31484. tmat.invert();
  31485. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  31486. };
  31487. return Bone;
  31488. }(BABYLON.Node));
  31489. BABYLON.Bone = Bone;
  31490. })(BABYLON || (BABYLON = {}));
  31491. //# sourceMappingURL=babylon.bone.js.map
  31492. var BABYLON;
  31493. (function (BABYLON) {
  31494. var BoneIKController = (function () {
  31495. function BoneIKController(mesh, bone, options) {
  31496. this.targetPosition = BABYLON.Vector3.Zero();
  31497. this.poleTargetPosition = BABYLON.Vector3.Zero();
  31498. this.poleTargetLocalOffset = BABYLON.Vector3.Zero();
  31499. this.poleAngle = 0;
  31500. this.slerpAmount = 1;
  31501. this._bone1Quat = BABYLON.Quaternion.Identity();
  31502. this._bone1Mat = BABYLON.Matrix.Identity();
  31503. this._bone2Ang = Math.PI;
  31504. this._maxAngle = Math.PI;
  31505. this._tmpVec1 = BABYLON.Vector3.Zero();
  31506. this._tmpVec2 = BABYLON.Vector3.Zero();
  31507. this._tmpVec3 = BABYLON.Vector3.Zero();
  31508. this._tmpVec4 = BABYLON.Vector3.Zero();
  31509. this._tmpVec5 = BABYLON.Vector3.Zero();
  31510. this._tmpMat1 = BABYLON.Matrix.Identity();
  31511. this._tmpMat2 = BABYLON.Matrix.Identity();
  31512. this._tmpQuat1 = BABYLON.Quaternion.Identity();
  31513. this._rightHandedSystem = false;
  31514. this._bendAxis = BABYLON.Vector3.Right();
  31515. this._slerping = false;
  31516. this._bone2 = bone;
  31517. this._bone1 = bone.getParent();
  31518. this.mesh = mesh;
  31519. if (bone.getAbsoluteTransform().determinant() > 0) {
  31520. this._rightHandedSystem = true;
  31521. this._bendAxis.x = 0;
  31522. this._bendAxis.y = 0;
  31523. this._bendAxis.z = 1;
  31524. }
  31525. if (this._bone1.length) {
  31526. var boneScale1 = this._bone1.getScale();
  31527. var boneScale2 = this._bone2.getScale();
  31528. this._bone1Length = this._bone1.length * boneScale1.y * this.mesh.scaling.y;
  31529. this._bone2Length = this._bone2.length * boneScale2.y * this.mesh.scaling.y;
  31530. }
  31531. else if (this._bone1.children[0]) {
  31532. mesh.computeWorldMatrix(true);
  31533. var pos1 = this._bone2.children[0].getAbsolutePosition(mesh);
  31534. var pos2 = this._bone2.getAbsolutePosition(mesh);
  31535. var pos3 = this._bone1.getAbsolutePosition(mesh);
  31536. this._bone1Length = BABYLON.Vector3.Distance(pos1, pos2);
  31537. this._bone2Length = BABYLON.Vector3.Distance(pos2, pos3);
  31538. }
  31539. this._bone1.getRotationMatrixToRef(BABYLON.Space.WORLD, mesh, this._bone1Mat);
  31540. this.maxAngle = Math.PI;
  31541. if (options) {
  31542. if (options.targetMesh) {
  31543. this.targetMesh = options.targetMesh;
  31544. this.targetMesh.computeWorldMatrix(true);
  31545. }
  31546. if (options.poleTargetMesh) {
  31547. this.poleTargetMesh = options.poleTargetMesh;
  31548. this.poleTargetMesh.computeWorldMatrix(true);
  31549. }
  31550. else if (options.poleTargetBone) {
  31551. this.poleTargetBone = options.poleTargetBone;
  31552. }
  31553. else if (this._bone1.getParent()) {
  31554. this.poleTargetBone = this._bone1.getParent();
  31555. }
  31556. if (options.poleTargetLocalOffset) {
  31557. this.poleTargetLocalOffset.copyFrom(options.poleTargetLocalOffset);
  31558. }
  31559. if (options.poleAngle) {
  31560. this.poleAngle = options.poleAngle;
  31561. }
  31562. if (options.bendAxis) {
  31563. this._bendAxis.copyFrom(options.bendAxis);
  31564. }
  31565. if (options.maxAngle) {
  31566. this.maxAngle = options.maxAngle;
  31567. }
  31568. if (options.slerpAmount) {
  31569. this.slerpAmount = options.slerpAmount;
  31570. }
  31571. }
  31572. }
  31573. Object.defineProperty(BoneIKController.prototype, "maxAngle", {
  31574. get: function () {
  31575. return this._maxAngle;
  31576. },
  31577. set: function (value) {
  31578. this._setMaxAngle(value);
  31579. },
  31580. enumerable: true,
  31581. configurable: true
  31582. });
  31583. BoneIKController.prototype._setMaxAngle = function (ang) {
  31584. if (ang < 0) {
  31585. ang = 0;
  31586. }
  31587. if (ang > Math.PI || ang == undefined) {
  31588. ang = Math.PI;
  31589. }
  31590. this._maxAngle = ang;
  31591. var a = this._bone1Length;
  31592. var b = this._bone2Length;
  31593. this._maxReach = Math.sqrt(a * a + b * b - 2 * a * b * Math.cos(ang));
  31594. };
  31595. BoneIKController.prototype.update = function () {
  31596. var bone1 = this._bone1;
  31597. var target = this.targetPosition;
  31598. var poleTarget = this.poleTargetPosition;
  31599. var mat1 = this._tmpMat1;
  31600. var mat2 = this._tmpMat2;
  31601. if (this.targetMesh) {
  31602. target.copyFrom(this.targetMesh.getAbsolutePosition());
  31603. }
  31604. if (this.poleTargetBone) {
  31605. this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset, this.mesh, poleTarget);
  31606. }
  31607. else if (this.poleTargetMesh) {
  31608. BABYLON.Vector3.TransformCoordinatesToRef(this.poleTargetLocalOffset, this.poleTargetMesh.getWorldMatrix(), poleTarget);
  31609. }
  31610. var bonePos = this._tmpVec1;
  31611. var zaxis = this._tmpVec2;
  31612. var xaxis = this._tmpVec3;
  31613. var yaxis = this._tmpVec4;
  31614. var upAxis = this._tmpVec5;
  31615. bone1.getAbsolutePositionToRef(this.mesh, bonePos);
  31616. poleTarget.subtractToRef(bonePos, upAxis);
  31617. if (upAxis.x == 0 && upAxis.y == 0 && upAxis.z == 0) {
  31618. upAxis.y = 1;
  31619. }
  31620. else {
  31621. upAxis.normalize();
  31622. }
  31623. target.subtractToRef(bonePos, yaxis);
  31624. yaxis.normalize();
  31625. BABYLON.Vector3.CrossToRef(yaxis, upAxis, zaxis);
  31626. zaxis.normalize();
  31627. BABYLON.Vector3.CrossToRef(yaxis, zaxis, xaxis);
  31628. xaxis.normalize();
  31629. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1);
  31630. var a = this._bone1Length;
  31631. var b = this._bone2Length;
  31632. var c = BABYLON.Vector3.Distance(bonePos, target);
  31633. if (this._maxReach > 0) {
  31634. c = Math.min(this._maxReach, c);
  31635. }
  31636. var acosa = (b * b + c * c - a * a) / (2 * b * c);
  31637. var acosb = (c * c + a * a - b * b) / (2 * c * a);
  31638. if (acosa > 1) {
  31639. acosa = 1;
  31640. }
  31641. if (acosb > 1) {
  31642. acosb = 1;
  31643. }
  31644. if (acosa < -1) {
  31645. acosa = -1;
  31646. }
  31647. if (acosb < -1) {
  31648. acosb = -1;
  31649. }
  31650. var angA = Math.acos(acosa);
  31651. var angB = Math.acos(acosb);
  31652. var angC = -angA - angB;
  31653. if (this._rightHandedSystem) {
  31654. BABYLON.Matrix.RotationYawPitchRollToRef(0, 0, Math.PI * .5, mat2);
  31655. mat2.multiplyToRef(mat1, mat1);
  31656. BABYLON.Matrix.RotationAxisToRef(this._bendAxis, angB, mat2);
  31657. mat2.multiplyToRef(mat1, mat1);
  31658. }
  31659. else {
  31660. this._tmpVec1.copyFrom(this._bendAxis);
  31661. this._tmpVec1.x *= -1;
  31662. BABYLON.Matrix.RotationAxisToRef(this._tmpVec1, -angB, mat2);
  31663. mat2.multiplyToRef(mat1, mat1);
  31664. }
  31665. if (this.poleAngle) {
  31666. BABYLON.Matrix.RotationAxisToRef(yaxis, this.poleAngle, mat2);
  31667. mat1.multiplyToRef(mat2, mat1);
  31668. }
  31669. if (this.slerpAmount < 1) {
  31670. if (!this._slerping) {
  31671. BABYLON.Quaternion.FromRotationMatrixToRef(this._bone1Mat, this._bone1Quat);
  31672. }
  31673. BABYLON.Quaternion.FromRotationMatrixToRef(mat1, this._tmpQuat1);
  31674. BABYLON.Quaternion.SlerpToRef(this._bone1Quat, this._tmpQuat1, this.slerpAmount, this._bone1Quat);
  31675. angC = this._bone2Ang * (1.0 - this.slerpAmount) + angC * this.slerpAmount;
  31676. this._bone1.setRotationQuaternion(this._bone1Quat, BABYLON.Space.WORLD, this.mesh);
  31677. this._slerping = true;
  31678. }
  31679. else {
  31680. this._bone1.setRotationMatrix(mat1, BABYLON.Space.WORLD, this.mesh);
  31681. this._bone1Mat.copyFrom(mat1);
  31682. this._slerping = false;
  31683. }
  31684. this._bone2.setAxisAngle(this._bendAxis, angC, BABYLON.Space.LOCAL);
  31685. this._bone2Ang = angC;
  31686. };
  31687. return BoneIKController;
  31688. }());
  31689. BABYLON.BoneIKController = BoneIKController;
  31690. })(BABYLON || (BABYLON = {}));
  31691. //# sourceMappingURL=babylon.boneIKController.js.map
  31692. var BABYLON;
  31693. (function (BABYLON) {
  31694. var BoneLookController = (function () {
  31695. function BoneLookController(mesh, bone, target, options) {
  31696. this.upAxis = BABYLON.Vector3.Up();
  31697. this.adjustYaw = 0;
  31698. this.adjustPitch = 0;
  31699. this.adjustRoll = 0;
  31700. this._tmpVec1 = BABYLON.Vector3.Zero();
  31701. this._tmpVec2 = BABYLON.Vector3.Zero();
  31702. this._tmpVec3 = BABYLON.Vector3.Zero();
  31703. this._tmpVec4 = BABYLON.Vector3.Zero();
  31704. this._tmpMat1 = BABYLON.Matrix.Identity();
  31705. this._tmpMat2 = BABYLON.Matrix.Identity();
  31706. this.mesh = mesh;
  31707. this.bone = bone;
  31708. this.target = target;
  31709. if (options) {
  31710. if (options.adjustYaw) {
  31711. this.adjustYaw = options.adjustYaw;
  31712. }
  31713. if (options.adjustPitch) {
  31714. this.adjustPitch = options.adjustPitch;
  31715. }
  31716. if (options.adjustRoll) {
  31717. this.adjustRoll = options.adjustRoll;
  31718. }
  31719. }
  31720. }
  31721. BoneLookController.prototype.update = function () {
  31722. var bone = this.bone;
  31723. var target = this.target;
  31724. var bonePos = this._tmpVec1;
  31725. var zaxis = this._tmpVec2;
  31726. var xaxis = this._tmpVec3;
  31727. var yaxis = this._tmpVec4;
  31728. var mat1 = this._tmpMat1;
  31729. var mat2 = this._tmpMat2;
  31730. bone.getAbsolutePositionToRef(this.mesh, bonePos);
  31731. target.subtractToRef(bonePos, zaxis);
  31732. zaxis.normalize();
  31733. BABYLON.Vector3.CrossToRef(this.upAxis, zaxis, xaxis);
  31734. xaxis.normalize();
  31735. BABYLON.Vector3.CrossToRef(zaxis, xaxis, yaxis);
  31736. yaxis.normalize();
  31737. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1);
  31738. if (this.adjustYaw || this.adjustPitch || this.adjustRoll) {
  31739. BABYLON.Matrix.RotationYawPitchRollToRef(this.adjustYaw, this.adjustPitch, this.adjustRoll, mat2);
  31740. mat2.multiplyToRef(mat1, mat1);
  31741. }
  31742. this.bone.setRotationMatrix(mat1, BABYLON.Space.WORLD, this.mesh);
  31743. };
  31744. return BoneLookController;
  31745. }());
  31746. BABYLON.BoneLookController = BoneLookController;
  31747. })(BABYLON || (BABYLON = {}));
  31748. //# sourceMappingURL=babylon.boneLookController.js.map
  31749. var BABYLON;
  31750. (function (BABYLON) {
  31751. var Skeleton = (function () {
  31752. function Skeleton(name, id, scene) {
  31753. this.name = name;
  31754. this.id = id;
  31755. this.bones = new Array();
  31756. this.needInitialSkinMatrix = false;
  31757. this._isDirty = true;
  31758. this._meshesWithPoseMatrix = new Array();
  31759. this._identity = BABYLON.Matrix.Identity();
  31760. this._ranges = {};
  31761. this._lastAbsoluteTransformsUpdateId = -1;
  31762. this.bones = [];
  31763. this._scene = scene;
  31764. scene.skeletons.push(this);
  31765. //make sure it will recalculate the matrix next time prepare is called.
  31766. this._isDirty = true;
  31767. }
  31768. // Members
  31769. Skeleton.prototype.getTransformMatrices = function (mesh) {
  31770. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  31771. return mesh._bonesTransformMatrices;
  31772. }
  31773. if (!this._transformMatrices) {
  31774. this.prepare();
  31775. }
  31776. return this._transformMatrices;
  31777. };
  31778. Skeleton.prototype.getScene = function () {
  31779. return this._scene;
  31780. };
  31781. // Methods
  31782. /**
  31783. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  31784. */
  31785. Skeleton.prototype.toString = function (fullDetails) {
  31786. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  31787. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  31788. if (fullDetails) {
  31789. ret += ", Ranges: {";
  31790. var first = true;
  31791. for (var name_1 in this._ranges) {
  31792. if (first) {
  31793. ret += ", ";
  31794. first = false;
  31795. }
  31796. ret += name_1;
  31797. }
  31798. ret += "}";
  31799. }
  31800. return ret;
  31801. };
  31802. /**
  31803. * Get bone's index searching by name
  31804. * @param {string} name is bone's name to search for
  31805. * @return {number} Indice of the bone. Returns -1 if not found
  31806. */
  31807. Skeleton.prototype.getBoneIndexByName = function (name) {
  31808. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  31809. if (this.bones[boneIndex].name === name) {
  31810. return boneIndex;
  31811. }
  31812. }
  31813. return -1;
  31814. };
  31815. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  31816. // check name not already in use
  31817. if (!this._ranges[name]) {
  31818. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  31819. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  31820. if (this.bones[i].animations[0]) {
  31821. this.bones[i].animations[0].createRange(name, from, to);
  31822. }
  31823. }
  31824. }
  31825. };
  31826. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  31827. if (deleteFrames === void 0) { deleteFrames = true; }
  31828. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  31829. if (this.bones[i].animations[0]) {
  31830. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  31831. }
  31832. }
  31833. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  31834. };
  31835. Skeleton.prototype.getAnimationRange = function (name) {
  31836. return this._ranges[name];
  31837. };
  31838. /**
  31839. * Returns as an Array, all AnimationRanges defined on this skeleton
  31840. */
  31841. Skeleton.prototype.getAnimationRanges = function () {
  31842. var animationRanges = [];
  31843. var name;
  31844. var i = 0;
  31845. for (name in this._ranges) {
  31846. animationRanges[i] = this._ranges[name];
  31847. i++;
  31848. }
  31849. return animationRanges;
  31850. };
  31851. /**
  31852. * note: This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  31853. */
  31854. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  31855. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  31856. if (this._ranges[name] || !source.getAnimationRange(name)) {
  31857. return false;
  31858. }
  31859. var ret = true;
  31860. var frameOffset = this._getHighestAnimationFrame() + 1;
  31861. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  31862. var boneDict = {};
  31863. var sourceBones = source.bones;
  31864. var nBones;
  31865. var i;
  31866. for (i = 0, nBones = sourceBones.length; i < nBones; i++) {
  31867. boneDict[sourceBones[i].name] = sourceBones[i];
  31868. }
  31869. if (this.bones.length !== sourceBones.length) {
  31870. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  31871. ret = false;
  31872. }
  31873. var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;
  31874. for (i = 0, nBones = this.bones.length; i < nBones; i++) {
  31875. var boneName = this.bones[i].name;
  31876. var sourceBone = boneDict[boneName];
  31877. if (sourceBone) {
  31878. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio);
  31879. }
  31880. else {
  31881. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  31882. ret = false;
  31883. }
  31884. }
  31885. // do not call createAnimationRange(), since it also is done to bones, which was already done
  31886. var range = source.getAnimationRange(name);
  31887. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  31888. return ret;
  31889. };
  31890. Skeleton.prototype.returnToRest = function () {
  31891. for (var index = 0; index < this.bones.length; index++) {
  31892. this.bones[index].returnToRest();
  31893. }
  31894. };
  31895. Skeleton.prototype._getHighestAnimationFrame = function () {
  31896. var ret = 0;
  31897. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  31898. if (this.bones[i].animations[0]) {
  31899. var highest = this.bones[i].animations[0].getHighestFrame();
  31900. if (ret < highest) {
  31901. ret = highest;
  31902. }
  31903. }
  31904. }
  31905. return ret;
  31906. };
  31907. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  31908. var range = this.getAnimationRange(name);
  31909. if (!range) {
  31910. return null;
  31911. }
  31912. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  31913. };
  31914. Skeleton.prototype._markAsDirty = function () {
  31915. this._isDirty = true;
  31916. };
  31917. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  31918. this._meshesWithPoseMatrix.push(mesh);
  31919. };
  31920. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  31921. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  31922. if (index > -1) {
  31923. this._meshesWithPoseMatrix.splice(index, 1);
  31924. }
  31925. };
  31926. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  31927. for (var index = 0; index < this.bones.length; index++) {
  31928. var bone = this.bones[index];
  31929. var parentBone = bone.getParent();
  31930. if (parentBone) {
  31931. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  31932. }
  31933. else {
  31934. if (initialSkinMatrix) {
  31935. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  31936. }
  31937. else {
  31938. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  31939. }
  31940. }
  31941. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, index * 16);
  31942. }
  31943. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  31944. };
  31945. Skeleton.prototype.prepare = function () {
  31946. if (!this._isDirty) {
  31947. return;
  31948. }
  31949. if (this.needInitialSkinMatrix) {
  31950. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  31951. var mesh = this._meshesWithPoseMatrix[index];
  31952. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  31953. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  31954. }
  31955. var poseMatrix = mesh.getPoseMatrix();
  31956. // Prepare bones
  31957. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  31958. var bone = this.bones[boneIndex];
  31959. if (!bone.getParent()) {
  31960. var matrix = bone.getBaseMatrix();
  31961. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[0]);
  31962. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[0]);
  31963. }
  31964. }
  31965. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  31966. }
  31967. }
  31968. else {
  31969. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  31970. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  31971. }
  31972. this._computeTransformMatrices(this._transformMatrices, null);
  31973. }
  31974. this._isDirty = false;
  31975. this._scene._activeBones.addCount(this.bones.length, false);
  31976. };
  31977. Skeleton.prototype.getAnimatables = function () {
  31978. if (!this._animatables || this._animatables.length !== this.bones.length) {
  31979. this._animatables = [];
  31980. for (var index = 0; index < this.bones.length; index++) {
  31981. this._animatables.push(this.bones[index]);
  31982. }
  31983. }
  31984. return this._animatables;
  31985. };
  31986. Skeleton.prototype.clone = function (name, id) {
  31987. var result = new Skeleton(name, id || name, this._scene);
  31988. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  31989. for (var index = 0; index < this.bones.length; index++) {
  31990. var source = this.bones[index];
  31991. var parentBone = null;
  31992. if (source.getParent()) {
  31993. var parentIndex = this.bones.indexOf(source.getParent());
  31994. parentBone = result.bones[parentIndex];
  31995. }
  31996. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  31997. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  31998. }
  31999. if (this._ranges) {
  32000. result._ranges = {};
  32001. for (var rangeName in this._ranges) {
  32002. result._ranges[rangeName] = this._ranges[rangeName].clone();
  32003. }
  32004. }
  32005. this._isDirty = true;
  32006. return result;
  32007. };
  32008. Skeleton.prototype.enableBlending = function (blendingSpeed) {
  32009. if (blendingSpeed === void 0) { blendingSpeed = 0.01; }
  32010. this.bones.forEach(function (bone) {
  32011. bone.animations.forEach(function (animation) {
  32012. animation.enableBlending = true;
  32013. animation.blendingSpeed = blendingSpeed;
  32014. });
  32015. });
  32016. };
  32017. Skeleton.prototype.dispose = function () {
  32018. this._meshesWithPoseMatrix = [];
  32019. // Animations
  32020. this.getScene().stopAnimation(this);
  32021. // Remove from scene
  32022. this.getScene().removeSkeleton(this);
  32023. };
  32024. Skeleton.prototype.serialize = function () {
  32025. var serializationObject = {};
  32026. serializationObject.name = this.name;
  32027. serializationObject.id = this.id;
  32028. serializationObject.dimensionsAtRest = this.dimensionsAtRest;
  32029. serializationObject.bones = [];
  32030. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  32031. for (var index = 0; index < this.bones.length; index++) {
  32032. var bone = this.bones[index];
  32033. var serializedBone = {
  32034. parentBoneIndex: bone.getParent() ? this.bones.indexOf(bone.getParent()) : -1,
  32035. name: bone.name,
  32036. matrix: bone.getLocalMatrix().toArray(),
  32037. rest: bone.getRestPose().toArray()
  32038. };
  32039. serializationObject.bones.push(serializedBone);
  32040. if (bone.length) {
  32041. serializedBone.length = bone.length;
  32042. }
  32043. if (bone.animations && bone.animations.length > 0) {
  32044. serializedBone.animation = bone.animations[0].serialize();
  32045. }
  32046. serializationObject.ranges = [];
  32047. for (var name in this._ranges) {
  32048. var range = {};
  32049. range.name = name;
  32050. range.from = this._ranges[name].from;
  32051. range.to = this._ranges[name].to;
  32052. serializationObject.ranges.push(range);
  32053. }
  32054. }
  32055. return serializationObject;
  32056. };
  32057. Skeleton.Parse = function (parsedSkeleton, scene) {
  32058. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  32059. if (parsedSkeleton.dimensionsAtRest) {
  32060. skeleton.dimensionsAtRest = BABYLON.Vector3.FromArray(parsedSkeleton.dimensionsAtRest);
  32061. }
  32062. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  32063. var index;
  32064. for (index = 0; index < parsedSkeleton.bones.length; index++) {
  32065. var parsedBone = parsedSkeleton.bones[index];
  32066. var parentBone = null;
  32067. if (parsedBone.parentBoneIndex > -1) {
  32068. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  32069. }
  32070. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  32071. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  32072. if (parsedBone.length) {
  32073. bone.length = parsedBone.length;
  32074. }
  32075. if (parsedBone.animation) {
  32076. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  32077. }
  32078. }
  32079. // placed after bones, so createAnimationRange can cascade down
  32080. if (parsedSkeleton.ranges) {
  32081. for (index = 0; index < parsedSkeleton.ranges.length; index++) {
  32082. var data = parsedSkeleton.ranges[index];
  32083. skeleton.createAnimationRange(data.name, data.from, data.to);
  32084. }
  32085. }
  32086. return skeleton;
  32087. };
  32088. Skeleton.prototype.computeAbsoluteTransforms = function (forceUpdate) {
  32089. if (forceUpdate === void 0) { forceUpdate = false; }
  32090. var renderId = this._scene.getRenderId();
  32091. if (this._lastAbsoluteTransformsUpdateId != renderId || forceUpdate) {
  32092. this.bones[0].computeAbsoluteTransforms();
  32093. this._lastAbsoluteTransformsUpdateId = renderId;
  32094. }
  32095. };
  32096. Skeleton.prototype.getPoseMatrix = function () {
  32097. var poseMatrix;
  32098. if (this._meshesWithPoseMatrix.length > 0) {
  32099. poseMatrix = this._meshesWithPoseMatrix[0].getPoseMatrix();
  32100. }
  32101. return poseMatrix;
  32102. };
  32103. return Skeleton;
  32104. }());
  32105. BABYLON.Skeleton = Skeleton;
  32106. })(BABYLON || (BABYLON = {}));
  32107. //# sourceMappingURL=babylon.skeleton.js.map
  32108. var BABYLON;
  32109. (function (BABYLON) {
  32110. var PostProcess = (function () {
  32111. function PostProcess(name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType) {
  32112. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  32113. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  32114. this.name = name;
  32115. this.width = -1;
  32116. this.height = -1;
  32117. /*
  32118. Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  32119. Can only be used on a single postprocess or on the last one of a chain.
  32120. */
  32121. this.enablePixelPerfectMode = false;
  32122. this._reusable = false;
  32123. this._textures = new BABYLON.SmartArray(2);
  32124. this._currentRenderTextureInd = 0;
  32125. this._scaleRatio = new BABYLON.Vector2(1, 1);
  32126. // Events
  32127. /**
  32128. * An event triggered when the postprocess is activated.
  32129. * @type {BABYLON.Observable}
  32130. */
  32131. this.onActivateObservable = new BABYLON.Observable();
  32132. /**
  32133. * An event triggered when the postprocess changes its size.
  32134. * @type {BABYLON.Observable}
  32135. */
  32136. this.onSizeChangedObservable = new BABYLON.Observable();
  32137. /**
  32138. * An event triggered when the postprocess applies its effect.
  32139. * @type {BABYLON.Observable}
  32140. */
  32141. this.onApplyObservable = new BABYLON.Observable();
  32142. /**
  32143. * An event triggered before rendering the postprocess
  32144. * @type {BABYLON.Observable}
  32145. */
  32146. this.onBeforeRenderObservable = new BABYLON.Observable();
  32147. /**
  32148. * An event triggered after rendering the postprocess
  32149. * @type {BABYLON.Observable}
  32150. */
  32151. this.onAfterRenderObservable = new BABYLON.Observable();
  32152. if (camera != null) {
  32153. this._camera = camera;
  32154. this._scene = camera.getScene();
  32155. camera.attachPostProcess(this);
  32156. this._engine = this._scene.getEngine();
  32157. }
  32158. else {
  32159. this._engine = engine;
  32160. }
  32161. this._options = options;
  32162. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  32163. this._reusable = reusable || false;
  32164. this._textureType = textureType;
  32165. this._samplers = samplers || [];
  32166. this._samplers.push("textureSampler");
  32167. this._fragmentUrl = fragmentUrl;
  32168. this._parameters = parameters || [];
  32169. this._parameters.push("scale");
  32170. this.updateEffect(defines);
  32171. }
  32172. Object.defineProperty(PostProcess.prototype, "onActivate", {
  32173. set: function (callback) {
  32174. if (this._onActivateObserver) {
  32175. this.onActivateObservable.remove(this._onActivateObserver);
  32176. }
  32177. this._onActivateObserver = this.onActivateObservable.add(callback);
  32178. },
  32179. enumerable: true,
  32180. configurable: true
  32181. });
  32182. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  32183. set: function (callback) {
  32184. if (this._onSizeChangedObserver) {
  32185. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  32186. }
  32187. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  32188. },
  32189. enumerable: true,
  32190. configurable: true
  32191. });
  32192. Object.defineProperty(PostProcess.prototype, "onApply", {
  32193. set: function (callback) {
  32194. if (this._onApplyObserver) {
  32195. this.onApplyObservable.remove(this._onApplyObserver);
  32196. }
  32197. this._onApplyObserver = this.onApplyObservable.add(callback);
  32198. },
  32199. enumerable: true,
  32200. configurable: true
  32201. });
  32202. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  32203. set: function (callback) {
  32204. if (this._onBeforeRenderObserver) {
  32205. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  32206. }
  32207. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  32208. },
  32209. enumerable: true,
  32210. configurable: true
  32211. });
  32212. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  32213. set: function (callback) {
  32214. if (this._onAfterRenderObserver) {
  32215. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  32216. }
  32217. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  32218. },
  32219. enumerable: true,
  32220. configurable: true
  32221. });
  32222. PostProcess.prototype.updateEffect = function (defines) {
  32223. this._effect = this._engine.createEffect({ vertex: "postprocess", fragment: this._fragmentUrl }, ["position"], this._parameters, this._samplers, defines !== undefined ? defines : "");
  32224. };
  32225. PostProcess.prototype.isReusable = function () {
  32226. return this._reusable;
  32227. };
  32228. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  32229. PostProcess.prototype.markTextureDirty = function () {
  32230. this.width = -1;
  32231. };
  32232. PostProcess.prototype.activate = function (camera, sourceTexture) {
  32233. camera = camera || this._camera;
  32234. var scene = camera.getScene();
  32235. var maxSize = camera.getEngine().getCaps().maxTextureSize;
  32236. var requiredWidth = ((sourceTexture ? sourceTexture._width : this._engine.getRenderingCanvas().width) * this._options) | 0;
  32237. var requiredHeight = ((sourceTexture ? sourceTexture._height : this._engine.getRenderingCanvas().height) * this._options) | 0;
  32238. var desiredWidth = this._options.width || requiredWidth;
  32239. var desiredHeight = this._options.height || requiredHeight;
  32240. if (this.renderTargetSamplingMode !== BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  32241. if (!this._options.width) {
  32242. desiredWidth = BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize);
  32243. }
  32244. if (!this._options.height) {
  32245. desiredHeight = BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize);
  32246. }
  32247. }
  32248. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  32249. if (this._textures.length > 0) {
  32250. for (var i = 0; i < this._textures.length; i++) {
  32251. this._engine._releaseTexture(this._textures.data[i]);
  32252. }
  32253. this._textures.reset();
  32254. }
  32255. this.width = desiredWidth;
  32256. this.height = desiredHeight;
  32257. var textureSize = { width: this.width, height: this.height };
  32258. var textureOptions = {
  32259. generateMipMaps: false,
  32260. generateDepthBuffer: camera._postProcesses.indexOf(this) === 0,
  32261. generateStencilBuffer: camera._postProcesses.indexOf(this) === 0 && this._engine.isStencilEnable,
  32262. samplingMode: this.renderTargetSamplingMode,
  32263. type: this._textureType
  32264. };
  32265. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  32266. if (this._reusable) {
  32267. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  32268. }
  32269. this.onSizeChangedObservable.notifyObservers(this);
  32270. }
  32271. if (this.enablePixelPerfectMode) {
  32272. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  32273. this._engine.bindFramebuffer(this._textures.data[this._currentRenderTextureInd], 0, requiredWidth, requiredHeight);
  32274. }
  32275. else {
  32276. this._scaleRatio.copyFromFloats(1, 1);
  32277. this._engine.bindFramebuffer(this._textures.data[this._currentRenderTextureInd]);
  32278. }
  32279. this.onActivateObservable.notifyObservers(camera);
  32280. // Clear
  32281. if (this.clearColor) {
  32282. this._engine.clear(this.clearColor, true, true, true);
  32283. }
  32284. else {
  32285. this._engine.clear(scene.clearColor, scene.autoClear || scene.forceWireframe, true, true);
  32286. }
  32287. if (this._reusable) {
  32288. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  32289. }
  32290. };
  32291. Object.defineProperty(PostProcess.prototype, "isSupported", {
  32292. get: function () {
  32293. return this._effect.isSupported;
  32294. },
  32295. enumerable: true,
  32296. configurable: true
  32297. });
  32298. PostProcess.prototype.apply = function () {
  32299. // Check
  32300. if (!this._effect.isReady())
  32301. return null;
  32302. // States
  32303. this._engine.enableEffect(this._effect);
  32304. this._engine.setState(false);
  32305. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  32306. this._engine.setDepthBuffer(false);
  32307. this._engine.setDepthWrite(false);
  32308. // Texture
  32309. this._effect._bindTexture("textureSampler", this._textures.data[this._currentRenderTextureInd]);
  32310. // Parameters
  32311. this._effect.setVector2("scale", this._scaleRatio);
  32312. this.onApplyObservable.notifyObservers(this._effect);
  32313. return this._effect;
  32314. };
  32315. PostProcess.prototype.dispose = function (camera) {
  32316. camera = camera || this._camera;
  32317. if (this._textures.length > 0) {
  32318. for (var i = 0; i < this._textures.length; i++) {
  32319. this._engine._releaseTexture(this._textures.data[i]);
  32320. }
  32321. this._textures.reset();
  32322. }
  32323. if (!camera) {
  32324. return;
  32325. }
  32326. camera.detachPostProcess(this);
  32327. var index = camera._postProcesses.indexOf(this);
  32328. if (index === 0 && camera._postProcesses.length > 0) {
  32329. this._camera._postProcesses[0].markTextureDirty();
  32330. }
  32331. this.onActivateObservable.clear();
  32332. this.onAfterRenderObservable.clear();
  32333. this.onApplyObservable.clear();
  32334. this.onBeforeRenderObservable.clear();
  32335. this.onSizeChangedObservable.clear();
  32336. };
  32337. return PostProcess;
  32338. }());
  32339. BABYLON.PostProcess = PostProcess;
  32340. })(BABYLON || (BABYLON = {}));
  32341. //# sourceMappingURL=babylon.postProcess.js.map
  32342. var BABYLON;
  32343. (function (BABYLON) {
  32344. var PostProcessManager = (function () {
  32345. function PostProcessManager(scene) {
  32346. this._vertexBuffers = {};
  32347. this._scene = scene;
  32348. }
  32349. PostProcessManager.prototype._prepareBuffers = function () {
  32350. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  32351. return;
  32352. }
  32353. // VBO
  32354. var vertices = [];
  32355. vertices.push(1, 1);
  32356. vertices.push(-1, 1);
  32357. vertices.push(-1, -1);
  32358. vertices.push(1, -1);
  32359. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  32360. // Indices
  32361. var indices = [];
  32362. indices.push(0);
  32363. indices.push(1);
  32364. indices.push(2);
  32365. indices.push(0);
  32366. indices.push(2);
  32367. indices.push(3);
  32368. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  32369. };
  32370. // Methods
  32371. PostProcessManager.prototype._prepareFrame = function (sourceTexture) {
  32372. var postProcesses = this._scene.activeCamera._postProcesses;
  32373. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  32374. return false;
  32375. }
  32376. postProcesses[0].activate(this._scene.activeCamera, sourceTexture);
  32377. return true;
  32378. };
  32379. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture) {
  32380. var engine = this._scene.getEngine();
  32381. for (var index = 0; index < postProcesses.length; index++) {
  32382. if (index < postProcesses.length - 1) {
  32383. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  32384. }
  32385. else {
  32386. if (targetTexture) {
  32387. engine.bindFramebuffer(targetTexture);
  32388. }
  32389. else {
  32390. engine.restoreDefaultFramebuffer();
  32391. }
  32392. }
  32393. var pp = postProcesses[index];
  32394. var effect = pp.apply();
  32395. if (effect) {
  32396. pp.onBeforeRenderObservable.notifyObservers(effect);
  32397. // VBOs
  32398. this._prepareBuffers();
  32399. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  32400. // Draw order
  32401. engine.draw(true, 0, 6);
  32402. pp.onAfterRenderObservable.notifyObservers(effect);
  32403. }
  32404. }
  32405. // Restore depth buffer
  32406. engine.setDepthBuffer(true);
  32407. engine.setDepthWrite(true);
  32408. };
  32409. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses) {
  32410. postProcesses = postProcesses || this._scene.activeCamera._postProcesses;
  32411. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  32412. return;
  32413. }
  32414. var engine = this._scene.getEngine();
  32415. for (var index = 0, len = postProcesses.length; index < len; index++) {
  32416. if (index < len - 1) {
  32417. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  32418. }
  32419. else {
  32420. if (targetTexture) {
  32421. engine.bindFramebuffer(targetTexture, faceIndex);
  32422. }
  32423. else {
  32424. engine.restoreDefaultFramebuffer();
  32425. }
  32426. }
  32427. if (doNotPresent) {
  32428. break;
  32429. }
  32430. var pp = postProcesses[index];
  32431. var effect = pp.apply();
  32432. if (effect) {
  32433. pp.onBeforeRenderObservable.notifyObservers(effect);
  32434. // VBOs
  32435. this._prepareBuffers();
  32436. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  32437. // Draw order
  32438. engine.draw(true, 0, 6);
  32439. pp.onAfterRenderObservable.notifyObservers(effect);
  32440. }
  32441. }
  32442. // Restore depth buffer
  32443. engine.setDepthBuffer(true);
  32444. engine.setDepthWrite(true);
  32445. };
  32446. PostProcessManager.prototype.dispose = function () {
  32447. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  32448. if (buffer) {
  32449. buffer.dispose();
  32450. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  32451. }
  32452. if (this._indexBuffer) {
  32453. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  32454. this._indexBuffer = null;
  32455. }
  32456. };
  32457. return PostProcessManager;
  32458. }());
  32459. BABYLON.PostProcessManager = PostProcessManager;
  32460. })(BABYLON || (BABYLON = {}));
  32461. //# sourceMappingURL=babylon.postProcessManager.js.map
  32462. var BABYLON;
  32463. (function (BABYLON) {
  32464. var PassPostProcess = (function (_super) {
  32465. __extends(PassPostProcess, _super);
  32466. function PassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  32467. return _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable) || this;
  32468. }
  32469. return PassPostProcess;
  32470. }(BABYLON.PostProcess));
  32471. BABYLON.PassPostProcess = PassPostProcess;
  32472. })(BABYLON || (BABYLON = {}));
  32473. //# sourceMappingURL=babylon.passPostProcess.js.map
  32474. var BABYLON;
  32475. (function (BABYLON) {
  32476. /**
  32477. * This is a holder class for the physics joint created by the physics plugin.
  32478. * It holds a set of functions to control the underlying joint.
  32479. */
  32480. var PhysicsJoint = (function () {
  32481. function PhysicsJoint(type, jointData) {
  32482. this.type = type;
  32483. this.jointData = jointData;
  32484. jointData.nativeParams = jointData.nativeParams || {};
  32485. }
  32486. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  32487. get: function () {
  32488. return this._physicsJoint;
  32489. },
  32490. set: function (newJoint) {
  32491. if (this._physicsJoint) {
  32492. }
  32493. this._physicsJoint = newJoint;
  32494. },
  32495. enumerable: true,
  32496. configurable: true
  32497. });
  32498. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  32499. set: function (physicsPlugin) {
  32500. this._physicsPlugin = physicsPlugin;
  32501. },
  32502. enumerable: true,
  32503. configurable: true
  32504. });
  32505. /**
  32506. * Execute a function that is physics-plugin specific.
  32507. * @param {Function} func the function that will be executed.
  32508. * It accepts two parameters: the physics world and the physics joint.
  32509. */
  32510. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  32511. func(this._physicsPlugin.world, this._physicsJoint);
  32512. };
  32513. return PhysicsJoint;
  32514. }());
  32515. //TODO check if the native joints are the same
  32516. //Joint Types
  32517. PhysicsJoint.DistanceJoint = 0;
  32518. PhysicsJoint.HingeJoint = 1;
  32519. PhysicsJoint.BallAndSocketJoint = 2;
  32520. PhysicsJoint.WheelJoint = 3;
  32521. PhysicsJoint.SliderJoint = 4;
  32522. //OIMO
  32523. PhysicsJoint.PrismaticJoint = 5;
  32524. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  32525. PhysicsJoint.UniversalJoint = 6;
  32526. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  32527. //Cannon
  32528. //Similar to a Ball-Joint. Different in params
  32529. PhysicsJoint.PointToPointJoint = 8;
  32530. //Cannon only at the moment
  32531. PhysicsJoint.SpringJoint = 9;
  32532. PhysicsJoint.LockJoint = 10;
  32533. BABYLON.PhysicsJoint = PhysicsJoint;
  32534. /**
  32535. * A class representing a physics distance joint.
  32536. */
  32537. var DistanceJoint = (function (_super) {
  32538. __extends(DistanceJoint, _super);
  32539. function DistanceJoint(jointData) {
  32540. return _super.call(this, PhysicsJoint.DistanceJoint, jointData) || this;
  32541. }
  32542. /**
  32543. * Update the predefined distance.
  32544. */
  32545. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  32546. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  32547. };
  32548. return DistanceJoint;
  32549. }(PhysicsJoint));
  32550. BABYLON.DistanceJoint = DistanceJoint;
  32551. var MotorEnabledJoint = (function (_super) {
  32552. __extends(MotorEnabledJoint, _super);
  32553. function MotorEnabledJoint(type, jointData) {
  32554. return _super.call(this, type, jointData) || this;
  32555. }
  32556. /**
  32557. * Set the motor values.
  32558. * Attention, this function is plugin specific. Engines won't react 100% the same.
  32559. * @param {number} force the force to apply
  32560. * @param {number} maxForce max force for this motor.
  32561. */
  32562. MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
  32563. this._physicsPlugin.setMotor(this, force, maxForce);
  32564. };
  32565. /**
  32566. * Set the motor's limits.
  32567. * Attention, this function is plugin specific. Engines won't react 100% the same.
  32568. */
  32569. MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  32570. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  32571. };
  32572. return MotorEnabledJoint;
  32573. }(PhysicsJoint));
  32574. BABYLON.MotorEnabledJoint = MotorEnabledJoint;
  32575. /**
  32576. * This class represents a single hinge physics joint
  32577. */
  32578. var HingeJoint = (function (_super) {
  32579. __extends(HingeJoint, _super);
  32580. function HingeJoint(jointData) {
  32581. return _super.call(this, PhysicsJoint.HingeJoint, jointData) || this;
  32582. }
  32583. /**
  32584. * Set the motor values.
  32585. * Attention, this function is plugin specific. Engines won't react 100% the same.
  32586. * @param {number} force the force to apply
  32587. * @param {number} maxForce max force for this motor.
  32588. */
  32589. HingeJoint.prototype.setMotor = function (force, maxForce) {
  32590. this._physicsPlugin.setMotor(this, force, maxForce);
  32591. };
  32592. /**
  32593. * Set the motor's limits.
  32594. * Attention, this function is plugin specific. Engines won't react 100% the same.
  32595. */
  32596. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  32597. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  32598. };
  32599. return HingeJoint;
  32600. }(MotorEnabledJoint));
  32601. BABYLON.HingeJoint = HingeJoint;
  32602. /**
  32603. * This class represents a dual hinge physics joint (same as wheel joint)
  32604. */
  32605. var Hinge2Joint = (function (_super) {
  32606. __extends(Hinge2Joint, _super);
  32607. function Hinge2Joint(jointData) {
  32608. return _super.call(this, PhysicsJoint.Hinge2Joint, jointData) || this;
  32609. }
  32610. /**
  32611. * Set the motor values.
  32612. * Attention, this function is plugin specific. Engines won't react 100% the same.
  32613. * @param {number} force the force to apply
  32614. * @param {number} maxForce max force for this motor.
  32615. * @param {motorIndex} the motor's index, 0 or 1.
  32616. */
  32617. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  32618. if (motorIndex === void 0) { motorIndex = 0; }
  32619. this._physicsPlugin.setMotor(this, force, maxForce, motorIndex);
  32620. };
  32621. /**
  32622. * Set the motor limits.
  32623. * Attention, this function is plugin specific. Engines won't react 100% the same.
  32624. * @param {number} upperLimit the upper limit
  32625. * @param {number} lowerLimit lower limit
  32626. * @param {motorIndex} the motor's index, 0 or 1.
  32627. */
  32628. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  32629. if (motorIndex === void 0) { motorIndex = 0; }
  32630. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  32631. };
  32632. return Hinge2Joint;
  32633. }(MotorEnabledJoint));
  32634. BABYLON.Hinge2Joint = Hinge2Joint;
  32635. })(BABYLON || (BABYLON = {}));
  32636. //# sourceMappingURL=babylon.physicsJoint.js.map
  32637. var BABYLON;
  32638. (function (BABYLON) {
  32639. var PhysicsImpostor = (function () {
  32640. function PhysicsImpostor(object, type, _options, _scene) {
  32641. if (_options === void 0) { _options = { mass: 0 }; }
  32642. var _this = this;
  32643. this.object = object;
  32644. this.type = type;
  32645. this._options = _options;
  32646. this._scene = _scene;
  32647. this._bodyUpdateRequired = false;
  32648. this._onBeforePhysicsStepCallbacks = new Array();
  32649. this._onAfterPhysicsStepCallbacks = new Array();
  32650. this._onPhysicsCollideCallbacks = [];
  32651. this._deltaPosition = BABYLON.Vector3.Zero();
  32652. this._tmpPositionWithDelta = BABYLON.Vector3.Zero();
  32653. this._tmpRotationWithDelta = new BABYLON.Quaternion();
  32654. /**
  32655. * this function is executed by the physics engine.
  32656. */
  32657. this.beforeStep = function () {
  32658. _this.object.position.subtractToRef(_this._deltaPosition, _this._tmpPositionWithDelta);
  32659. //conjugate deltaRotation
  32660. if (_this._deltaRotationConjugated) {
  32661. _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this._tmpRotationWithDelta);
  32662. }
  32663. else {
  32664. _this._tmpRotationWithDelta.copyFrom(_this.object.rotationQuaternion);
  32665. }
  32666. _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, _this._tmpPositionWithDelta, _this._tmpRotationWithDelta);
  32667. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  32668. func(_this);
  32669. });
  32670. };
  32671. /**
  32672. * this function is executed by the physics engine.
  32673. */
  32674. this.afterStep = function () {
  32675. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  32676. func(_this);
  32677. });
  32678. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  32679. _this.object.position.addInPlace(_this._deltaPosition);
  32680. if (_this._deltaRotation) {
  32681. _this.object.rotationQuaternion.multiplyInPlace(_this._deltaRotation);
  32682. }
  32683. };
  32684. /**
  32685. * Legacy collision detection event support
  32686. */
  32687. this.onCollideEvent = null;
  32688. //event and body object due to cannon's event-based architecture.
  32689. this.onCollide = function (e) {
  32690. if (!_this._onPhysicsCollideCallbacks.length && !_this.onCollideEvent)
  32691. return;
  32692. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  32693. if (otherImpostor) {
  32694. // Legacy collision detection event support
  32695. if (_this.onCollideEvent) {
  32696. _this.onCollideEvent(_this, otherImpostor);
  32697. }
  32698. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  32699. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  32700. }).forEach(function (obj) {
  32701. obj.callback(_this, otherImpostor);
  32702. });
  32703. }
  32704. };
  32705. //sanity check!
  32706. if (!this.object) {
  32707. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  32708. return;
  32709. }
  32710. //legacy support for old syntax.
  32711. if (!this._scene && object.getScene) {
  32712. this._scene = object.getScene();
  32713. }
  32714. this._physicsEngine = this._scene.getPhysicsEngine();
  32715. if (!this._physicsEngine) {
  32716. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  32717. }
  32718. else {
  32719. //set the object's quaternion, if not set
  32720. if (!this.object.rotationQuaternion) {
  32721. if (this.object.rotation) {
  32722. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  32723. }
  32724. else {
  32725. this.object.rotationQuaternion = new BABYLON.Quaternion();
  32726. }
  32727. }
  32728. //default options params
  32729. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  32730. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  32731. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  32732. this._joints = [];
  32733. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  32734. if (!this.object.parent) {
  32735. this._init();
  32736. }
  32737. }
  32738. }
  32739. /**
  32740. * This function will completly initialize this impostor.
  32741. * It will create a new body - but only if this mesh has no parent.
  32742. * If it has, this impostor will not be used other than to define the impostor
  32743. * of the child mesh.
  32744. */
  32745. PhysicsImpostor.prototype._init = function () {
  32746. this._physicsEngine.removeImpostor(this);
  32747. this.physicsBody = null;
  32748. this._parent = this._parent || this._getPhysicsParent();
  32749. if (!this.parent) {
  32750. this._physicsEngine.addImpostor(this);
  32751. }
  32752. };
  32753. PhysicsImpostor.prototype._getPhysicsParent = function () {
  32754. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  32755. var parentMesh = this.object.parent;
  32756. return parentMesh.physicsImpostor;
  32757. }
  32758. return;
  32759. };
  32760. /**
  32761. * Should a new body be generated.
  32762. */
  32763. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  32764. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  32765. };
  32766. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  32767. this.forceUpdate();
  32768. };
  32769. /**
  32770. * Force a regeneration of this or the parent's impostor's body.
  32771. * Use under cautious - This will remove all joints already implemented.
  32772. */
  32773. PhysicsImpostor.prototype.forceUpdate = function () {
  32774. this._init();
  32775. if (this.parent) {
  32776. this.parent.forceUpdate();
  32777. }
  32778. };
  32779. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  32780. /*public get mesh(): AbstractMesh {
  32781. return this._mesh;
  32782. }*/
  32783. /**
  32784. * Gets the body that holds this impostor. Either its own, or its parent.
  32785. */
  32786. get: function () {
  32787. return this._parent ? this._parent.physicsBody : this._physicsBody;
  32788. },
  32789. /**
  32790. * Set the physics body. Used mainly by the physics engine/plugin
  32791. */
  32792. set: function (physicsBody) {
  32793. if (this._physicsBody) {
  32794. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  32795. }
  32796. this._physicsBody = physicsBody;
  32797. this.resetUpdateFlags();
  32798. },
  32799. enumerable: true,
  32800. configurable: true
  32801. });
  32802. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  32803. get: function () {
  32804. return this._parent;
  32805. },
  32806. set: function (value) {
  32807. this._parent = value;
  32808. },
  32809. enumerable: true,
  32810. configurable: true
  32811. });
  32812. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  32813. this._bodyUpdateRequired = false;
  32814. };
  32815. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  32816. if (this.object.getBoundingInfo) {
  32817. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  32818. return this.object.getBoundingInfo().boundingBox.extendSize.scale(2).multiply(this.object.scaling);
  32819. }
  32820. else {
  32821. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  32822. }
  32823. };
  32824. PhysicsImpostor.prototype.getObjectCenter = function () {
  32825. if (this.object.getBoundingInfo) {
  32826. return this.object.getBoundingInfo().boundingBox.center;
  32827. }
  32828. else {
  32829. return this.object.position;
  32830. }
  32831. };
  32832. /**
  32833. * Get a specific parametes from the options parameter.
  32834. */
  32835. PhysicsImpostor.prototype.getParam = function (paramName) {
  32836. return this._options[paramName];
  32837. };
  32838. /**
  32839. * Sets a specific parameter in the options given to the physics plugin
  32840. */
  32841. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  32842. this._options[paramName] = value;
  32843. this._bodyUpdateRequired = true;
  32844. };
  32845. /**
  32846. * Specifically change the body's mass option. Won't recreate the physics body object
  32847. */
  32848. PhysicsImpostor.prototype.setMass = function (mass) {
  32849. if (this.getParam("mass") !== mass) {
  32850. this.setParam("mass", mass);
  32851. }
  32852. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  32853. };
  32854. PhysicsImpostor.prototype.getLinearVelocity = function () {
  32855. return this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this);
  32856. };
  32857. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  32858. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  32859. };
  32860. PhysicsImpostor.prototype.getAngularVelocity = function () {
  32861. return this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this);
  32862. };
  32863. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  32864. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  32865. };
  32866. /**
  32867. * Execute a function with the physics plugin native code.
  32868. * Provide a function the will have two variables - the world object and the physics body object.
  32869. */
  32870. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  32871. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  32872. };
  32873. /**
  32874. * Register a function that will be executed before the physics world is stepping forward.
  32875. */
  32876. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  32877. this._onBeforePhysicsStepCallbacks.push(func);
  32878. };
  32879. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  32880. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  32881. if (index > -1) {
  32882. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  32883. }
  32884. else {
  32885. BABYLON.Tools.Warn("Function to remove was not found");
  32886. }
  32887. };
  32888. /**
  32889. * Register a function that will be executed after the physics step
  32890. */
  32891. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  32892. this._onAfterPhysicsStepCallbacks.push(func);
  32893. };
  32894. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  32895. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  32896. if (index > -1) {
  32897. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  32898. }
  32899. else {
  32900. BABYLON.Tools.Warn("Function to remove was not found");
  32901. }
  32902. };
  32903. /**
  32904. * register a function that will be executed when this impostor collides against a different body.
  32905. */
  32906. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  32907. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  32908. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  32909. };
  32910. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  32911. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  32912. var index = this._onPhysicsCollideCallbacks.indexOf({ callback: func, otherImpostors: collidedAgainstList });
  32913. if (index > -1) {
  32914. this._onPhysicsCollideCallbacks.splice(index, 1);
  32915. }
  32916. else {
  32917. BABYLON.Tools.Warn("Function to remove was not found");
  32918. }
  32919. };
  32920. /**
  32921. * Apply a force
  32922. */
  32923. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  32924. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  32925. };
  32926. /**
  32927. * Apply an impulse
  32928. */
  32929. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  32930. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  32931. };
  32932. /**
  32933. * A help function to create a joint.
  32934. */
  32935. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  32936. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  32937. this.addJoint(otherImpostor, joint);
  32938. };
  32939. /**
  32940. * Add a joint to this impostor with a different impostor.
  32941. */
  32942. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  32943. this._joints.push({
  32944. otherImpostor: otherImpostor,
  32945. joint: joint
  32946. });
  32947. this._physicsEngine.addJoint(this, otherImpostor, joint);
  32948. };
  32949. /**
  32950. * Will keep this body still, in a sleep mode.
  32951. */
  32952. PhysicsImpostor.prototype.sleep = function () {
  32953. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  32954. };
  32955. /**
  32956. * Wake the body up.
  32957. */
  32958. PhysicsImpostor.prototype.wakeUp = function () {
  32959. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  32960. };
  32961. PhysicsImpostor.prototype.clone = function (newObject) {
  32962. if (!newObject)
  32963. return null;
  32964. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  32965. };
  32966. PhysicsImpostor.prototype.dispose = function () {
  32967. var _this = this;
  32968. //no dispose if no physics engine is available.
  32969. if (!this._physicsEngine) {
  32970. return;
  32971. }
  32972. this._joints.forEach(function (j) {
  32973. _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
  32974. });
  32975. //dispose the physics body
  32976. this._physicsEngine.removeImpostor(this);
  32977. if (this.parent) {
  32978. this.parent.forceUpdate();
  32979. }
  32980. else {
  32981. }
  32982. };
  32983. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  32984. this._deltaPosition.copyFrom(position);
  32985. };
  32986. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  32987. if (!this._deltaRotation) {
  32988. this._deltaRotation = new BABYLON.Quaternion();
  32989. }
  32990. this._deltaRotation.copyFrom(rotation);
  32991. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  32992. };
  32993. return PhysicsImpostor;
  32994. }());
  32995. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  32996. //Impostor types
  32997. PhysicsImpostor.NoImpostor = 0;
  32998. PhysicsImpostor.SphereImpostor = 1;
  32999. PhysicsImpostor.BoxImpostor = 2;
  33000. PhysicsImpostor.PlaneImpostor = 3;
  33001. PhysicsImpostor.MeshImpostor = 4;
  33002. PhysicsImpostor.CylinderImpostor = 7;
  33003. PhysicsImpostor.ParticleImpostor = 8;
  33004. PhysicsImpostor.HeightmapImpostor = 9;
  33005. BABYLON.PhysicsImpostor = PhysicsImpostor;
  33006. })(BABYLON || (BABYLON = {}));
  33007. //# sourceMappingURL=babylon.physicsImpostor.js.map
  33008. var BABYLON;
  33009. (function (BABYLON) {
  33010. var PhysicsEngine = (function () {
  33011. function PhysicsEngine(gravity, _physicsPlugin) {
  33012. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  33013. this._physicsPlugin = _physicsPlugin;
  33014. //new methods and parameters
  33015. this._impostors = [];
  33016. this._joints = [];
  33017. if (!this._physicsPlugin.isSupported()) {
  33018. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  33019. + "Please make sure it is included.");
  33020. }
  33021. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  33022. this.setGravity(gravity);
  33023. this.setTimeStep();
  33024. }
  33025. PhysicsEngine.prototype.setGravity = function (gravity) {
  33026. this.gravity = gravity;
  33027. this._physicsPlugin.setGravity(this.gravity);
  33028. };
  33029. /**
  33030. * Set the time step of the physics engine.
  33031. * default is 1/60.
  33032. * To slow it down, enter 1/600 for example.
  33033. * To speed it up, 1/30
  33034. * @param {number} newTimeStep the new timestep to apply to this world.
  33035. */
  33036. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  33037. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  33038. this._physicsPlugin.setTimeStep(newTimeStep);
  33039. };
  33040. PhysicsEngine.prototype.dispose = function () {
  33041. this._impostors.forEach(function (impostor) {
  33042. impostor.dispose();
  33043. });
  33044. this._physicsPlugin.dispose();
  33045. };
  33046. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  33047. return this._physicsPlugin.name;
  33048. };
  33049. /**
  33050. * Adding a new impostor for the impostor tracking.
  33051. * This will be done by the impostor itself.
  33052. * @param {PhysicsImpostor} impostor the impostor to add
  33053. */
  33054. PhysicsEngine.prototype.addImpostor = function (impostor) {
  33055. impostor.uniqueId = this._impostors.push(impostor);
  33056. //if no parent, generate the body
  33057. if (!impostor.parent) {
  33058. this._physicsPlugin.generatePhysicsBody(impostor);
  33059. }
  33060. };
  33061. /**
  33062. * Remove an impostor from the engine.
  33063. * This impostor and its mesh will not longer be updated by the physics engine.
  33064. * @param {PhysicsImpostor} impostor the impostor to remove
  33065. */
  33066. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  33067. var index = this._impostors.indexOf(impostor);
  33068. if (index > -1) {
  33069. var removed = this._impostors.splice(index, 1);
  33070. //Is it needed?
  33071. if (removed.length) {
  33072. //this will also remove it from the world.
  33073. removed[0].physicsBody = null;
  33074. }
  33075. }
  33076. };
  33077. /**
  33078. * Add a joint to the physics engine
  33079. * @param {PhysicsImpostor} mainImpostor the main impostor to which the joint is added.
  33080. * @param {PhysicsImpostor} connectedImpostor the impostor that is connected to the main impostor using this joint
  33081. * @param {PhysicsJoint} the joint that will connect both impostors.
  33082. */
  33083. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  33084. var impostorJoint = {
  33085. mainImpostor: mainImpostor,
  33086. connectedImpostor: connectedImpostor,
  33087. joint: joint
  33088. };
  33089. joint.physicsPlugin = this._physicsPlugin;
  33090. this._joints.push(impostorJoint);
  33091. this._physicsPlugin.generateJoint(impostorJoint);
  33092. };
  33093. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  33094. var matchingJoints = this._joints.filter(function (impostorJoint) {
  33095. return (impostorJoint.connectedImpostor === connectedImpostor
  33096. && impostorJoint.joint === joint
  33097. && impostorJoint.mainImpostor === mainImpostor);
  33098. });
  33099. if (matchingJoints.length) {
  33100. this._physicsPlugin.removeJoint(matchingJoints[0]);
  33101. }
  33102. };
  33103. /**
  33104. * Called by the scene. no need to call it.
  33105. */
  33106. PhysicsEngine.prototype._step = function (delta) {
  33107. var _this = this;
  33108. //check if any mesh has no body / requires an update
  33109. this._impostors.forEach(function (impostor) {
  33110. if (impostor.isBodyInitRequired()) {
  33111. _this._physicsPlugin.generatePhysicsBody(impostor);
  33112. }
  33113. });
  33114. if (delta > 0.1) {
  33115. delta = 0.1;
  33116. }
  33117. else if (delta <= 0) {
  33118. delta = 1.0 / 60.0;
  33119. }
  33120. this._physicsPlugin.executeStep(delta, this._impostors);
  33121. };
  33122. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  33123. return this._physicsPlugin;
  33124. };
  33125. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  33126. for (var i = 0; i < this._impostors.length; ++i) {
  33127. if (this._impostors[i].object === object) {
  33128. return this._impostors[i];
  33129. }
  33130. }
  33131. };
  33132. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  33133. for (var i = 0; i < this._impostors.length; ++i) {
  33134. if (this._impostors[i].physicsBody === body) {
  33135. return this._impostors[i];
  33136. }
  33137. }
  33138. };
  33139. return PhysicsEngine;
  33140. }());
  33141. // Statics, Legacy support.
  33142. /**
  33143. * @Deprecated
  33144. *
  33145. */
  33146. PhysicsEngine.NoImpostor = BABYLON.PhysicsImpostor.NoImpostor;
  33147. PhysicsEngine.SphereImpostor = BABYLON.PhysicsImpostor.SphereImpostor;
  33148. PhysicsEngine.BoxImpostor = BABYLON.PhysicsImpostor.BoxImpostor;
  33149. PhysicsEngine.PlaneImpostor = BABYLON.PhysicsImpostor.PlaneImpostor;
  33150. PhysicsEngine.MeshImpostor = BABYLON.PhysicsImpostor.MeshImpostor;
  33151. PhysicsEngine.CylinderImpostor = BABYLON.PhysicsImpostor.CylinderImpostor;
  33152. PhysicsEngine.HeightmapImpostor = BABYLON.PhysicsImpostor.HeightmapImpostor;
  33153. PhysicsEngine.CapsuleImpostor = -1;
  33154. PhysicsEngine.ConeImpostor = -1;
  33155. PhysicsEngine.ConvexHullImpostor = -1;
  33156. PhysicsEngine.Epsilon = 0.001;
  33157. BABYLON.PhysicsEngine = PhysicsEngine;
  33158. })(BABYLON || (BABYLON = {}));
  33159. //# sourceMappingURL=babylon.physicsEngine.js.map
  33160. var BABYLON;
  33161. (function (BABYLON) {
  33162. var VertexData = (function () {
  33163. function VertexData() {
  33164. }
  33165. VertexData.prototype.set = function (data, kind) {
  33166. switch (kind) {
  33167. case BABYLON.VertexBuffer.PositionKind:
  33168. this.positions = data;
  33169. break;
  33170. case BABYLON.VertexBuffer.NormalKind:
  33171. this.normals = data;
  33172. break;
  33173. case BABYLON.VertexBuffer.UVKind:
  33174. this.uvs = data;
  33175. break;
  33176. case BABYLON.VertexBuffer.UV2Kind:
  33177. this.uvs2 = data;
  33178. break;
  33179. case BABYLON.VertexBuffer.UV3Kind:
  33180. this.uvs3 = data;
  33181. break;
  33182. case BABYLON.VertexBuffer.UV4Kind:
  33183. this.uvs4 = data;
  33184. break;
  33185. case BABYLON.VertexBuffer.UV5Kind:
  33186. this.uvs5 = data;
  33187. break;
  33188. case BABYLON.VertexBuffer.UV6Kind:
  33189. this.uvs6 = data;
  33190. break;
  33191. case BABYLON.VertexBuffer.ColorKind:
  33192. this.colors = data;
  33193. break;
  33194. case BABYLON.VertexBuffer.MatricesIndicesKind:
  33195. this.matricesIndices = data;
  33196. break;
  33197. case BABYLON.VertexBuffer.MatricesWeightsKind:
  33198. this.matricesWeights = data;
  33199. break;
  33200. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  33201. this.matricesIndicesExtra = data;
  33202. break;
  33203. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  33204. this.matricesWeightsExtra = data;
  33205. break;
  33206. }
  33207. };
  33208. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  33209. this._applyTo(mesh, updatable);
  33210. };
  33211. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  33212. this._applyTo(geometry, updatable);
  33213. };
  33214. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  33215. this._update(mesh);
  33216. };
  33217. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  33218. this._update(geometry);
  33219. };
  33220. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  33221. if (this.positions) {
  33222. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  33223. }
  33224. if (this.normals) {
  33225. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  33226. }
  33227. if (this.uvs) {
  33228. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  33229. }
  33230. if (this.uvs2) {
  33231. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  33232. }
  33233. if (this.uvs3) {
  33234. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  33235. }
  33236. if (this.uvs4) {
  33237. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  33238. }
  33239. if (this.uvs5) {
  33240. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  33241. }
  33242. if (this.uvs6) {
  33243. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  33244. }
  33245. if (this.colors) {
  33246. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  33247. }
  33248. if (this.matricesIndices) {
  33249. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  33250. }
  33251. if (this.matricesWeights) {
  33252. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  33253. }
  33254. if (this.matricesIndicesExtra) {
  33255. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  33256. }
  33257. if (this.matricesWeightsExtra) {
  33258. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  33259. }
  33260. if (this.indices) {
  33261. meshOrGeometry.setIndices(this.indices);
  33262. }
  33263. };
  33264. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  33265. if (this.positions) {
  33266. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  33267. }
  33268. if (this.normals) {
  33269. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  33270. }
  33271. if (this.uvs) {
  33272. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  33273. }
  33274. if (this.uvs2) {
  33275. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  33276. }
  33277. if (this.uvs3) {
  33278. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  33279. }
  33280. if (this.uvs4) {
  33281. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  33282. }
  33283. if (this.uvs5) {
  33284. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  33285. }
  33286. if (this.uvs6) {
  33287. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  33288. }
  33289. if (this.colors) {
  33290. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  33291. }
  33292. if (this.matricesIndices) {
  33293. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  33294. }
  33295. if (this.matricesWeights) {
  33296. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  33297. }
  33298. if (this.matricesIndicesExtra) {
  33299. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  33300. }
  33301. if (this.matricesWeightsExtra) {
  33302. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  33303. }
  33304. if (this.indices) {
  33305. meshOrGeometry.setIndices(this.indices);
  33306. }
  33307. };
  33308. VertexData.prototype.transform = function (matrix) {
  33309. var transformed = BABYLON.Vector3.Zero();
  33310. var index;
  33311. if (this.positions) {
  33312. var position = BABYLON.Vector3.Zero();
  33313. for (index = 0; index < this.positions.length; index += 3) {
  33314. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  33315. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  33316. this.positions[index] = transformed.x;
  33317. this.positions[index + 1] = transformed.y;
  33318. this.positions[index + 2] = transformed.z;
  33319. }
  33320. }
  33321. if (this.normals) {
  33322. var normal = BABYLON.Vector3.Zero();
  33323. for (index = 0; index < this.normals.length; index += 3) {
  33324. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  33325. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  33326. this.normals[index] = transformed.x;
  33327. this.normals[index + 1] = transformed.y;
  33328. this.normals[index + 2] = transformed.z;
  33329. }
  33330. }
  33331. };
  33332. VertexData.prototype.merge = function (other) {
  33333. if (other.indices) {
  33334. if (!this.indices) {
  33335. this.indices = [];
  33336. }
  33337. var offset = this.positions ? this.positions.length / 3 : 0;
  33338. for (var index = 0; index < other.indices.length; index++) {
  33339. //TODO check type - if Int32Array | Uint32Array | Uint16Array!
  33340. this.indices.push(other.indices[index] + offset);
  33341. }
  33342. }
  33343. this.positions = this._mergeElement(this.positions, other.positions);
  33344. this.normals = this._mergeElement(this.normals, other.normals);
  33345. this.uvs = this._mergeElement(this.uvs, other.uvs);
  33346. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);
  33347. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);
  33348. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);
  33349. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);
  33350. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);
  33351. this.colors = this._mergeElement(this.colors, other.colors);
  33352. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);
  33353. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);
  33354. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);
  33355. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);
  33356. };
  33357. VertexData.prototype._mergeElement = function (source, other) {
  33358. if (!other)
  33359. return source;
  33360. if (!source)
  33361. return other;
  33362. var len = other.length + source.length;
  33363. var isSrcTypedArray = source instanceof Float32Array;
  33364. var isOthTypedArray = other instanceof Float32Array;
  33365. // use non-loop method when the source is Float32Array
  33366. if (isSrcTypedArray) {
  33367. var ret32 = new Float32Array(len);
  33368. ret32.set(source);
  33369. ret32.set(other, source.length);
  33370. return ret32;
  33371. }
  33372. else if (!isOthTypedArray) {
  33373. return source.concat(other);
  33374. }
  33375. else {
  33376. var ret = source.slice(0); // copy source to a separate array
  33377. for (var i = 0, len = other.length; i < len; i++) {
  33378. ret.push(other[i]);
  33379. }
  33380. return ret;
  33381. }
  33382. };
  33383. VertexData.prototype.serialize = function () {
  33384. var serializationObject = this.serialize();
  33385. if (this.positions) {
  33386. serializationObject.positions = this.positions;
  33387. }
  33388. if (this.normals) {
  33389. serializationObject.normals = this.normals;
  33390. }
  33391. if (this.uvs) {
  33392. serializationObject.uvs = this.uvs;
  33393. }
  33394. if (this.uvs2) {
  33395. serializationObject.uvs2 = this.uvs2;
  33396. }
  33397. if (this.uvs3) {
  33398. serializationObject.uvs3 = this.uvs3;
  33399. }
  33400. if (this.uvs4) {
  33401. serializationObject.uvs4 = this.uvs4;
  33402. }
  33403. if (this.uvs5) {
  33404. serializationObject.uvs5 = this.uvs5;
  33405. }
  33406. if (this.uvs6) {
  33407. serializationObject.uvs6 = this.uvs6;
  33408. }
  33409. if (this.colors) {
  33410. serializationObject.colors = this.colors;
  33411. }
  33412. if (this.matricesIndices) {
  33413. serializationObject.matricesIndices = this.matricesIndices;
  33414. serializationObject.matricesIndices._isExpanded = true;
  33415. }
  33416. if (this.matricesWeights) {
  33417. serializationObject.matricesWeights = this.matricesWeights;
  33418. }
  33419. if (this.matricesIndicesExtra) {
  33420. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  33421. serializationObject.matricesIndicesExtra._isExpanded = true;
  33422. }
  33423. if (this.matricesWeightsExtra) {
  33424. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  33425. }
  33426. serializationObject.indices = this.indices;
  33427. return serializationObject;
  33428. };
  33429. // Statics
  33430. VertexData.ExtractFromMesh = function (mesh, copyWhenShared) {
  33431. return VertexData._ExtractFrom(mesh, copyWhenShared);
  33432. };
  33433. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared) {
  33434. return VertexData._ExtractFrom(geometry, copyWhenShared);
  33435. };
  33436. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared) {
  33437. var result = new VertexData();
  33438. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  33439. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared);
  33440. }
  33441. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  33442. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared);
  33443. }
  33444. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  33445. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared);
  33446. }
  33447. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  33448. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared);
  33449. }
  33450. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  33451. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared);
  33452. }
  33453. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  33454. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared);
  33455. }
  33456. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  33457. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared);
  33458. }
  33459. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  33460. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared);
  33461. }
  33462. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  33463. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared);
  33464. }
  33465. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  33466. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared);
  33467. }
  33468. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  33469. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared);
  33470. }
  33471. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  33472. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared);
  33473. }
  33474. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  33475. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared);
  33476. }
  33477. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  33478. return result;
  33479. };
  33480. VertexData.CreateRibbon = function (options) {
  33481. var pathArray = options.pathArray;
  33482. var closeArray = options.closeArray || false;
  33483. var closePath = options.closePath || false;
  33484. var invertUV = options.invertUV || false;
  33485. var defaultOffset = Math.floor(pathArray[0].length / 2);
  33486. var offset = options.offset || defaultOffset;
  33487. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  33488. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33489. var positions = [];
  33490. var indices = [];
  33491. var normals = [];
  33492. var uvs = [];
  33493. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  33494. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  33495. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  33496. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  33497. var minlg; // minimal length among all paths from pathArray
  33498. var lg = []; // array of path lengths : nb of vertex per path
  33499. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  33500. var p; // path iterator
  33501. var i; // point iterator
  33502. var j; // point iterator
  33503. // if single path in pathArray
  33504. if (pathArray.length < 2) {
  33505. var ar1 = [];
  33506. var ar2 = [];
  33507. for (i = 0; i < pathArray[0].length - offset; i++) {
  33508. ar1.push(pathArray[0][i]);
  33509. ar2.push(pathArray[0][i + offset]);
  33510. }
  33511. pathArray = [ar1, ar2];
  33512. }
  33513. // positions and horizontal distances (u)
  33514. var idc = 0;
  33515. var closePathCorr = (closePath) ? 1 : 0;
  33516. var path;
  33517. var l;
  33518. minlg = pathArray[0].length;
  33519. var vectlg;
  33520. var dist;
  33521. for (p = 0; p < pathArray.length; p++) {
  33522. uTotalDistance[p] = 0;
  33523. us[p] = [0];
  33524. path = pathArray[p];
  33525. l = path.length;
  33526. minlg = (minlg < l) ? minlg : l;
  33527. j = 0;
  33528. while (j < l) {
  33529. positions.push(path[j].x, path[j].y, path[j].z);
  33530. if (j > 0) {
  33531. vectlg = path[j].subtract(path[j - 1]).length();
  33532. dist = vectlg + uTotalDistance[p];
  33533. us[p].push(dist);
  33534. uTotalDistance[p] = dist;
  33535. }
  33536. j++;
  33537. }
  33538. if (closePath) {
  33539. j--;
  33540. positions.push(path[0].x, path[0].y, path[0].z);
  33541. vectlg = path[j].subtract(path[0]).length();
  33542. dist = vectlg + uTotalDistance[p];
  33543. us[p].push(dist);
  33544. uTotalDistance[p] = dist;
  33545. }
  33546. lg[p] = l + closePathCorr;
  33547. idx[p] = idc;
  33548. idc += (l + closePathCorr);
  33549. }
  33550. // vertical distances (v)
  33551. var path1;
  33552. var path2;
  33553. var vertex1;
  33554. var vertex2;
  33555. for (i = 0; i < minlg + closePathCorr; i++) {
  33556. vTotalDistance[i] = 0;
  33557. vs[i] = [0];
  33558. for (p = 0; p < pathArray.length - 1; p++) {
  33559. path1 = pathArray[p];
  33560. path2 = pathArray[p + 1];
  33561. if (i === minlg) {
  33562. vertex1 = path1[0];
  33563. vertex2 = path2[0];
  33564. }
  33565. else {
  33566. vertex1 = path1[i];
  33567. vertex2 = path2[i];
  33568. }
  33569. vectlg = vertex2.subtract(vertex1).length();
  33570. dist = vectlg + vTotalDistance[i];
  33571. vs[i].push(dist);
  33572. vTotalDistance[i] = dist;
  33573. }
  33574. if (closeArray) {
  33575. path1 = pathArray[p];
  33576. path2 = pathArray[0];
  33577. if (i === minlg) {
  33578. vertex2 = path2[0];
  33579. }
  33580. vectlg = vertex2.subtract(vertex1).length();
  33581. dist = vectlg + vTotalDistance[i];
  33582. vTotalDistance[i] = dist;
  33583. }
  33584. }
  33585. // uvs
  33586. var u;
  33587. var v;
  33588. for (p = 0; p < pathArray.length; p++) {
  33589. for (i = 0; i < minlg + closePathCorr; i++) {
  33590. u = (uTotalDistance[p] != 0.0) ? us[p][i] / uTotalDistance[p] : 0.0;
  33591. v = (vTotalDistance[i] != 0.0) ? vs[i][p] / vTotalDistance[i] : 0.0;
  33592. if (invertUV) {
  33593. uvs.push(v, u);
  33594. }
  33595. else {
  33596. uvs.push(u, v);
  33597. }
  33598. }
  33599. }
  33600. // indices
  33601. p = 0; // path index
  33602. var pi = 0; // positions array index
  33603. var l1 = lg[p] - 1; // path1 length
  33604. var l2 = lg[p + 1] - 1; // path2 length
  33605. var min = (l1 < l2) ? l1 : l2; // current path stop index
  33606. var shft = idx[1] - idx[0]; // shift
  33607. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  33608. while (pi <= min && p < path1nb) {
  33609. // 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
  33610. indices.push(pi, pi + shft, pi + 1);
  33611. indices.push(pi + shft + 1, pi + 1, pi + shft);
  33612. pi += 1;
  33613. if (pi === min) {
  33614. p++;
  33615. if (p === lg.length - 1) {
  33616. shft = idx[0] - idx[p];
  33617. l1 = lg[p] - 1;
  33618. l2 = lg[0] - 1;
  33619. }
  33620. else {
  33621. shft = idx[p + 1] - idx[p];
  33622. l1 = lg[p] - 1;
  33623. l2 = lg[p + 1] - 1;
  33624. }
  33625. pi = idx[p];
  33626. min = (l1 < l2) ? l1 + pi : l2 + pi;
  33627. }
  33628. }
  33629. // normals
  33630. VertexData.ComputeNormals(positions, indices, normals);
  33631. if (closePath) {
  33632. var indexFirst = 0;
  33633. var indexLast = 0;
  33634. for (p = 0; p < pathArray.length; p++) {
  33635. indexFirst = idx[p] * 3;
  33636. if (p + 1 < pathArray.length) {
  33637. indexLast = (idx[p + 1] - 1) * 3;
  33638. }
  33639. else {
  33640. indexLast = normals.length - 3;
  33641. }
  33642. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  33643. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  33644. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  33645. normals[indexLast] = normals[indexFirst];
  33646. normals[indexLast + 1] = normals[indexFirst + 1];
  33647. normals[indexLast + 2] = normals[indexFirst + 2];
  33648. }
  33649. }
  33650. // sides
  33651. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  33652. // Result
  33653. var vertexData = new VertexData();
  33654. vertexData.indices = indices;
  33655. vertexData.positions = positions;
  33656. vertexData.normals = normals;
  33657. vertexData.uvs = uvs;
  33658. if (closePath) {
  33659. vertexData._idx = idx;
  33660. }
  33661. return vertexData;
  33662. };
  33663. VertexData.CreateBox = function (options) {
  33664. var normalsSource = [
  33665. new BABYLON.Vector3(0, 0, 1),
  33666. new BABYLON.Vector3(0, 0, -1),
  33667. new BABYLON.Vector3(1, 0, 0),
  33668. new BABYLON.Vector3(-1, 0, 0),
  33669. new BABYLON.Vector3(0, 1, 0),
  33670. new BABYLON.Vector3(0, -1, 0)
  33671. ];
  33672. var indices = [];
  33673. var positions = [];
  33674. var normals = [];
  33675. var uvs = [];
  33676. var width = options.width || options.size || 1;
  33677. var height = options.height || options.size || 1;
  33678. var depth = options.depth || options.size || 1;
  33679. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33680. var faceUV = options.faceUV || new Array(6);
  33681. var faceColors = options.faceColors;
  33682. var colors = [];
  33683. // default face colors and UV if undefined
  33684. for (var f = 0; f < 6; f++) {
  33685. if (faceUV[f] === undefined) {
  33686. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  33687. }
  33688. if (faceColors && faceColors[f] === undefined) {
  33689. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  33690. }
  33691. }
  33692. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  33693. // Create each face in turn.
  33694. for (var index = 0; index < normalsSource.length; index++) {
  33695. var normal = normalsSource[index];
  33696. // Get two vectors perpendicular to the face normal and to each other.
  33697. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  33698. var side2 = BABYLON.Vector3.Cross(normal, side1);
  33699. // Six indices (two triangles) per face.
  33700. var verticesLength = positions.length / 3;
  33701. indices.push(verticesLength);
  33702. indices.push(verticesLength + 1);
  33703. indices.push(verticesLength + 2);
  33704. indices.push(verticesLength);
  33705. indices.push(verticesLength + 2);
  33706. indices.push(verticesLength + 3);
  33707. // Four vertices per face.
  33708. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  33709. positions.push(vertex.x, vertex.y, vertex.z);
  33710. normals.push(normal.x, normal.y, normal.z);
  33711. uvs.push(faceUV[index].z, faceUV[index].w);
  33712. if (faceColors) {
  33713. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  33714. }
  33715. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  33716. positions.push(vertex.x, vertex.y, vertex.z);
  33717. normals.push(normal.x, normal.y, normal.z);
  33718. uvs.push(faceUV[index].x, faceUV[index].w);
  33719. if (faceColors) {
  33720. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  33721. }
  33722. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  33723. positions.push(vertex.x, vertex.y, vertex.z);
  33724. normals.push(normal.x, normal.y, normal.z);
  33725. uvs.push(faceUV[index].x, faceUV[index].y);
  33726. if (faceColors) {
  33727. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  33728. }
  33729. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  33730. positions.push(vertex.x, vertex.y, vertex.z);
  33731. normals.push(normal.x, normal.y, normal.z);
  33732. uvs.push(faceUV[index].z, faceUV[index].y);
  33733. if (faceColors) {
  33734. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  33735. }
  33736. }
  33737. // sides
  33738. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  33739. // Result
  33740. var vertexData = new VertexData();
  33741. vertexData.indices = indices;
  33742. vertexData.positions = positions;
  33743. vertexData.normals = normals;
  33744. vertexData.uvs = uvs;
  33745. if (faceColors) {
  33746. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  33747. vertexData.colors = totalColors;
  33748. }
  33749. return vertexData;
  33750. };
  33751. VertexData.CreateSphere = function (options) {
  33752. var segments = options.segments || 32;
  33753. var diameterX = options.diameterX || options.diameter || 1;
  33754. var diameterY = options.diameterY || options.diameter || 1;
  33755. var diameterZ = options.diameterZ || options.diameter || 1;
  33756. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  33757. var slice = (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  33758. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33759. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  33760. var totalZRotationSteps = 2 + segments;
  33761. var totalYRotationSteps = 2 * totalZRotationSteps;
  33762. var indices = [];
  33763. var positions = [];
  33764. var normals = [];
  33765. var uvs = [];
  33766. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  33767. var normalizedZ = zRotationStep / totalZRotationSteps;
  33768. var angleZ = normalizedZ * Math.PI * slice;
  33769. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  33770. var normalizedY = yRotationStep / totalYRotationSteps;
  33771. var angleY = normalizedY * Math.PI * 2 * arc;
  33772. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  33773. var rotationY = BABYLON.Matrix.RotationY(angleY);
  33774. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  33775. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  33776. var vertex = complete.multiply(radius);
  33777. var normal = complete.divide(radius).normalize();
  33778. positions.push(vertex.x, vertex.y, vertex.z);
  33779. normals.push(normal.x, normal.y, normal.z);
  33780. uvs.push(normalizedY, normalizedZ);
  33781. }
  33782. if (zRotationStep > 0) {
  33783. var verticesCount = positions.length / 3;
  33784. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  33785. indices.push((firstIndex));
  33786. indices.push((firstIndex + 1));
  33787. indices.push(firstIndex + totalYRotationSteps + 1);
  33788. indices.push((firstIndex + totalYRotationSteps + 1));
  33789. indices.push((firstIndex + 1));
  33790. indices.push((firstIndex + totalYRotationSteps + 2));
  33791. }
  33792. }
  33793. }
  33794. // Sides
  33795. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  33796. // Result
  33797. var vertexData = new VertexData();
  33798. vertexData.indices = indices;
  33799. vertexData.positions = positions;
  33800. vertexData.normals = normals;
  33801. vertexData.uvs = uvs;
  33802. return vertexData;
  33803. };
  33804. // Cylinder and cone
  33805. VertexData.CreateCylinder = function (options) {
  33806. var height = options.height || 2;
  33807. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  33808. var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;
  33809. var tessellation = options.tessellation || 24;
  33810. var subdivisions = options.subdivisions || 1;
  33811. var hasRings = options.hasRings;
  33812. var enclose = options.enclose;
  33813. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  33814. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33815. var faceUV = options.faceUV || new Array(3);
  33816. var faceColors = options.faceColors;
  33817. // default face colors and UV if undefined
  33818. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  33819. var ringNb = (hasRings) ? subdivisions : 1;
  33820. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  33821. var f;
  33822. for (f = 0; f < surfaceNb; f++) {
  33823. if (faceColors && faceColors[f] === undefined) {
  33824. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  33825. }
  33826. }
  33827. for (f = 0; f < surfaceNb; f++) {
  33828. if (faceUV && faceUV[f] === undefined) {
  33829. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  33830. }
  33831. }
  33832. var indices = [];
  33833. var positions = [];
  33834. var normals = [];
  33835. var uvs = [];
  33836. var colors = [];
  33837. var angle_step = Math.PI * 2 * arc / tessellation;
  33838. var angle;
  33839. var h;
  33840. var radius;
  33841. var tan = (diameterBottom - diameterTop) / 2 / height;
  33842. var ringVertex = BABYLON.Vector3.Zero();
  33843. var ringNormal = BABYLON.Vector3.Zero();
  33844. var ringFirstVertex = BABYLON.Vector3.Zero();
  33845. var ringFirstNormal = BABYLON.Vector3.Zero();
  33846. var quadNormal = BABYLON.Vector3.Zero();
  33847. var Y = BABYLON.Axis.Y;
  33848. // positions, normals, uvs
  33849. var i;
  33850. var j;
  33851. var r;
  33852. var ringIdx = 1;
  33853. var s = 1; // surface index
  33854. var cs = 0;
  33855. var v = 0;
  33856. for (i = 0; i <= subdivisions; i++) {
  33857. h = i / subdivisions;
  33858. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  33859. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  33860. for (r = 0; r < ringIdx; r++) {
  33861. if (hasRings) {
  33862. s += r;
  33863. }
  33864. if (enclose) {
  33865. s += 2 * r;
  33866. }
  33867. for (j = 0; j <= tessellation; j++) {
  33868. angle = j * angle_step;
  33869. // position
  33870. ringVertex.x = Math.cos(-angle) * radius;
  33871. ringVertex.y = -height / 2 + h * height;
  33872. ringVertex.z = Math.sin(-angle) * radius;
  33873. // normal
  33874. if (diameterTop === 0 && i === subdivisions) {
  33875. // if no top cap, reuse former normals
  33876. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  33877. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  33878. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  33879. }
  33880. else {
  33881. ringNormal.x = ringVertex.x;
  33882. ringNormal.z = ringVertex.z;
  33883. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  33884. ringNormal.normalize();
  33885. }
  33886. // keep first ring vertex values for enclose
  33887. if (j === 0) {
  33888. ringFirstVertex.copyFrom(ringVertex);
  33889. ringFirstNormal.copyFrom(ringNormal);
  33890. }
  33891. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  33892. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  33893. if (hasRings) {
  33894. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  33895. }
  33896. else {
  33897. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  33898. }
  33899. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  33900. if (faceColors) {
  33901. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  33902. }
  33903. }
  33904. // if enclose, add four vertices and their dedicated normals
  33905. if (arc !== 1 && enclose) {
  33906. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  33907. positions.push(0, ringVertex.y, 0);
  33908. positions.push(0, ringVertex.y, 0);
  33909. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  33910. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  33911. quadNormal.normalize();
  33912. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  33913. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  33914. quadNormal.normalize();
  33915. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  33916. if (hasRings) {
  33917. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  33918. }
  33919. else {
  33920. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  33921. }
  33922. uvs.push(faceUV[s + 1].x, v);
  33923. uvs.push(faceUV[s + 1].z, v);
  33924. if (hasRings) {
  33925. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  33926. }
  33927. else {
  33928. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  33929. }
  33930. uvs.push(faceUV[s + 2].x, v);
  33931. uvs.push(faceUV[s + 2].z, v);
  33932. if (faceColors) {
  33933. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  33934. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  33935. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  33936. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  33937. }
  33938. }
  33939. if (cs !== s) {
  33940. cs = s;
  33941. }
  33942. }
  33943. }
  33944. // indices
  33945. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  33946. var s;
  33947. i = 0;
  33948. for (s = 0; s < subdivisions; s++) {
  33949. for (j = 0; j < tessellation; j++) {
  33950. var i0 = i * (e + 1) + j;
  33951. var i1 = (i + 1) * (e + 1) + j;
  33952. var i2 = i * (e + 1) + (j + 1);
  33953. var i3 = (i + 1) * (e + 1) + (j + 1);
  33954. indices.push(i0, i1, i2);
  33955. indices.push(i3, i2, i1);
  33956. }
  33957. if (arc !== 1 && enclose) {
  33958. indices.push(i0 + 2, i1 + 2, i2 + 2);
  33959. indices.push(i3 + 2, i2 + 2, i1 + 2);
  33960. indices.push(i0 + 4, i1 + 4, i2 + 4);
  33961. indices.push(i3 + 4, i2 + 4, i1 + 4);
  33962. }
  33963. i = (hasRings) ? (i + 2) : (i + 1);
  33964. }
  33965. // Caps
  33966. var createCylinderCap = function (isTop) {
  33967. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  33968. if (radius === 0) {
  33969. return;
  33970. }
  33971. // Cap positions, normals & uvs
  33972. var angle;
  33973. var circleVector;
  33974. var i;
  33975. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  33976. var c;
  33977. if (faceColors) {
  33978. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  33979. }
  33980. // cap center
  33981. var vbase = positions.length / 3;
  33982. var offset = isTop ? height / 2 : -height / 2;
  33983. var center = new BABYLON.Vector3(0, offset, 0);
  33984. positions.push(center.x, center.y, center.z);
  33985. normals.push(0, isTop ? 1 : -1, 0);
  33986. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  33987. if (faceColors) {
  33988. colors.push(c.r, c.g, c.b, c.a);
  33989. }
  33990. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  33991. for (i = 0; i <= tessellation; i++) {
  33992. angle = Math.PI * 2 * i * arc / tessellation;
  33993. var cos = Math.cos(-angle);
  33994. var sin = Math.sin(-angle);
  33995. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  33996. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  33997. positions.push(circleVector.x, circleVector.y, circleVector.z);
  33998. normals.push(0, isTop ? 1 : -1, 0);
  33999. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  34000. if (faceColors) {
  34001. colors.push(c.r, c.g, c.b, c.a);
  34002. }
  34003. }
  34004. // Cap indices
  34005. for (i = 0; i < tessellation; i++) {
  34006. if (!isTop) {
  34007. indices.push(vbase);
  34008. indices.push(vbase + (i + 1));
  34009. indices.push(vbase + (i + 2));
  34010. }
  34011. else {
  34012. indices.push(vbase);
  34013. indices.push(vbase + (i + 2));
  34014. indices.push(vbase + (i + 1));
  34015. }
  34016. }
  34017. };
  34018. // add caps to geometry
  34019. createCylinderCap(false);
  34020. createCylinderCap(true);
  34021. // Sides
  34022. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  34023. var vertexData = new VertexData();
  34024. vertexData.indices = indices;
  34025. vertexData.positions = positions;
  34026. vertexData.normals = normals;
  34027. vertexData.uvs = uvs;
  34028. if (faceColors) {
  34029. vertexData.colors = colors;
  34030. }
  34031. return vertexData;
  34032. };
  34033. VertexData.CreateTorus = function (options) {
  34034. var indices = [];
  34035. var positions = [];
  34036. var normals = [];
  34037. var uvs = [];
  34038. var diameter = options.diameter || 1;
  34039. var thickness = options.thickness || 0.5;
  34040. var tessellation = options.tessellation || 16;
  34041. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  34042. var stride = tessellation + 1;
  34043. for (var i = 0; i <= tessellation; i++) {
  34044. var u = i / tessellation;
  34045. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  34046. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  34047. for (var j = 0; j <= tessellation; j++) {
  34048. var v = 1 - j / tessellation;
  34049. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  34050. var dx = Math.cos(innerAngle);
  34051. var dy = Math.sin(innerAngle);
  34052. // Create a vertex.
  34053. var normal = new BABYLON.Vector3(dx, dy, 0);
  34054. var position = normal.scale(thickness / 2);
  34055. var textureCoordinate = new BABYLON.Vector2(u, v);
  34056. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  34057. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  34058. positions.push(position.x, position.y, position.z);
  34059. normals.push(normal.x, normal.y, normal.z);
  34060. uvs.push(textureCoordinate.x, textureCoordinate.y);
  34061. // And create indices for two triangles.
  34062. var nextI = (i + 1) % stride;
  34063. var nextJ = (j + 1) % stride;
  34064. indices.push(i * stride + j);
  34065. indices.push(i * stride + nextJ);
  34066. indices.push(nextI * stride + j);
  34067. indices.push(i * stride + nextJ);
  34068. indices.push(nextI * stride + nextJ);
  34069. indices.push(nextI * stride + j);
  34070. }
  34071. }
  34072. // Sides
  34073. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  34074. // Result
  34075. var vertexData = new VertexData();
  34076. vertexData.indices = indices;
  34077. vertexData.positions = positions;
  34078. vertexData.normals = normals;
  34079. vertexData.uvs = uvs;
  34080. return vertexData;
  34081. };
  34082. VertexData.CreateLineSystem = function (options) {
  34083. var indices = [];
  34084. var positions = [];
  34085. var lines = options.lines;
  34086. var idx = 0;
  34087. for (var l = 0; l < lines.length; l++) {
  34088. var points = lines[l];
  34089. for (var index = 0; index < points.length; index++) {
  34090. positions.push(points[index].x, points[index].y, points[index].z);
  34091. if (index > 0) {
  34092. indices.push(idx - 1);
  34093. indices.push(idx);
  34094. }
  34095. idx++;
  34096. }
  34097. }
  34098. var vertexData = new VertexData();
  34099. vertexData.indices = indices;
  34100. vertexData.positions = positions;
  34101. return vertexData;
  34102. };
  34103. VertexData.CreateDashedLines = function (options) {
  34104. var dashSize = options.dashSize || 3;
  34105. var gapSize = options.gapSize || 1;
  34106. var dashNb = options.dashNb || 200;
  34107. var points = options.points;
  34108. var positions = new Array();
  34109. var indices = new Array();
  34110. var curvect = BABYLON.Vector3.Zero();
  34111. var lg = 0;
  34112. var nb = 0;
  34113. var shft = 0;
  34114. var dashshft = 0;
  34115. var curshft = 0;
  34116. var idx = 0;
  34117. var i = 0;
  34118. for (i = 0; i < points.length - 1; i++) {
  34119. points[i + 1].subtractToRef(points[i], curvect);
  34120. lg += curvect.length();
  34121. }
  34122. shft = lg / dashNb;
  34123. dashshft = dashSize * shft / (dashSize + gapSize);
  34124. for (i = 0; i < points.length - 1; i++) {
  34125. points[i + 1].subtractToRef(points[i], curvect);
  34126. nb = Math.floor(curvect.length() / shft);
  34127. curvect.normalize();
  34128. for (var j = 0; j < nb; j++) {
  34129. curshft = shft * j;
  34130. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  34131. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  34132. indices.push(idx, idx + 1);
  34133. idx += 2;
  34134. }
  34135. }
  34136. // Result
  34137. var vertexData = new VertexData();
  34138. vertexData.positions = positions;
  34139. vertexData.indices = indices;
  34140. return vertexData;
  34141. };
  34142. VertexData.CreateGround = function (options) {
  34143. var indices = [];
  34144. var positions = [];
  34145. var normals = [];
  34146. var uvs = [];
  34147. var row, col;
  34148. var width = options.width || 1;
  34149. var height = options.height || 1;
  34150. var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  34151. var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  34152. for (row = 0; row <= subdivisionsY; row++) {
  34153. for (col = 0; col <= subdivisionsX; col++) {
  34154. var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
  34155. var normal = new BABYLON.Vector3(0, 1.0, 0);
  34156. positions.push(position.x, position.y, position.z);
  34157. normals.push(normal.x, normal.y, normal.z);
  34158. uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsY);
  34159. }
  34160. }
  34161. for (row = 0; row < subdivisionsY; row++) {
  34162. for (col = 0; col < subdivisionsX; col++) {
  34163. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  34164. indices.push(col + 1 + row * (subdivisionsX + 1));
  34165. indices.push(col + row * (subdivisionsX + 1));
  34166. indices.push(col + (row + 1) * (subdivisionsX + 1));
  34167. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  34168. indices.push(col + row * (subdivisionsX + 1));
  34169. }
  34170. }
  34171. // Result
  34172. var vertexData = new VertexData();
  34173. vertexData.indices = indices;
  34174. vertexData.positions = positions;
  34175. vertexData.normals = normals;
  34176. vertexData.uvs = uvs;
  34177. return vertexData;
  34178. };
  34179. VertexData.CreateTiledGround = function (options) {
  34180. var xmin = options.xmin || -1.0;
  34181. var zmin = options.zmin || -1.0;
  34182. var xmax = options.xmax || 1.0;
  34183. var zmax = options.zmax || 1.0;
  34184. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  34185. var precision = options.precision || { w: 1, h: 1 };
  34186. var indices = [];
  34187. var positions = [];
  34188. var normals = [];
  34189. var uvs = [];
  34190. var row, col, tileRow, tileCol;
  34191. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  34192. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  34193. precision.w = (precision.w < 1) ? 1 : precision.w;
  34194. precision.h = (precision.h < 1) ? 1 : precision.h;
  34195. var tileSize = {
  34196. 'w': (xmax - xmin) / subdivisions.w,
  34197. 'h': (zmax - zmin) / subdivisions.h
  34198. };
  34199. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  34200. // Indices
  34201. var base = positions.length / 3;
  34202. var rowLength = precision.w + 1;
  34203. for (row = 0; row < precision.h; row++) {
  34204. for (col = 0; col < precision.w; col++) {
  34205. var square = [
  34206. base + col + row * rowLength,
  34207. base + (col + 1) + row * rowLength,
  34208. base + (col + 1) + (row + 1) * rowLength,
  34209. base + col + (row + 1) * rowLength
  34210. ];
  34211. indices.push(square[1]);
  34212. indices.push(square[2]);
  34213. indices.push(square[3]);
  34214. indices.push(square[0]);
  34215. indices.push(square[1]);
  34216. indices.push(square[3]);
  34217. }
  34218. }
  34219. // Position, normals and uvs
  34220. var position = BABYLON.Vector3.Zero();
  34221. var normal = new BABYLON.Vector3(0, 1.0, 0);
  34222. for (row = 0; row <= precision.h; row++) {
  34223. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  34224. for (col = 0; col <= precision.w; col++) {
  34225. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  34226. position.y = 0;
  34227. positions.push(position.x, position.y, position.z);
  34228. normals.push(normal.x, normal.y, normal.z);
  34229. uvs.push(col / precision.w, row / precision.h);
  34230. }
  34231. }
  34232. }
  34233. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  34234. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  34235. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  34236. }
  34237. }
  34238. // Result
  34239. var vertexData = new VertexData();
  34240. vertexData.indices = indices;
  34241. vertexData.positions = positions;
  34242. vertexData.normals = normals;
  34243. vertexData.uvs = uvs;
  34244. return vertexData;
  34245. };
  34246. VertexData.CreateGroundFromHeightMap = function (options) {
  34247. var indices = [];
  34248. var positions = [];
  34249. var normals = [];
  34250. var uvs = [];
  34251. var row, col;
  34252. // Vertices
  34253. for (row = 0; row <= options.subdivisions; row++) {
  34254. for (col = 0; col <= options.subdivisions; col++) {
  34255. 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));
  34256. // Compute height
  34257. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  34258. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  34259. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  34260. var r = options.buffer[pos] / 255.0;
  34261. var g = options.buffer[pos + 1] / 255.0;
  34262. var b = options.buffer[pos + 2] / 255.0;
  34263. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  34264. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  34265. // Add vertex
  34266. positions.push(position.x, position.y, position.z);
  34267. normals.push(0, 0, 0);
  34268. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  34269. }
  34270. }
  34271. // Indices
  34272. for (row = 0; row < options.subdivisions; row++) {
  34273. for (col = 0; col < options.subdivisions; col++) {
  34274. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  34275. indices.push(col + 1 + row * (options.subdivisions + 1));
  34276. indices.push(col + row * (options.subdivisions + 1));
  34277. indices.push(col + (row + 1) * (options.subdivisions + 1));
  34278. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  34279. indices.push(col + row * (options.subdivisions + 1));
  34280. }
  34281. }
  34282. // Normals
  34283. VertexData.ComputeNormals(positions, indices, normals);
  34284. // Result
  34285. var vertexData = new VertexData();
  34286. vertexData.indices = indices;
  34287. vertexData.positions = positions;
  34288. vertexData.normals = normals;
  34289. vertexData.uvs = uvs;
  34290. return vertexData;
  34291. };
  34292. VertexData.CreatePlane = function (options) {
  34293. var indices = [];
  34294. var positions = [];
  34295. var normals = [];
  34296. var uvs = [];
  34297. var width = options.width || options.size || 1;
  34298. var height = options.height || options.size || 1;
  34299. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  34300. // Vertices
  34301. var halfWidth = width / 2.0;
  34302. var halfHeight = height / 2.0;
  34303. positions.push(-halfWidth, -halfHeight, 0);
  34304. normals.push(0, 0, -1.0);
  34305. uvs.push(0.0, 0.0);
  34306. positions.push(halfWidth, -halfHeight, 0);
  34307. normals.push(0, 0, -1.0);
  34308. uvs.push(1.0, 0.0);
  34309. positions.push(halfWidth, halfHeight, 0);
  34310. normals.push(0, 0, -1.0);
  34311. uvs.push(1.0, 1.0);
  34312. positions.push(-halfWidth, halfHeight, 0);
  34313. normals.push(0, 0, -1.0);
  34314. uvs.push(0.0, 1.0);
  34315. // Indices
  34316. indices.push(0);
  34317. indices.push(1);
  34318. indices.push(2);
  34319. indices.push(0);
  34320. indices.push(2);
  34321. indices.push(3);
  34322. // Sides
  34323. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  34324. // Result
  34325. var vertexData = new VertexData();
  34326. vertexData.indices = indices;
  34327. vertexData.positions = positions;
  34328. vertexData.normals = normals;
  34329. vertexData.uvs = uvs;
  34330. return vertexData;
  34331. };
  34332. VertexData.CreateDisc = function (options) {
  34333. var positions = [];
  34334. var indices = [];
  34335. var normals = [];
  34336. var uvs = [];
  34337. var radius = options.radius || 0.5;
  34338. var tessellation = options.tessellation || 64;
  34339. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  34340. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  34341. // positions and uvs
  34342. positions.push(0, 0, 0); // disc center first
  34343. uvs.push(0.5, 0.5);
  34344. var theta = Math.PI * 2 * arc;
  34345. var step = theta / tessellation;
  34346. for (var a = 0; a < theta; a += step) {
  34347. var x = Math.cos(a);
  34348. var y = Math.sin(a);
  34349. var u = (x + 1) / 2;
  34350. var v = (1 - y) / 2;
  34351. positions.push(radius * x, radius * y, 0);
  34352. uvs.push(u, v);
  34353. }
  34354. if (arc === 1) {
  34355. positions.push(positions[3], positions[4], positions[5]); // close the circle
  34356. uvs.push(uvs[2], uvs[3]);
  34357. }
  34358. //indices
  34359. var vertexNb = positions.length / 3;
  34360. for (var i = 1; i < vertexNb - 1; i++) {
  34361. indices.push(i + 1, 0, i);
  34362. }
  34363. // result
  34364. VertexData.ComputeNormals(positions, indices, normals);
  34365. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  34366. var vertexData = new VertexData();
  34367. vertexData.indices = indices;
  34368. vertexData.positions = positions;
  34369. vertexData.normals = normals;
  34370. vertexData.uvs = uvs;
  34371. return vertexData;
  34372. };
  34373. VertexData.CreateIcoSphere = function (options) {
  34374. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  34375. var radius = options.radius || 1;
  34376. var flat = (options.flat === undefined) ? true : options.flat;
  34377. var subdivisions = options.subdivisions || 4;
  34378. var radiusX = options.radiusX || radius;
  34379. var radiusY = options.radiusY || radius;
  34380. var radiusZ = options.radiusZ || radius;
  34381. var t = (1 + Math.sqrt(5)) / 2;
  34382. // 12 vertex x,y,z
  34383. var ico_vertices = [
  34384. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  34385. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  34386. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  34387. ];
  34388. // index of 3 vertex makes a face of icopshere
  34389. var ico_indices = [
  34390. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  34391. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  34392. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  34393. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  34394. ];
  34395. // vertex for uv have aliased position, not for UV
  34396. var vertices_unalias_id = [
  34397. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  34398. // vertex alias
  34399. 0,
  34400. 2,
  34401. 3,
  34402. 3,
  34403. 3,
  34404. 4,
  34405. 7,
  34406. 8,
  34407. 9,
  34408. 9,
  34409. 10,
  34410. 11 // 23: B + 12
  34411. ];
  34412. // uv as integer step (not pixels !)
  34413. var ico_vertexuv = [
  34414. 5, 1, 3, 1, 6, 4, 0, 0,
  34415. 5, 3, 4, 2, 2, 2, 4, 0,
  34416. 2, 0, 1, 1, 6, 0, 6, 2,
  34417. // vertex alias (for same vertex on different faces)
  34418. 0, 4,
  34419. 3, 3,
  34420. 4, 4,
  34421. 3, 1,
  34422. 4, 2,
  34423. 4, 4,
  34424. 0, 2,
  34425. 1, 1,
  34426. 2, 2,
  34427. 3, 3,
  34428. 1, 3,
  34429. 2, 4 // 23: B + 12
  34430. ];
  34431. // Vertices[0, 1, ...9, A, B] : position on UV plane
  34432. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  34433. // First island of uv mapping
  34434. // v = 4h 3+ 2
  34435. // v = 3h 9+ 4
  34436. // v = 2h 9+ 5 B
  34437. // v = 1h 9 1 0
  34438. // v = 0h 3 8 7 A
  34439. // u = 0 1 2 3 4 5 6 *a
  34440. // Second island of uv mapping
  34441. // v = 4h 0+ B+ 4+
  34442. // v = 3h A+ 2+
  34443. // v = 2h 7+ 6 3+
  34444. // v = 1h 8+ 3+
  34445. // v = 0h
  34446. // u = 0 1 2 3 4 5 6 *a
  34447. // Face layout on texture UV mapping
  34448. // ============
  34449. // \ 4 /\ 16 / ======
  34450. // \ / \ / /\ 11 /
  34451. // \/ 7 \/ / \ /
  34452. // ======= / 10 \/
  34453. // /\ 17 /\ =======
  34454. // / \ / \ \ 15 /\
  34455. // / 8 \/ 12 \ \ / \
  34456. // ============ \/ 6 \
  34457. // \ 18 /\ ============
  34458. // \ / \ \ 5 /\ 0 /
  34459. // \/ 13 \ \ / \ /
  34460. // ======= \/ 1 \/
  34461. // =============
  34462. // /\ 19 /\ 2 /\
  34463. // / \ / \ / \
  34464. // / 14 \/ 9 \/ 3 \
  34465. // ===================
  34466. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  34467. var ustep = 138 / 1024;
  34468. var vstep = 239 / 1024;
  34469. var uoffset = 60 / 1024;
  34470. var voffset = 26 / 1024;
  34471. // Second island should have margin, not to touch the first island
  34472. // avoid any borderline artefact in pixel rounding
  34473. var island_u_offset = -40 / 1024;
  34474. var island_v_offset = +20 / 1024;
  34475. // face is either island 0 or 1 :
  34476. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  34477. var island = [
  34478. 0, 0, 0, 0, 1,
  34479. 0, 0, 1, 1, 0,
  34480. 0, 0, 1, 1, 0,
  34481. 0, 1, 1, 1, 0 // 15 - 19
  34482. ];
  34483. var indices = [];
  34484. var positions = [];
  34485. var normals = [];
  34486. var uvs = [];
  34487. var current_indice = 0;
  34488. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  34489. var face_vertex_pos = new Array(3);
  34490. var face_vertex_uv = new Array(3);
  34491. var v012;
  34492. for (v012 = 0; v012 < 3; v012++) {
  34493. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  34494. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  34495. }
  34496. // create all with normals
  34497. for (var face = 0; face < 20; face++) {
  34498. // 3 vertex per face
  34499. for (v012 = 0; v012 < 3; v012++) {
  34500. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  34501. var v_id = ico_indices[3 * face + v012];
  34502. // vertex have 3D position (x,y,z)
  34503. 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]);
  34504. // Normalize to get normal, then scale to radius
  34505. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  34506. // uv Coordinates from vertex ID
  34507. 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);
  34508. }
  34509. // Subdivide the face (interpolate pos, norm, uv)
  34510. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  34511. // - norm is linear interpolation of vertex corner normal
  34512. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  34513. // - uv is linear interpolation
  34514. //
  34515. // Topology is as below for sub-divide by 2
  34516. // vertex shown as v0,v1,v2
  34517. // interp index is i1 to progress in range [v0,v1[
  34518. // interp index is i2 to progress in range [v0,v2[
  34519. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  34520. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  34521. //
  34522. //
  34523. // i2 v2
  34524. // ^ ^
  34525. // / / \
  34526. // / / \
  34527. // / / \
  34528. // / / (0,1) \
  34529. // / #---------\
  34530. // / / \ (0,0)'/ \
  34531. // / / \ / \
  34532. // / / \ / \
  34533. // / / (0,0) \ / (1,0) \
  34534. // / #---------#---------\
  34535. // v0 v1
  34536. //
  34537. // --------------------> i1
  34538. //
  34539. // interp of (i1,i2):
  34540. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  34541. // along i1 : lerp(x0,x1, i1/(S-i2))
  34542. //
  34543. // centroid of triangle is needed to get help normal computation
  34544. // (c1,c2) are used for centroid location
  34545. var interp_vertex = function (i1, i2, c1, c2) {
  34546. // vertex is interpolated from
  34547. // - face_vertex_pos[0..2]
  34548. // - face_vertex_uv[0..2]
  34549. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  34550. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  34551. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  34552. pos_interp.normalize();
  34553. var vertex_normal;
  34554. if (flat) {
  34555. // in flat mode, recalculate normal as face centroid normal
  34556. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  34557. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  34558. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  34559. }
  34560. else {
  34561. // in smooth mode, recalculate normal from each single vertex position
  34562. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  34563. }
  34564. // Vertex normal need correction due to X,Y,Z radius scaling
  34565. vertex_normal.x /= radiusX;
  34566. vertex_normal.y /= radiusY;
  34567. vertex_normal.z /= radiusZ;
  34568. vertex_normal.normalize();
  34569. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  34570. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  34571. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  34572. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  34573. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  34574. uvs.push(uv_interp.x, uv_interp.y);
  34575. // push each vertex has member of a face
  34576. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  34577. indices.push(current_indice);
  34578. current_indice++;
  34579. };
  34580. for (var i2 = 0; i2 < subdivisions; i2++) {
  34581. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  34582. // face : (i1,i2) for /\ :
  34583. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  34584. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  34585. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  34586. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  34587. if (i1 + i2 + 1 < subdivisions) {
  34588. // face : (i1,i2)' for \/ :
  34589. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  34590. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  34591. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  34592. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  34593. }
  34594. }
  34595. }
  34596. }
  34597. // Sides
  34598. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  34599. // Result
  34600. var vertexData = new VertexData();
  34601. vertexData.indices = indices;
  34602. vertexData.positions = positions;
  34603. vertexData.normals = normals;
  34604. vertexData.uvs = uvs;
  34605. return vertexData;
  34606. };
  34607. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  34608. VertexData.CreatePolyhedron = function (options) {
  34609. // provided polyhedron types :
  34610. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  34611. // 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)
  34612. var polyhedra = [];
  34613. 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]] };
  34614. 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]] };
  34615. polyhedra[2] = {
  34616. 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]],
  34617. 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]]
  34618. };
  34619. polyhedra[3] = {
  34620. 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]],
  34621. 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]]
  34622. };
  34623. polyhedra[4] = {
  34624. 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]],
  34625. 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]]
  34626. };
  34627. 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]] };
  34628. 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]] };
  34629. 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]] };
  34630. 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]] };
  34631. 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]] };
  34632. 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]] };
  34633. 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]] };
  34634. 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]] };
  34635. 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]] };
  34636. polyhedra[14] = {
  34637. 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]],
  34638. 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]]
  34639. };
  34640. var type = (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  34641. var size = options.size;
  34642. var sizeX = options.sizeX || size || 1;
  34643. var sizeY = options.sizeY || size || 1;
  34644. var sizeZ = options.sizeZ || size || 1;
  34645. var data = options.custom || polyhedra[type];
  34646. var nbfaces = data.face.length;
  34647. var faceUV = options.faceUV || new Array(nbfaces);
  34648. var faceColors = options.faceColors;
  34649. var flat = (options.flat === undefined) ? true : options.flat;
  34650. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  34651. var positions = [];
  34652. var indices = [];
  34653. var normals = [];
  34654. var uvs = [];
  34655. var colors = [];
  34656. var index = 0;
  34657. var faceIdx = 0; // face cursor in the array "indexes"
  34658. var indexes = [];
  34659. var i = 0;
  34660. var f = 0;
  34661. var u, v, ang, x, y, tmp;
  34662. // default face colors and UV if undefined
  34663. if (flat) {
  34664. for (f = 0; f < nbfaces; f++) {
  34665. if (faceColors && faceColors[f] === undefined) {
  34666. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  34667. }
  34668. if (faceUV && faceUV[f] === undefined) {
  34669. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  34670. }
  34671. }
  34672. }
  34673. if (!flat) {
  34674. for (i = 0; i < data.vertex.length; i++) {
  34675. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  34676. uvs.push(0, 0);
  34677. }
  34678. for (f = 0; f < nbfaces; f++) {
  34679. for (i = 0; i < data.face[f].length - 2; i++) {
  34680. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  34681. }
  34682. }
  34683. }
  34684. else {
  34685. for (f = 0; f < nbfaces; f++) {
  34686. var fl = data.face[f].length; // number of vertices of the current face
  34687. ang = 2 * Math.PI / fl;
  34688. x = 0.5 * Math.tan(ang / 2);
  34689. y = 0.5;
  34690. // positions, uvs, colors
  34691. for (i = 0; i < fl; i++) {
  34692. // positions
  34693. 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);
  34694. indexes.push(index);
  34695. index++;
  34696. // uvs
  34697. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  34698. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  34699. uvs.push(u, v);
  34700. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  34701. y = x * Math.sin(ang) + y * Math.cos(ang);
  34702. x = tmp;
  34703. // colors
  34704. if (faceColors) {
  34705. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  34706. }
  34707. }
  34708. // indices from indexes
  34709. for (i = 0; i < fl - 2; i++) {
  34710. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  34711. }
  34712. faceIdx += fl;
  34713. }
  34714. }
  34715. VertexData.ComputeNormals(positions, indices, normals);
  34716. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  34717. var vertexData = new VertexData();
  34718. vertexData.positions = positions;
  34719. vertexData.indices = indices;
  34720. vertexData.normals = normals;
  34721. vertexData.uvs = uvs;
  34722. if (faceColors && flat) {
  34723. vertexData.colors = colors;
  34724. }
  34725. return vertexData;
  34726. };
  34727. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  34728. VertexData.CreateTorusKnot = function (options) {
  34729. var indices = [];
  34730. var positions = [];
  34731. var normals = [];
  34732. var uvs = [];
  34733. var radius = options.radius || 2;
  34734. var tube = options.tube || 0.5;
  34735. var radialSegments = options.radialSegments || 32;
  34736. var tubularSegments = options.tubularSegments || 32;
  34737. var p = options.p || 2;
  34738. var q = options.q || 3;
  34739. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  34740. // Helper
  34741. var getPos = function (angle) {
  34742. var cu = Math.cos(angle);
  34743. var su = Math.sin(angle);
  34744. var quOverP = q / p * angle;
  34745. var cs = Math.cos(quOverP);
  34746. var tx = radius * (2 + cs) * 0.5 * cu;
  34747. var ty = radius * (2 + cs) * su * 0.5;
  34748. var tz = radius * Math.sin(quOverP) * 0.5;
  34749. return new BABYLON.Vector3(tx, ty, tz);
  34750. };
  34751. // Vertices
  34752. var i;
  34753. var j;
  34754. for (i = 0; i <= radialSegments; i++) {
  34755. var modI = i % radialSegments;
  34756. var u = modI / radialSegments * 2 * p * Math.PI;
  34757. var p1 = getPos(u);
  34758. var p2 = getPos(u + 0.01);
  34759. var tang = p2.subtract(p1);
  34760. var n = p2.add(p1);
  34761. var bitan = BABYLON.Vector3.Cross(tang, n);
  34762. n = BABYLON.Vector3.Cross(bitan, tang);
  34763. bitan.normalize();
  34764. n.normalize();
  34765. for (j = 0; j < tubularSegments; j++) {
  34766. var modJ = j % tubularSegments;
  34767. var v = modJ / tubularSegments * 2 * Math.PI;
  34768. var cx = -tube * Math.cos(v);
  34769. var cy = tube * Math.sin(v);
  34770. positions.push(p1.x + cx * n.x + cy * bitan.x);
  34771. positions.push(p1.y + cx * n.y + cy * bitan.y);
  34772. positions.push(p1.z + cx * n.z + cy * bitan.z);
  34773. uvs.push(i / radialSegments);
  34774. uvs.push(j / tubularSegments);
  34775. }
  34776. }
  34777. for (i = 0; i < radialSegments; i++) {
  34778. for (j = 0; j < tubularSegments; j++) {
  34779. var jNext = (j + 1) % tubularSegments;
  34780. var a = i * tubularSegments + j;
  34781. var b = (i + 1) * tubularSegments + j;
  34782. var c = (i + 1) * tubularSegments + jNext;
  34783. var d = i * tubularSegments + jNext;
  34784. indices.push(d);
  34785. indices.push(b);
  34786. indices.push(a);
  34787. indices.push(d);
  34788. indices.push(c);
  34789. indices.push(b);
  34790. }
  34791. }
  34792. // Normals
  34793. VertexData.ComputeNormals(positions, indices, normals);
  34794. // Sides
  34795. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  34796. // Result
  34797. var vertexData = new VertexData();
  34798. vertexData.indices = indices;
  34799. vertexData.positions = positions;
  34800. vertexData.normals = normals;
  34801. vertexData.uvs = uvs;
  34802. return vertexData;
  34803. };
  34804. // Tools
  34805. /**
  34806. * @param {any} - positions (number[] or Float32Array)
  34807. * @param {any} - indices (number[] or Uint16Array)
  34808. * @param {any} - normals (number[] or Float32Array)
  34809. * options (optional) :
  34810. * facetPositions : optional array of facet positions (vector3)
  34811. * facetNormals : optional array of facet normals (vector3)
  34812. * facetPartitioning : optional partitioning array. facetPositions is required for facetPartitioning computation
  34813. * subDiv : optional partitioning data about subdivsions on each axis (int), required for facetPartitioning computation
  34814. * ratio : optional partitioning ratio / bounding box, required for facetPartitioning computation
  34815. * bbSize : optional bounding box size data, required for facetPartitioning computation
  34816. * bInfo : optional bounding info, required for facetPartitioning computation
  34817. */
  34818. VertexData.ComputeNormals = function (positions, indices, normals, options) {
  34819. // temporary scalar variables
  34820. var index = 0; // facet index
  34821. var p1p2x = 0.0; // p1p2 vector x coordinate
  34822. var p1p2y = 0.0; // p1p2 vector y coordinate
  34823. var p1p2z = 0.0; // p1p2 vector z coordinate
  34824. var p3p2x = 0.0; // p3p2 vector x coordinate
  34825. var p3p2y = 0.0; // p3p2 vector y coordinate
  34826. var p3p2z = 0.0; // p3p2 vector z coordinate
  34827. var faceNormalx = 0.0; // facet normal x coordinate
  34828. var faceNormaly = 0.0; // facet normal y coordinate
  34829. var faceNormalz = 0.0; // facet normal z coordinate
  34830. var length = 0.0; // facet normal length before normalization
  34831. var v1x = 0; // vector1 x index in the positions array
  34832. var v1y = 0; // vector1 y index in the positions array
  34833. var v1z = 0; // vector1 z index in the positions array
  34834. var v2x = 0; // vector2 x index in the positions array
  34835. var v2y = 0; // vector2 y index in the positions array
  34836. var v2z = 0; // vector2 z index in the positions array
  34837. var v3x = 0; // vector3 x index in the positions array
  34838. var v3y = 0; // vector3 y index in the positions array
  34839. var v3z = 0; // vector3 z index in the positions array
  34840. var computeFacetNormals = false;
  34841. var computeFacetPositions = false;
  34842. var computeFacetPartitioning = false;
  34843. if (options) {
  34844. computeFacetNormals = (options.facetNormals) ? true : false;
  34845. computeFacetPositions = (options.facetPositions) ? true : false;
  34846. computeFacetPartitioning = (options.facetPartitioning) ? true : false;
  34847. }
  34848. // facetPartitioning reinit if needed
  34849. if (computeFacetPartitioning) {
  34850. var ox = 0; // X partitioning index for facet position
  34851. var oy = 0; // Y partinioning index for facet position
  34852. var oz = 0; // Z partinioning index for facet position
  34853. var b1x = 0; // X partitioning index for facet v1 vertex
  34854. var b1y = 0; // Y partitioning index for facet v1 vertex
  34855. var b1z = 0; // z partitioning index for facet v1 vertex
  34856. var b2x = 0; // X partitioning index for facet v2 vertex
  34857. var b2y = 0; // Y partitioning index for facet v2 vertex
  34858. var b2z = 0; // Z partitioning index for facet v2 vertex
  34859. var b3x = 0; // X partitioning index for facet v3 vertex
  34860. var b3y = 0; // Y partitioning index for facet v3 vertex
  34861. var b3z = 0; // Z partitioning index for facet v3 vertex
  34862. var block_idx_o = 0; // facet barycenter block index
  34863. var block_idx_v1 = 0; // v1 vertex block index
  34864. var block_idx_v2 = 0; // v2 vertex block index
  34865. var block_idx_v3 = 0; // v3 vertex block index
  34866. var bbSizeMax = (options.bbSize.x > options.bbSize.y) ? options.bbSize.x : options.bbSize.y;
  34867. bbSizeMax = (bbSizeMax > options.bbSize.z) ? bbSizeMax : options.bbSize.z;
  34868. var xSubRatio = options.subDiv.X * options.ratio / options.bbSize.x;
  34869. var ySubRatio = options.subDiv.Y * options.ratio / options.bbSize.y;
  34870. var zSubRatio = options.subDiv.Z * options.ratio / options.bbSize.z;
  34871. var subSq = options.subDiv.max * options.subDiv.max;
  34872. options.facetPartitioning.length = 0;
  34873. }
  34874. // reset the normals
  34875. for (index = 0; index < positions.length; index++) {
  34876. normals[index] = 0.0;
  34877. }
  34878. // Loop : 1 indice triplet = 1 facet
  34879. var nbFaces = indices.length / 3;
  34880. for (index = 0; index < nbFaces; index++) {
  34881. // get the indexes of the coordinates of each vertex of the facet
  34882. v1x = indices[index * 3] * 3;
  34883. v1y = v1x + 1;
  34884. v1z = v1x + 2;
  34885. v2x = indices[index * 3 + 1] * 3;
  34886. v2y = v2x + 1;
  34887. v2z = v2x + 2;
  34888. v3x = indices[index * 3 + 2] * 3;
  34889. v3y = v3x + 1;
  34890. v3z = v3x + 2;
  34891. p1p2x = positions[v1x] - positions[v2x]; // compute two vectors per facet : p1p2 and p3p2
  34892. p1p2y = positions[v1y] - positions[v2y];
  34893. p1p2z = positions[v1z] - positions[v2z];
  34894. p3p2x = positions[v3x] - positions[v2x];
  34895. p3p2y = positions[v3y] - positions[v2y];
  34896. p3p2z = positions[v3z] - positions[v2z];
  34897. // compute the face normal with the cross product
  34898. faceNormalx = p1p2y * p3p2z - p1p2z * p3p2y;
  34899. faceNormaly = p1p2z * p3p2x - p1p2x * p3p2z;
  34900. faceNormalz = p1p2x * p3p2y - p1p2y * p3p2x;
  34901. // normalize this normal and store it in the array facetData
  34902. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  34903. length = (length === 0) ? 1.0 : length;
  34904. faceNormalx /= length;
  34905. faceNormaly /= length;
  34906. faceNormalz /= length;
  34907. if (computeFacetNormals) {
  34908. options.facetNormals[index].x = faceNormalx;
  34909. options.facetNormals[index].y = faceNormaly;
  34910. options.facetNormals[index].z = faceNormalz;
  34911. }
  34912. if (computeFacetPositions) {
  34913. // compute and the facet barycenter coordinates in the array facetPositions
  34914. options.facetPositions[index].x = (positions[v1x] + positions[v2x] + positions[v3x]) / 3.0;
  34915. options.facetPositions[index].y = (positions[v1y] + positions[v2y] + positions[v3y]) / 3.0;
  34916. options.facetPositions[index].z = (positions[v1z] + positions[v2z] + positions[v3z]) / 3.0;
  34917. }
  34918. if (computeFacetPartitioning) {
  34919. // store the facet indexes in arrays in the main facetPartitioning array :
  34920. // compute each facet vertex (+ facet barycenter) index in the partiniong array
  34921. ox = Math.floor((options.facetPositions[index].x - options.bInfo.minimum.x * options.ratio) * xSubRatio);
  34922. oy = Math.floor((options.facetPositions[index].y - options.bInfo.minimum.y * options.ratio) * ySubRatio);
  34923. oz = Math.floor((options.facetPositions[index].z - options.bInfo.minimum.z * options.ratio) * zSubRatio);
  34924. b1x = Math.floor((positions[v1x] - options.bInfo.minimum.x * options.ratio) * xSubRatio);
  34925. b1y = Math.floor((positions[v1y] - options.bInfo.minimum.y * options.ratio) * ySubRatio);
  34926. b1z = Math.floor((positions[v1z] - options.bInfo.minimum.z * options.ratio) * zSubRatio);
  34927. b2x = Math.floor((positions[v2x] - options.bInfo.minimum.x * options.ratio) * xSubRatio);
  34928. b2y = Math.floor((positions[v2y] - options.bInfo.minimum.y * options.ratio) * ySubRatio);
  34929. b2z = Math.floor((positions[v2z] - options.bInfo.minimum.z * options.ratio) * zSubRatio);
  34930. b3x = Math.floor((positions[v3x] - options.bInfo.minimum.x * options.ratio) * xSubRatio);
  34931. b3y = Math.floor((positions[v3y] - options.bInfo.minimum.y * options.ratio) * ySubRatio);
  34932. b3z = Math.floor((positions[v3z] - options.bInfo.minimum.z * options.ratio) * zSubRatio);
  34933. block_idx_v1 = b1x + options.subDiv.max * b1y + subSq * b1z;
  34934. block_idx_v2 = b2x + options.subDiv.max * b2y + subSq * b2z;
  34935. block_idx_v3 = b3x + options.subDiv.max * b3y + subSq * b3z;
  34936. block_idx_o = ox + options.subDiv.max * oy + subSq * oz;
  34937. options.facetPartitioning[block_idx_o] = options.facetPartitioning[block_idx_o] ? options.facetPartitioning[block_idx_o] : new Array();
  34938. options.facetPartitioning[block_idx_v1] = options.facetPartitioning[block_idx_v1] ? options.facetPartitioning[block_idx_v1] : new Array();
  34939. options.facetPartitioning[block_idx_v2] = options.facetPartitioning[block_idx_v2] ? options.facetPartitioning[block_idx_v2] : new Array();
  34940. options.facetPartitioning[block_idx_v3] = options.facetPartitioning[block_idx_v3] ? options.facetPartitioning[block_idx_v3] : new Array();
  34941. // push each facet index in each block containing the vertex
  34942. options.facetPartitioning[block_idx_v1].push(index);
  34943. if (block_idx_v2 != block_idx_v1) {
  34944. options.facetPartitioning[block_idx_v2].push(index);
  34945. }
  34946. if (!(block_idx_v3 == block_idx_v2 || block_idx_v3 == block_idx_v1)) {
  34947. options.facetPartitioning[block_idx_v3].push(index);
  34948. }
  34949. if (!(block_idx_o == block_idx_v1 || block_idx_o == block_idx_v2 || block_idx_o == block_idx_v3)) {
  34950. options.facetPartitioning[block_idx_o].push(index);
  34951. }
  34952. }
  34953. // compute the normals anyway
  34954. normals[v1x] += faceNormalx; // accumulate all the normals per face
  34955. normals[v1y] += faceNormaly;
  34956. normals[v1z] += faceNormalz;
  34957. normals[v2x] += faceNormalx;
  34958. normals[v2y] += faceNormaly;
  34959. normals[v2z] += faceNormalz;
  34960. normals[v3x] += faceNormalx;
  34961. normals[v3y] += faceNormaly;
  34962. normals[v3z] += faceNormalz;
  34963. }
  34964. // last normalization of each normal
  34965. for (index = 0; index < normals.length / 3; index++) {
  34966. faceNormalx = normals[index * 3];
  34967. faceNormaly = normals[index * 3 + 1];
  34968. faceNormalz = normals[index * 3 + 2];
  34969. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  34970. length = (length === 0) ? 1.0 : length;
  34971. faceNormalx /= length;
  34972. faceNormaly /= length;
  34973. faceNormalz /= length;
  34974. normals[index * 3] = faceNormalx;
  34975. normals[index * 3 + 1] = faceNormaly;
  34976. normals[index * 3 + 2] = faceNormalz;
  34977. }
  34978. };
  34979. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs) {
  34980. var li = indices.length;
  34981. var ln = normals.length;
  34982. var i;
  34983. var n;
  34984. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  34985. switch (sideOrientation) {
  34986. case BABYLON.Mesh.FRONTSIDE:
  34987. // nothing changed
  34988. break;
  34989. case BABYLON.Mesh.BACKSIDE:
  34990. var tmp;
  34991. // indices
  34992. for (i = 0; i < li; i += 3) {
  34993. tmp = indices[i];
  34994. indices[i] = indices[i + 2];
  34995. indices[i + 2] = tmp;
  34996. }
  34997. // normals
  34998. for (n = 0; n < ln; n++) {
  34999. normals[n] = -normals[n];
  35000. }
  35001. break;
  35002. case BABYLON.Mesh.DOUBLESIDE:
  35003. // positions
  35004. var lp = positions.length;
  35005. var l = lp / 3;
  35006. for (var p = 0; p < lp; p++) {
  35007. positions[lp + p] = positions[p];
  35008. }
  35009. // indices
  35010. for (i = 0; i < li; i += 3) {
  35011. indices[i + li] = indices[i + 2] + l;
  35012. indices[i + 1 + li] = indices[i + 1] + l;
  35013. indices[i + 2 + li] = indices[i] + l;
  35014. }
  35015. // normals
  35016. for (n = 0; n < ln; n++) {
  35017. normals[ln + n] = -normals[n];
  35018. }
  35019. // uvs
  35020. var lu = uvs.length;
  35021. for (var u = 0; u < lu; u++) {
  35022. uvs[u + lu] = uvs[u];
  35023. }
  35024. break;
  35025. }
  35026. };
  35027. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  35028. var vertexData = new VertexData();
  35029. // positions
  35030. var positions = parsedVertexData.positions;
  35031. if (positions) {
  35032. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  35033. }
  35034. // normals
  35035. var normals = parsedVertexData.normals;
  35036. if (normals) {
  35037. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  35038. }
  35039. // uvs
  35040. var uvs = parsedVertexData.uvs;
  35041. if (uvs) {
  35042. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  35043. }
  35044. // uv2s
  35045. var uv2s = parsedVertexData.uv2s;
  35046. if (uv2s) {
  35047. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  35048. }
  35049. // uv3s
  35050. var uv3s = parsedVertexData.uv3s;
  35051. if (uv3s) {
  35052. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  35053. }
  35054. // uv4s
  35055. var uv4s = parsedVertexData.uv4s;
  35056. if (uv4s) {
  35057. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  35058. }
  35059. // uv5s
  35060. var uv5s = parsedVertexData.uv5s;
  35061. if (uv5s) {
  35062. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  35063. }
  35064. // uv6s
  35065. var uv6s = parsedVertexData.uv6s;
  35066. if (uv6s) {
  35067. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  35068. }
  35069. // colors
  35070. var colors = parsedVertexData.colors;
  35071. if (colors) {
  35072. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  35073. }
  35074. // matricesIndices
  35075. var matricesIndices = parsedVertexData.matricesIndices;
  35076. if (matricesIndices) {
  35077. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  35078. }
  35079. // matricesWeights
  35080. var matricesWeights = parsedVertexData.matricesWeights;
  35081. if (matricesWeights) {
  35082. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  35083. }
  35084. // indices
  35085. var indices = parsedVertexData.indices;
  35086. if (indices) {
  35087. vertexData.indices = indices;
  35088. }
  35089. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  35090. };
  35091. return VertexData;
  35092. }());
  35093. BABYLON.VertexData = VertexData;
  35094. })(BABYLON || (BABYLON = {}));
  35095. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  35096. var BABYLON;
  35097. (function (BABYLON) {
  35098. var Tags = (function () {
  35099. function Tags() {
  35100. }
  35101. Tags.EnableFor = function (obj) {
  35102. obj._tags = obj._tags || {};
  35103. obj.hasTags = function () {
  35104. return Tags.HasTags(obj);
  35105. };
  35106. obj.addTags = function (tagsString) {
  35107. return Tags.AddTagsTo(obj, tagsString);
  35108. };
  35109. obj.removeTags = function (tagsString) {
  35110. return Tags.RemoveTagsFrom(obj, tagsString);
  35111. };
  35112. obj.matchesTagsQuery = function (tagsQuery) {
  35113. return Tags.MatchesQuery(obj, tagsQuery);
  35114. };
  35115. };
  35116. Tags.DisableFor = function (obj) {
  35117. delete obj._tags;
  35118. delete obj.hasTags;
  35119. delete obj.addTags;
  35120. delete obj.removeTags;
  35121. delete obj.matchesTagsQuery;
  35122. };
  35123. Tags.HasTags = function (obj) {
  35124. if (!obj._tags) {
  35125. return false;
  35126. }
  35127. return !BABYLON.Tools.IsEmpty(obj._tags);
  35128. };
  35129. Tags.GetTags = function (obj, asString) {
  35130. if (asString === void 0) { asString = true; }
  35131. if (!obj._tags) {
  35132. return null;
  35133. }
  35134. if (asString) {
  35135. var tagsArray = [];
  35136. for (var tag in obj._tags) {
  35137. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  35138. tagsArray.push(tag);
  35139. }
  35140. }
  35141. return tagsArray.join(" ");
  35142. }
  35143. else {
  35144. return obj._tags;
  35145. }
  35146. };
  35147. // the tags 'true' and 'false' are reserved and cannot be used as tags
  35148. // a tag cannot start with '||', '&&', and '!'
  35149. // it cannot contain whitespaces
  35150. Tags.AddTagsTo = function (obj, tagsString) {
  35151. if (!tagsString) {
  35152. return;
  35153. }
  35154. if (typeof tagsString !== "string") {
  35155. return;
  35156. }
  35157. var tags = tagsString.split(" ");
  35158. tags.forEach(function (tag, index, array) {
  35159. Tags._AddTagTo(obj, tag);
  35160. });
  35161. };
  35162. Tags._AddTagTo = function (obj, tag) {
  35163. tag = tag.trim();
  35164. if (tag === "" || tag === "true" || tag === "false") {
  35165. return;
  35166. }
  35167. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  35168. return;
  35169. }
  35170. Tags.EnableFor(obj);
  35171. obj._tags[tag] = true;
  35172. };
  35173. Tags.RemoveTagsFrom = function (obj, tagsString) {
  35174. if (!Tags.HasTags(obj)) {
  35175. return;
  35176. }
  35177. var tags = tagsString.split(" ");
  35178. for (var t in tags) {
  35179. Tags._RemoveTagFrom(obj, tags[t]);
  35180. }
  35181. };
  35182. Tags._RemoveTagFrom = function (obj, tag) {
  35183. delete obj._tags[tag];
  35184. };
  35185. Tags.MatchesQuery = function (obj, tagsQuery) {
  35186. if (tagsQuery === undefined) {
  35187. return true;
  35188. }
  35189. if (tagsQuery === "") {
  35190. return Tags.HasTags(obj);
  35191. }
  35192. return BABYLON.Internals.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  35193. };
  35194. return Tags;
  35195. }());
  35196. BABYLON.Tags = Tags;
  35197. })(BABYLON || (BABYLON = {}));
  35198. //# sourceMappingURL=babylon.tags.js.map
  35199. var BABYLON;
  35200. (function (BABYLON) {
  35201. var Internals;
  35202. (function (Internals) {
  35203. var AndOrNotEvaluator = (function () {
  35204. function AndOrNotEvaluator() {
  35205. }
  35206. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  35207. if (!query.match(/\([^\(\)]*\)/g)) {
  35208. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  35209. }
  35210. else {
  35211. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  35212. // remove parenthesis
  35213. r = r.slice(1, r.length - 1);
  35214. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  35215. });
  35216. }
  35217. if (query === "true") {
  35218. return true;
  35219. }
  35220. if (query === "false") {
  35221. return false;
  35222. }
  35223. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  35224. };
  35225. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  35226. evaluateCallback = evaluateCallback || (function (r) {
  35227. return r === "true" ? true : false;
  35228. });
  35229. var result;
  35230. var or = parenthesisContent.split("||");
  35231. for (var i in or) {
  35232. if (or.hasOwnProperty(i)) {
  35233. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  35234. var and = ori.split("&&");
  35235. if (and.length > 1) {
  35236. for (var j = 0; j < and.length; ++j) {
  35237. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  35238. if (andj !== "true" && andj !== "false") {
  35239. if (andj[0] === "!") {
  35240. result = !evaluateCallback(andj.substring(1));
  35241. }
  35242. else {
  35243. result = evaluateCallback(andj);
  35244. }
  35245. }
  35246. else {
  35247. result = andj === "true" ? true : false;
  35248. }
  35249. if (!result) {
  35250. ori = "false";
  35251. break;
  35252. }
  35253. }
  35254. }
  35255. if (result || ori === "true") {
  35256. result = true;
  35257. break;
  35258. }
  35259. // result equals false (or undefined)
  35260. if (ori !== "true" && ori !== "false") {
  35261. if (ori[0] === "!") {
  35262. result = !evaluateCallback(ori.substring(1));
  35263. }
  35264. else {
  35265. result = evaluateCallback(ori);
  35266. }
  35267. }
  35268. else {
  35269. result = ori === "true" ? true : false;
  35270. }
  35271. }
  35272. }
  35273. // the whole parenthesis scope is replaced by 'true' or 'false'
  35274. return result ? "true" : "false";
  35275. };
  35276. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  35277. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  35278. // remove whitespaces
  35279. r = r.replace(/[\s]/g, function () { return ""; });
  35280. return r.length % 2 ? "!" : "";
  35281. });
  35282. booleanString = booleanString.trim();
  35283. if (booleanString === "!true") {
  35284. booleanString = "false";
  35285. }
  35286. else if (booleanString === "!false") {
  35287. booleanString = "true";
  35288. }
  35289. return booleanString;
  35290. };
  35291. return AndOrNotEvaluator;
  35292. }());
  35293. Internals.AndOrNotEvaluator = AndOrNotEvaluator;
  35294. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  35295. })(BABYLON || (BABYLON = {}));
  35296. //# sourceMappingURL=babylon.andOrNotEvaluator.js.map
  35297. var BABYLON;
  35298. (function (BABYLON) {
  35299. var PostProcessRenderPass = (function () {
  35300. function PostProcessRenderPass(scene, name, size, renderList, beforeRender, afterRender) {
  35301. this._enabled = true;
  35302. this._refCount = 0;
  35303. this._name = name;
  35304. this._renderTexture = new BABYLON.RenderTargetTexture(name, size, scene);
  35305. this.setRenderList(renderList);
  35306. this._renderTexture.onBeforeRenderObservable.add(beforeRender);
  35307. this._renderTexture.onAfterRenderObservable.add(afterRender);
  35308. this._scene = scene;
  35309. this._renderList = renderList;
  35310. }
  35311. // private
  35312. PostProcessRenderPass.prototype._incRefCount = function () {
  35313. if (this._refCount === 0) {
  35314. this._scene.customRenderTargets.push(this._renderTexture);
  35315. }
  35316. return ++this._refCount;
  35317. };
  35318. PostProcessRenderPass.prototype._decRefCount = function () {
  35319. this._refCount--;
  35320. if (this._refCount <= 0) {
  35321. this._scene.customRenderTargets.splice(this._scene.customRenderTargets.indexOf(this._renderTexture), 1);
  35322. }
  35323. return this._refCount;
  35324. };
  35325. PostProcessRenderPass.prototype._update = function () {
  35326. this.setRenderList(this._renderList);
  35327. };
  35328. // public
  35329. PostProcessRenderPass.prototype.setRenderList = function (renderList) {
  35330. this._renderTexture.renderList = renderList;
  35331. };
  35332. PostProcessRenderPass.prototype.getRenderTexture = function () {
  35333. return this._renderTexture;
  35334. };
  35335. return PostProcessRenderPass;
  35336. }());
  35337. BABYLON.PostProcessRenderPass = PostProcessRenderPass;
  35338. })(BABYLON || (BABYLON = {}));
  35339. //# sourceMappingURL=babylon.postProcessRenderPass.js.map
  35340. var BABYLON;
  35341. (function (BABYLON) {
  35342. var PostProcessRenderEffect = (function () {
  35343. function PostProcessRenderEffect(engine, name, getPostProcess, singleInstance) {
  35344. this._engine = engine;
  35345. this._name = name;
  35346. this._singleInstance = singleInstance || true;
  35347. this._getPostProcess = getPostProcess;
  35348. this._cameras = [];
  35349. this._indicesForCamera = [];
  35350. this._postProcesses = {};
  35351. this._renderPasses = {};
  35352. this._renderEffectAsPasses = {};
  35353. }
  35354. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  35355. get: function () {
  35356. for (var index in this._postProcesses) {
  35357. if (!this._postProcesses[index].isSupported) {
  35358. return false;
  35359. }
  35360. }
  35361. return true;
  35362. },
  35363. enumerable: true,
  35364. configurable: true
  35365. });
  35366. PostProcessRenderEffect.prototype._update = function () {
  35367. for (var renderPassName in this._renderPasses) {
  35368. this._renderPasses[renderPassName]._update();
  35369. }
  35370. };
  35371. PostProcessRenderEffect.prototype.addPass = function (renderPass) {
  35372. this._renderPasses[renderPass._name] = renderPass;
  35373. this._linkParameters();
  35374. };
  35375. PostProcessRenderEffect.prototype.removePass = function (renderPass) {
  35376. delete this._renderPasses[renderPass._name];
  35377. this._linkParameters();
  35378. };
  35379. PostProcessRenderEffect.prototype.addRenderEffectAsPass = function (renderEffect) {
  35380. this._renderEffectAsPasses[renderEffect._name] = renderEffect;
  35381. this._linkParameters();
  35382. };
  35383. PostProcessRenderEffect.prototype.getPass = function (passName) {
  35384. for (var renderPassName in this._renderPasses) {
  35385. if (renderPassName === passName) {
  35386. return this._renderPasses[passName];
  35387. }
  35388. }
  35389. };
  35390. PostProcessRenderEffect.prototype.emptyPasses = function () {
  35391. this._renderPasses = {};
  35392. this._linkParameters();
  35393. };
  35394. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  35395. var cameraKey;
  35396. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  35397. for (var i = 0; i < _cam.length; i++) {
  35398. var camera = _cam[i];
  35399. var cameraName = camera.name;
  35400. if (this._singleInstance) {
  35401. cameraKey = 0;
  35402. }
  35403. else {
  35404. cameraKey = cameraName;
  35405. }
  35406. this._postProcesses[cameraKey] = this._postProcesses[cameraKey] || this._getPostProcess();
  35407. var index = camera.attachPostProcess(this._postProcesses[cameraKey]);
  35408. if (!this._indicesForCamera[cameraName]) {
  35409. this._indicesForCamera[cameraName] = [];
  35410. }
  35411. this._indicesForCamera[cameraName].push(index);
  35412. if (this._cameras.indexOf(camera) === -1) {
  35413. this._cameras[cameraName] = camera;
  35414. }
  35415. for (var passName in this._renderPasses) {
  35416. this._renderPasses[passName]._incRefCount();
  35417. }
  35418. }
  35419. this._linkParameters();
  35420. };
  35421. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  35422. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  35423. for (var i = 0; i < _cam.length; i++) {
  35424. var camera = _cam[i];
  35425. var cameraName = camera.name;
  35426. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  35427. var index = this._cameras.indexOf(cameraName);
  35428. this._indicesForCamera.splice(index, 1);
  35429. this._cameras.splice(index, 1);
  35430. for (var passName in this._renderPasses) {
  35431. this._renderPasses[passName]._decRefCount();
  35432. }
  35433. }
  35434. };
  35435. PostProcessRenderEffect.prototype._enable = function (cameras) {
  35436. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  35437. for (var i = 0; i < _cam.length; i++) {
  35438. var camera = _cam[i];
  35439. var cameraName = camera.name;
  35440. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  35441. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
  35442. cameras[i].attachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName][j]);
  35443. }
  35444. }
  35445. for (var passName in this._renderPasses) {
  35446. this._renderPasses[passName]._incRefCount();
  35447. }
  35448. }
  35449. };
  35450. PostProcessRenderEffect.prototype._disable = function (cameras) {
  35451. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  35452. for (var i = 0; i < _cam.length; i++) {
  35453. var camera = _cam[i];
  35454. var cameraName = camera.Name;
  35455. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  35456. for (var passName in this._renderPasses) {
  35457. this._renderPasses[passName]._decRefCount();
  35458. }
  35459. }
  35460. };
  35461. PostProcessRenderEffect.prototype.getPostProcess = function (camera) {
  35462. if (this._singleInstance) {
  35463. return this._postProcesses[0];
  35464. }
  35465. else {
  35466. return this._postProcesses[camera.name];
  35467. }
  35468. };
  35469. PostProcessRenderEffect.prototype._linkParameters = function () {
  35470. var _this = this;
  35471. for (var index in this._postProcesses) {
  35472. if (this.applyParameters) {
  35473. this.applyParameters(this._postProcesses[index]);
  35474. }
  35475. this._postProcesses[index].onBeforeRenderObservable.add(function (effect) {
  35476. _this._linkTextures(effect);
  35477. });
  35478. }
  35479. };
  35480. PostProcessRenderEffect.prototype._linkTextures = function (effect) {
  35481. for (var renderPassName in this._renderPasses) {
  35482. effect.setTexture(renderPassName, this._renderPasses[renderPassName].getRenderTexture());
  35483. }
  35484. for (var renderEffectName in this._renderEffectAsPasses) {
  35485. effect.setTextureFromPostProcess(renderEffectName + "Sampler", this._renderEffectAsPasses[renderEffectName].getPostProcess());
  35486. }
  35487. };
  35488. return PostProcessRenderEffect;
  35489. }());
  35490. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  35491. })(BABYLON || (BABYLON = {}));
  35492. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  35493. var BABYLON;
  35494. (function (BABYLON) {
  35495. var PostProcessRenderPipeline = (function () {
  35496. function PostProcessRenderPipeline(engine, name) {
  35497. this._engine = engine;
  35498. this._name = name;
  35499. this._renderEffects = {};
  35500. this._renderEffectsForIsolatedPass = {};
  35501. this._cameras = [];
  35502. }
  35503. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  35504. get: function () {
  35505. for (var renderEffectName in this._renderEffects) {
  35506. if (!this._renderEffects[renderEffectName].isSupported) {
  35507. return false;
  35508. }
  35509. }
  35510. return true;
  35511. },
  35512. enumerable: true,
  35513. configurable: true
  35514. });
  35515. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  35516. this._renderEffects[renderEffect._name] = renderEffect;
  35517. };
  35518. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  35519. var renderEffects = this._renderEffects[renderEffectName];
  35520. if (!renderEffects) {
  35521. return;
  35522. }
  35523. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  35524. };
  35525. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  35526. var renderEffects = this._renderEffects[renderEffectName];
  35527. if (!renderEffects) {
  35528. return;
  35529. }
  35530. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  35531. };
  35532. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  35533. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  35534. var indicesToDelete = [];
  35535. var i;
  35536. for (i = 0; i < _cam.length; i++) {
  35537. var camera = _cam[i];
  35538. var cameraName = camera.name;
  35539. if (this._cameras.indexOf(camera) === -1) {
  35540. this._cameras[cameraName] = camera;
  35541. }
  35542. else if (unique) {
  35543. indicesToDelete.push(i);
  35544. }
  35545. }
  35546. for (i = 0; i < indicesToDelete.length; i++) {
  35547. cameras.splice(indicesToDelete[i], 1);
  35548. }
  35549. for (var renderEffectName in this._renderEffects) {
  35550. this._renderEffects[renderEffectName]._attachCameras(_cam);
  35551. }
  35552. };
  35553. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  35554. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  35555. for (var renderEffectName in this._renderEffects) {
  35556. this._renderEffects[renderEffectName]._detachCameras(_cam);
  35557. }
  35558. for (var i = 0; i < _cam.length; i++) {
  35559. this._cameras.splice(this._cameras.indexOf(_cam[i]), 1);
  35560. }
  35561. };
  35562. PostProcessRenderPipeline.prototype._enableDisplayOnlyPass = function (passName, cameras) {
  35563. var _this = this;
  35564. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  35565. var pass = null;
  35566. var renderEffectName;
  35567. for (renderEffectName in this._renderEffects) {
  35568. pass = this._renderEffects[renderEffectName].getPass(passName);
  35569. if (pass != null) {
  35570. break;
  35571. }
  35572. }
  35573. if (pass === null) {
  35574. return;
  35575. }
  35576. for (renderEffectName in this._renderEffects) {
  35577. this._renderEffects[renderEffectName]._disable(_cam);
  35578. }
  35579. pass._name = PostProcessRenderPipeline.PASS_SAMPLER_NAME;
  35580. for (var i = 0; i < _cam.length; i++) {
  35581. var camera = _cam[i];
  35582. var cameraName = camera.name;
  35583. 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); });
  35584. this._renderEffectsForIsolatedPass[cameraName].emptyPasses();
  35585. this._renderEffectsForIsolatedPass[cameraName].addPass(pass);
  35586. this._renderEffectsForIsolatedPass[cameraName]._attachCameras(camera);
  35587. }
  35588. };
  35589. PostProcessRenderPipeline.prototype._disableDisplayOnlyPass = function (cameras) {
  35590. var _this = this;
  35591. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  35592. for (var i = 0; i < _cam.length; i++) {
  35593. var camera = _cam[i];
  35594. var cameraName = camera.name;
  35595. 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); });
  35596. this._renderEffectsForIsolatedPass[cameraName]._disable(camera);
  35597. }
  35598. for (var renderEffectName in this._renderEffects) {
  35599. this._renderEffects[renderEffectName]._enable(_cam);
  35600. }
  35601. };
  35602. PostProcessRenderPipeline.prototype._update = function () {
  35603. for (var renderEffectName in this._renderEffects) {
  35604. this._renderEffects[renderEffectName]._update();
  35605. }
  35606. for (var i = 0; i < this._cameras.length; i++) {
  35607. var cameraName = this._cameras[i].name;
  35608. if (this._renderEffectsForIsolatedPass[cameraName]) {
  35609. this._renderEffectsForIsolatedPass[cameraName]._update();
  35610. }
  35611. }
  35612. };
  35613. PostProcessRenderPipeline.prototype.dispose = function () {
  35614. // Must be implemented by children
  35615. };
  35616. return PostProcessRenderPipeline;
  35617. }());
  35618. PostProcessRenderPipeline.PASS_EFFECT_NAME = "passEffect";
  35619. PostProcessRenderPipeline.PASS_SAMPLER_NAME = "passSampler";
  35620. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  35621. })(BABYLON || (BABYLON = {}));
  35622. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  35623. var BABYLON;
  35624. (function (BABYLON) {
  35625. var PostProcessRenderPipelineManager = (function () {
  35626. function PostProcessRenderPipelineManager() {
  35627. this._renderPipelines = {};
  35628. }
  35629. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  35630. this._renderPipelines[renderPipeline._name] = renderPipeline;
  35631. };
  35632. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  35633. var renderPipeline = this._renderPipelines[renderPipelineName];
  35634. if (!renderPipeline) {
  35635. return;
  35636. }
  35637. renderPipeline._attachCameras(cameras, unique);
  35638. };
  35639. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  35640. var renderPipeline = this._renderPipelines[renderPipelineName];
  35641. if (!renderPipeline) {
  35642. return;
  35643. }
  35644. renderPipeline._detachCameras(cameras);
  35645. };
  35646. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  35647. var renderPipeline = this._renderPipelines[renderPipelineName];
  35648. if (!renderPipeline) {
  35649. return;
  35650. }
  35651. renderPipeline._enableEffect(renderEffectName, cameras);
  35652. };
  35653. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  35654. var renderPipeline = this._renderPipelines[renderPipelineName];
  35655. if (!renderPipeline) {
  35656. return;
  35657. }
  35658. renderPipeline._disableEffect(renderEffectName, cameras);
  35659. };
  35660. PostProcessRenderPipelineManager.prototype.enableDisplayOnlyPassInPipeline = function (renderPipelineName, passName, cameras) {
  35661. var renderPipeline = this._renderPipelines[renderPipelineName];
  35662. if (!renderPipeline) {
  35663. return;
  35664. }
  35665. renderPipeline._enableDisplayOnlyPass(passName, cameras);
  35666. };
  35667. PostProcessRenderPipelineManager.prototype.disableDisplayOnlyPassInPipeline = function (renderPipelineName, cameras) {
  35668. var renderPipeline = this._renderPipelines[renderPipelineName];
  35669. if (!renderPipeline) {
  35670. return;
  35671. }
  35672. renderPipeline._disableDisplayOnlyPass(cameras);
  35673. };
  35674. PostProcessRenderPipelineManager.prototype.update = function () {
  35675. for (var renderPipelineName in this._renderPipelines) {
  35676. var pipeline = this._renderPipelines[renderPipelineName];
  35677. if (!pipeline.isSupported) {
  35678. pipeline.dispose();
  35679. delete this._renderPipelines[renderPipelineName];
  35680. }
  35681. else {
  35682. pipeline._update();
  35683. }
  35684. }
  35685. };
  35686. return PostProcessRenderPipelineManager;
  35687. }());
  35688. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  35689. })(BABYLON || (BABYLON = {}));
  35690. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  35691. var BABYLON;
  35692. (function (BABYLON) {
  35693. var BoundingBoxRenderer = (function () {
  35694. function BoundingBoxRenderer(scene) {
  35695. this.frontColor = new BABYLON.Color3(1, 1, 1);
  35696. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  35697. this.showBackLines = true;
  35698. this.renderList = new BABYLON.SmartArray(32);
  35699. this._vertexBuffers = {};
  35700. this._scene = scene;
  35701. }
  35702. BoundingBoxRenderer.prototype._prepareRessources = function () {
  35703. if (this._colorShader) {
  35704. return;
  35705. }
  35706. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  35707. attributes: [BABYLON.VertexBuffer.PositionKind],
  35708. uniforms: ["worldViewProjection", "color"]
  35709. });
  35710. var engine = this._scene.getEngine();
  35711. var boxdata = BABYLON.VertexData.CreateBox(1.0);
  35712. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  35713. 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]);
  35714. };
  35715. BoundingBoxRenderer.prototype.reset = function () {
  35716. this.renderList.reset();
  35717. };
  35718. BoundingBoxRenderer.prototype.render = function () {
  35719. if (this.renderList.length === 0) {
  35720. return;
  35721. }
  35722. this._prepareRessources();
  35723. if (!this._colorShader.isReady()) {
  35724. return;
  35725. }
  35726. var engine = this._scene.getEngine();
  35727. engine.setDepthWrite(false);
  35728. this._colorShader._preBind();
  35729. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  35730. var boundingBox = this.renderList.data[boundingBoxIndex];
  35731. var min = boundingBox.minimum;
  35732. var max = boundingBox.maximum;
  35733. var diff = max.subtract(min);
  35734. var median = min.add(diff.scale(0.5));
  35735. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  35736. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  35737. .multiply(boundingBox.getWorldMatrix());
  35738. // VBOs
  35739. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  35740. if (this.showBackLines) {
  35741. // Back
  35742. engine.setDepthFunctionToGreaterOrEqual();
  35743. this._scene.resetCachedMaterial();
  35744. this._colorShader.setColor4("color", this.backColor.toColor4());
  35745. this._colorShader.bind(worldMatrix);
  35746. // Draw order
  35747. engine.draw(false, 0, 24);
  35748. }
  35749. // Front
  35750. engine.setDepthFunctionToLess();
  35751. this._scene.resetCachedMaterial();
  35752. this._colorShader.setColor4("color", this.frontColor.toColor4());
  35753. this._colorShader.bind(worldMatrix);
  35754. // Draw order
  35755. engine.draw(false, 0, 24);
  35756. }
  35757. this._colorShader.unbind();
  35758. engine.setDepthFunctionToLessOrEqual();
  35759. engine.setDepthWrite(true);
  35760. };
  35761. BoundingBoxRenderer.prototype.dispose = function () {
  35762. if (!this._colorShader) {
  35763. return;
  35764. }
  35765. this._colorShader.dispose();
  35766. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  35767. if (buffer) {
  35768. buffer.dispose();
  35769. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  35770. }
  35771. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  35772. };
  35773. return BoundingBoxRenderer;
  35774. }());
  35775. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  35776. })(BABYLON || (BABYLON = {}));
  35777. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  35778. var BABYLON;
  35779. (function (BABYLON) {
  35780. var Condition = (function () {
  35781. function Condition(actionManager) {
  35782. this._actionManager = actionManager;
  35783. }
  35784. Condition.prototype.isValid = function () {
  35785. return true;
  35786. };
  35787. Condition.prototype._getProperty = function (propertyPath) {
  35788. return this._actionManager._getProperty(propertyPath);
  35789. };
  35790. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  35791. return this._actionManager._getEffectiveTarget(target, propertyPath);
  35792. };
  35793. Condition.prototype.serialize = function () {
  35794. };
  35795. Condition.prototype._serialize = function (serializedCondition) {
  35796. return {
  35797. type: 2,
  35798. children: [],
  35799. name: serializedCondition.name,
  35800. properties: serializedCondition.properties
  35801. };
  35802. };
  35803. return Condition;
  35804. }());
  35805. BABYLON.Condition = Condition;
  35806. var ValueCondition = (function (_super) {
  35807. __extends(ValueCondition, _super);
  35808. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  35809. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  35810. var _this = _super.call(this, actionManager) || this;
  35811. _this.propertyPath = propertyPath;
  35812. _this.value = value;
  35813. _this.operator = operator;
  35814. _this._target = target;
  35815. _this._effectiveTarget = _this._getEffectiveTarget(target, _this.propertyPath);
  35816. _this._property = _this._getProperty(_this.propertyPath);
  35817. return _this;
  35818. }
  35819. Object.defineProperty(ValueCondition, "IsEqual", {
  35820. get: function () {
  35821. return ValueCondition._IsEqual;
  35822. },
  35823. enumerable: true,
  35824. configurable: true
  35825. });
  35826. Object.defineProperty(ValueCondition, "IsDifferent", {
  35827. get: function () {
  35828. return ValueCondition._IsDifferent;
  35829. },
  35830. enumerable: true,
  35831. configurable: true
  35832. });
  35833. Object.defineProperty(ValueCondition, "IsGreater", {
  35834. get: function () {
  35835. return ValueCondition._IsGreater;
  35836. },
  35837. enumerable: true,
  35838. configurable: true
  35839. });
  35840. Object.defineProperty(ValueCondition, "IsLesser", {
  35841. get: function () {
  35842. return ValueCondition._IsLesser;
  35843. },
  35844. enumerable: true,
  35845. configurable: true
  35846. });
  35847. // Methods
  35848. ValueCondition.prototype.isValid = function () {
  35849. switch (this.operator) {
  35850. case ValueCondition.IsGreater:
  35851. return this._effectiveTarget[this._property] > this.value;
  35852. case ValueCondition.IsLesser:
  35853. return this._effectiveTarget[this._property] < this.value;
  35854. case ValueCondition.IsEqual:
  35855. case ValueCondition.IsDifferent:
  35856. var check;
  35857. if (this.value.equals) {
  35858. check = this.value.equals(this._effectiveTarget[this._property]);
  35859. }
  35860. else {
  35861. check = this.value === this._effectiveTarget[this._property];
  35862. }
  35863. return this.operator === ValueCondition.IsEqual ? check : !check;
  35864. }
  35865. return false;
  35866. };
  35867. ValueCondition.prototype.serialize = function () {
  35868. return this._serialize({
  35869. name: "ValueCondition",
  35870. properties: [
  35871. BABYLON.Action._GetTargetProperty(this._target),
  35872. { name: "propertyPath", value: this.propertyPath },
  35873. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  35874. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  35875. ]
  35876. });
  35877. };
  35878. ValueCondition.GetOperatorName = function (operator) {
  35879. switch (operator) {
  35880. case ValueCondition._IsEqual: return "IsEqual";
  35881. case ValueCondition._IsDifferent: return "IsDifferent";
  35882. case ValueCondition._IsGreater: return "IsGreater";
  35883. case ValueCondition._IsLesser: return "IsLesser";
  35884. default: return "";
  35885. }
  35886. };
  35887. return ValueCondition;
  35888. }(Condition));
  35889. // Statics
  35890. ValueCondition._IsEqual = 0;
  35891. ValueCondition._IsDifferent = 1;
  35892. ValueCondition._IsGreater = 2;
  35893. ValueCondition._IsLesser = 3;
  35894. BABYLON.ValueCondition = ValueCondition;
  35895. var PredicateCondition = (function (_super) {
  35896. __extends(PredicateCondition, _super);
  35897. function PredicateCondition(actionManager, predicate) {
  35898. var _this = _super.call(this, actionManager) || this;
  35899. _this.predicate = predicate;
  35900. return _this;
  35901. }
  35902. PredicateCondition.prototype.isValid = function () {
  35903. return this.predicate();
  35904. };
  35905. return PredicateCondition;
  35906. }(Condition));
  35907. BABYLON.PredicateCondition = PredicateCondition;
  35908. var StateCondition = (function (_super) {
  35909. __extends(StateCondition, _super);
  35910. function StateCondition(actionManager, target, value) {
  35911. var _this = _super.call(this, actionManager) || this;
  35912. _this.value = value;
  35913. _this._target = target;
  35914. return _this;
  35915. }
  35916. // Methods
  35917. StateCondition.prototype.isValid = function () {
  35918. return this._target.state === this.value;
  35919. };
  35920. StateCondition.prototype.serialize = function () {
  35921. return this._serialize({
  35922. name: "StateCondition",
  35923. properties: [
  35924. BABYLON.Action._GetTargetProperty(this._target),
  35925. { name: "value", value: this.value }
  35926. ]
  35927. });
  35928. };
  35929. return StateCondition;
  35930. }(Condition));
  35931. BABYLON.StateCondition = StateCondition;
  35932. })(BABYLON || (BABYLON = {}));
  35933. //# sourceMappingURL=babylon.condition.js.map
  35934. var BABYLON;
  35935. (function (BABYLON) {
  35936. var Action = (function () {
  35937. function Action(triggerOptions, condition) {
  35938. this.triggerOptions = triggerOptions;
  35939. if (triggerOptions.parameter) {
  35940. this.trigger = triggerOptions.trigger;
  35941. this._triggerParameter = triggerOptions.parameter;
  35942. }
  35943. else {
  35944. this.trigger = triggerOptions;
  35945. }
  35946. this._nextActiveAction = this;
  35947. this._condition = condition;
  35948. }
  35949. // Methods
  35950. Action.prototype._prepare = function () {
  35951. };
  35952. Action.prototype.getTriggerParameter = function () {
  35953. return this._triggerParameter;
  35954. };
  35955. Action.prototype._executeCurrent = function (evt) {
  35956. if (this._nextActiveAction._condition) {
  35957. var condition = this._nextActiveAction._condition;
  35958. var currentRenderId = this._actionManager.getScene().getRenderId();
  35959. // We cache the current evaluation for the current frame
  35960. if (condition._evaluationId === currentRenderId) {
  35961. if (!condition._currentResult) {
  35962. return;
  35963. }
  35964. }
  35965. else {
  35966. condition._evaluationId = currentRenderId;
  35967. if (!condition.isValid()) {
  35968. condition._currentResult = false;
  35969. return;
  35970. }
  35971. condition._currentResult = true;
  35972. }
  35973. }
  35974. this._nextActiveAction.execute(evt);
  35975. this.skipToNextActiveAction();
  35976. };
  35977. Action.prototype.execute = function (evt) {
  35978. };
  35979. Action.prototype.skipToNextActiveAction = function () {
  35980. if (this._nextActiveAction._child) {
  35981. if (!this._nextActiveAction._child._actionManager) {
  35982. this._nextActiveAction._child._actionManager = this._actionManager;
  35983. }
  35984. this._nextActiveAction = this._nextActiveAction._child;
  35985. }
  35986. else {
  35987. this._nextActiveAction = this;
  35988. }
  35989. };
  35990. Action.prototype.then = function (action) {
  35991. this._child = action;
  35992. action._actionManager = this._actionManager;
  35993. action._prepare();
  35994. return action;
  35995. };
  35996. Action.prototype._getProperty = function (propertyPath) {
  35997. return this._actionManager._getProperty(propertyPath);
  35998. };
  35999. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  36000. return this._actionManager._getEffectiveTarget(target, propertyPath);
  36001. };
  36002. Action.prototype.serialize = function (parent) {
  36003. };
  36004. // Called by BABYLON.Action objects in serialize(...). Internal use
  36005. Action.prototype._serialize = function (serializedAction, parent) {
  36006. var serializationObject = {
  36007. type: 1,
  36008. children: [],
  36009. name: serializedAction.name,
  36010. properties: serializedAction.properties || []
  36011. };
  36012. // Serialize child
  36013. if (this._child) {
  36014. this._child.serialize(serializationObject);
  36015. }
  36016. // Check if "this" has a condition
  36017. if (this._condition) {
  36018. var serializedCondition = this._condition.serialize();
  36019. serializedCondition.children.push(serializationObject);
  36020. if (parent) {
  36021. parent.children.push(serializedCondition);
  36022. }
  36023. return serializedCondition;
  36024. }
  36025. if (parent) {
  36026. parent.children.push(serializationObject);
  36027. }
  36028. return serializationObject;
  36029. };
  36030. return Action;
  36031. }());
  36032. Action._SerializeValueAsString = function (value) {
  36033. if (typeof value === "number") {
  36034. return value.toString();
  36035. }
  36036. if (typeof value === "boolean") {
  36037. return value ? "true" : "false";
  36038. }
  36039. if (value instanceof BABYLON.Vector2) {
  36040. return value.x + ", " + value.y;
  36041. }
  36042. if (value instanceof BABYLON.Vector3) {
  36043. return value.x + ", " + value.y + ", " + value.z;
  36044. }
  36045. if (value instanceof BABYLON.Color3) {
  36046. return value.r + ", " + value.g + ", " + value.b;
  36047. }
  36048. if (value instanceof BABYLON.Color4) {
  36049. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  36050. }
  36051. return value; // string
  36052. };
  36053. Action._GetTargetProperty = function (target) {
  36054. return {
  36055. name: "target",
  36056. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  36057. : target instanceof BABYLON.Light ? "LightProperties"
  36058. : target instanceof BABYLON.Camera ? "CameraProperties"
  36059. : "SceneProperties",
  36060. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  36061. };
  36062. };
  36063. BABYLON.Action = Action;
  36064. })(BABYLON || (BABYLON = {}));
  36065. //# sourceMappingURL=babylon.action.js.map
  36066. var BABYLON;
  36067. (function (BABYLON) {
  36068. /**
  36069. * ActionEvent is the event beint sent when an action is triggered.
  36070. */
  36071. var ActionEvent = (function () {
  36072. /**
  36073. * @constructor
  36074. * @param source The mesh or sprite that triggered the action.
  36075. * @param pointerX The X mouse cursor position at the time of the event
  36076. * @param pointerY The Y mouse cursor position at the time of the event
  36077. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  36078. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  36079. */
  36080. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent, additionalData) {
  36081. this.source = source;
  36082. this.pointerX = pointerX;
  36083. this.pointerY = pointerY;
  36084. this.meshUnderPointer = meshUnderPointer;
  36085. this.sourceEvent = sourceEvent;
  36086. this.additionalData = additionalData;
  36087. }
  36088. /**
  36089. * Helper function to auto-create an ActionEvent from a source mesh.
  36090. * @param source The source mesh that triggered the event
  36091. * @param evt {Event} The original (browser) event
  36092. */
  36093. ActionEvent.CreateNew = function (source, evt, additionalData) {
  36094. var scene = source.getScene();
  36095. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  36096. };
  36097. /**
  36098. * Helper function to auto-create an ActionEvent from a source mesh.
  36099. * @param source The source sprite that triggered the event
  36100. * @param scene Scene associated with the sprite
  36101. * @param evt {Event} The original (browser) event
  36102. */
  36103. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  36104. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  36105. };
  36106. /**
  36107. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  36108. * @param scene the scene where the event occurred
  36109. * @param evt {Event} The original (browser) event
  36110. */
  36111. ActionEvent.CreateNewFromScene = function (scene, evt) {
  36112. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  36113. };
  36114. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  36115. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  36116. };
  36117. return ActionEvent;
  36118. }());
  36119. BABYLON.ActionEvent = ActionEvent;
  36120. /**
  36121. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  36122. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  36123. */
  36124. var ActionManager = (function () {
  36125. function ActionManager(scene) {
  36126. // Members
  36127. this.actions = new Array();
  36128. this.hoverCursor = '';
  36129. this._scene = scene;
  36130. scene._actionManagers.push(this);
  36131. }
  36132. Object.defineProperty(ActionManager, "NothingTrigger", {
  36133. get: function () {
  36134. return ActionManager._NothingTrigger;
  36135. },
  36136. enumerable: true,
  36137. configurable: true
  36138. });
  36139. Object.defineProperty(ActionManager, "OnPickTrigger", {
  36140. get: function () {
  36141. return ActionManager._OnPickTrigger;
  36142. },
  36143. enumerable: true,
  36144. configurable: true
  36145. });
  36146. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  36147. get: function () {
  36148. return ActionManager._OnLeftPickTrigger;
  36149. },
  36150. enumerable: true,
  36151. configurable: true
  36152. });
  36153. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  36154. get: function () {
  36155. return ActionManager._OnRightPickTrigger;
  36156. },
  36157. enumerable: true,
  36158. configurable: true
  36159. });
  36160. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  36161. get: function () {
  36162. return ActionManager._OnCenterPickTrigger;
  36163. },
  36164. enumerable: true,
  36165. configurable: true
  36166. });
  36167. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  36168. get: function () {
  36169. return ActionManager._OnPickDownTrigger;
  36170. },
  36171. enumerable: true,
  36172. configurable: true
  36173. });
  36174. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  36175. get: function () {
  36176. return ActionManager._OnPickUpTrigger;
  36177. },
  36178. enumerable: true,
  36179. configurable: true
  36180. });
  36181. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  36182. /// This trigger will only be raised if you also declared a OnPickDown
  36183. get: function () {
  36184. return ActionManager._OnPickOutTrigger;
  36185. },
  36186. enumerable: true,
  36187. configurable: true
  36188. });
  36189. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  36190. get: function () {
  36191. return ActionManager._OnLongPressTrigger;
  36192. },
  36193. enumerable: true,
  36194. configurable: true
  36195. });
  36196. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  36197. get: function () {
  36198. return ActionManager._OnPointerOverTrigger;
  36199. },
  36200. enumerable: true,
  36201. configurable: true
  36202. });
  36203. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  36204. get: function () {
  36205. return ActionManager._OnPointerOutTrigger;
  36206. },
  36207. enumerable: true,
  36208. configurable: true
  36209. });
  36210. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  36211. get: function () {
  36212. return ActionManager._OnEveryFrameTrigger;
  36213. },
  36214. enumerable: true,
  36215. configurable: true
  36216. });
  36217. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  36218. get: function () {
  36219. return ActionManager._OnIntersectionEnterTrigger;
  36220. },
  36221. enumerable: true,
  36222. configurable: true
  36223. });
  36224. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  36225. get: function () {
  36226. return ActionManager._OnIntersectionExitTrigger;
  36227. },
  36228. enumerable: true,
  36229. configurable: true
  36230. });
  36231. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  36232. get: function () {
  36233. return ActionManager._OnKeyDownTrigger;
  36234. },
  36235. enumerable: true,
  36236. configurable: true
  36237. });
  36238. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  36239. get: function () {
  36240. return ActionManager._OnKeyUpTrigger;
  36241. },
  36242. enumerable: true,
  36243. configurable: true
  36244. });
  36245. // Methods
  36246. ActionManager.prototype.dispose = function () {
  36247. var index = this._scene._actionManagers.indexOf(this);
  36248. if (index > -1) {
  36249. this._scene._actionManagers.splice(index, 1);
  36250. }
  36251. };
  36252. ActionManager.prototype.getScene = function () {
  36253. return this._scene;
  36254. };
  36255. /**
  36256. * Does this action manager handles actions of any of the given triggers
  36257. * @param {number[]} triggers - the triggers to be tested
  36258. * @return {boolean} whether one (or more) of the triggers is handeled
  36259. */
  36260. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  36261. for (var index = 0; index < this.actions.length; index++) {
  36262. var action = this.actions[index];
  36263. if (triggers.indexOf(action.trigger) > -1) {
  36264. return true;
  36265. }
  36266. }
  36267. return false;
  36268. };
  36269. /**
  36270. * Does this action manager handles actions of a given trigger
  36271. * @param {number} trigger - the trigger to be tested
  36272. * @return {boolean} whether the trigger is handeled
  36273. */
  36274. ActionManager.prototype.hasSpecificTrigger = function (trigger) {
  36275. for (var index = 0; index < this.actions.length; index++) {
  36276. var action = this.actions[index];
  36277. if (action.trigger === trigger) {
  36278. return true;
  36279. }
  36280. }
  36281. return false;
  36282. };
  36283. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  36284. /**
  36285. * Does this action manager has pointer triggers
  36286. * @return {boolean} whether or not it has pointer triggers
  36287. */
  36288. get: function () {
  36289. for (var index = 0; index < this.actions.length; index++) {
  36290. var action = this.actions[index];
  36291. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  36292. return true;
  36293. }
  36294. }
  36295. return false;
  36296. },
  36297. enumerable: true,
  36298. configurable: true
  36299. });
  36300. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  36301. /**
  36302. * Does this action manager has pick triggers
  36303. * @return {boolean} whether or not it has pick triggers
  36304. */
  36305. get: function () {
  36306. for (var index = 0; index < this.actions.length; index++) {
  36307. var action = this.actions[index];
  36308. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  36309. return true;
  36310. }
  36311. }
  36312. return false;
  36313. },
  36314. enumerable: true,
  36315. configurable: true
  36316. });
  36317. /**
  36318. * Registers an action to this action manager
  36319. * @param {BABYLON.Action} action - the action to be registered
  36320. * @return {BABYLON.Action} the action amended (prepared) after registration
  36321. */
  36322. ActionManager.prototype.registerAction = function (action) {
  36323. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  36324. if (this.getScene().actionManager !== this) {
  36325. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  36326. return null;
  36327. }
  36328. }
  36329. this.actions.push(action);
  36330. action._actionManager = this;
  36331. action._prepare();
  36332. return action;
  36333. };
  36334. /**
  36335. * Process a specific trigger
  36336. * @param {number} trigger - the trigger to process
  36337. * @param evt {BABYLON.ActionEvent} the event details to be processed
  36338. */
  36339. ActionManager.prototype.processTrigger = function (trigger, evt) {
  36340. for (var index = 0; index < this.actions.length; index++) {
  36341. var action = this.actions[index];
  36342. if (action.trigger === trigger) {
  36343. if (trigger === ActionManager.OnKeyUpTrigger
  36344. || trigger === ActionManager.OnKeyDownTrigger) {
  36345. var parameter = action.getTriggerParameter();
  36346. if (parameter) {
  36347. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  36348. var actualkey = String.fromCharCode(unicode).toLowerCase();
  36349. if (actualkey !== parameter.toLowerCase()) {
  36350. continue;
  36351. }
  36352. }
  36353. }
  36354. action._executeCurrent(evt);
  36355. }
  36356. }
  36357. };
  36358. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  36359. var properties = propertyPath.split(".");
  36360. for (var index = 0; index < properties.length - 1; index++) {
  36361. target = target[properties[index]];
  36362. }
  36363. return target;
  36364. };
  36365. ActionManager.prototype._getProperty = function (propertyPath) {
  36366. var properties = propertyPath.split(".");
  36367. return properties[properties.length - 1];
  36368. };
  36369. ActionManager.prototype.serialize = function (name) {
  36370. var root = {
  36371. children: [],
  36372. name: name,
  36373. type: 3,
  36374. properties: [] // Empty for root but required
  36375. };
  36376. for (var i = 0; i < this.actions.length; i++) {
  36377. var triggerObject = {
  36378. type: 0,
  36379. children: [],
  36380. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  36381. properties: []
  36382. };
  36383. var triggerOptions = this.actions[i].triggerOptions;
  36384. if (triggerOptions && typeof triggerOptions !== "number") {
  36385. if (triggerOptions.parameter instanceof BABYLON.Node) {
  36386. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  36387. }
  36388. else {
  36389. var parameter = {};
  36390. BABYLON.Tools.DeepCopy(triggerOptions.parameter, parameter, ["mesh"]);
  36391. if (triggerOptions.parameter.mesh) {
  36392. parameter._meshId = triggerOptions.parameter.mesh.id;
  36393. }
  36394. triggerObject.properties.push({ name: "parameter", targetType: null, value: parameter });
  36395. }
  36396. }
  36397. // Serialize child action, recursively
  36398. this.actions[i].serialize(triggerObject);
  36399. // Add serialized trigger
  36400. root.children.push(triggerObject);
  36401. }
  36402. return root;
  36403. };
  36404. ActionManager.Parse = function (parsedActions, object, scene) {
  36405. var actionManager = new BABYLON.ActionManager(scene);
  36406. if (object === null)
  36407. scene.actionManager = actionManager;
  36408. else
  36409. object.actionManager = actionManager;
  36410. // instanciate a new object
  36411. var instanciate = function (name, params) {
  36412. var newInstance = Object.create(BABYLON[name].prototype);
  36413. newInstance.constructor.apply(newInstance, params);
  36414. return newInstance;
  36415. };
  36416. var parseParameter = function (name, value, target, propertyPath) {
  36417. if (propertyPath === null) {
  36418. // String, boolean or float
  36419. var floatValue = parseFloat(value);
  36420. if (value === "true" || value === "false")
  36421. return value === "true";
  36422. else
  36423. return isNaN(floatValue) ? value : floatValue;
  36424. }
  36425. var effectiveTarget = propertyPath.split(".");
  36426. var values = value.split(",");
  36427. // Get effective Target
  36428. for (var i = 0; i < effectiveTarget.length; i++) {
  36429. target = target[effectiveTarget[i]];
  36430. }
  36431. // Return appropriate value with its type
  36432. if (typeof (target) === "boolean")
  36433. return values[0] === "true";
  36434. if (typeof (target) === "string")
  36435. return values[0];
  36436. // Parameters with multiple values such as Vector3 etc.
  36437. var split = new Array();
  36438. for (var i = 0; i < values.length; i++)
  36439. split.push(parseFloat(values[i]));
  36440. if (target instanceof BABYLON.Vector3)
  36441. return BABYLON.Vector3.FromArray(split);
  36442. if (target instanceof BABYLON.Vector4)
  36443. return BABYLON.Vector4.FromArray(split);
  36444. if (target instanceof BABYLON.Color3)
  36445. return BABYLON.Color3.FromArray(split);
  36446. if (target instanceof BABYLON.Color4)
  36447. return BABYLON.Color4.FromArray(split);
  36448. return parseFloat(values[0]);
  36449. };
  36450. // traverse graph per trigger
  36451. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  36452. if (combineArray === void 0) { combineArray = null; }
  36453. if (parsedAction.detached)
  36454. return;
  36455. var parameters = new Array();
  36456. var target = null;
  36457. var propertyPath = null;
  36458. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  36459. // Parameters
  36460. if (parsedAction.type === 2)
  36461. parameters.push(actionManager);
  36462. else
  36463. parameters.push(trigger);
  36464. if (combine) {
  36465. var actions = new Array();
  36466. for (var j = 0; j < parsedAction.combine.length; j++) {
  36467. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  36468. }
  36469. parameters.push(actions);
  36470. }
  36471. else {
  36472. for (var i = 0; i < parsedAction.properties.length; i++) {
  36473. var value = parsedAction.properties[i].value;
  36474. var name = parsedAction.properties[i].name;
  36475. var targetType = parsedAction.properties[i].targetType;
  36476. if (name === "target")
  36477. if (targetType !== null && targetType === "SceneProperties")
  36478. value = target = scene;
  36479. else
  36480. value = target = scene.getNodeByName(value);
  36481. else if (name === "parent")
  36482. value = scene.getNodeByName(value);
  36483. else if (name === "sound")
  36484. value = scene.getSoundByName(value);
  36485. else if (name !== "propertyPath") {
  36486. if (parsedAction.type === 2 && name === "operator")
  36487. value = BABYLON.ValueCondition[value];
  36488. else
  36489. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  36490. }
  36491. else {
  36492. propertyPath = value;
  36493. }
  36494. parameters.push(value);
  36495. }
  36496. }
  36497. if (combineArray === null) {
  36498. parameters.push(condition);
  36499. }
  36500. else {
  36501. parameters.push(null);
  36502. }
  36503. // If interpolate value action
  36504. if (parsedAction.name === "InterpolateValueAction") {
  36505. var param = parameters[parameters.length - 2];
  36506. parameters[parameters.length - 1] = param;
  36507. parameters[parameters.length - 2] = condition;
  36508. }
  36509. // Action or condition(s) and not CombineAction
  36510. var newAction = instanciate(parsedAction.name, parameters);
  36511. if (newAction instanceof BABYLON.Condition && condition !== null) {
  36512. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  36513. if (action)
  36514. action.then(nothing);
  36515. else
  36516. actionManager.registerAction(nothing);
  36517. action = nothing;
  36518. }
  36519. if (combineArray === null) {
  36520. if (newAction instanceof BABYLON.Condition) {
  36521. condition = newAction;
  36522. newAction = action;
  36523. }
  36524. else {
  36525. condition = null;
  36526. if (action)
  36527. action.then(newAction);
  36528. else
  36529. actionManager.registerAction(newAction);
  36530. }
  36531. }
  36532. else {
  36533. combineArray.push(newAction);
  36534. }
  36535. for (var i = 0; i < parsedAction.children.length; i++)
  36536. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  36537. };
  36538. // triggers
  36539. for (var i = 0; i < parsedActions.children.length; i++) {
  36540. var triggerParams;
  36541. var trigger = parsedActions.children[i];
  36542. if (trigger.properties.length > 0) {
  36543. var param = trigger.properties[0].value;
  36544. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  36545. if (value._meshId) {
  36546. value.mesh = scene.getMeshByID(value._meshId);
  36547. }
  36548. triggerParams = { trigger: BABYLON.ActionManager[trigger.name], parameter: value };
  36549. }
  36550. else
  36551. triggerParams = BABYLON.ActionManager[trigger.name];
  36552. for (var j = 0; j < trigger.children.length; j++) {
  36553. if (!trigger.detached)
  36554. traverse(trigger.children[j], triggerParams, null, null);
  36555. }
  36556. }
  36557. };
  36558. ActionManager.GetTriggerName = function (trigger) {
  36559. switch (trigger) {
  36560. case 0: return "NothingTrigger";
  36561. case 1: return "OnPickTrigger";
  36562. case 2: return "OnLeftPickTrigger";
  36563. case 3: return "OnRightPickTrigger";
  36564. case 4: return "OnCenterPickTrigger";
  36565. case 5: return "OnPickDownTrigger";
  36566. case 6: return "OnPickUpTrigger";
  36567. case 7: return "OnLongPressTrigger";
  36568. case 8: return "OnPointerOverTrigger";
  36569. case 9: return "OnPointerOutTrigger";
  36570. case 10: return "OnEveryFrameTrigger";
  36571. case 11: return "OnIntersectionEnterTrigger";
  36572. case 12: return "OnIntersectionExitTrigger";
  36573. case 13: return "OnKeyDownTrigger";
  36574. case 14: return "OnKeyUpTrigger";
  36575. case 15: return "OnPickOutTrigger";
  36576. default: return "";
  36577. }
  36578. };
  36579. return ActionManager;
  36580. }());
  36581. // Statics
  36582. ActionManager._NothingTrigger = 0;
  36583. ActionManager._OnPickTrigger = 1;
  36584. ActionManager._OnLeftPickTrigger = 2;
  36585. ActionManager._OnRightPickTrigger = 3;
  36586. ActionManager._OnCenterPickTrigger = 4;
  36587. ActionManager._OnPickDownTrigger = 5;
  36588. ActionManager._OnPickUpTrigger = 6;
  36589. ActionManager._OnLongPressTrigger = 7;
  36590. ActionManager._OnPointerOverTrigger = 8;
  36591. ActionManager._OnPointerOutTrigger = 9;
  36592. ActionManager._OnEveryFrameTrigger = 10;
  36593. ActionManager._OnIntersectionEnterTrigger = 11;
  36594. ActionManager._OnIntersectionExitTrigger = 12;
  36595. ActionManager._OnKeyDownTrigger = 13;
  36596. ActionManager._OnKeyUpTrigger = 14;
  36597. ActionManager._OnPickOutTrigger = 15;
  36598. ActionManager.DragMovementThreshold = 10; // in pixels
  36599. ActionManager.LongPressDelay = 500; // in milliseconds
  36600. BABYLON.ActionManager = ActionManager;
  36601. })(BABYLON || (BABYLON = {}));
  36602. //# sourceMappingURL=babylon.actionManager.js.map
  36603. var BABYLON;
  36604. (function (BABYLON) {
  36605. var InterpolateValueAction = (function (_super) {
  36606. __extends(InterpolateValueAction, _super);
  36607. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  36608. if (duration === void 0) { duration = 1000; }
  36609. var _this = _super.call(this, triggerOptions, condition) || this;
  36610. _this.propertyPath = propertyPath;
  36611. _this.value = value;
  36612. _this.duration = duration;
  36613. _this.stopOtherAnimations = stopOtherAnimations;
  36614. _this.onInterpolationDone = onInterpolationDone;
  36615. _this._target = _this._effectiveTarget = target;
  36616. return _this;
  36617. }
  36618. InterpolateValueAction.prototype._prepare = function () {
  36619. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  36620. this._property = this._getProperty(this.propertyPath);
  36621. };
  36622. InterpolateValueAction.prototype.execute = function () {
  36623. var scene = this._actionManager.getScene();
  36624. var keys = [
  36625. {
  36626. frame: 0,
  36627. value: this._effectiveTarget[this._property]
  36628. }, {
  36629. frame: 100,
  36630. value: this.value
  36631. }
  36632. ];
  36633. var dataType;
  36634. if (typeof this.value === "number") {
  36635. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  36636. }
  36637. else if (this.value instanceof BABYLON.Color3) {
  36638. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  36639. }
  36640. else if (this.value instanceof BABYLON.Vector3) {
  36641. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  36642. }
  36643. else if (this.value instanceof BABYLON.Matrix) {
  36644. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  36645. }
  36646. else if (this.value instanceof BABYLON.Quaternion) {
  36647. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  36648. }
  36649. else {
  36650. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  36651. return;
  36652. }
  36653. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  36654. animation.setKeys(keys);
  36655. if (this.stopOtherAnimations) {
  36656. scene.stopAnimation(this._effectiveTarget);
  36657. }
  36658. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, this.onInterpolationDone);
  36659. };
  36660. InterpolateValueAction.prototype.serialize = function (parent) {
  36661. return _super.prototype._serialize.call(this, {
  36662. name: "InterpolateValueAction",
  36663. properties: [
  36664. BABYLON.Action._GetTargetProperty(this._target),
  36665. { name: "propertyPath", value: this.propertyPath },
  36666. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  36667. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  36668. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  36669. ]
  36670. }, parent);
  36671. };
  36672. return InterpolateValueAction;
  36673. }(BABYLON.Action));
  36674. BABYLON.InterpolateValueAction = InterpolateValueAction;
  36675. })(BABYLON || (BABYLON = {}));
  36676. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  36677. var BABYLON;
  36678. (function (BABYLON) {
  36679. var SwitchBooleanAction = (function (_super) {
  36680. __extends(SwitchBooleanAction, _super);
  36681. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  36682. var _this = _super.call(this, triggerOptions, condition) || this;
  36683. _this.propertyPath = propertyPath;
  36684. _this._target = _this._effectiveTarget = target;
  36685. return _this;
  36686. }
  36687. SwitchBooleanAction.prototype._prepare = function () {
  36688. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  36689. this._property = this._getProperty(this.propertyPath);
  36690. };
  36691. SwitchBooleanAction.prototype.execute = function () {
  36692. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  36693. };
  36694. SwitchBooleanAction.prototype.serialize = function (parent) {
  36695. return _super.prototype._serialize.call(this, {
  36696. name: "SwitchBooleanAction",
  36697. properties: [
  36698. BABYLON.Action._GetTargetProperty(this._target),
  36699. { name: "propertyPath", value: this.propertyPath }
  36700. ]
  36701. }, parent);
  36702. };
  36703. return SwitchBooleanAction;
  36704. }(BABYLON.Action));
  36705. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  36706. var SetStateAction = (function (_super) {
  36707. __extends(SetStateAction, _super);
  36708. function SetStateAction(triggerOptions, target, value, condition) {
  36709. var _this = _super.call(this, triggerOptions, condition) || this;
  36710. _this.value = value;
  36711. _this._target = target;
  36712. return _this;
  36713. }
  36714. SetStateAction.prototype.execute = function () {
  36715. this._target.state = this.value;
  36716. };
  36717. SetStateAction.prototype.serialize = function (parent) {
  36718. return _super.prototype._serialize.call(this, {
  36719. name: "SetStateAction",
  36720. properties: [
  36721. BABYLON.Action._GetTargetProperty(this._target),
  36722. { name: "value", value: this.value }
  36723. ]
  36724. }, parent);
  36725. };
  36726. return SetStateAction;
  36727. }(BABYLON.Action));
  36728. BABYLON.SetStateAction = SetStateAction;
  36729. var SetValueAction = (function (_super) {
  36730. __extends(SetValueAction, _super);
  36731. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  36732. var _this = _super.call(this, triggerOptions, condition) || this;
  36733. _this.propertyPath = propertyPath;
  36734. _this.value = value;
  36735. _this._target = _this._effectiveTarget = target;
  36736. return _this;
  36737. }
  36738. SetValueAction.prototype._prepare = function () {
  36739. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  36740. this._property = this._getProperty(this.propertyPath);
  36741. };
  36742. SetValueAction.prototype.execute = function () {
  36743. this._effectiveTarget[this._property] = this.value;
  36744. if (this._target.markAsDirty) {
  36745. this._target.markAsDirty(this._property);
  36746. }
  36747. };
  36748. SetValueAction.prototype.serialize = function (parent) {
  36749. return _super.prototype._serialize.call(this, {
  36750. name: "SetValueAction",
  36751. properties: [
  36752. BABYLON.Action._GetTargetProperty(this._target),
  36753. { name: "propertyPath", value: this.propertyPath },
  36754. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  36755. ]
  36756. }, parent);
  36757. };
  36758. return SetValueAction;
  36759. }(BABYLON.Action));
  36760. BABYLON.SetValueAction = SetValueAction;
  36761. var IncrementValueAction = (function (_super) {
  36762. __extends(IncrementValueAction, _super);
  36763. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  36764. var _this = _super.call(this, triggerOptions, condition) || this;
  36765. _this.propertyPath = propertyPath;
  36766. _this.value = value;
  36767. _this._target = _this._effectiveTarget = target;
  36768. return _this;
  36769. }
  36770. IncrementValueAction.prototype._prepare = function () {
  36771. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  36772. this._property = this._getProperty(this.propertyPath);
  36773. if (typeof this._effectiveTarget[this._property] !== "number") {
  36774. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  36775. }
  36776. };
  36777. IncrementValueAction.prototype.execute = function () {
  36778. this._effectiveTarget[this._property] += this.value;
  36779. if (this._target.markAsDirty) {
  36780. this._target.markAsDirty(this._property);
  36781. }
  36782. };
  36783. IncrementValueAction.prototype.serialize = function (parent) {
  36784. return _super.prototype._serialize.call(this, {
  36785. name: "IncrementValueAction",
  36786. properties: [
  36787. BABYLON.Action._GetTargetProperty(this._target),
  36788. { name: "propertyPath", value: this.propertyPath },
  36789. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  36790. ]
  36791. }, parent);
  36792. };
  36793. return IncrementValueAction;
  36794. }(BABYLON.Action));
  36795. BABYLON.IncrementValueAction = IncrementValueAction;
  36796. var PlayAnimationAction = (function (_super) {
  36797. __extends(PlayAnimationAction, _super);
  36798. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  36799. var _this = _super.call(this, triggerOptions, condition) || this;
  36800. _this.from = from;
  36801. _this.to = to;
  36802. _this.loop = loop;
  36803. _this._target = target;
  36804. return _this;
  36805. }
  36806. PlayAnimationAction.prototype._prepare = function () {
  36807. };
  36808. PlayAnimationAction.prototype.execute = function () {
  36809. var scene = this._actionManager.getScene();
  36810. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  36811. };
  36812. PlayAnimationAction.prototype.serialize = function (parent) {
  36813. return _super.prototype._serialize.call(this, {
  36814. name: "PlayAnimationAction",
  36815. properties: [
  36816. BABYLON.Action._GetTargetProperty(this._target),
  36817. { name: "from", value: String(this.from) },
  36818. { name: "to", value: String(this.to) },
  36819. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  36820. ]
  36821. }, parent);
  36822. };
  36823. return PlayAnimationAction;
  36824. }(BABYLON.Action));
  36825. BABYLON.PlayAnimationAction = PlayAnimationAction;
  36826. var StopAnimationAction = (function (_super) {
  36827. __extends(StopAnimationAction, _super);
  36828. function StopAnimationAction(triggerOptions, target, condition) {
  36829. var _this = _super.call(this, triggerOptions, condition) || this;
  36830. _this._target = target;
  36831. return _this;
  36832. }
  36833. StopAnimationAction.prototype._prepare = function () {
  36834. };
  36835. StopAnimationAction.prototype.execute = function () {
  36836. var scene = this._actionManager.getScene();
  36837. scene.stopAnimation(this._target);
  36838. };
  36839. StopAnimationAction.prototype.serialize = function (parent) {
  36840. return _super.prototype._serialize.call(this, {
  36841. name: "StopAnimationAction",
  36842. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  36843. }, parent);
  36844. };
  36845. return StopAnimationAction;
  36846. }(BABYLON.Action));
  36847. BABYLON.StopAnimationAction = StopAnimationAction;
  36848. var DoNothingAction = (function (_super) {
  36849. __extends(DoNothingAction, _super);
  36850. function DoNothingAction(triggerOptions, condition) {
  36851. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  36852. return _super.call(this, triggerOptions, condition) || this;
  36853. }
  36854. DoNothingAction.prototype.execute = function () {
  36855. };
  36856. DoNothingAction.prototype.serialize = function (parent) {
  36857. return _super.prototype._serialize.call(this, {
  36858. name: "DoNothingAction",
  36859. properties: []
  36860. }, parent);
  36861. };
  36862. return DoNothingAction;
  36863. }(BABYLON.Action));
  36864. BABYLON.DoNothingAction = DoNothingAction;
  36865. var CombineAction = (function (_super) {
  36866. __extends(CombineAction, _super);
  36867. function CombineAction(triggerOptions, children, condition) {
  36868. var _this = _super.call(this, triggerOptions, condition) || this;
  36869. _this.children = children;
  36870. return _this;
  36871. }
  36872. CombineAction.prototype._prepare = function () {
  36873. for (var index = 0; index < this.children.length; index++) {
  36874. this.children[index]._actionManager = this._actionManager;
  36875. this.children[index]._prepare();
  36876. }
  36877. };
  36878. CombineAction.prototype.execute = function (evt) {
  36879. for (var index = 0; index < this.children.length; index++) {
  36880. this.children[index].execute(evt);
  36881. }
  36882. };
  36883. CombineAction.prototype.serialize = function (parent) {
  36884. var serializationObject = _super.prototype._serialize.call(this, {
  36885. name: "CombineAction",
  36886. properties: [],
  36887. combine: []
  36888. }, parent);
  36889. for (var i = 0; i < this.children.length; i++) {
  36890. serializationObject.combine.push(this.children[i].serialize(null));
  36891. }
  36892. return serializationObject;
  36893. };
  36894. return CombineAction;
  36895. }(BABYLON.Action));
  36896. BABYLON.CombineAction = CombineAction;
  36897. var ExecuteCodeAction = (function (_super) {
  36898. __extends(ExecuteCodeAction, _super);
  36899. function ExecuteCodeAction(triggerOptions, func, condition) {
  36900. var _this = _super.call(this, triggerOptions, condition) || this;
  36901. _this.func = func;
  36902. return _this;
  36903. }
  36904. ExecuteCodeAction.prototype.execute = function (evt) {
  36905. this.func(evt);
  36906. };
  36907. return ExecuteCodeAction;
  36908. }(BABYLON.Action));
  36909. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  36910. var SetParentAction = (function (_super) {
  36911. __extends(SetParentAction, _super);
  36912. function SetParentAction(triggerOptions, target, parent, condition) {
  36913. var _this = _super.call(this, triggerOptions, condition) || this;
  36914. _this._target = target;
  36915. _this._parent = parent;
  36916. return _this;
  36917. }
  36918. SetParentAction.prototype._prepare = function () {
  36919. };
  36920. SetParentAction.prototype.execute = function () {
  36921. if (this._target.parent === this._parent) {
  36922. return;
  36923. }
  36924. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  36925. invertParentWorldMatrix.invert();
  36926. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  36927. this._target.parent = this._parent;
  36928. };
  36929. SetParentAction.prototype.serialize = function (parent) {
  36930. return _super.prototype._serialize.call(this, {
  36931. name: "SetParentAction",
  36932. properties: [
  36933. BABYLON.Action._GetTargetProperty(this._target),
  36934. BABYLON.Action._GetTargetProperty(this._parent),
  36935. ]
  36936. }, parent);
  36937. };
  36938. return SetParentAction;
  36939. }(BABYLON.Action));
  36940. BABYLON.SetParentAction = SetParentAction;
  36941. var PlaySoundAction = (function (_super) {
  36942. __extends(PlaySoundAction, _super);
  36943. function PlaySoundAction(triggerOptions, sound, condition) {
  36944. var _this = _super.call(this, triggerOptions, condition) || this;
  36945. _this._sound = sound;
  36946. return _this;
  36947. }
  36948. PlaySoundAction.prototype._prepare = function () {
  36949. };
  36950. PlaySoundAction.prototype.execute = function () {
  36951. if (this._sound !== undefined)
  36952. this._sound.play();
  36953. };
  36954. PlaySoundAction.prototype.serialize = function (parent) {
  36955. return _super.prototype._serialize.call(this, {
  36956. name: "PlaySoundAction",
  36957. properties: [{ name: "sound", value: this._sound.name }]
  36958. }, parent);
  36959. };
  36960. return PlaySoundAction;
  36961. }(BABYLON.Action));
  36962. BABYLON.PlaySoundAction = PlaySoundAction;
  36963. var StopSoundAction = (function (_super) {
  36964. __extends(StopSoundAction, _super);
  36965. function StopSoundAction(triggerOptions, sound, condition) {
  36966. var _this = _super.call(this, triggerOptions, condition) || this;
  36967. _this._sound = sound;
  36968. return _this;
  36969. }
  36970. StopSoundAction.prototype._prepare = function () {
  36971. };
  36972. StopSoundAction.prototype.execute = function () {
  36973. if (this._sound !== undefined)
  36974. this._sound.stop();
  36975. };
  36976. StopSoundAction.prototype.serialize = function (parent) {
  36977. return _super.prototype._serialize.call(this, {
  36978. name: "StopSoundAction",
  36979. properties: [{ name: "sound", value: this._sound.name }]
  36980. }, parent);
  36981. };
  36982. return StopSoundAction;
  36983. }(BABYLON.Action));
  36984. BABYLON.StopSoundAction = StopSoundAction;
  36985. })(BABYLON || (BABYLON = {}));
  36986. //# sourceMappingURL=babylon.directActions.js.map
  36987. var BABYLON;
  36988. (function (BABYLON) {
  36989. var Geometry = (function () {
  36990. function Geometry(id, scene, vertexData, updatable, mesh) {
  36991. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  36992. this._totalVertices = 0;
  36993. this._isDisposed = false;
  36994. this.id = id;
  36995. this._engine = scene.getEngine();
  36996. this._meshes = [];
  36997. this._scene = scene;
  36998. //Init vertex buffer cache
  36999. this._vertexBuffers = {};
  37000. this._indices = [];
  37001. // vertexData
  37002. if (vertexData) {
  37003. this.setAllVerticesData(vertexData, updatable);
  37004. }
  37005. else {
  37006. this._totalVertices = 0;
  37007. this._indices = [];
  37008. }
  37009. if (this._engine.getCaps().vertexArrayObject) {
  37010. this._vertexArrayObjects = {};
  37011. }
  37012. // applyToMesh
  37013. if (mesh) {
  37014. if (mesh instanceof BABYLON.LinesMesh) {
  37015. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  37016. this.updateExtend();
  37017. }
  37018. this.applyToMesh(mesh);
  37019. mesh.computeWorldMatrix(true);
  37020. }
  37021. }
  37022. Object.defineProperty(Geometry.prototype, "boundingBias", {
  37023. /**
  37024. * 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
  37025. * @returns The Bias Vector
  37026. */
  37027. get: function () {
  37028. return this._boundingBias;
  37029. },
  37030. set: function (value) {
  37031. if (this._boundingBias && this._boundingBias.equals(value)) {
  37032. return;
  37033. }
  37034. this._boundingBias = value.clone();
  37035. this.updateBoundingInfo(true, null);
  37036. },
  37037. enumerable: true,
  37038. configurable: true
  37039. });
  37040. Object.defineProperty(Geometry.prototype, "extend", {
  37041. get: function () {
  37042. return this._extend;
  37043. },
  37044. enumerable: true,
  37045. configurable: true
  37046. });
  37047. Geometry.prototype.getScene = function () {
  37048. return this._scene;
  37049. };
  37050. Geometry.prototype.getEngine = function () {
  37051. return this._engine;
  37052. };
  37053. Geometry.prototype.isReady = function () {
  37054. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  37055. };
  37056. Object.defineProperty(Geometry.prototype, "doNotSerialize", {
  37057. get: function () {
  37058. for (var index = 0; index < this._meshes.length; index++) {
  37059. if (!this._meshes[index].doNotSerialize) {
  37060. return false;
  37061. }
  37062. }
  37063. return true;
  37064. },
  37065. enumerable: true,
  37066. configurable: true
  37067. });
  37068. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  37069. vertexData.applyToGeometry(this, updatable);
  37070. this.notifyUpdate();
  37071. };
  37072. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  37073. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  37074. this.setVerticesBuffer(buffer);
  37075. };
  37076. Geometry.prototype.setVerticesBuffer = function (buffer) {
  37077. var kind = buffer.getKind();
  37078. if (this._vertexBuffers[kind]) {
  37079. this._vertexBuffers[kind].dispose();
  37080. }
  37081. this._vertexBuffers[kind] = buffer;
  37082. if (kind === BABYLON.VertexBuffer.PositionKind) {
  37083. var data = buffer.getData();
  37084. var stride = buffer.getStrideSize();
  37085. this._totalVertices = data.length / stride;
  37086. this.updateExtend(data, stride);
  37087. var meshes = this._meshes;
  37088. var numOfMeshes = meshes.length;
  37089. for (var index = 0; index < numOfMeshes; index++) {
  37090. var mesh = meshes[index];
  37091. mesh._resetPointsArrayCache();
  37092. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  37093. mesh._createGlobalSubMesh();
  37094. mesh.computeWorldMatrix(true);
  37095. }
  37096. }
  37097. this.notifyUpdate(kind);
  37098. if (this._vertexArrayObjects) {
  37099. this._disposeVertexArrayObjects();
  37100. this._vertexArrayObjects = {}; // Will trigger a rebuild of the VAO if supported
  37101. }
  37102. };
  37103. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  37104. var vertexBuffer = this.getVertexBuffer(kind);
  37105. if (!vertexBuffer) {
  37106. return;
  37107. }
  37108. vertexBuffer.updateDirectly(data, offset);
  37109. this.notifyUpdate(kind);
  37110. };
  37111. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  37112. var vertexBuffer = this.getVertexBuffer(kind);
  37113. if (!vertexBuffer) {
  37114. return;
  37115. }
  37116. vertexBuffer.update(data);
  37117. if (kind === BABYLON.VertexBuffer.PositionKind) {
  37118. var stride = vertexBuffer.getStrideSize();
  37119. this._totalVertices = data.length / stride;
  37120. this.updateBoundingInfo(updateExtends, data);
  37121. }
  37122. this.notifyUpdate(kind);
  37123. };
  37124. Geometry.prototype.updateBoundingInfo = function (updateExtends, data) {
  37125. if (updateExtends) {
  37126. this.updateExtend(data);
  37127. }
  37128. var meshes = this._meshes;
  37129. var numOfMeshes = meshes.length;
  37130. for (var index = 0; index < numOfMeshes; index++) {
  37131. var mesh = meshes[index];
  37132. mesh._resetPointsArrayCache();
  37133. if (updateExtends) {
  37134. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  37135. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  37136. var subMesh = mesh.subMeshes[subIndex];
  37137. subMesh.refreshBoundingInfo();
  37138. }
  37139. }
  37140. }
  37141. };
  37142. Geometry.prototype._bind = function (effect, indexToBind) {
  37143. if (indexToBind === void 0) { indexToBind = undefined; }
  37144. if (indexToBind === undefined) {
  37145. indexToBind = this._indexBuffer;
  37146. }
  37147. if (indexToBind != this._indexBuffer || !this._vertexArrayObjects) {
  37148. this._engine.bindBuffers(this.getVertexBuffers(), indexToBind, effect);
  37149. return;
  37150. }
  37151. // Using VAO
  37152. if (!this._vertexArrayObjects[effect.key]) {
  37153. this._vertexArrayObjects[effect.key] = this._engine.recordVertexArrayObject(this.getVertexBuffers(), indexToBind, effect);
  37154. }
  37155. this._engine.bindVertexArrayObject(this._vertexArrayObjects[effect.key], indexToBind);
  37156. };
  37157. Geometry.prototype.getTotalVertices = function () {
  37158. if (!this.isReady()) {
  37159. return 0;
  37160. }
  37161. return this._totalVertices;
  37162. };
  37163. Geometry.prototype.getVerticesData = function (kind, copyWhenShared) {
  37164. var vertexBuffer = this.getVertexBuffer(kind);
  37165. if (!vertexBuffer) {
  37166. return null;
  37167. }
  37168. var orig = vertexBuffer.getData();
  37169. if (!copyWhenShared || this._meshes.length === 1) {
  37170. return orig;
  37171. }
  37172. else {
  37173. var len = orig.length;
  37174. var copy = [];
  37175. for (var i = 0; i < len; i++) {
  37176. copy.push(orig[i]);
  37177. }
  37178. return copy;
  37179. }
  37180. };
  37181. Geometry.prototype.getVertexBuffer = function (kind) {
  37182. if (!this.isReady()) {
  37183. return null;
  37184. }
  37185. return this._vertexBuffers[kind];
  37186. };
  37187. Geometry.prototype.getVertexBuffers = function () {
  37188. if (!this.isReady()) {
  37189. return null;
  37190. }
  37191. return this._vertexBuffers;
  37192. };
  37193. Geometry.prototype.isVerticesDataPresent = function (kind) {
  37194. if (!this._vertexBuffers) {
  37195. if (this._delayInfo) {
  37196. return this._delayInfo.indexOf(kind) !== -1;
  37197. }
  37198. return false;
  37199. }
  37200. return this._vertexBuffers[kind] !== undefined;
  37201. };
  37202. Geometry.prototype.getVerticesDataKinds = function () {
  37203. var result = [];
  37204. var kind;
  37205. if (!this._vertexBuffers && this._delayInfo) {
  37206. for (kind in this._delayInfo) {
  37207. result.push(kind);
  37208. }
  37209. }
  37210. else {
  37211. for (kind in this._vertexBuffers) {
  37212. result.push(kind);
  37213. }
  37214. }
  37215. return result;
  37216. };
  37217. Geometry.prototype.setIndices = function (indices, totalVertices) {
  37218. if (this._indexBuffer) {
  37219. this._engine._releaseBuffer(this._indexBuffer);
  37220. }
  37221. this._disposeVertexArrayObjects();
  37222. this._indices = indices;
  37223. if (this._meshes.length !== 0 && this._indices) {
  37224. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  37225. }
  37226. if (totalVertices !== undefined) {
  37227. this._totalVertices = totalVertices;
  37228. }
  37229. var meshes = this._meshes;
  37230. var numOfMeshes = meshes.length;
  37231. for (var index = 0; index < numOfMeshes; index++) {
  37232. meshes[index]._createGlobalSubMesh();
  37233. }
  37234. this.notifyUpdate();
  37235. };
  37236. Geometry.prototype.getTotalIndices = function () {
  37237. if (!this.isReady()) {
  37238. return 0;
  37239. }
  37240. return this._indices.length;
  37241. };
  37242. Geometry.prototype.getIndices = function (copyWhenShared) {
  37243. if (!this.isReady()) {
  37244. return null;
  37245. }
  37246. var orig = this._indices;
  37247. if (!copyWhenShared || this._meshes.length === 1) {
  37248. return orig;
  37249. }
  37250. else {
  37251. var len = orig.length;
  37252. var copy = [];
  37253. for (var i = 0; i < len; i++) {
  37254. copy.push(orig[i]);
  37255. }
  37256. return copy;
  37257. }
  37258. };
  37259. Geometry.prototype.getIndexBuffer = function () {
  37260. if (!this.isReady()) {
  37261. return null;
  37262. }
  37263. return this._indexBuffer;
  37264. };
  37265. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  37266. var meshes = this._meshes;
  37267. var index = meshes.indexOf(mesh);
  37268. if (index === -1) {
  37269. return;
  37270. }
  37271. meshes.splice(index, 1);
  37272. mesh._geometry = null;
  37273. if (meshes.length === 0 && shouldDispose) {
  37274. this.dispose();
  37275. }
  37276. };
  37277. Geometry.prototype.applyToMesh = function (mesh) {
  37278. if (mesh._geometry === this) {
  37279. return;
  37280. }
  37281. var previousGeometry = mesh._geometry;
  37282. if (previousGeometry) {
  37283. previousGeometry.releaseForMesh(mesh);
  37284. }
  37285. var meshes = this._meshes;
  37286. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  37287. mesh._geometry = this;
  37288. this._scene.pushGeometry(this);
  37289. meshes.push(mesh);
  37290. if (this.isReady()) {
  37291. this._applyToMesh(mesh);
  37292. }
  37293. else {
  37294. mesh._boundingInfo = this._boundingInfo;
  37295. }
  37296. };
  37297. Geometry.prototype.updateExtend = function (data, stride) {
  37298. if (data === void 0) { data = null; }
  37299. if (!data) {
  37300. data = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind].getData();
  37301. }
  37302. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, stride);
  37303. };
  37304. Geometry.prototype._applyToMesh = function (mesh) {
  37305. var numOfMeshes = this._meshes.length;
  37306. // vertexBuffers
  37307. for (var kind in this._vertexBuffers) {
  37308. if (numOfMeshes === 1) {
  37309. this._vertexBuffers[kind].create();
  37310. }
  37311. this._vertexBuffers[kind].getBuffer().references = numOfMeshes;
  37312. if (kind === BABYLON.VertexBuffer.PositionKind) {
  37313. mesh._resetPointsArrayCache();
  37314. if (!this._extend) {
  37315. this.updateExtend(this._vertexBuffers[kind].getData());
  37316. }
  37317. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  37318. mesh._createGlobalSubMesh();
  37319. //bounding info was just created again, world matrix should be applied again.
  37320. mesh._updateBoundingInfo();
  37321. }
  37322. }
  37323. // indexBuffer
  37324. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  37325. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  37326. }
  37327. if (this._indexBuffer) {
  37328. this._indexBuffer.references = numOfMeshes;
  37329. }
  37330. };
  37331. Geometry.prototype.notifyUpdate = function (kind) {
  37332. if (this.onGeometryUpdated) {
  37333. this.onGeometryUpdated(this, kind);
  37334. }
  37335. };
  37336. Geometry.prototype.load = function (scene, onLoaded) {
  37337. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  37338. return;
  37339. }
  37340. if (this.isReady()) {
  37341. if (onLoaded) {
  37342. onLoaded();
  37343. }
  37344. return;
  37345. }
  37346. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  37347. this._queueLoad(scene, onLoaded);
  37348. };
  37349. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  37350. var _this = this;
  37351. scene._addPendingData(this);
  37352. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  37353. _this._delayLoadingFunction(JSON.parse(data), _this);
  37354. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  37355. _this._delayInfo = [];
  37356. scene._removePendingData(_this);
  37357. var meshes = _this._meshes;
  37358. var numOfMeshes = meshes.length;
  37359. for (var index = 0; index < numOfMeshes; index++) {
  37360. _this._applyToMesh(meshes[index]);
  37361. }
  37362. if (onLoaded) {
  37363. onLoaded();
  37364. }
  37365. }, function () { }, scene.database);
  37366. };
  37367. /**
  37368. * Invert the geometry to move from a right handed system to a left handed one.
  37369. */
  37370. Geometry.prototype.toLeftHanded = function () {
  37371. // Flip faces
  37372. var tIndices = this.getIndices(false);
  37373. if (tIndices != null && tIndices.length > 0) {
  37374. for (var i = 0; i < tIndices.length; i += 3) {
  37375. var tTemp = tIndices[i + 0];
  37376. tIndices[i + 0] = tIndices[i + 2];
  37377. tIndices[i + 2] = tTemp;
  37378. }
  37379. this.setIndices(tIndices);
  37380. }
  37381. // Negate position.z
  37382. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  37383. if (tPositions != null && tPositions.length > 0) {
  37384. for (var i = 0; i < tPositions.length; i += 3) {
  37385. tPositions[i + 2] = -tPositions[i + 2];
  37386. }
  37387. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  37388. }
  37389. // Negate normal.z
  37390. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  37391. if (tNormals != null && tNormals.length > 0) {
  37392. for (var i = 0; i < tNormals.length; i += 3) {
  37393. tNormals[i + 2] = -tNormals[i + 2];
  37394. }
  37395. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  37396. }
  37397. };
  37398. Geometry.prototype.isDisposed = function () {
  37399. return this._isDisposed;
  37400. };
  37401. Geometry.prototype._disposeVertexArrayObjects = function () {
  37402. if (this._vertexArrayObjects) {
  37403. for (var kind in this._vertexArrayObjects) {
  37404. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[kind]);
  37405. }
  37406. this._vertexArrayObjects = {};
  37407. }
  37408. };
  37409. Geometry.prototype.dispose = function () {
  37410. var meshes = this._meshes;
  37411. var numOfMeshes = meshes.length;
  37412. var index;
  37413. for (index = 0; index < numOfMeshes; index++) {
  37414. this.releaseForMesh(meshes[index]);
  37415. }
  37416. this._meshes = [];
  37417. this._disposeVertexArrayObjects();
  37418. for (var kind in this._vertexBuffers) {
  37419. this._vertexBuffers[kind].dispose();
  37420. }
  37421. this._vertexBuffers = {};
  37422. this._totalVertices = 0;
  37423. if (this._indexBuffer) {
  37424. this._engine._releaseBuffer(this._indexBuffer);
  37425. }
  37426. this._indexBuffer = null;
  37427. this._indices = [];
  37428. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  37429. this.delayLoadingFile = null;
  37430. this._delayLoadingFunction = null;
  37431. this._delayInfo = [];
  37432. this._boundingInfo = null;
  37433. this._scene.removeGeometry(this);
  37434. this._isDisposed = true;
  37435. };
  37436. Geometry.prototype.copy = function (id) {
  37437. var vertexData = new BABYLON.VertexData();
  37438. vertexData.indices = [];
  37439. var indices = this.getIndices();
  37440. for (var index = 0; index < indices.length; index++) {
  37441. vertexData.indices.push(indices[index]);
  37442. }
  37443. var updatable = false;
  37444. var stopChecking = false;
  37445. var kind;
  37446. for (kind in this._vertexBuffers) {
  37447. // using slice() to make a copy of the array and not just reference it
  37448. var data = this.getVerticesData(kind);
  37449. if (data instanceof Float32Array) {
  37450. vertexData.set(new Float32Array(data), kind);
  37451. }
  37452. else {
  37453. vertexData.set(data.slice(0), kind);
  37454. }
  37455. if (!stopChecking) {
  37456. updatable = this.getVertexBuffer(kind).isUpdatable();
  37457. stopChecking = !updatable;
  37458. }
  37459. }
  37460. var geometry = new Geometry(id, this._scene, vertexData, updatable, null);
  37461. geometry.delayLoadState = this.delayLoadState;
  37462. geometry.delayLoadingFile = this.delayLoadingFile;
  37463. geometry._delayLoadingFunction = this._delayLoadingFunction;
  37464. for (kind in this._delayInfo) {
  37465. geometry._delayInfo = geometry._delayInfo || [];
  37466. geometry._delayInfo.push(kind);
  37467. }
  37468. // Bounding info
  37469. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  37470. return geometry;
  37471. };
  37472. Geometry.prototype.serialize = function () {
  37473. var serializationObject = {};
  37474. serializationObject.id = this.id;
  37475. if (BABYLON.Tags.HasTags(this)) {
  37476. serializationObject.tags = BABYLON.Tags.GetTags(this);
  37477. }
  37478. return serializationObject;
  37479. };
  37480. Geometry.prototype.serializeVerticeData = function () {
  37481. var serializationObject = this.serialize();
  37482. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  37483. serializationObject.positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  37484. if (this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable) {
  37485. serializationObject.positions._updatable = true;
  37486. }
  37487. }
  37488. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  37489. serializationObject.normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  37490. if (this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable) {
  37491. serializationObject.normals._updatable = true;
  37492. }
  37493. }
  37494. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  37495. serializationObject.uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  37496. if (this.getVertexBuffer(BABYLON.VertexBuffer.UVKind).isUpdatable) {
  37497. serializationObject.uvs._updatable = true;
  37498. }
  37499. }
  37500. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  37501. serializationObject.uv2s = this.getVerticesData(BABYLON.VertexBuffer.UV2Kind);
  37502. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV2Kind).isUpdatable) {
  37503. serializationObject.uv2s._updatable = true;
  37504. }
  37505. }
  37506. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  37507. serializationObject.uv3s = this.getVerticesData(BABYLON.VertexBuffer.UV3Kind);
  37508. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV3Kind).isUpdatable) {
  37509. serializationObject.uv3s._updatable = true;
  37510. }
  37511. }
  37512. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  37513. serializationObject.uv4s = this.getVerticesData(BABYLON.VertexBuffer.UV4Kind);
  37514. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV4Kind).isUpdatable) {
  37515. serializationObject.uv4s._updatable = true;
  37516. }
  37517. }
  37518. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  37519. serializationObject.uv5s = this.getVerticesData(BABYLON.VertexBuffer.UV5Kind);
  37520. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV5Kind).isUpdatable) {
  37521. serializationObject.uv5s._updatable = true;
  37522. }
  37523. }
  37524. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  37525. serializationObject.uv6s = this.getVerticesData(BABYLON.VertexBuffer.UV6Kind);
  37526. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV6Kind).isUpdatable) {
  37527. serializationObject.uv6s._updatable = true;
  37528. }
  37529. }
  37530. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  37531. serializationObject.colors = this.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  37532. if (this.getVertexBuffer(BABYLON.VertexBuffer.ColorKind).isUpdatable) {
  37533. serializationObject.colors._updatable = true;
  37534. }
  37535. }
  37536. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  37537. serializationObject.matricesIndices = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  37538. serializationObject.matricesIndices._isExpanded = true;
  37539. if (this.getVertexBuffer(BABYLON.VertexBuffer.MatricesIndicesKind).isUpdatable) {
  37540. serializationObject.matricesIndices._updatable = true;
  37541. }
  37542. }
  37543. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  37544. serializationObject.matricesWeights = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  37545. if (this.getVertexBuffer(BABYLON.VertexBuffer.MatricesWeightsKind).isUpdatable) {
  37546. serializationObject.matricesWeights._updatable = true;
  37547. }
  37548. }
  37549. serializationObject.indices = this.getIndices();
  37550. return serializationObject;
  37551. };
  37552. // Statics
  37553. Geometry.ExtractFromMesh = function (mesh, id) {
  37554. var geometry = mesh._geometry;
  37555. if (!geometry) {
  37556. return null;
  37557. }
  37558. return geometry.copy(id);
  37559. };
  37560. /**
  37561. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  37562. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  37563. * Be aware Math.random() could cause collisions, but:
  37564. * "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"
  37565. */
  37566. Geometry.RandomId = function () {
  37567. return BABYLON.Tools.RandomId();
  37568. };
  37569. Geometry.ImportGeometry = function (parsedGeometry, mesh) {
  37570. var scene = mesh.getScene();
  37571. // Geometry
  37572. var geometryId = parsedGeometry.geometryId;
  37573. if (geometryId) {
  37574. var geometry = scene.getGeometryByID(geometryId);
  37575. if (geometry) {
  37576. geometry.applyToMesh(mesh);
  37577. }
  37578. }
  37579. else if (parsedGeometry instanceof ArrayBuffer) {
  37580. var binaryInfo = mesh._binaryInfo;
  37581. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  37582. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  37583. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  37584. }
  37585. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  37586. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  37587. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  37588. }
  37589. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  37590. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  37591. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  37592. }
  37593. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  37594. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  37595. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  37596. }
  37597. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  37598. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  37599. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  37600. }
  37601. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  37602. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  37603. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  37604. }
  37605. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  37606. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  37607. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  37608. }
  37609. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  37610. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  37611. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  37612. }
  37613. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  37614. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  37615. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  37616. }
  37617. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  37618. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  37619. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  37620. }
  37621. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  37622. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  37623. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  37624. }
  37625. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  37626. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  37627. mesh.setIndices(indicesData);
  37628. }
  37629. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  37630. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  37631. mesh.subMeshes = [];
  37632. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  37633. var materialIndex = subMeshesData[(i * 5) + 0];
  37634. var verticesStart = subMeshesData[(i * 5) + 1];
  37635. var verticesCount = subMeshesData[(i * 5) + 2];
  37636. var indexStart = subMeshesData[(i * 5) + 3];
  37637. var indexCount = subMeshesData[(i * 5) + 4];
  37638. var subMesh = new BABYLON.SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  37639. }
  37640. }
  37641. }
  37642. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  37643. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, parsedGeometry.positions._updatable);
  37644. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, parsedGeometry.normals._updatable);
  37645. if (parsedGeometry.uvs) {
  37646. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, parsedGeometry.uvs._updatable);
  37647. }
  37648. if (parsedGeometry.uvs2) {
  37649. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, parsedGeometry.uvs2._updatable);
  37650. }
  37651. if (parsedGeometry.uvs3) {
  37652. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, parsedGeometry.uvs3._updatable);
  37653. }
  37654. if (parsedGeometry.uvs4) {
  37655. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, parsedGeometry.uvs4._updatable);
  37656. }
  37657. if (parsedGeometry.uvs5) {
  37658. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, parsedGeometry.uvs5._updatable);
  37659. }
  37660. if (parsedGeometry.uvs6) {
  37661. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, parsedGeometry.uvs6._updatable);
  37662. }
  37663. if (parsedGeometry.colors) {
  37664. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), parsedGeometry.colors._updatable);
  37665. }
  37666. if (parsedGeometry.matricesIndices) {
  37667. if (!parsedGeometry.matricesIndices._isExpanded) {
  37668. var floatIndices = [];
  37669. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  37670. var matricesIndex = parsedGeometry.matricesIndices[i];
  37671. floatIndices.push(matricesIndex & 0x000000FF);
  37672. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  37673. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  37674. floatIndices.push(matricesIndex >> 24);
  37675. }
  37676. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, parsedGeometry.matricesIndices._updatable);
  37677. }
  37678. else {
  37679. delete parsedGeometry.matricesIndices._isExpanded;
  37680. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, parsedGeometry.matricesIndices._updatable);
  37681. }
  37682. }
  37683. if (parsedGeometry.matricesIndicesExtra) {
  37684. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  37685. var floatIndices = [];
  37686. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  37687. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  37688. floatIndices.push(matricesIndex & 0x000000FF);
  37689. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  37690. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  37691. floatIndices.push(matricesIndex >> 24);
  37692. }
  37693. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, parsedGeometry.matricesIndicesExtra._updatable);
  37694. }
  37695. else {
  37696. delete parsedGeometry.matricesIndices._isExpanded;
  37697. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, parsedGeometry.matricesIndicesExtra._updatable);
  37698. }
  37699. }
  37700. if (parsedGeometry.matricesWeights) {
  37701. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, parsedGeometry.matricesWeights._updatable);
  37702. }
  37703. if (parsedGeometry.matricesWeightsExtra) {
  37704. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, parsedGeometry.matricesWeights._updatable);
  37705. }
  37706. mesh.setIndices(parsedGeometry.indices);
  37707. }
  37708. // SubMeshes
  37709. if (parsedGeometry.subMeshes) {
  37710. mesh.subMeshes = [];
  37711. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  37712. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  37713. var subMesh = new BABYLON.SubMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  37714. }
  37715. }
  37716. // Flat shading
  37717. if (mesh._shouldGenerateFlatShading) {
  37718. mesh.convertToFlatShadedMesh();
  37719. delete mesh._shouldGenerateFlatShading;
  37720. }
  37721. // Update
  37722. mesh.computeWorldMatrix(true);
  37723. // Octree
  37724. if (scene['_selectionOctree']) {
  37725. scene['_selectionOctree'].addMesh(mesh);
  37726. }
  37727. };
  37728. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  37729. if (scene.getGeometryByID(parsedVertexData.id)) {
  37730. return null; // null since geometry could be something else than a box...
  37731. }
  37732. var geometry = new Geometry(parsedVertexData.id, scene);
  37733. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  37734. if (parsedVertexData.delayLoadingFile) {
  37735. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  37736. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  37737. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  37738. geometry._delayInfo = [];
  37739. if (parsedVertexData.hasUVs) {
  37740. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  37741. }
  37742. if (parsedVertexData.hasUVs2) {
  37743. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  37744. }
  37745. if (parsedVertexData.hasUVs3) {
  37746. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  37747. }
  37748. if (parsedVertexData.hasUVs4) {
  37749. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  37750. }
  37751. if (parsedVertexData.hasUVs5) {
  37752. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  37753. }
  37754. if (parsedVertexData.hasUVs6) {
  37755. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  37756. }
  37757. if (parsedVertexData.hasColors) {
  37758. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  37759. }
  37760. if (parsedVertexData.hasMatricesIndices) {
  37761. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  37762. }
  37763. if (parsedVertexData.hasMatricesWeights) {
  37764. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  37765. }
  37766. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  37767. }
  37768. else {
  37769. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  37770. }
  37771. scene.pushGeometry(geometry, true);
  37772. return geometry;
  37773. };
  37774. return Geometry;
  37775. }());
  37776. BABYLON.Geometry = Geometry;
  37777. /////// Primitives //////////////////////////////////////////////
  37778. (function (Geometry) {
  37779. var Primitives;
  37780. (function (Primitives) {
  37781. /// Abstract class
  37782. var _Primitive = (function (_super) {
  37783. __extends(_Primitive, _super);
  37784. function _Primitive(id, scene, _canBeRegenerated, mesh) {
  37785. var _this = _super.call(this, id, scene, null, false, mesh) || this;
  37786. _this._canBeRegenerated = _canBeRegenerated;
  37787. _this._beingRegenerated = true;
  37788. _this.regenerate();
  37789. _this._beingRegenerated = false;
  37790. return _this;
  37791. }
  37792. _Primitive.prototype.canBeRegenerated = function () {
  37793. return this._canBeRegenerated;
  37794. };
  37795. _Primitive.prototype.regenerate = function () {
  37796. if (!this._canBeRegenerated) {
  37797. return;
  37798. }
  37799. this._beingRegenerated = true;
  37800. this.setAllVerticesData(this._regenerateVertexData(), false);
  37801. this._beingRegenerated = false;
  37802. };
  37803. _Primitive.prototype.asNewGeometry = function (id) {
  37804. return _super.prototype.copy.call(this, id);
  37805. };
  37806. // overrides
  37807. _Primitive.prototype.setAllVerticesData = function (vertexData, updatable) {
  37808. if (!this._beingRegenerated) {
  37809. return;
  37810. }
  37811. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  37812. };
  37813. _Primitive.prototype.setVerticesData = function (kind, data, updatable) {
  37814. if (!this._beingRegenerated) {
  37815. return;
  37816. }
  37817. _super.prototype.setVerticesData.call(this, kind, data, false);
  37818. };
  37819. // to override
  37820. // protected
  37821. _Primitive.prototype._regenerateVertexData = function () {
  37822. throw new Error("Abstract method");
  37823. };
  37824. _Primitive.prototype.copy = function (id) {
  37825. throw new Error("Must be overriden in sub-classes.");
  37826. };
  37827. _Primitive.prototype.serialize = function () {
  37828. var serializationObject = _super.prototype.serialize.call(this);
  37829. serializationObject.canBeRegenerated = this.canBeRegenerated();
  37830. return serializationObject;
  37831. };
  37832. return _Primitive;
  37833. }(Geometry));
  37834. Primitives._Primitive = _Primitive;
  37835. var Ribbon = (function (_super) {
  37836. __extends(Ribbon, _super);
  37837. // Members
  37838. function Ribbon(id, scene, pathArray, closeArray, closePath, offset, canBeRegenerated, mesh, side) {
  37839. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  37840. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  37841. _this.pathArray = pathArray;
  37842. _this.closeArray = closeArray;
  37843. _this.closePath = closePath;
  37844. _this.offset = offset;
  37845. _this.side = side;
  37846. return _this;
  37847. }
  37848. Ribbon.prototype._regenerateVertexData = function () {
  37849. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  37850. };
  37851. Ribbon.prototype.copy = function (id) {
  37852. return new Ribbon(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), null, this.side);
  37853. };
  37854. return Ribbon;
  37855. }(_Primitive));
  37856. Primitives.Ribbon = Ribbon;
  37857. var Box = (function (_super) {
  37858. __extends(Box, _super);
  37859. // Members
  37860. function Box(id, scene, size, canBeRegenerated, mesh, side) {
  37861. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  37862. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  37863. _this.size = size;
  37864. _this.side = side;
  37865. return _this;
  37866. }
  37867. Box.prototype._regenerateVertexData = function () {
  37868. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  37869. };
  37870. Box.prototype.copy = function (id) {
  37871. return new Box(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  37872. };
  37873. Box.prototype.serialize = function () {
  37874. var serializationObject = _super.prototype.serialize.call(this);
  37875. serializationObject.size = this.size;
  37876. return serializationObject;
  37877. };
  37878. Box.Parse = function (parsedBox, scene) {
  37879. if (scene.getGeometryByID(parsedBox.id)) {
  37880. return null; // null since geometry could be something else than a box...
  37881. }
  37882. var box = new Geometry.Primitives.Box(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  37883. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  37884. scene.pushGeometry(box, true);
  37885. return box;
  37886. };
  37887. return Box;
  37888. }(_Primitive));
  37889. Primitives.Box = Box;
  37890. var Sphere = (function (_super) {
  37891. __extends(Sphere, _super);
  37892. function Sphere(id, scene, segments, diameter, canBeRegenerated, mesh, side) {
  37893. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  37894. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  37895. _this.segments = segments;
  37896. _this.diameter = diameter;
  37897. _this.side = side;
  37898. return _this;
  37899. }
  37900. Sphere.prototype._regenerateVertexData = function () {
  37901. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  37902. };
  37903. Sphere.prototype.copy = function (id) {
  37904. return new Sphere(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  37905. };
  37906. Sphere.prototype.serialize = function () {
  37907. var serializationObject = _super.prototype.serialize.call(this);
  37908. serializationObject.segments = this.segments;
  37909. serializationObject.diameter = this.diameter;
  37910. return serializationObject;
  37911. };
  37912. Sphere.Parse = function (parsedSphere, scene) {
  37913. if (scene.getGeometryByID(parsedSphere.id)) {
  37914. return null; // null since geometry could be something else than a sphere...
  37915. }
  37916. var sphere = new Geometry.Primitives.Sphere(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  37917. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  37918. scene.pushGeometry(sphere, true);
  37919. return sphere;
  37920. };
  37921. return Sphere;
  37922. }(_Primitive));
  37923. Primitives.Sphere = Sphere;
  37924. var Disc = (function (_super) {
  37925. __extends(Disc, _super);
  37926. // Members
  37927. function Disc(id, scene, radius, tessellation, canBeRegenerated, mesh, side) {
  37928. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  37929. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  37930. _this.radius = radius;
  37931. _this.tessellation = tessellation;
  37932. _this.side = side;
  37933. return _this;
  37934. }
  37935. Disc.prototype._regenerateVertexData = function () {
  37936. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  37937. };
  37938. Disc.prototype.copy = function (id) {
  37939. return new Disc(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  37940. };
  37941. return Disc;
  37942. }(_Primitive));
  37943. Primitives.Disc = Disc;
  37944. var Cylinder = (function (_super) {
  37945. __extends(Cylinder, _super);
  37946. function Cylinder(id, scene, height, diameterTop, diameterBottom, tessellation, subdivisions, canBeRegenerated, mesh, side) {
  37947. if (subdivisions === void 0) { subdivisions = 1; }
  37948. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  37949. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  37950. _this.height = height;
  37951. _this.diameterTop = diameterTop;
  37952. _this.diameterBottom = diameterBottom;
  37953. _this.tessellation = tessellation;
  37954. _this.subdivisions = subdivisions;
  37955. _this.side = side;
  37956. return _this;
  37957. }
  37958. Cylinder.prototype._regenerateVertexData = function () {
  37959. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  37960. };
  37961. Cylinder.prototype.copy = function (id) {
  37962. return new Cylinder(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  37963. };
  37964. Cylinder.prototype.serialize = function () {
  37965. var serializationObject = _super.prototype.serialize.call(this);
  37966. serializationObject.height = this.height;
  37967. serializationObject.diameterTop = this.diameterTop;
  37968. serializationObject.diameterBottom = this.diameterBottom;
  37969. serializationObject.tessellation = this.tessellation;
  37970. return serializationObject;
  37971. };
  37972. Cylinder.Parse = function (parsedCylinder, scene) {
  37973. if (scene.getGeometryByID(parsedCylinder.id)) {
  37974. return null; // null since geometry could be something else than a cylinder...
  37975. }
  37976. var cylinder = new Geometry.Primitives.Cylinder(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  37977. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  37978. scene.pushGeometry(cylinder, true);
  37979. return cylinder;
  37980. };
  37981. return Cylinder;
  37982. }(_Primitive));
  37983. Primitives.Cylinder = Cylinder;
  37984. var Torus = (function (_super) {
  37985. __extends(Torus, _super);
  37986. function Torus(id, scene, diameter, thickness, tessellation, canBeRegenerated, mesh, side) {
  37987. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  37988. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  37989. _this.diameter = diameter;
  37990. _this.thickness = thickness;
  37991. _this.tessellation = tessellation;
  37992. _this.side = side;
  37993. return _this;
  37994. }
  37995. Torus.prototype._regenerateVertexData = function () {
  37996. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  37997. };
  37998. Torus.prototype.copy = function (id) {
  37999. return new Torus(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  38000. };
  38001. Torus.prototype.serialize = function () {
  38002. var serializationObject = _super.prototype.serialize.call(this);
  38003. serializationObject.diameter = this.diameter;
  38004. serializationObject.thickness = this.thickness;
  38005. serializationObject.tessellation = this.tessellation;
  38006. return serializationObject;
  38007. };
  38008. Torus.Parse = function (parsedTorus, scene) {
  38009. if (scene.getGeometryByID(parsedTorus.id)) {
  38010. return null; // null since geometry could be something else than a torus...
  38011. }
  38012. var torus = new Geometry.Primitives.Torus(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  38013. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  38014. scene.pushGeometry(torus, true);
  38015. return torus;
  38016. };
  38017. return Torus;
  38018. }(_Primitive));
  38019. Primitives.Torus = Torus;
  38020. var Ground = (function (_super) {
  38021. __extends(Ground, _super);
  38022. function Ground(id, scene, width, height, subdivisions, canBeRegenerated, mesh) {
  38023. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  38024. _this.width = width;
  38025. _this.height = height;
  38026. _this.subdivisions = subdivisions;
  38027. return _this;
  38028. }
  38029. Ground.prototype._regenerateVertexData = function () {
  38030. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  38031. };
  38032. Ground.prototype.copy = function (id) {
  38033. return new Ground(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  38034. };
  38035. Ground.prototype.serialize = function () {
  38036. var serializationObject = _super.prototype.serialize.call(this);
  38037. serializationObject.width = this.width;
  38038. serializationObject.height = this.height;
  38039. serializationObject.subdivisions = this.subdivisions;
  38040. return serializationObject;
  38041. };
  38042. Ground.Parse = function (parsedGround, scene) {
  38043. if (scene.getGeometryByID(parsedGround.id)) {
  38044. return null; // null since geometry could be something else than a ground...
  38045. }
  38046. var ground = new Geometry.Primitives.Ground(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  38047. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  38048. scene.pushGeometry(ground, true);
  38049. return ground;
  38050. };
  38051. return Ground;
  38052. }(_Primitive));
  38053. Primitives.Ground = Ground;
  38054. var TiledGround = (function (_super) {
  38055. __extends(TiledGround, _super);
  38056. function TiledGround(id, scene, xmin, zmin, xmax, zmax, subdivisions, precision, canBeRegenerated, mesh) {
  38057. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  38058. _this.xmin = xmin;
  38059. _this.zmin = zmin;
  38060. _this.xmax = xmax;
  38061. _this.zmax = zmax;
  38062. _this.subdivisions = subdivisions;
  38063. _this.precision = precision;
  38064. return _this;
  38065. }
  38066. TiledGround.prototype._regenerateVertexData = function () {
  38067. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  38068. };
  38069. TiledGround.prototype.copy = function (id) {
  38070. return new TiledGround(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  38071. };
  38072. return TiledGround;
  38073. }(_Primitive));
  38074. Primitives.TiledGround = TiledGround;
  38075. var Plane = (function (_super) {
  38076. __extends(Plane, _super);
  38077. function Plane(id, scene, size, canBeRegenerated, mesh, side) {
  38078. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  38079. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  38080. _this.size = size;
  38081. _this.side = side;
  38082. return _this;
  38083. }
  38084. Plane.prototype._regenerateVertexData = function () {
  38085. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  38086. };
  38087. Plane.prototype.copy = function (id) {
  38088. return new Plane(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  38089. };
  38090. Plane.prototype.serialize = function () {
  38091. var serializationObject = _super.prototype.serialize.call(this);
  38092. serializationObject.size = this.size;
  38093. return serializationObject;
  38094. };
  38095. Plane.Parse = function (parsedPlane, scene) {
  38096. if (scene.getGeometryByID(parsedPlane.id)) {
  38097. return null; // null since geometry could be something else than a ground...
  38098. }
  38099. var plane = new Geometry.Primitives.Plane(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  38100. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  38101. scene.pushGeometry(plane, true);
  38102. return plane;
  38103. };
  38104. return Plane;
  38105. }(_Primitive));
  38106. Primitives.Plane = Plane;
  38107. var TorusKnot = (function (_super) {
  38108. __extends(TorusKnot, _super);
  38109. function TorusKnot(id, scene, radius, tube, radialSegments, tubularSegments, p, q, canBeRegenerated, mesh, side) {
  38110. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  38111. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  38112. _this.radius = radius;
  38113. _this.tube = tube;
  38114. _this.radialSegments = radialSegments;
  38115. _this.tubularSegments = tubularSegments;
  38116. _this.p = p;
  38117. _this.q = q;
  38118. _this.side = side;
  38119. return _this;
  38120. }
  38121. TorusKnot.prototype._regenerateVertexData = function () {
  38122. 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 });
  38123. };
  38124. TorusKnot.prototype.copy = function (id) {
  38125. return new TorusKnot(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  38126. };
  38127. TorusKnot.prototype.serialize = function () {
  38128. var serializationObject = _super.prototype.serialize.call(this);
  38129. serializationObject.radius = this.radius;
  38130. serializationObject.tube = this.tube;
  38131. serializationObject.radialSegments = this.radialSegments;
  38132. serializationObject.tubularSegments = this.tubularSegments;
  38133. serializationObject.p = this.p;
  38134. serializationObject.q = this.q;
  38135. return serializationObject;
  38136. };
  38137. ;
  38138. TorusKnot.Parse = function (parsedTorusKnot, scene) {
  38139. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  38140. return null; // null since geometry could be something else than a ground...
  38141. }
  38142. var torusKnot = new Geometry.Primitives.TorusKnot(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  38143. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  38144. scene.pushGeometry(torusKnot, true);
  38145. return torusKnot;
  38146. };
  38147. return TorusKnot;
  38148. }(_Primitive));
  38149. Primitives.TorusKnot = TorusKnot;
  38150. })(Primitives = Geometry.Primitives || (Geometry.Primitives = {}));
  38151. })(Geometry = BABYLON.Geometry || (BABYLON.Geometry = {}));
  38152. })(BABYLON || (BABYLON = {}));
  38153. //# sourceMappingURL=babylon.geometry.js.map
  38154. var BABYLON;
  38155. (function (BABYLON) {
  38156. var GroundMesh = (function (_super) {
  38157. __extends(GroundMesh, _super);
  38158. function GroundMesh(name, scene) {
  38159. var _this = _super.call(this, name, scene) || this;
  38160. _this.generateOctree = false;
  38161. _this._worldInverse = new BABYLON.Matrix();
  38162. return _this;
  38163. }
  38164. GroundMesh.prototype.getClassName = function () {
  38165. return "GroundMesh";
  38166. };
  38167. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  38168. get: function () {
  38169. return Math.min(this._subdivisionsX, this._subdivisionsY);
  38170. },
  38171. enumerable: true,
  38172. configurable: true
  38173. });
  38174. Object.defineProperty(GroundMesh.prototype, "subdivisionsX", {
  38175. get: function () {
  38176. return this._subdivisionsX;
  38177. },
  38178. enumerable: true,
  38179. configurable: true
  38180. });
  38181. Object.defineProperty(GroundMesh.prototype, "subdivisionsY", {
  38182. get: function () {
  38183. return this._subdivisionsY;
  38184. },
  38185. enumerable: true,
  38186. configurable: true
  38187. });
  38188. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  38189. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  38190. this._subdivisionsX = chunksCount;
  38191. this._subdivisionsY = chunksCount;
  38192. this.subdivide(chunksCount);
  38193. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  38194. };
  38195. /**
  38196. * Returns a height (y) value in the Worl system :
  38197. * the ground altitude at the coordinates (x, z) expressed in the World system.
  38198. * Returns the ground y position if (x, z) are outside the ground surface.
  38199. */
  38200. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  38201. var world = this.getWorldMatrix();
  38202. var invMat = BABYLON.Tmp.Matrix[5];
  38203. world.invertToRef(invMat);
  38204. var tmpVect = BABYLON.Tmp.Vector3[8];
  38205. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, invMat, tmpVect); // transform x,z in the mesh local space
  38206. x = tmpVect.x;
  38207. z = tmpVect.z;
  38208. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  38209. return this.position.y;
  38210. }
  38211. if (!this._heightQuads || this._heightQuads.length == 0) {
  38212. this._initHeightQuads();
  38213. this._computeHeightQuads();
  38214. }
  38215. var facet = this._getFacetAt(x, z);
  38216. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  38217. // return y in the World system
  38218. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0.0, y, 0.0, world, tmpVect);
  38219. return tmpVect.y;
  38220. };
  38221. /**
  38222. * Returns a normalized vector (Vector3) orthogonal to the ground
  38223. * at the ground coordinates (x, z) expressed in the World system.
  38224. * Returns Vector3(0.0, 1.0, 0.0) if (x, z) are outside the ground surface.
  38225. */
  38226. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  38227. var normal = new BABYLON.Vector3(0.0, 1.0, 0.0);
  38228. this.getNormalAtCoordinatesToRef(x, z, normal);
  38229. return normal;
  38230. };
  38231. /**
  38232. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  38233. * at the ground coordinates (x, z) expressed in the World system.
  38234. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  38235. * Returns the GroundMesh.
  38236. */
  38237. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  38238. var world = this.getWorldMatrix();
  38239. var tmpMat = BABYLON.Tmp.Matrix[5];
  38240. world.invertToRef(tmpMat);
  38241. var tmpVect = BABYLON.Tmp.Vector3[8];
  38242. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, tmpMat, tmpVect); // transform x,z in the mesh local space
  38243. x = tmpVect.x;
  38244. z = tmpVect.z;
  38245. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  38246. return this;
  38247. }
  38248. if (!this._heightQuads || this._heightQuads.length == 0) {
  38249. this._initHeightQuads();
  38250. this._computeHeightQuads();
  38251. }
  38252. var facet = this._getFacetAt(x, z);
  38253. BABYLON.Vector3.TransformNormalFromFloatsToRef(facet.x, facet.y, facet.z, world, ref);
  38254. return this;
  38255. };
  38256. /**
  38257. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  38258. * if the ground has been updated.
  38259. * This can be used in the render loop
  38260. */
  38261. GroundMesh.prototype.updateCoordinateHeights = function () {
  38262. if (!this._heightQuads || this._heightQuads.length == 0) {
  38263. this._initHeightQuads();
  38264. }
  38265. this._computeHeightQuads();
  38266. };
  38267. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  38268. GroundMesh.prototype._getFacetAt = function (x, z) {
  38269. // retrieve col and row from x, z coordinates in the ground local system
  38270. var subdivisionsX = this._subdivisionsX;
  38271. var subdivisionsY = this._subdivisionsY;
  38272. var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);
  38273. var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);
  38274. var quad = this._heightQuads[row * this._subdivisionsX + col];
  38275. var facet;
  38276. if (z < quad.slope.x * x + quad.slope.y) {
  38277. facet = quad.facet1;
  38278. }
  38279. else {
  38280. facet = quad.facet2;
  38281. }
  38282. return facet;
  38283. };
  38284. // Creates and populates the heightMap array with "facet" elements :
  38285. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  38286. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  38287. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  38288. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  38289. GroundMesh.prototype._initHeightQuads = function () {
  38290. var subdivisionsX = this._subdivisionsX;
  38291. var subdivisionsY = this._subdivisionsY;
  38292. this._heightQuads = new Array();
  38293. for (var row = 0; row < subdivisionsY; row++) {
  38294. for (var col = 0; col < subdivisionsX; col++) {
  38295. 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) };
  38296. this._heightQuads[row * subdivisionsX + col] = quad;
  38297. }
  38298. }
  38299. };
  38300. // Compute each quad element values and update the the heightMap array :
  38301. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  38302. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  38303. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  38304. GroundMesh.prototype._computeHeightQuads = function () {
  38305. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  38306. var v1 = BABYLON.Tmp.Vector3[3];
  38307. var v2 = BABYLON.Tmp.Vector3[2];
  38308. var v3 = BABYLON.Tmp.Vector3[1];
  38309. var v4 = BABYLON.Tmp.Vector3[0];
  38310. var v1v2 = BABYLON.Tmp.Vector3[4];
  38311. var v1v3 = BABYLON.Tmp.Vector3[5];
  38312. var v1v4 = BABYLON.Tmp.Vector3[6];
  38313. var norm1 = BABYLON.Tmp.Vector3[7];
  38314. var norm2 = BABYLON.Tmp.Vector3[8];
  38315. var i = 0;
  38316. var j = 0;
  38317. var k = 0;
  38318. var cd = 0; // 2D slope coefficient : z = cd * x + h
  38319. var h = 0;
  38320. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  38321. var d2 = 0;
  38322. var subdivisionsX = this._subdivisionsX;
  38323. var subdivisionsY = this._subdivisionsY;
  38324. for (var row = 0; row < subdivisionsY; row++) {
  38325. for (var col = 0; col < subdivisionsX; col++) {
  38326. i = col * 3;
  38327. j = row * (subdivisionsX + 1) * 3;
  38328. k = (row + 1) * (subdivisionsX + 1) * 3;
  38329. v1.x = positions[j + i];
  38330. v1.y = positions[j + i + 1];
  38331. v1.z = positions[j + i + 2];
  38332. v2.x = positions[j + i + 3];
  38333. v2.y = positions[j + i + 4];
  38334. v2.z = positions[j + i + 5];
  38335. v3.x = positions[k + i];
  38336. v3.y = positions[k + i + 1];
  38337. v3.z = positions[k + i + 2];
  38338. v4.x = positions[k + i + 3];
  38339. v4.y = positions[k + i + 4];
  38340. v4.z = positions[k + i + 5];
  38341. // 2D slope V1V4
  38342. cd = (v4.z - v1.z) / (v4.x - v1.x);
  38343. h = v1.z - cd * v1.x; // v1 belongs to the slope
  38344. // facet equations :
  38345. // we compute each facet normal vector
  38346. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  38347. // we compute the value d by applying the equation to v1 which belongs to the plane
  38348. // then we store the facet equation in a Vector4
  38349. v2.subtractToRef(v1, v1v2);
  38350. v3.subtractToRef(v1, v1v3);
  38351. v4.subtractToRef(v1, v1v4);
  38352. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  38353. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  38354. norm1.normalize();
  38355. norm2.normalize();
  38356. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  38357. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  38358. var quad = this._heightQuads[row * subdivisionsX + col];
  38359. quad.slope.copyFromFloats(cd, h);
  38360. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  38361. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  38362. }
  38363. }
  38364. };
  38365. return GroundMesh;
  38366. }(BABYLON.Mesh));
  38367. BABYLON.GroundMesh = GroundMesh;
  38368. })(BABYLON || (BABYLON = {}));
  38369. //# sourceMappingURL=babylon.groundMesh.js.map
  38370. var BABYLON;
  38371. (function (BABYLON) {
  38372. var LinesMesh = (function (_super) {
  38373. __extends(LinesMesh, _super);
  38374. function LinesMesh(name, scene, parent, source, doNotCloneChildren) {
  38375. if (parent === void 0) { parent = null; }
  38376. var _this = _super.call(this, name, scene, parent, source, doNotCloneChildren) || this;
  38377. _this.color = new BABYLON.Color3(1, 1, 1);
  38378. _this.alpha = 1;
  38379. _this._positionBuffer = {};
  38380. if (source) {
  38381. _this.color = source.color.clone();
  38382. _this.alpha = source.alpha;
  38383. }
  38384. _this._intersectionThreshold = 0.1;
  38385. _this._colorShader = new BABYLON.ShaderMaterial("colorShader", scene, "color", {
  38386. attributes: [BABYLON.VertexBuffer.PositionKind],
  38387. uniforms: ["worldViewProjection", "color"],
  38388. needAlphaBlending: true
  38389. });
  38390. _this._positionBuffer[BABYLON.VertexBuffer.PositionKind] = null;
  38391. return _this;
  38392. }
  38393. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  38394. /**
  38395. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  38396. * This margin is expressed in world space coordinates, so its value may vary.
  38397. * Default value is 0.1
  38398. * @returns the intersection Threshold value.
  38399. */
  38400. get: function () {
  38401. return this._intersectionThreshold;
  38402. },
  38403. /**
  38404. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  38405. * This margin is expressed in world space coordinates, so its value may vary.
  38406. * @param value the new threshold to apply
  38407. */
  38408. set: function (value) {
  38409. if (this._intersectionThreshold === value) {
  38410. return;
  38411. }
  38412. this._intersectionThreshold = value;
  38413. if (this.geometry) {
  38414. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  38415. }
  38416. },
  38417. enumerable: true,
  38418. configurable: true
  38419. });
  38420. LinesMesh.prototype.getClassName = function () {
  38421. return "LinesMesh";
  38422. };
  38423. Object.defineProperty(LinesMesh.prototype, "material", {
  38424. get: function () {
  38425. return this._colorShader;
  38426. },
  38427. enumerable: true,
  38428. configurable: true
  38429. });
  38430. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  38431. get: function () {
  38432. return false;
  38433. },
  38434. enumerable: true,
  38435. configurable: true
  38436. });
  38437. LinesMesh.prototype.createInstance = function (name) {
  38438. BABYLON.Tools.Log("LinesMeshes do not support createInstance.");
  38439. return null;
  38440. };
  38441. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  38442. var engine = this.getScene().getEngine();
  38443. this._positionBuffer[BABYLON.VertexBuffer.PositionKind] = this._geometry.getVertexBuffer(BABYLON.VertexBuffer.PositionKind);
  38444. // VBOs
  38445. engine.bindBuffers(this._positionBuffer, this._geometry.getIndexBuffer(), this._colorShader.getEffect());
  38446. // Color
  38447. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  38448. };
  38449. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  38450. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  38451. return;
  38452. }
  38453. var engine = this.getScene().getEngine();
  38454. // Draw order
  38455. engine.draw(false, subMesh.indexStart, subMesh.indexCount);
  38456. };
  38457. LinesMesh.prototype.dispose = function (doNotRecurse) {
  38458. this._colorShader.dispose();
  38459. _super.prototype.dispose.call(this, doNotRecurse);
  38460. };
  38461. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  38462. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  38463. };
  38464. return LinesMesh;
  38465. }(BABYLON.Mesh));
  38466. BABYLON.LinesMesh = LinesMesh;
  38467. })(BABYLON || (BABYLON = {}));
  38468. //# sourceMappingURL=babylon.linesMesh.js.map
  38469. var BABYLON;
  38470. (function (BABYLON) {
  38471. var DefaultLoadingScreen = (function () {
  38472. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  38473. if (_loadingText === void 0) { _loadingText = ""; }
  38474. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  38475. var _this = this;
  38476. this._renderingCanvas = _renderingCanvas;
  38477. this._loadingText = _loadingText;
  38478. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  38479. // Resize
  38480. this._resizeLoadingUI = function () {
  38481. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  38482. _this._loadingDiv.style.position = "absolute";
  38483. _this._loadingDiv.style.left = canvasRect.left + "px";
  38484. _this._loadingDiv.style.top = canvasRect.top + "px";
  38485. _this._loadingDiv.style.width = canvasRect.width + "px";
  38486. _this._loadingDiv.style.height = canvasRect.height + "px";
  38487. };
  38488. }
  38489. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  38490. var _this = this;
  38491. if (this._loadingDiv) {
  38492. // Do not add a loading screen if there is already one
  38493. return;
  38494. }
  38495. this._loadingDiv = document.createElement("div");
  38496. this._loadingDiv.id = "babylonjsLoadingDiv";
  38497. this._loadingDiv.style.opacity = "0";
  38498. this._loadingDiv.style.transition = "opacity 1.5s ease";
  38499. // Loading text
  38500. this._loadingTextDiv = document.createElement("div");
  38501. this._loadingTextDiv.style.position = "absolute";
  38502. this._loadingTextDiv.style.left = "0";
  38503. this._loadingTextDiv.style.top = "50%";
  38504. this._loadingTextDiv.style.marginTop = "80px";
  38505. this._loadingTextDiv.style.width = "100%";
  38506. this._loadingTextDiv.style.height = "20px";
  38507. this._loadingTextDiv.style.fontFamily = "Arial";
  38508. this._loadingTextDiv.style.fontSize = "14px";
  38509. this._loadingTextDiv.style.color = "white";
  38510. this._loadingTextDiv.style.textAlign = "center";
  38511. this._loadingTextDiv.innerHTML = "Loading";
  38512. this._loadingDiv.appendChild(this._loadingTextDiv);
  38513. //set the predefined text
  38514. this._loadingTextDiv.innerHTML = this._loadingText;
  38515. // Loading img
  38516. var imgBack = new Image();
  38517. 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==";
  38518. imgBack.style.position = "absolute";
  38519. imgBack.style.left = "50%";
  38520. imgBack.style.top = "50%";
  38521. imgBack.style.marginLeft = "-50px";
  38522. imgBack.style.marginTop = "-50px";
  38523. imgBack.style.transition = "transform 1.0s ease";
  38524. imgBack.style.webkitTransition = "-webkit-transform 1.0s ease";
  38525. var deg = 360;
  38526. var onTransitionEnd = function () {
  38527. deg += 360;
  38528. imgBack.style.transform = "rotateZ(" + deg + "deg)";
  38529. imgBack.style.webkitTransform = "rotateZ(" + deg + "deg)";
  38530. };
  38531. imgBack.addEventListener("transitionend", onTransitionEnd);
  38532. imgBack.addEventListener("webkitTransitionEnd", onTransitionEnd);
  38533. this._loadingDiv.appendChild(imgBack);
  38534. // front image
  38535. var imgFront = new Image();
  38536. 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=";
  38537. imgFront.style.position = "absolute";
  38538. imgFront.style.left = "50%";
  38539. imgFront.style.top = "50%";
  38540. imgFront.style.marginLeft = "-50px";
  38541. imgFront.style.marginTop = "-50px";
  38542. this._loadingDiv.appendChild(imgFront);
  38543. this._resizeLoadingUI();
  38544. window.addEventListener("resize", this._resizeLoadingUI);
  38545. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  38546. document.body.appendChild(this._loadingDiv);
  38547. setTimeout(function () {
  38548. _this._loadingDiv.style.opacity = "1";
  38549. imgBack.style.transform = "rotateZ(360deg)";
  38550. imgBack.style.webkitTransform = "rotateZ(360deg)";
  38551. }, 0);
  38552. };
  38553. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  38554. var _this = this;
  38555. if (!this._loadingDiv) {
  38556. return;
  38557. }
  38558. var onTransitionEnd = function () {
  38559. if (!_this._loadingDiv) {
  38560. return;
  38561. }
  38562. document.body.removeChild(_this._loadingDiv);
  38563. window.removeEventListener("resize", _this._resizeLoadingUI);
  38564. _this._loadingDiv = null;
  38565. };
  38566. this._loadingDiv.style.opacity = "0";
  38567. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  38568. };
  38569. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  38570. set: function (text) {
  38571. this._loadingText = text;
  38572. if (this._loadingTextDiv) {
  38573. this._loadingTextDiv.innerHTML = this._loadingText;
  38574. }
  38575. },
  38576. enumerable: true,
  38577. configurable: true
  38578. });
  38579. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  38580. get: function () {
  38581. return this._loadingDivBackgroundColor;
  38582. },
  38583. set: function (color) {
  38584. this._loadingDivBackgroundColor = color;
  38585. if (!this._loadingDiv) {
  38586. return;
  38587. }
  38588. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  38589. },
  38590. enumerable: true,
  38591. configurable: true
  38592. });
  38593. return DefaultLoadingScreen;
  38594. }());
  38595. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  38596. })(BABYLON || (BABYLON = {}));
  38597. //# sourceMappingURL=babylon.loadingScreen.js.map
  38598. var BABYLON;
  38599. (function (BABYLON) {
  38600. var AudioEngine = (function () {
  38601. function AudioEngine() {
  38602. this._audioContext = null;
  38603. this._audioContextInitialized = false;
  38604. this.canUseWebAudio = false;
  38605. this.WarnedWebAudioUnsupported = false;
  38606. this.unlocked = false;
  38607. this.isMP3supported = false;
  38608. this.isOGGsupported = false;
  38609. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  38610. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  38611. this.canUseWebAudio = true;
  38612. }
  38613. var audioElem = document.createElement('audio');
  38614. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/, '')) {
  38615. this.isMP3supported = true;
  38616. }
  38617. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) {
  38618. this.isOGGsupported = true;
  38619. }
  38620. if (/iPad|iPhone|iPod/.test(navigator.platform)) {
  38621. this._unlockiOSaudio();
  38622. }
  38623. else {
  38624. this.unlocked = true;
  38625. }
  38626. }
  38627. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  38628. get: function () {
  38629. if (!this._audioContextInitialized) {
  38630. this._initializeAudioContext();
  38631. }
  38632. return this._audioContext;
  38633. },
  38634. enumerable: true,
  38635. configurable: true
  38636. });
  38637. AudioEngine.prototype._unlockiOSaudio = function () {
  38638. var _this = this;
  38639. var unlockaudio = function () {
  38640. var buffer = _this.audioContext.createBuffer(1, 1, 22050);
  38641. var source = _this.audioContext.createBufferSource();
  38642. source.buffer = buffer;
  38643. source.connect(_this.audioContext.destination);
  38644. source.start(0);
  38645. setTimeout(function () {
  38646. if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
  38647. _this.unlocked = true;
  38648. window.removeEventListener('touchend', unlockaudio, false);
  38649. if (_this.onAudioUnlocked) {
  38650. _this.onAudioUnlocked();
  38651. }
  38652. }
  38653. }, 0);
  38654. };
  38655. window.addEventListener('touchend', unlockaudio, false);
  38656. };
  38657. AudioEngine.prototype._initializeAudioContext = function () {
  38658. try {
  38659. if (this.canUseWebAudio) {
  38660. this._audioContext = new AudioContext();
  38661. // create a global volume gain node
  38662. this.masterGain = this._audioContext.createGain();
  38663. this.masterGain.gain.value = 1;
  38664. this.masterGain.connect(this._audioContext.destination);
  38665. this._audioContextInitialized = true;
  38666. }
  38667. }
  38668. catch (e) {
  38669. this.canUseWebAudio = false;
  38670. BABYLON.Tools.Error("Web Audio: " + e.message);
  38671. }
  38672. };
  38673. AudioEngine.prototype.dispose = function () {
  38674. if (this.canUseWebAudio && this._audioContextInitialized) {
  38675. if (this._connectedAnalyser) {
  38676. this._connectedAnalyser.stopDebugCanvas();
  38677. this._connectedAnalyser.dispose();
  38678. this.masterGain.disconnect();
  38679. this.masterGain.connect(this._audioContext.destination);
  38680. this._connectedAnalyser = null;
  38681. }
  38682. this.masterGain.gain.value = 1;
  38683. }
  38684. this.WarnedWebAudioUnsupported = false;
  38685. };
  38686. AudioEngine.prototype.getGlobalVolume = function () {
  38687. if (this.canUseWebAudio && this._audioContextInitialized) {
  38688. return this.masterGain.gain.value;
  38689. }
  38690. else {
  38691. return -1;
  38692. }
  38693. };
  38694. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  38695. if (this.canUseWebAudio && this._audioContextInitialized) {
  38696. this.masterGain.gain.value = newVolume;
  38697. }
  38698. };
  38699. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  38700. if (this._connectedAnalyser) {
  38701. this._connectedAnalyser.stopDebugCanvas();
  38702. }
  38703. if (this.canUseWebAudio && this._audioContextInitialized) {
  38704. this._connectedAnalyser = analyser;
  38705. this.masterGain.disconnect();
  38706. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  38707. }
  38708. };
  38709. return AudioEngine;
  38710. }());
  38711. BABYLON.AudioEngine = AudioEngine;
  38712. })(BABYLON || (BABYLON = {}));
  38713. //# sourceMappingURL=babylon.audioEngine.js.map
  38714. var BABYLON;
  38715. (function (BABYLON) {
  38716. var Sound = (function () {
  38717. /**
  38718. * Create a sound and attach it to a scene
  38719. * @param name Name of your sound
  38720. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  38721. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  38722. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  38723. */
  38724. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  38725. var _this = this;
  38726. this.autoplay = false;
  38727. this.loop = false;
  38728. this.useCustomAttenuation = false;
  38729. this.spatialSound = false;
  38730. this.refDistance = 1;
  38731. this.rolloffFactor = 1;
  38732. this.maxDistance = 100;
  38733. this.distanceModel = "linear";
  38734. this._panningModel = "equalpower";
  38735. this._playbackRate = 1;
  38736. this._streaming = false;
  38737. this._startTime = 0;
  38738. this._startOffset = 0;
  38739. this._position = BABYLON.Vector3.Zero();
  38740. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  38741. this._volume = 1;
  38742. this._isLoaded = false;
  38743. this._isReadyToPlay = false;
  38744. this.isPlaying = false;
  38745. this.isPaused = false;
  38746. this._isDirectional = false;
  38747. // Used if you'd like to create a directional sound.
  38748. // If not set, the sound will be omnidirectional
  38749. this._coneInnerAngle = 360;
  38750. this._coneOuterAngle = 360;
  38751. this._coneOuterGain = 0;
  38752. this._isOutputConnected = false;
  38753. this._urlType = "Unknown";
  38754. this.name = name;
  38755. this._scene = scene;
  38756. this._readyToPlayCallback = readyToPlayCallback;
  38757. // Default custom attenuation function is a linear attenuation
  38758. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  38759. if (currentDistance < maxDistance) {
  38760. return currentVolume * (1 - currentDistance / maxDistance);
  38761. }
  38762. else {
  38763. return 0;
  38764. }
  38765. };
  38766. if (options) {
  38767. this.autoplay = options.autoplay || false;
  38768. this.loop = options.loop || false;
  38769. // if volume === 0, we need another way to check this option
  38770. if (options.volume !== undefined) {
  38771. this._volume = options.volume;
  38772. }
  38773. this.spatialSound = options.spatialSound || false;
  38774. this.maxDistance = options.maxDistance || 100;
  38775. this.useCustomAttenuation = options.useCustomAttenuation || false;
  38776. this.rolloffFactor = options.rolloffFactor || 1;
  38777. this.refDistance = options.refDistance || 1;
  38778. this.distanceModel = options.distanceModel || "linear";
  38779. this._playbackRate = options.playbackRate || 1;
  38780. this._streaming = options.streaming || false;
  38781. }
  38782. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  38783. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  38784. this._soundGain.gain.value = this._volume;
  38785. this._inputAudioNode = this._soundGain;
  38786. this._ouputAudioNode = this._soundGain;
  38787. if (this.spatialSound) {
  38788. this._createSpatialParameters();
  38789. }
  38790. this._scene.mainSoundTrack.AddSound(this);
  38791. var validParameter = true;
  38792. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  38793. if (urlOrArrayBuffer) {
  38794. if (typeof (urlOrArrayBuffer) === "string")
  38795. this._urlType = "String";
  38796. if (Array.isArray(urlOrArrayBuffer))
  38797. this._urlType = "Array";
  38798. if (urlOrArrayBuffer instanceof ArrayBuffer)
  38799. this._urlType = "ArrayBuffer";
  38800. var urls = [];
  38801. var codecSupportedFound = false;
  38802. switch (this._urlType) {
  38803. case "ArrayBuffer":
  38804. if (urlOrArrayBuffer.byteLength > 0) {
  38805. codecSupportedFound = true;
  38806. this._soundLoaded(urlOrArrayBuffer);
  38807. }
  38808. break;
  38809. case "String":
  38810. urls.push(urlOrArrayBuffer);
  38811. case "Array":
  38812. if (urls.length === 0)
  38813. urls = urlOrArrayBuffer;
  38814. // If we found a supported format, we load it immediately and stop the loop
  38815. for (var i = 0; i < urls.length; i++) {
  38816. var url = urls[i];
  38817. if (url.indexOf(".mp3", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isMP3supported) {
  38818. codecSupportedFound = true;
  38819. }
  38820. if (url.indexOf(".ogg", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isOGGsupported) {
  38821. codecSupportedFound = true;
  38822. }
  38823. if (url.indexOf(".wav", url.length - 4) !== -1) {
  38824. codecSupportedFound = true;
  38825. }
  38826. if (codecSupportedFound) {
  38827. // Loading sound using XHR2
  38828. if (!this._streaming) {
  38829. BABYLON.Tools.LoadFile(url, function (data) { _this._soundLoaded(data); }, null, this._scene.database, true);
  38830. }
  38831. else {
  38832. this._htmlAudioElement = new Audio(url);
  38833. this._htmlAudioElement.controls = false;
  38834. this._htmlAudioElement.loop = this.loop;
  38835. this._htmlAudioElement.crossOrigin = "anonymous";
  38836. this._htmlAudioElement.preload = "auto";
  38837. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  38838. _this._isReadyToPlay = true;
  38839. if (_this.autoplay) {
  38840. _this.play();
  38841. }
  38842. if (_this._readyToPlayCallback) {
  38843. _this._readyToPlayCallback();
  38844. }
  38845. });
  38846. document.body.appendChild(this._htmlAudioElement);
  38847. }
  38848. break;
  38849. }
  38850. }
  38851. break;
  38852. default:
  38853. validParameter = false;
  38854. break;
  38855. }
  38856. if (!validParameter) {
  38857. BABYLON.Tools.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.");
  38858. }
  38859. else {
  38860. if (!codecSupportedFound) {
  38861. this._isReadyToPlay = true;
  38862. // Simulating a ready to play event to avoid breaking code path
  38863. if (this._readyToPlayCallback) {
  38864. window.setTimeout(function () {
  38865. _this._readyToPlayCallback();
  38866. }, 1000);
  38867. }
  38868. }
  38869. }
  38870. }
  38871. }
  38872. else {
  38873. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  38874. this._scene.mainSoundTrack.AddSound(this);
  38875. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  38876. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  38877. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  38878. }
  38879. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  38880. if (this._readyToPlayCallback) {
  38881. window.setTimeout(function () {
  38882. _this._readyToPlayCallback();
  38883. }, 1000);
  38884. }
  38885. }
  38886. }
  38887. Sound.prototype.dispose = function () {
  38888. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isReadyToPlay) {
  38889. if (this.isPlaying) {
  38890. this.stop();
  38891. }
  38892. this._isReadyToPlay = false;
  38893. if (this.soundTrackId === -1) {
  38894. this._scene.mainSoundTrack.RemoveSound(this);
  38895. }
  38896. else {
  38897. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  38898. }
  38899. if (this._soundGain) {
  38900. this._soundGain.disconnect();
  38901. this._soundGain = null;
  38902. }
  38903. if (this._soundPanner) {
  38904. this._soundPanner.disconnect();
  38905. this._soundPanner = null;
  38906. }
  38907. if (this._soundSource) {
  38908. this._soundSource.disconnect();
  38909. this._soundSource = null;
  38910. }
  38911. this._audioBuffer = null;
  38912. if (this._htmlAudioElement) {
  38913. this._htmlAudioElement.pause();
  38914. this._htmlAudioElement.src = "";
  38915. document.body.removeChild(this._htmlAudioElement);
  38916. }
  38917. if (this._connectedMesh) {
  38918. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  38919. this._connectedMesh = null;
  38920. }
  38921. }
  38922. };
  38923. Sound.prototype.isReady = function () {
  38924. return this._isReadyToPlay;
  38925. };
  38926. Sound.prototype._soundLoaded = function (audioData) {
  38927. var _this = this;
  38928. this._isLoaded = true;
  38929. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  38930. _this._audioBuffer = buffer;
  38931. _this._isReadyToPlay = true;
  38932. if (_this.autoplay) {
  38933. _this.play();
  38934. }
  38935. if (_this._readyToPlayCallback) {
  38936. _this._readyToPlayCallback();
  38937. }
  38938. }, function (err) { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name + " / Error: " + err); });
  38939. };
  38940. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  38941. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  38942. this._audioBuffer = audioBuffer;
  38943. this._isReadyToPlay = true;
  38944. }
  38945. };
  38946. Sound.prototype.updateOptions = function (options) {
  38947. if (options) {
  38948. this.loop = options.loop || this.loop;
  38949. this.maxDistance = options.maxDistance || this.maxDistance;
  38950. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  38951. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  38952. this.refDistance = options.refDistance || this.refDistance;
  38953. this.distanceModel = options.distanceModel || this.distanceModel;
  38954. this._playbackRate = options.playbackRate || this._playbackRate;
  38955. this._updateSpatialParameters();
  38956. if (this.isPlaying) {
  38957. if (this._streaming) {
  38958. this._htmlAudioElement.playbackRate = this._playbackRate;
  38959. }
  38960. else {
  38961. this._soundSource.playbackRate.value = this._playbackRate;
  38962. }
  38963. }
  38964. }
  38965. };
  38966. Sound.prototype._createSpatialParameters = function () {
  38967. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  38968. if (this._scene.headphone) {
  38969. this._panningModel = "HRTF";
  38970. }
  38971. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  38972. this._updateSpatialParameters();
  38973. this._soundPanner.connect(this._ouputAudioNode);
  38974. this._inputAudioNode = this._soundPanner;
  38975. }
  38976. };
  38977. Sound.prototype._updateSpatialParameters = function () {
  38978. if (this.spatialSound) {
  38979. if (this.useCustomAttenuation) {
  38980. // Tricks to disable in a way embedded Web Audio attenuation
  38981. this._soundPanner.distanceModel = "linear";
  38982. this._soundPanner.maxDistance = Number.MAX_VALUE;
  38983. this._soundPanner.refDistance = 1;
  38984. this._soundPanner.rolloffFactor = 1;
  38985. this._soundPanner.panningModel = this._panningModel;
  38986. }
  38987. else {
  38988. this._soundPanner.distanceModel = this.distanceModel;
  38989. this._soundPanner.maxDistance = this.maxDistance;
  38990. this._soundPanner.refDistance = this.refDistance;
  38991. this._soundPanner.rolloffFactor = this.rolloffFactor;
  38992. this._soundPanner.panningModel = this._panningModel;
  38993. }
  38994. }
  38995. };
  38996. Sound.prototype.switchPanningModelToHRTF = function () {
  38997. this._panningModel = "HRTF";
  38998. this._switchPanningModel();
  38999. };
  39000. Sound.prototype.switchPanningModelToEqualPower = function () {
  39001. this._panningModel = "equalpower";
  39002. this._switchPanningModel();
  39003. };
  39004. Sound.prototype._switchPanningModel = function () {
  39005. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  39006. this._soundPanner.panningModel = this._panningModel;
  39007. }
  39008. };
  39009. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  39010. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  39011. if (this._isOutputConnected) {
  39012. this._ouputAudioNode.disconnect();
  39013. }
  39014. this._ouputAudioNode.connect(soundTrackAudioNode);
  39015. this._isOutputConnected = true;
  39016. }
  39017. };
  39018. /**
  39019. * Transform this sound into a directional source
  39020. * @param coneInnerAngle Size of the inner cone in degree
  39021. * @param coneOuterAngle Size of the outer cone in degree
  39022. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  39023. */
  39024. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  39025. if (coneOuterAngle < coneInnerAngle) {
  39026. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  39027. return;
  39028. }
  39029. this._coneInnerAngle = coneInnerAngle;
  39030. this._coneOuterAngle = coneOuterAngle;
  39031. this._coneOuterGain = coneOuterGain;
  39032. this._isDirectional = true;
  39033. if (this.isPlaying && this.loop) {
  39034. this.stop();
  39035. this.play();
  39036. }
  39037. };
  39038. Sound.prototype.setPosition = function (newPosition) {
  39039. this._position = newPosition;
  39040. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  39041. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  39042. }
  39043. };
  39044. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  39045. this._localDirection = newLocalDirection;
  39046. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  39047. this._updateDirection();
  39048. }
  39049. };
  39050. Sound.prototype._updateDirection = function () {
  39051. var mat = this._connectedMesh.getWorldMatrix();
  39052. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  39053. direction.normalize();
  39054. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  39055. };
  39056. Sound.prototype.updateDistanceFromListener = function () {
  39057. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation) {
  39058. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  39059. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  39060. }
  39061. };
  39062. Sound.prototype.setAttenuationFunction = function (callback) {
  39063. this._customAttenuationFunction = callback;
  39064. };
  39065. /**
  39066. * Play the sound
  39067. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  39068. * @param offset (optional) Start the sound setting it at a specific time
  39069. */
  39070. Sound.prototype.play = function (time, offset) {
  39071. var _this = this;
  39072. if (this._isReadyToPlay && this._scene.audioEnabled) {
  39073. try {
  39074. if (this._startOffset < 0) {
  39075. time = -this._startOffset;
  39076. this._startOffset = 0;
  39077. }
  39078. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  39079. if (!this._soundSource || !this._streamingSource) {
  39080. if (this.spatialSound) {
  39081. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  39082. if (this._isDirectional) {
  39083. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  39084. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  39085. this._soundPanner.coneOuterGain = this._coneOuterGain;
  39086. if (this._connectedMesh) {
  39087. this._updateDirection();
  39088. }
  39089. else {
  39090. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  39091. }
  39092. }
  39093. }
  39094. }
  39095. if (this._streaming) {
  39096. if (!this._streamingSource) {
  39097. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  39098. this._htmlAudioElement.onended = function () { _this._onended(); };
  39099. this._htmlAudioElement.playbackRate = this._playbackRate;
  39100. }
  39101. this._streamingSource.disconnect();
  39102. this._streamingSource.connect(this._inputAudioNode);
  39103. this._htmlAudioElement.play();
  39104. }
  39105. else {
  39106. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  39107. this._soundSource.buffer = this._audioBuffer;
  39108. this._soundSource.connect(this._inputAudioNode);
  39109. this._soundSource.loop = this.loop;
  39110. this._soundSource.playbackRate.value = this._playbackRate;
  39111. this._soundSource.onended = function () { _this._onended(); };
  39112. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : offset ? offset : 0);
  39113. }
  39114. this._startTime = startTime;
  39115. this.isPlaying = true;
  39116. this.isPaused = false;
  39117. }
  39118. catch (ex) {
  39119. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  39120. }
  39121. }
  39122. };
  39123. Sound.prototype._onended = function () {
  39124. this.isPlaying = false;
  39125. if (this.onended) {
  39126. this.onended();
  39127. }
  39128. };
  39129. /**
  39130. * Stop the sound
  39131. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  39132. */
  39133. Sound.prototype.stop = function (time) {
  39134. if (this.isPlaying) {
  39135. if (this._streaming) {
  39136. this._htmlAudioElement.pause();
  39137. // Test needed for Firefox or it will generate an Invalid State Error
  39138. if (this._htmlAudioElement.currentTime > 0) {
  39139. this._htmlAudioElement.currentTime = 0;
  39140. }
  39141. }
  39142. else {
  39143. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  39144. this._soundSource.stop(stopTime);
  39145. this._soundSource.onended = null;
  39146. if (!this.isPaused) {
  39147. this._startOffset = 0;
  39148. }
  39149. }
  39150. this.isPlaying = false;
  39151. }
  39152. };
  39153. Sound.prototype.pause = function () {
  39154. if (this.isPlaying) {
  39155. this.isPaused = true;
  39156. if (this._streaming) {
  39157. this._htmlAudioElement.pause();
  39158. }
  39159. else {
  39160. this.stop(0);
  39161. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  39162. }
  39163. }
  39164. };
  39165. Sound.prototype.setVolume = function (newVolume, time) {
  39166. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  39167. if (time) {
  39168. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  39169. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  39170. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  39171. }
  39172. else {
  39173. this._soundGain.gain.value = newVolume;
  39174. }
  39175. }
  39176. this._volume = newVolume;
  39177. };
  39178. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  39179. this._playbackRate = newPlaybackRate;
  39180. if (this.isPlaying) {
  39181. if (this._streaming) {
  39182. this._htmlAudioElement.playbackRate = this._playbackRate;
  39183. }
  39184. else {
  39185. this._soundSource.playbackRate.value = this._playbackRate;
  39186. }
  39187. }
  39188. };
  39189. Sound.prototype.getVolume = function () {
  39190. return this._volume;
  39191. };
  39192. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  39193. var _this = this;
  39194. if (this._connectedMesh) {
  39195. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  39196. this._registerFunc = null;
  39197. }
  39198. this._connectedMesh = meshToConnectTo;
  39199. if (!this.spatialSound) {
  39200. this.spatialSound = true;
  39201. this._createSpatialParameters();
  39202. if (this.isPlaying && this.loop) {
  39203. this.stop();
  39204. this.play();
  39205. }
  39206. }
  39207. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  39208. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  39209. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  39210. };
  39211. Sound.prototype.detachFromMesh = function () {
  39212. if (this._connectedMesh) {
  39213. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  39214. this._registerFunc = null;
  39215. this._connectedMesh = null;
  39216. }
  39217. };
  39218. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (connectedMesh) {
  39219. this.setPosition(connectedMesh.getBoundingInfo().boundingSphere.centerWorld);
  39220. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  39221. this._updateDirection();
  39222. }
  39223. };
  39224. Sound.prototype.clone = function () {
  39225. var _this = this;
  39226. if (!this._streaming) {
  39227. var setBufferAndRun = function () {
  39228. if (_this._isReadyToPlay) {
  39229. clonedSound._audioBuffer = _this.getAudioBuffer();
  39230. clonedSound._isReadyToPlay = true;
  39231. if (clonedSound.autoplay) {
  39232. clonedSound.play();
  39233. }
  39234. }
  39235. else {
  39236. window.setTimeout(setBufferAndRun, 300);
  39237. }
  39238. };
  39239. var currentOptions = {
  39240. autoplay: this.autoplay, loop: this.loop,
  39241. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  39242. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  39243. refDistance: this.refDistance, distanceModel: this.distanceModel
  39244. };
  39245. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  39246. if (this.useCustomAttenuation) {
  39247. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  39248. }
  39249. clonedSound.setPosition(this._position);
  39250. clonedSound.setPlaybackRate(this._playbackRate);
  39251. setBufferAndRun();
  39252. return clonedSound;
  39253. }
  39254. else {
  39255. return null;
  39256. }
  39257. };
  39258. Sound.prototype.getAudioBuffer = function () {
  39259. return this._audioBuffer;
  39260. };
  39261. Sound.prototype.serialize = function () {
  39262. var serializationObject = {
  39263. name: this.name,
  39264. url: this.name,
  39265. autoplay: this.autoplay,
  39266. loop: this.loop,
  39267. volume: this._volume,
  39268. spatialSound: this.spatialSound,
  39269. maxDistance: this.maxDistance,
  39270. rolloffFactor: this.rolloffFactor,
  39271. refDistance: this.refDistance,
  39272. distanceModel: this.distanceModel,
  39273. playbackRate: this._playbackRate,
  39274. panningModel: this._panningModel,
  39275. soundTrackId: this.soundTrackId
  39276. };
  39277. if (this.spatialSound) {
  39278. if (this._connectedMesh)
  39279. serializationObject.connectedMeshId = this._connectedMesh.id;
  39280. serializationObject.position = this._position.asArray();
  39281. serializationObject.refDistance = this.refDistance;
  39282. serializationObject.distanceModel = this.distanceModel;
  39283. serializationObject.isDirectional = this._isDirectional;
  39284. serializationObject.localDirectionToMesh = this._localDirection.asArray();
  39285. serializationObject.coneInnerAngle = this._coneInnerAngle;
  39286. serializationObject.coneOuterAngle = this._coneOuterAngle;
  39287. serializationObject.coneOuterGain = this._coneOuterGain;
  39288. }
  39289. return serializationObject;
  39290. };
  39291. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  39292. var soundName = parsedSound.name;
  39293. var soundUrl;
  39294. if (parsedSound.url) {
  39295. soundUrl = rootUrl + parsedSound.url;
  39296. }
  39297. else {
  39298. soundUrl = rootUrl + soundName;
  39299. }
  39300. var options = {
  39301. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  39302. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  39303. rolloffFactor: parsedSound.rolloffFactor,
  39304. refDistance: parsedSound.refDistance,
  39305. distanceModel: parsedSound.distanceModel,
  39306. playbackRate: parsedSound.playbackRate
  39307. };
  39308. var newSound;
  39309. if (!sourceSound) {
  39310. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  39311. scene._addPendingData(newSound);
  39312. }
  39313. else {
  39314. var setBufferAndRun = function () {
  39315. if (sourceSound._isReadyToPlay) {
  39316. newSound._audioBuffer = sourceSound.getAudioBuffer();
  39317. newSound._isReadyToPlay = true;
  39318. if (newSound.autoplay) {
  39319. newSound.play();
  39320. }
  39321. }
  39322. else {
  39323. window.setTimeout(setBufferAndRun, 300);
  39324. }
  39325. };
  39326. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  39327. setBufferAndRun();
  39328. }
  39329. if (parsedSound.position) {
  39330. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  39331. newSound.setPosition(soundPosition);
  39332. }
  39333. if (parsedSound.isDirectional) {
  39334. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  39335. if (parsedSound.localDirectionToMesh) {
  39336. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  39337. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  39338. }
  39339. }
  39340. if (parsedSound.connectedMeshId) {
  39341. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  39342. if (connectedMesh) {
  39343. newSound.attachToMesh(connectedMesh);
  39344. }
  39345. }
  39346. return newSound;
  39347. };
  39348. return Sound;
  39349. }());
  39350. BABYLON.Sound = Sound;
  39351. })(BABYLON || (BABYLON = {}));
  39352. //# sourceMappingURL=babylon.sound.js.map
  39353. var BABYLON;
  39354. (function (BABYLON) {
  39355. var SoundTrack = (function () {
  39356. function SoundTrack(scene, options) {
  39357. this.id = -1;
  39358. this._isMainTrack = false;
  39359. this._isInitialized = false;
  39360. this._scene = scene;
  39361. this.soundCollection = new Array();
  39362. this._options = options;
  39363. if (!this._isMainTrack) {
  39364. this._scene.soundTracks.push(this);
  39365. this.id = this._scene.soundTracks.length - 1;
  39366. }
  39367. }
  39368. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  39369. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  39370. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  39371. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  39372. if (this._options) {
  39373. if (this._options.volume) {
  39374. this._outputAudioNode.gain.value = this._options.volume;
  39375. }
  39376. if (this._options.mainTrack) {
  39377. this._isMainTrack = this._options.mainTrack;
  39378. }
  39379. }
  39380. this._isInitialized = true;
  39381. }
  39382. };
  39383. SoundTrack.prototype.dispose = function () {
  39384. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  39385. if (this._connectedAnalyser) {
  39386. this._connectedAnalyser.stopDebugCanvas();
  39387. }
  39388. while (this.soundCollection.length) {
  39389. this.soundCollection[0].dispose();
  39390. }
  39391. if (this._outputAudioNode) {
  39392. this._outputAudioNode.disconnect();
  39393. }
  39394. this._outputAudioNode = null;
  39395. }
  39396. };
  39397. SoundTrack.prototype.AddSound = function (sound) {
  39398. if (!this._isInitialized) {
  39399. this._initializeSoundTrackAudioGraph();
  39400. }
  39401. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  39402. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  39403. }
  39404. if (sound.soundTrackId) {
  39405. if (sound.soundTrackId === -1) {
  39406. this._scene.mainSoundTrack.RemoveSound(sound);
  39407. }
  39408. else {
  39409. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  39410. }
  39411. }
  39412. this.soundCollection.push(sound);
  39413. sound.soundTrackId = this.id;
  39414. };
  39415. SoundTrack.prototype.RemoveSound = function (sound) {
  39416. var index = this.soundCollection.indexOf(sound);
  39417. if (index !== -1) {
  39418. this.soundCollection.splice(index, 1);
  39419. }
  39420. };
  39421. SoundTrack.prototype.setVolume = function (newVolume) {
  39422. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  39423. this._outputAudioNode.gain.value = newVolume;
  39424. }
  39425. };
  39426. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  39427. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  39428. for (var i = 0; i < this.soundCollection.length; i++) {
  39429. this.soundCollection[i].switchPanningModelToHRTF();
  39430. }
  39431. }
  39432. };
  39433. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  39434. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  39435. for (var i = 0; i < this.soundCollection.length; i++) {
  39436. this.soundCollection[i].switchPanningModelToEqualPower();
  39437. }
  39438. }
  39439. };
  39440. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  39441. if (this._connectedAnalyser) {
  39442. this._connectedAnalyser.stopDebugCanvas();
  39443. }
  39444. this._connectedAnalyser = analyser;
  39445. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  39446. this._outputAudioNode.disconnect();
  39447. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  39448. }
  39449. };
  39450. return SoundTrack;
  39451. }());
  39452. BABYLON.SoundTrack = SoundTrack;
  39453. })(BABYLON || (BABYLON = {}));
  39454. //# sourceMappingURL=babylon.soundtrack.js.map
  39455. var BABYLON;
  39456. (function (BABYLON) {
  39457. /**
  39458. * Special Glow Blur post process only blurring the alpha channel
  39459. * It enforces keeping the most luminous color in the color channel.
  39460. */
  39461. var GlowBlurPostProcess = (function (_super) {
  39462. __extends(GlowBlurPostProcess, _super);
  39463. function GlowBlurPostProcess(name, direction, blurWidth, options, camera, samplingMode, engine, reusable) {
  39464. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  39465. var _this = _super.call(this, name, "glowBlurPostProcess", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable) || this;
  39466. _this.direction = direction;
  39467. _this.blurWidth = blurWidth;
  39468. _this.onApplyObservable.add(function (effect) {
  39469. effect.setFloat2("screenSize", _this.width, _this.height);
  39470. effect.setVector2("direction", _this.direction);
  39471. effect.setFloat("blurWidth", _this.blurWidth);
  39472. });
  39473. return _this;
  39474. }
  39475. return GlowBlurPostProcess;
  39476. }(BABYLON.PostProcess));
  39477. /**
  39478. * The highlight layer Helps adding a glow effect around a mesh.
  39479. *
  39480. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  39481. * glowy meshes to your scene.
  39482. *
  39483. * !!! THIS REQUIRES AN ACTIVE STENCIL BUFFER ON THE CANVAS !!!
  39484. */
  39485. var HighlightLayer = (function () {
  39486. /**
  39487. * Instantiates a new highlight Layer and references it to the scene..
  39488. * @param name The name of the layer
  39489. * @param scene The scene to use the layer in
  39490. * @param options Sets of none mandatory options to use with the layer (see IHighlightLayerOptions for more information)
  39491. */
  39492. function HighlightLayer(name, scene, options) {
  39493. this._vertexBuffers = {};
  39494. this._mainTextureDesiredSize = { width: 0, height: 0 };
  39495. this._meshes = {};
  39496. this._maxSize = 0;
  39497. this._shouldRender = false;
  39498. this._instanceGlowingMeshStencilReference = HighlightLayer.glowingMeshStencilReference++;
  39499. this._excludedMeshes = {};
  39500. /**
  39501. * Specifies whether or not the inner glow is ACTIVE in the layer.
  39502. */
  39503. this.innerGlow = true;
  39504. /**
  39505. * Specifies whether or not the outer glow is ACTIVE in the layer.
  39506. */
  39507. this.outerGlow = true;
  39508. /**
  39509. * Specifies wether the highlight layer is enabled or not.
  39510. */
  39511. this.isEnabled = true;
  39512. /**
  39513. * An event triggered when the highlight layer has been disposed.
  39514. * @type {BABYLON.Observable}
  39515. */
  39516. this.onDisposeObservable = new BABYLON.Observable();
  39517. /**
  39518. * An event triggered when the highlight layer is about rendering the main texture with the glowy parts.
  39519. * @type {BABYLON.Observable}
  39520. */
  39521. this.onBeforeRenderMainTextureObservable = new BABYLON.Observable();
  39522. /**
  39523. * An event triggered when the highlight layer is being blurred.
  39524. * @type {BABYLON.Observable}
  39525. */
  39526. this.onBeforeBlurObservable = new BABYLON.Observable();
  39527. /**
  39528. * An event triggered when the highlight layer has been blurred.
  39529. * @type {BABYLON.Observable}
  39530. */
  39531. this.onAfterBlurObservable = new BABYLON.Observable();
  39532. /**
  39533. * An event triggered when the glowing blurred texture is being merged in the scene.
  39534. * @type {BABYLON.Observable}
  39535. */
  39536. this.onBeforeComposeObservable = new BABYLON.Observable();
  39537. /**
  39538. * An event triggered when the glowing blurred texture has been merged in the scene.
  39539. * @type {BABYLON.Observable}
  39540. */
  39541. this.onAfterComposeObservable = new BABYLON.Observable();
  39542. /**
  39543. * An event triggered when the highlight layer changes its size.
  39544. * @type {BABYLON.Observable}
  39545. */
  39546. this.onSizeChangedObservable = new BABYLON.Observable();
  39547. this._scene = scene;
  39548. var engine = scene.getEngine();
  39549. this._engine = engine;
  39550. this._maxSize = this._engine.getCaps().maxTextureSize;
  39551. this._scene.highlightLayers.push(this);
  39552. // Warn on stencil.
  39553. if (!this._engine.isStencilEnable) {
  39554. 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 }");
  39555. }
  39556. // Adapt options
  39557. this._options = options || {
  39558. mainTextureRatio: 0.25,
  39559. blurTextureSizeRatio: 0.5,
  39560. blurHorizontalSize: 1,
  39561. blurVerticalSize: 1,
  39562. alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE
  39563. };
  39564. this._options.mainTextureRatio = this._options.mainTextureRatio || 0.25;
  39565. this._options.blurTextureSizeRatio = this._options.blurTextureSizeRatio || 0.5;
  39566. this._options.blurHorizontalSize = this._options.blurHorizontalSize || 1;
  39567. this._options.blurVerticalSize = this._options.blurVerticalSize || 1;
  39568. this._options.alphaBlendingMode = this._options.alphaBlendingMode || BABYLON.Engine.ALPHA_COMBINE;
  39569. // VBO
  39570. var vertices = [];
  39571. vertices.push(1, 1);
  39572. vertices.push(-1, 1);
  39573. vertices.push(-1, -1);
  39574. vertices.push(1, -1);
  39575. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  39576. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  39577. // Indices
  39578. var indices = [];
  39579. indices.push(0);
  39580. indices.push(1);
  39581. indices.push(2);
  39582. indices.push(0);
  39583. indices.push(2);
  39584. indices.push(3);
  39585. this._indexBuffer = engine.createIndexBuffer(indices);
  39586. // Effect
  39587. this._glowMapMergeEffect = engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler"], "");
  39588. // Render target
  39589. this.setMainTextureSize();
  39590. // Create Textures and post processes
  39591. this.createTextureAndPostProcesses();
  39592. }
  39593. Object.defineProperty(HighlightLayer.prototype, "blurHorizontalSize", {
  39594. /**
  39595. * Gets the horizontal size of the blur.
  39596. */
  39597. get: function () {
  39598. return this._horizontalBlurPostprocess.blurWidth;
  39599. },
  39600. /**
  39601. * Specifies the horizontal size of the blur.
  39602. */
  39603. set: function (value) {
  39604. this._horizontalBlurPostprocess.blurWidth = value;
  39605. },
  39606. enumerable: true,
  39607. configurable: true
  39608. });
  39609. Object.defineProperty(HighlightLayer.prototype, "blurVerticalSize", {
  39610. /**
  39611. * Gets the vertical size of the blur.
  39612. */
  39613. get: function () {
  39614. return this._verticalBlurPostprocess.blurWidth;
  39615. },
  39616. /**
  39617. * Specifies the vertical size of the blur.
  39618. */
  39619. set: function (value) {
  39620. this._verticalBlurPostprocess.blurWidth = value;
  39621. },
  39622. enumerable: true,
  39623. configurable: true
  39624. });
  39625. Object.defineProperty(HighlightLayer.prototype, "camera", {
  39626. /**
  39627. * Gets the camera attached to the layer.
  39628. */
  39629. get: function () {
  39630. return this._options.camera;
  39631. },
  39632. enumerable: true,
  39633. configurable: true
  39634. });
  39635. /**
  39636. * Creates the render target textures and post processes used in the highlight layer.
  39637. */
  39638. HighlightLayer.prototype.createTextureAndPostProcesses = function () {
  39639. var _this = this;
  39640. var blurTextureWidth = this._mainTextureDesiredSize.width * this._options.blurTextureSizeRatio;
  39641. var blurTextureHeight = this._mainTextureDesiredSize.height * this._options.blurTextureSizeRatio;
  39642. blurTextureWidth = BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize);
  39643. blurTextureHeight = BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize);
  39644. this._mainTexture = new BABYLON.RenderTargetTexture("HighlightLayerMainRTT", {
  39645. width: this._mainTextureDesiredSize.width,
  39646. height: this._mainTextureDesiredSize.height
  39647. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  39648. this._mainTexture.activeCamera = this._options.camera;
  39649. this._mainTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  39650. this._mainTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  39651. this._mainTexture.anisotropicFilteringLevel = 1;
  39652. this._mainTexture.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  39653. this._mainTexture.renderParticles = false;
  39654. this._mainTexture.renderList = null;
  39655. this._blurTexture = new BABYLON.RenderTargetTexture("HighlightLayerBlurRTT", {
  39656. width: blurTextureWidth,
  39657. height: blurTextureHeight
  39658. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  39659. this._blurTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  39660. this._blurTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  39661. this._blurTexture.anisotropicFilteringLevel = 16;
  39662. this._blurTexture.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  39663. this._blurTexture.renderParticles = false;
  39664. this._downSamplePostprocess = new BABYLON.PassPostProcess("HighlightLayerPPP", this._options.blurTextureSizeRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  39665. this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  39666. effect.setTexture("textureSampler", _this._mainTexture);
  39667. });
  39668. if (this._options.alphaBlendingMode === BABYLON.Engine.ALPHA_COMBINE) {
  39669. this._horizontalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  39670. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  39671. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  39672. });
  39673. this._verticalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  39674. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  39675. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  39676. });
  39677. }
  39678. else {
  39679. this._horizontalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  39680. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  39681. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  39682. });
  39683. this._verticalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  39684. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  39685. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  39686. });
  39687. }
  39688. this._mainTexture.onAfterUnbindObservable.add(function () {
  39689. _this.onBeforeBlurObservable.notifyObservers(_this);
  39690. _this._scene.postProcessManager.directRender([_this._downSamplePostprocess, _this._horizontalBlurPostprocess, _this._verticalBlurPostprocess], _this._blurTexture.getInternalTexture());
  39691. _this.onAfterBlurObservable.notifyObservers(_this);
  39692. });
  39693. // Custom render function
  39694. var renderSubMesh = function (subMesh) {
  39695. var mesh = subMesh.getRenderingMesh();
  39696. var scene = _this._scene;
  39697. var engine = scene.getEngine();
  39698. // Culling
  39699. engine.setState(subMesh.getMaterial().backFaceCulling);
  39700. // Managing instances
  39701. var batch = mesh._getInstancesRenderList(subMesh._id);
  39702. if (batch.mustReturn) {
  39703. return;
  39704. }
  39705. // Excluded Mesh
  39706. if (_this._excludedMeshes[mesh.uniqueId]) {
  39707. return;
  39708. }
  39709. ;
  39710. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  39711. var highlightLayerMesh = _this._meshes[mesh.uniqueId];
  39712. var material = subMesh.getMaterial();
  39713. var emissiveTexture = null;
  39714. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  39715. emissiveTexture = material.emissiveTexture;
  39716. }
  39717. if (_this.isReady(subMesh, hardwareInstancedRendering, emissiveTexture)) {
  39718. engine.enableEffect(_this._glowMapGenerationEffect);
  39719. mesh._bind(subMesh, _this._glowMapGenerationEffect, BABYLON.Material.TriangleFillMode);
  39720. _this._glowMapGenerationEffect.setMatrix("viewProjection", scene.getTransformMatrix());
  39721. if (highlightLayerMesh) {
  39722. _this._glowMapGenerationEffect.setFloat4("color", highlightLayerMesh.color.r, highlightLayerMesh.color.g, highlightLayerMesh.color.b, 1.0);
  39723. }
  39724. else {
  39725. _this._glowMapGenerationEffect.setFloat4("color", HighlightLayer.neutralColor.r, HighlightLayer.neutralColor.g, HighlightLayer.neutralColor.b, HighlightLayer.neutralColor.a);
  39726. }
  39727. // Alpha test
  39728. if (material && material.needAlphaTesting()) {
  39729. var alphaTexture = material.getAlphaTestTexture();
  39730. _this._glowMapGenerationEffect.setTexture("diffuseSampler", alphaTexture);
  39731. _this._glowMapGenerationEffect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  39732. }
  39733. // Glow emissive only
  39734. if (emissiveTexture) {
  39735. _this._glowMapGenerationEffect.setTexture("emissiveSampler", emissiveTexture);
  39736. _this._glowMapGenerationEffect.setMatrix("emissiveMatrix", emissiveTexture.getTextureMatrix());
  39737. }
  39738. // Bones
  39739. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  39740. _this._glowMapGenerationEffect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  39741. }
  39742. // Draw
  39743. mesh._processRendering(subMesh, _this._glowMapGenerationEffect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._glowMapGenerationEffect.setMatrix("world", world); });
  39744. }
  39745. else {
  39746. // Need to reset refresh rate of the shadowMap
  39747. _this._mainTexture.resetRefreshCounter();
  39748. }
  39749. };
  39750. this._mainTexture.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  39751. _this.onBeforeRenderMainTextureObservable.notifyObservers(_this);
  39752. var index;
  39753. for (index = 0; index < opaqueSubMeshes.length; index++) {
  39754. renderSubMesh(opaqueSubMeshes.data[index]);
  39755. }
  39756. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  39757. renderSubMesh(alphaTestSubMeshes.data[index]);
  39758. }
  39759. for (index = 0; index < transparentSubMeshes.length; index++) {
  39760. renderSubMesh(transparentSubMeshes.data[index]);
  39761. }
  39762. };
  39763. this._mainTexture.onClearObservable.add(function (engine) {
  39764. engine.clear(HighlightLayer.neutralColor, true, true, true);
  39765. });
  39766. };
  39767. /**
  39768. * Checks for the readiness of the element composing the layer.
  39769. * @param subMesh the mesh to check for
  39770. * @param useInstances specify wether or not to use instances to render the mesh
  39771. * @param emissiveTexture the associated emissive texture used to generate the glow
  39772. * @return true if ready otherwise, false
  39773. */
  39774. HighlightLayer.prototype.isReady = function (subMesh, useInstances, emissiveTexture) {
  39775. if (!subMesh.getMaterial().isReady(subMesh.getMesh(), useInstances)) {
  39776. return false;
  39777. }
  39778. var defines = [];
  39779. var attribs = [BABYLON.VertexBuffer.PositionKind];
  39780. var mesh = subMesh.getMesh();
  39781. var material = subMesh.getMaterial();
  39782. var uv1 = false;
  39783. var uv2 = false;
  39784. // Alpha test
  39785. if (material && material.needAlphaTesting()) {
  39786. var alphaTexture = material.getAlphaTestTexture();
  39787. if (alphaTexture) {
  39788. defines.push("#define ALPHATEST");
  39789. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  39790. alphaTexture.coordinatesIndex === 1) {
  39791. defines.push("#define DIFFUSEUV2");
  39792. uv2 = true;
  39793. }
  39794. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  39795. defines.push("#define DIFFUSEUV1");
  39796. uv1 = true;
  39797. }
  39798. }
  39799. }
  39800. // Emissive
  39801. if (emissiveTexture) {
  39802. defines.push("#define EMISSIVE");
  39803. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  39804. emissiveTexture.coordinatesIndex === 1) {
  39805. defines.push("#define EMISSIVEUV2");
  39806. uv2 = true;
  39807. }
  39808. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  39809. defines.push("#define EMISSIVEUV1");
  39810. uv1 = true;
  39811. }
  39812. }
  39813. if (uv1) {
  39814. attribs.push(BABYLON.VertexBuffer.UVKind);
  39815. defines.push("#define UV1");
  39816. }
  39817. if (uv2) {
  39818. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  39819. defines.push("#define UV2");
  39820. }
  39821. // Bones
  39822. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  39823. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  39824. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  39825. if (mesh.numBoneInfluencers > 4) {
  39826. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  39827. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  39828. }
  39829. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  39830. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  39831. }
  39832. else {
  39833. defines.push("#define NUM_BONE_INFLUENCERS 0");
  39834. }
  39835. // Instances
  39836. if (useInstances) {
  39837. defines.push("#define INSTANCES");
  39838. attribs.push("world0");
  39839. attribs.push("world1");
  39840. attribs.push("world2");
  39841. attribs.push("world3");
  39842. }
  39843. // Get correct effect
  39844. var join = defines.join("\n");
  39845. if (this._cachedDefines !== join) {
  39846. this._cachedDefines = join;
  39847. this._glowMapGenerationEffect = this._scene.getEngine().createEffect("glowMapGeneration", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "color", "emissiveMatrix"], ["diffuseSampler", "emissiveSampler"], join);
  39848. }
  39849. return this._glowMapGenerationEffect.isReady();
  39850. };
  39851. /**
  39852. * Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene.
  39853. */
  39854. HighlightLayer.prototype.render = function () {
  39855. var currentEffect = this._glowMapMergeEffect;
  39856. // Check
  39857. if (!currentEffect.isReady() || !this._blurTexture.isReady())
  39858. return;
  39859. var engine = this._scene.getEngine();
  39860. this.onBeforeComposeObservable.notifyObservers(this);
  39861. // Render
  39862. engine.enableEffect(currentEffect);
  39863. engine.setState(false);
  39864. // Cache
  39865. var previousStencilBuffer = engine.getStencilBuffer();
  39866. var previousStencilFunction = engine.getStencilFunction();
  39867. var previousStencilMask = engine.getStencilMask();
  39868. var previousAlphaMode = engine.getAlphaMode();
  39869. // Texture
  39870. currentEffect.setTexture("textureSampler", this._blurTexture);
  39871. // VBOs
  39872. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  39873. // Draw order
  39874. engine.setAlphaMode(this._options.alphaBlendingMode);
  39875. engine.setStencilMask(0x00);
  39876. engine.setStencilBuffer(true);
  39877. engine.setStencilFunctionReference(this._instanceGlowingMeshStencilReference);
  39878. if (this.outerGlow) {
  39879. currentEffect.setFloat("offset", 0);
  39880. engine.setStencilFunction(BABYLON.Engine.NOTEQUAL);
  39881. engine.draw(true, 0, 6);
  39882. }
  39883. if (this.innerGlow) {
  39884. currentEffect.setFloat("offset", 1);
  39885. engine.setStencilFunction(BABYLON.Engine.EQUAL);
  39886. engine.draw(true, 0, 6);
  39887. }
  39888. // Restore Cache
  39889. engine.setStencilFunction(previousStencilFunction);
  39890. engine.setStencilMask(previousStencilMask);
  39891. engine.setAlphaMode(previousAlphaMode);
  39892. engine.setStencilBuffer(previousStencilBuffer);
  39893. this.onAfterComposeObservable.notifyObservers(this);
  39894. // Handle size changes.
  39895. var size = this._mainTexture.getSize();
  39896. this.setMainTextureSize();
  39897. if (size.width !== this._mainTextureDesiredSize.width || size.height !== this._mainTextureDesiredSize.height) {
  39898. // Recreate RTT and post processes on size change.
  39899. this.onSizeChangedObservable.notifyObservers(this);
  39900. this.disposeTextureAndPostProcesses();
  39901. this.createTextureAndPostProcesses();
  39902. }
  39903. };
  39904. /**
  39905. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the highlight layer.
  39906. * @param mesh The mesh to exclude from the highlight layer
  39907. */
  39908. HighlightLayer.prototype.addExcludedMesh = function (mesh) {
  39909. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  39910. if (!meshExcluded) {
  39911. this._excludedMeshes[mesh.uniqueId] = {
  39912. mesh: mesh,
  39913. beforeRender: mesh.onBeforeRenderObservable.add(function (mesh) {
  39914. mesh.getEngine().setStencilBuffer(false);
  39915. }),
  39916. afterRender: mesh.onAfterRenderObservable.add(function (mesh) {
  39917. mesh.getEngine().setStencilBuffer(true);
  39918. }),
  39919. };
  39920. }
  39921. };
  39922. /**
  39923. * Remove a mesh from the exclusion list to let it impact or being impacted by the highlight layer.
  39924. * @param mesh The mesh to highlight
  39925. */
  39926. HighlightLayer.prototype.removeExcludedMesh = function (mesh) {
  39927. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  39928. if (meshExcluded) {
  39929. mesh.onBeforeRenderObservable.remove(meshExcluded.beforeRender);
  39930. mesh.onAfterRenderObservable.remove(meshExcluded.afterRender);
  39931. }
  39932. this._excludedMeshes[mesh.uniqueId] = undefined;
  39933. };
  39934. /**
  39935. * Add a mesh in the highlight layer in order to make it glow with the chosen color.
  39936. * @param mesh The mesh to highlight
  39937. * @param color The color of the highlight
  39938. * @param glowEmissiveOnly Extract the glow from the emissive texture
  39939. */
  39940. HighlightLayer.prototype.addMesh = function (mesh, color, glowEmissiveOnly) {
  39941. var _this = this;
  39942. if (glowEmissiveOnly === void 0) { glowEmissiveOnly = false; }
  39943. var meshHighlight = this._meshes[mesh.uniqueId];
  39944. if (meshHighlight) {
  39945. meshHighlight.color = color;
  39946. }
  39947. else {
  39948. this._meshes[mesh.uniqueId] = {
  39949. mesh: mesh,
  39950. color: color,
  39951. // Lambda required for capture due to Observable this context
  39952. observerHighlight: mesh.onBeforeRenderObservable.add(function (mesh) {
  39953. if (_this._excludedMeshes[mesh.uniqueId]) {
  39954. _this.defaultStencilReference(mesh);
  39955. }
  39956. else {
  39957. mesh.getScene().getEngine().setStencilFunctionReference(_this._instanceGlowingMeshStencilReference);
  39958. }
  39959. }),
  39960. observerDefault: mesh.onAfterRenderObservable.add(this.defaultStencilReference),
  39961. glowEmissiveOnly: glowEmissiveOnly
  39962. };
  39963. }
  39964. this._shouldRender = true;
  39965. };
  39966. /**
  39967. * Remove a mesh from the highlight layer in order to make it stop glowing.
  39968. * @param mesh The mesh to highlight
  39969. */
  39970. HighlightLayer.prototype.removeMesh = function (mesh) {
  39971. var meshHighlight = this._meshes[mesh.uniqueId];
  39972. if (meshHighlight) {
  39973. mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  39974. mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  39975. }
  39976. this._meshes[mesh.uniqueId] = undefined;
  39977. this._shouldRender = false;
  39978. for (var meshHighlightToCheck in this._meshes) {
  39979. if (meshHighlightToCheck) {
  39980. this._shouldRender = true;
  39981. break;
  39982. }
  39983. }
  39984. };
  39985. /**
  39986. * Returns true if the layer contains information to display, otherwise false.
  39987. */
  39988. HighlightLayer.prototype.shouldRender = function () {
  39989. return this.isEnabled && this._shouldRender;
  39990. };
  39991. /**
  39992. * Sets the main texture desired size which is the closest power of two
  39993. * of the engine canvas size.
  39994. */
  39995. HighlightLayer.prototype.setMainTextureSize = function () {
  39996. if (this._options.mainTextureFixedSize) {
  39997. this._mainTextureDesiredSize.width = this._options.mainTextureFixedSize;
  39998. this._mainTextureDesiredSize.height = this._options.mainTextureFixedSize;
  39999. }
  40000. else {
  40001. this._mainTextureDesiredSize.width = this._engine.getRenderingCanvas().width * this._options.mainTextureRatio;
  40002. this._mainTextureDesiredSize.height = this._engine.getRenderingCanvas().height * this._options.mainTextureRatio;
  40003. this._mainTextureDesiredSize.width = BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.width, this._maxSize);
  40004. this._mainTextureDesiredSize.height = BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.height, this._maxSize);
  40005. }
  40006. };
  40007. /**
  40008. * Force the stencil to the normal expected value for none glowing parts
  40009. */
  40010. HighlightLayer.prototype.defaultStencilReference = function (mesh) {
  40011. mesh.getScene().getEngine().setStencilFunctionReference(HighlightLayer.normalMeshStencilReference);
  40012. };
  40013. /**
  40014. * Dispose only the render target textures and post process.
  40015. */
  40016. HighlightLayer.prototype.disposeTextureAndPostProcesses = function () {
  40017. this._blurTexture.dispose();
  40018. this._mainTexture.dispose();
  40019. this._downSamplePostprocess.dispose();
  40020. this._horizontalBlurPostprocess.dispose();
  40021. this._verticalBlurPostprocess.dispose();
  40022. };
  40023. /**
  40024. * Dispose the highlight layer and free resources.
  40025. */
  40026. HighlightLayer.prototype.dispose = function () {
  40027. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  40028. if (vertexBuffer) {
  40029. vertexBuffer.dispose();
  40030. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  40031. }
  40032. if (this._indexBuffer) {
  40033. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  40034. this._indexBuffer = null;
  40035. }
  40036. // Clean textures and post processes
  40037. this.disposeTextureAndPostProcesses();
  40038. // Clean mesh references
  40039. for (var id in this._meshes) {
  40040. var meshHighlight = this._meshes[id];
  40041. if (meshHighlight && meshHighlight.mesh) {
  40042. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  40043. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  40044. }
  40045. }
  40046. this._meshes = null;
  40047. for (var id in this._excludedMeshes) {
  40048. var meshHighlight = this._excludedMeshes[id];
  40049. if (meshHighlight) {
  40050. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.beforeRender);
  40051. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.afterRender);
  40052. }
  40053. }
  40054. this._excludedMeshes = null;
  40055. // Remove from scene
  40056. var index = this._scene.highlightLayers.indexOf(this, 0);
  40057. if (index > -1) {
  40058. this._scene.highlightLayers.splice(index, 1);
  40059. }
  40060. // Callback
  40061. this.onDisposeObservable.notifyObservers(this);
  40062. this.onDisposeObservable.clear();
  40063. this.onBeforeRenderMainTextureObservable.clear();
  40064. this.onBeforeBlurObservable.clear();
  40065. this.onBeforeComposeObservable.clear();
  40066. this.onAfterComposeObservable.clear();
  40067. this.onSizeChangedObservable.clear();
  40068. };
  40069. return HighlightLayer;
  40070. }());
  40071. /**
  40072. * The neutral color used during the preparation of the glow effect.
  40073. * This is black by default as the blend operation is a blend operation.
  40074. */
  40075. HighlightLayer.neutralColor = new BABYLON.Color4(0, 0, 0, 0);
  40076. /**
  40077. * Stencil value used for glowing meshes.
  40078. */
  40079. HighlightLayer.glowingMeshStencilReference = 0x02;
  40080. /**
  40081. * Stencil value used for the other meshes in the scene.
  40082. */
  40083. HighlightLayer.normalMeshStencilReference = 0x01;
  40084. BABYLON.HighlightLayer = HighlightLayer;
  40085. })(BABYLON || (BABYLON = {}));
  40086. //# sourceMappingURL=babylon.highlightlayer.js.map
  40087. var BABYLON;
  40088. (function (BABYLON) {
  40089. var SIMDVector3 = (function () {
  40090. function SIMDVector3() {
  40091. }
  40092. SIMDVector3.TransformCoordinatesToRefSIMD = function (vector, transformation, result) {
  40093. SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD(vector.x, vector.y, vector.z, transformation, result);
  40094. };
  40095. SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD = function (x, y, z, transformation, result) {
  40096. var m = transformation.m;
  40097. var m0 = SIMD.Float32x4.load(m, 0);
  40098. var m1 = SIMD.Float32x4.load(m, 4);
  40099. var m2 = SIMD.Float32x4.load(m, 8);
  40100. var m3 = SIMD.Float32x4.load(m, 12);
  40101. 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));
  40102. r = SIMD.Float32x4.div(r, SIMD.Float32x4.swizzle(r, 3, 3, 3, 3));
  40103. result.x = SIMD.Float32x4.extractLane(r, 0);
  40104. result.y = SIMD.Float32x4.extractLane(r, 1);
  40105. result.z = SIMD.Float32x4.extractLane(r, 2);
  40106. };
  40107. return SIMDVector3;
  40108. }());
  40109. var SIMDMatrix = (function () {
  40110. function SIMDMatrix() {
  40111. }
  40112. SIMDMatrix.prototype.multiplyToArraySIMD = function (other, result, offset) {
  40113. var tm = this.m;
  40114. var om = other.m;
  40115. var m0 = SIMD.Float32x4.load(om, 0);
  40116. var m1 = SIMD.Float32x4.load(om, 4);
  40117. var m2 = SIMD.Float32x4.load(om, 8);
  40118. var m3 = SIMD.Float32x4.load(om, 12);
  40119. for (var i = 0; i < 16; i += 4) {
  40120. 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)))));
  40121. }
  40122. return this;
  40123. };
  40124. SIMDMatrix.prototype.invertToRefSIMD = function (other) {
  40125. var src = this.m;
  40126. var dest = other.m;
  40127. // Load the 4 rows
  40128. var src0 = SIMD.Float32x4.load(src, 0);
  40129. var src1 = SIMD.Float32x4.load(src, 4);
  40130. var src2 = SIMD.Float32x4.load(src, 8);
  40131. var src3 = SIMD.Float32x4.load(src, 12);
  40132. // Transpose the source matrix. Sort of. Not a true transpose operation
  40133. var tmp1 = SIMD.Float32x4.shuffle(src0, src1, 0, 1, 4, 5);
  40134. var row1 = SIMD.Float32x4.shuffle(src2, src3, 0, 1, 4, 5);
  40135. var row0 = SIMD.Float32x4.shuffle(tmp1, row1, 0, 2, 4, 6);
  40136. row1 = SIMD.Float32x4.shuffle(row1, tmp1, 1, 3, 5, 7);
  40137. tmp1 = SIMD.Float32x4.shuffle(src0, src1, 2, 3, 6, 7);
  40138. var row3 = SIMD.Float32x4.shuffle(src2, src3, 2, 3, 6, 7);
  40139. var row2 = SIMD.Float32x4.shuffle(tmp1, row3, 0, 2, 4, 6);
  40140. row3 = SIMD.Float32x4.shuffle(row3, tmp1, 1, 3, 5, 7);
  40141. // This is a true transposition, but it will lead to an incorrect result
  40142. //tmp1 = shuffle(src0, src1, 0, 1, 4, 5);
  40143. //tmp2 = shuffle(src2, src3, 0, 1, 4, 5);
  40144. //row0 = shuffle(tmp1, tmp2, 0, 2, 4, 6);
  40145. //row1 = shuffle(tmp1, tmp2, 1, 3, 5, 7);
  40146. //tmp1 = shuffle(src0, src1, 2, 3, 6, 7);
  40147. //tmp2 = shuffle(src2, src3, 2, 3, 6, 7);
  40148. //row2 = shuffle(tmp1, tmp2, 0, 2, 4, 6);
  40149. //row3 = shuffle(tmp1, tmp2, 1, 3, 5, 7);
  40150. // ----
  40151. tmp1 = SIMD.Float32x4.mul(row2, row3);
  40152. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  40153. var minor0 = SIMD.Float32x4.mul(row1, tmp1);
  40154. var minor1 = SIMD.Float32x4.mul(row0, tmp1);
  40155. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  40156. minor0 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row1, tmp1), minor0);
  40157. minor1 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row0, tmp1), minor1);
  40158. minor1 = SIMD.Float32x4.swizzle(minor1, 2, 3, 0, 1); // 0x4E = 01001110
  40159. // ----
  40160. tmp1 = SIMD.Float32x4.mul(row1, row2);
  40161. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  40162. minor0 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row3, tmp1), minor0);
  40163. var minor3 = SIMD.Float32x4.mul(row0, tmp1);
  40164. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  40165. minor0 = SIMD.Float32x4.sub(minor0, SIMD.Float32x4.mul(row3, tmp1));
  40166. minor3 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row0, tmp1), minor3);
  40167. minor3 = SIMD.Float32x4.swizzle(minor3, 2, 3, 0, 1); // 0x4E = 01001110
  40168. // ----
  40169. tmp1 = SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(row1, 2, 3, 0, 1), row3); // 0x4E = 01001110
  40170. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  40171. row2 = SIMD.Float32x4.swizzle(row2, 2, 3, 0, 1); // 0x4E = 01001110
  40172. minor0 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row2, tmp1), minor0);
  40173. var minor2 = SIMD.Float32x4.mul(row0, tmp1);
  40174. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  40175. minor0 = SIMD.Float32x4.sub(minor0, SIMD.Float32x4.mul(row2, tmp1));
  40176. minor2 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row0, tmp1), minor2);
  40177. minor2 = SIMD.Float32x4.swizzle(minor2, 2, 3, 0, 1); // 0x4E = 01001110
  40178. // ----
  40179. tmp1 = SIMD.Float32x4.mul(row0, row1);
  40180. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  40181. minor2 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row3, tmp1), minor2);
  40182. minor3 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row2, tmp1), minor3);
  40183. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  40184. minor2 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row3, tmp1), minor2);
  40185. minor3 = SIMD.Float32x4.sub(minor3, SIMD.Float32x4.mul(row2, tmp1));
  40186. // ----
  40187. tmp1 = SIMD.Float32x4.mul(row0, row3);
  40188. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  40189. minor1 = SIMD.Float32x4.sub(minor1, SIMD.Float32x4.mul(row2, tmp1));
  40190. minor2 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row1, tmp1), minor2);
  40191. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  40192. minor1 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row2, tmp1), minor1);
  40193. minor2 = SIMD.Float32x4.sub(minor2, SIMD.Float32x4.mul(row1, tmp1));
  40194. // ----
  40195. tmp1 = SIMD.Float32x4.mul(row0, row2);
  40196. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  40197. minor1 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row3, tmp1), minor1);
  40198. minor3 = SIMD.Float32x4.sub(minor3, SIMD.Float32x4.mul(row1, tmp1));
  40199. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  40200. minor1 = SIMD.Float32x4.sub(minor1, SIMD.Float32x4.mul(row3, tmp1));
  40201. minor3 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row1, tmp1), minor3);
  40202. // Compute determinant
  40203. var det = SIMD.Float32x4.mul(row0, minor0);
  40204. det = SIMD.Float32x4.add(SIMD.Float32x4.swizzle(det, 2, 3, 0, 1), det); // 0x4E = 01001110
  40205. det = SIMD.Float32x4.add(SIMD.Float32x4.swizzle(det, 1, 0, 3, 2), det); // 0xB1 = 10110001
  40206. tmp1 = SIMD.Float32x4.reciprocalApproximation(det);
  40207. det = SIMD.Float32x4.sub(SIMD.Float32x4.add(tmp1, tmp1), SIMD.Float32x4.mul(det, SIMD.Float32x4.mul(tmp1, tmp1)));
  40208. det = SIMD.Float32x4.swizzle(det, 0, 0, 0, 0);
  40209. // These shuffles aren't necessary if the faulty transposition is done
  40210. // up at the top of this function.
  40211. //minor0 =SIMD.Float32x4.swizzle(minor0, 2, 1, 0, 3);
  40212. //minor1 =SIMD.Float32x4.swizzle(minor1, 2, 1, 0, 3);
  40213. //minor2 =SIMD.Float32x4.swizzle(minor2, 2, 1, 0, 3);
  40214. //minor3 =SIMD.Float32x4.swizzle(minor3, 2, 1, 0, 3);
  40215. // Compute final values by multiplying with 1/det
  40216. SIMD.Float32x4.store(dest, 0, SIMD.Float32x4.mul(det, minor0));
  40217. SIMD.Float32x4.store(dest, 4, SIMD.Float32x4.mul(det, minor1));
  40218. SIMD.Float32x4.store(dest, 8, minor2 = SIMD.Float32x4.mul(det, minor2));
  40219. SIMD.Float32x4.store(dest, 12, SIMD.Float32x4.mul(det, minor3));
  40220. return this;
  40221. };
  40222. SIMDMatrix.LookAtLHToRefSIMD = function (eyeRef, targetRef, upRef, result) {
  40223. var out = result.m;
  40224. var center = SIMD.Float32x4(targetRef.x, targetRef.y, targetRef.z, 0.0);
  40225. var eye = SIMD.Float32x4(eyeRef.x, eyeRef.y, eyeRef.z, 0.0);
  40226. var up = SIMD.Float32x4(upRef.x, upRef.y, upRef.z, 0.0);
  40227. // cc.kmVec3Subtract(f, pCenter, pEye);
  40228. var f = SIMD.Float32x4.sub(center, eye);
  40229. // cc.kmVec3Normalize(f, f);
  40230. var tmp = SIMD.Float32x4.mul(f, f);
  40231. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  40232. f = SIMD.Float32x4.mul(f, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  40233. // cc.kmVec3Assign(up, pUp);
  40234. // cc.kmVec3Normalize(up, up);
  40235. tmp = SIMD.Float32x4.mul(up, up);
  40236. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  40237. up = SIMD.Float32x4.mul(up, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  40238. // cc.kmVec3Cross(s, f, up);
  40239. 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)));
  40240. // cc.kmVec3Normalize(s, s);
  40241. tmp = SIMD.Float32x4.mul(s, s);
  40242. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  40243. s = SIMD.Float32x4.mul(s, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  40244. // cc.kmVec3Cross(u, s, f);
  40245. 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)));
  40246. // cc.kmVec3Normalize(s, s);
  40247. tmp = SIMD.Float32x4.mul(s, s);
  40248. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  40249. s = SIMD.Float32x4.mul(s, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  40250. var zero = SIMD.Float32x4.splat(0.0);
  40251. s = SIMD.Float32x4.neg(s);
  40252. var tmp01 = SIMD.Float32x4.shuffle(s, u, 0, 1, 4, 5);
  40253. var tmp23 = SIMD.Float32x4.shuffle(f, zero, 0, 1, 4, 5);
  40254. var a0 = SIMD.Float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6);
  40255. var a1 = SIMD.Float32x4.shuffle(tmp01, tmp23, 1, 3, 5, 7);
  40256. 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);
  40257. var a3 = SIMD.Float32x4(0.0, 0.0, 0.0, 1.0);
  40258. var b = SIMD.Float32x4(1.0, 0.0, 0.0, 0.0);
  40259. 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)))));
  40260. b = SIMD.Float32x4(0.0, 1.0, 0.0, 0.0);
  40261. 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)))));
  40262. b = SIMD.Float32x4(0.0, 0.0, 1.0, 0.0);
  40263. 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)))));
  40264. b = SIMD.Float32x4.replaceLane(SIMD.Float32x4.neg(eye), 3, 1.0);
  40265. 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)))));
  40266. };
  40267. return SIMDMatrix;
  40268. }());
  40269. var previousMultiplyToArray = BABYLON.Matrix.prototype.multiplyToArray;
  40270. var previousInvertToRef = BABYLON.Matrix.prototype.invertToRef;
  40271. var previousLookAtLHToRef = BABYLON.Matrix.LookAtLHToRef;
  40272. var previousTransformCoordinatesToRef = BABYLON.Vector3.TransformCoordinatesToRef;
  40273. var previousTransformCoordinatesFromFloatsToRef = BABYLON.Vector3.TransformCoordinatesFromFloatsToRef;
  40274. var SIMDHelper = (function () {
  40275. function SIMDHelper() {
  40276. }
  40277. Object.defineProperty(SIMDHelper, "IsEnabled", {
  40278. get: function () {
  40279. return SIMDHelper._isEnabled;
  40280. },
  40281. enumerable: true,
  40282. configurable: true
  40283. });
  40284. SIMDHelper.DisableSIMD = function () {
  40285. // Replace functions
  40286. BABYLON.Matrix.prototype.multiplyToArray = previousMultiplyToArray;
  40287. BABYLON.Matrix.prototype.invertToRef = previousInvertToRef;
  40288. BABYLON.Matrix.LookAtLHToRef = previousLookAtLHToRef;
  40289. BABYLON.Vector3.TransformCoordinatesToRef = previousTransformCoordinatesToRef;
  40290. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = previousTransformCoordinatesFromFloatsToRef;
  40291. SIMDHelper._isEnabled = false;
  40292. };
  40293. SIMDHelper.EnableSIMD = function () {
  40294. if (self.SIMD === undefined) {
  40295. return;
  40296. }
  40297. // check if polyfills needed
  40298. if (!self.Math.fround) {
  40299. self.Math.fround = (function (array) { return function (x) {
  40300. return array[0] = x, array[0];
  40301. }; })(new Float32Array(1));
  40302. }
  40303. if (!self.Math.imul) {
  40304. self.Math.imul = function (a, b) {
  40305. var ah = (a >>> 16) & 0xffff;
  40306. var al = a & 0xffff;
  40307. var bh = (b >>> 16) & 0xffff;
  40308. var bl = b & 0xffff;
  40309. // the shift by 0 fixes the sign on the high part
  40310. // the final |0 converts the unsigned value into a signed value
  40311. return ((al * bl) + (((ah * bl + al * bh) << 16) >>> 0) | 0);
  40312. };
  40313. }
  40314. // Replace functions
  40315. BABYLON.Matrix.prototype.multiplyToArray = SIMDMatrix.prototype.multiplyToArraySIMD;
  40316. BABYLON.Matrix.prototype.invertToRef = SIMDMatrix.prototype.invertToRefSIMD;
  40317. BABYLON.Matrix.LookAtLHToRef = SIMDMatrix.LookAtLHToRefSIMD;
  40318. BABYLON.Vector3.TransformCoordinatesToRef = SIMDVector3.TransformCoordinatesToRefSIMD;
  40319. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD;
  40320. SIMDHelper._isEnabled = true;
  40321. };
  40322. return SIMDHelper;
  40323. }());
  40324. SIMDHelper._isEnabled = false;
  40325. BABYLON.SIMDHelper = SIMDHelper;
  40326. })(BABYLON || (BABYLON = {}));
  40327. //# sourceMappingURL=babylon.math.SIMD.js.map
  40328. var BABYLON;
  40329. (function (BABYLON) {
  40330. /**
  40331. * This class describe a rectangle that were added to the map.
  40332. * You have access to its coordinates either in pixel or normalized (UV)
  40333. */
  40334. var PackedRect = (function () {
  40335. function PackedRect(root, parent, pos, size) {
  40336. this._pos = pos;
  40337. this._size = size;
  40338. this._root = root;
  40339. this._parent = parent;
  40340. this._contentSize = null;
  40341. this._bottomNode = null;
  40342. this._leftNode = null;
  40343. this._initialSize = null;
  40344. this._rightNode = null;
  40345. }
  40346. Object.defineProperty(PackedRect.prototype, "pos", {
  40347. /**
  40348. * @returns the position of this node into the map
  40349. */
  40350. get: function () {
  40351. return this._pos;
  40352. },
  40353. enumerable: true,
  40354. configurable: true
  40355. });
  40356. Object.defineProperty(PackedRect.prototype, "contentSize", {
  40357. /**
  40358. * @returns the size of the rectangle this node handles
  40359. */
  40360. get: function () {
  40361. return this._contentSize;
  40362. },
  40363. enumerable: true,
  40364. configurable: true
  40365. });
  40366. Object.defineProperty(PackedRect.prototype, "UVs", {
  40367. /**
  40368. * Compute the UV of the top/left, top/right, bottom/right, bottom/left points of the rectangle this node handles into the map
  40369. * @returns And array of 4 Vector2, containing UV coordinates for the four corners of the Rectangle into the map
  40370. */
  40371. get: function () {
  40372. return this.getUVsForCustomSize(this._root._size);
  40373. },
  40374. enumerable: true,
  40375. configurable: true
  40376. });
  40377. /**
  40378. * You may have allocated the PackedRect using over-provisioning (you allocated more than you need in order to prevent frequent deallocations/reallocations) and then using only a part of the PackRect.
  40379. * This method will return the UVs for this part by given the custom size of what you really use
  40380. * @param customSize must be less/equal to the allocated size, UV will be compute from this
  40381. */
  40382. PackedRect.prototype.getUVsForCustomSize = function (customSize) {
  40383. var mainWidth = this._root._size.width;
  40384. var mainHeight = this._root._size.height;
  40385. var topLeft = new BABYLON.Vector2(this._pos.x / mainWidth, this._pos.y / mainHeight);
  40386. var rightBottom = new BABYLON.Vector2((this._pos.x + customSize.width - 1) / mainWidth, (this._pos.y + customSize.height - 1) / mainHeight);
  40387. var uvs = new Array();
  40388. uvs.push(topLeft);
  40389. uvs.push(new BABYLON.Vector2(rightBottom.x, topLeft.y));
  40390. uvs.push(rightBottom);
  40391. uvs.push(new BABYLON.Vector2(topLeft.x, rightBottom.y));
  40392. return uvs;
  40393. };
  40394. /**
  40395. * Free this rectangle from the map.
  40396. * Call this method when you no longer need the rectangle to be in the map.
  40397. */
  40398. PackedRect.prototype.freeContent = function () {
  40399. if (!this.contentSize) {
  40400. return;
  40401. }
  40402. this._contentSize = null;
  40403. // If everything below is also free, reset the whole node, and attempt to reset parents if they also become free
  40404. this.attemptDefrag();
  40405. };
  40406. Object.defineProperty(PackedRect.prototype, "isUsed", {
  40407. get: function () {
  40408. return this._contentSize != null || this._leftNode != null;
  40409. },
  40410. enumerable: true,
  40411. configurable: true
  40412. });
  40413. PackedRect.prototype.findAndSplitNode = function (contentSize) {
  40414. var node = this.findNode(contentSize);
  40415. // Not enough space...
  40416. if (!node) {
  40417. return null;
  40418. }
  40419. node.splitNode(contentSize);
  40420. return node;
  40421. };
  40422. PackedRect.prototype.findNode = function (size) {
  40423. var resNode = null;
  40424. // If this node is used, recurse to each of his subNodes to find an available one in its branch
  40425. if (this.isUsed) {
  40426. if (this._leftNode) {
  40427. resNode = this._leftNode.findNode(size);
  40428. }
  40429. if (!resNode && this._rightNode) {
  40430. resNode = this._rightNode.findNode(size);
  40431. }
  40432. if (!resNode && this._bottomNode) {
  40433. resNode = this._bottomNode.findNode(size);
  40434. }
  40435. }
  40436. else if (this._initialSize) {
  40437. if ((size.width <= this._initialSize.width) && (size.height <= this._initialSize.height)) {
  40438. resNode = this;
  40439. }
  40440. else {
  40441. return null;
  40442. }
  40443. }
  40444. else if ((size.width <= this._size.width) && (size.height <= this._size.height)) {
  40445. resNode = this;
  40446. }
  40447. return resNode;
  40448. };
  40449. PackedRect.prototype.splitNode = function (contentSize) {
  40450. // 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)
  40451. if (!this._contentSize && this._initialSize) {
  40452. this._contentSize = contentSize.clone();
  40453. 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));
  40454. return this._leftNode.splitNode(contentSize);
  40455. }
  40456. else {
  40457. this._contentSize = contentSize.clone();
  40458. this._initialSize = contentSize.clone();
  40459. if (contentSize.width !== this._size.width) {
  40460. this._rightNode = new PackedRect(this._root, this, new BABYLON.Vector2(this._pos.x + contentSize.width, this._pos.y), new BABYLON.Size(this._size.width - contentSize.width, contentSize.height));
  40461. }
  40462. if (contentSize.height !== this._size.height) {
  40463. this._bottomNode = new PackedRect(this._root, this, new BABYLON.Vector2(this._pos.x, this._pos.y + contentSize.height), new BABYLON.Size(this._size.width, this._size.height - contentSize.height));
  40464. }
  40465. return this;
  40466. }
  40467. };
  40468. PackedRect.prototype.attemptDefrag = function () {
  40469. if (!this.isUsed && this.isRecursiveFree) {
  40470. this.clearNode();
  40471. if (this._parent) {
  40472. this._parent.attemptDefrag();
  40473. }
  40474. }
  40475. };
  40476. PackedRect.prototype.clearNode = function () {
  40477. this._initialSize = null;
  40478. this._rightNode = null;
  40479. this._bottomNode = null;
  40480. };
  40481. Object.defineProperty(PackedRect.prototype, "isRecursiveFree", {
  40482. get: function () {
  40483. return !this.contentSize && (!this._leftNode || this._leftNode.isRecursiveFree) && (!this._rightNode || this._rightNode.isRecursiveFree) && (!this._bottomNode || this._bottomNode.isRecursiveFree);
  40484. },
  40485. enumerable: true,
  40486. configurable: true
  40487. });
  40488. PackedRect.prototype.evalFreeSize = function (size) {
  40489. var levelSize = 0;
  40490. if (!this.isUsed) {
  40491. if (this._initialSize) {
  40492. levelSize = this._initialSize.surface;
  40493. }
  40494. else {
  40495. levelSize = this._size.surface;
  40496. }
  40497. }
  40498. if (this._rightNode) {
  40499. levelSize += this._rightNode.evalFreeSize(0);
  40500. }
  40501. if (this._bottomNode) {
  40502. levelSize += this._bottomNode.evalFreeSize(0);
  40503. }
  40504. return levelSize + size;
  40505. };
  40506. return PackedRect;
  40507. }());
  40508. BABYLON.PackedRect = PackedRect;
  40509. /**
  40510. * The purpose of this class is to pack several Rectangles into a big map, while trying to fit everything as optimally as possible.
  40511. * This class is typically used to build lightmaps, sprite map or to pack several little textures into a big one.
  40512. * 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.
  40513. */
  40514. var RectPackingMap = (function (_super) {
  40515. __extends(RectPackingMap, _super);
  40516. /**
  40517. * Create an instance of the object with a dimension using the given size
  40518. * @param size The dimension of the rectangle that will contain all the sub ones.
  40519. */
  40520. function RectPackingMap(size) {
  40521. var _this = _super.call(this, null, null, BABYLON.Vector2.Zero(), size) || this;
  40522. _this._root = _this;
  40523. return _this;
  40524. }
  40525. /**
  40526. * Add a rectangle, finding the best location to store it into the map
  40527. * @param size the dimension of the rectangle to store
  40528. * @return the Node containing the rectangle information, or null if we couldn't find a free spot
  40529. */
  40530. RectPackingMap.prototype.addRect = function (size) {
  40531. var node = this.findAndSplitNode(size);
  40532. return node;
  40533. };
  40534. Object.defineProperty(RectPackingMap.prototype, "freeSpace", {
  40535. /**
  40536. * Return the current space free normalized between [0;1]
  40537. * @returns {}
  40538. */
  40539. get: function () {
  40540. var freeSize = 0;
  40541. freeSize = this.evalFreeSize(freeSize);
  40542. return freeSize / (this._size.width * this._size.height);
  40543. },
  40544. enumerable: true,
  40545. configurable: true
  40546. });
  40547. return RectPackingMap;
  40548. }(PackedRect));
  40549. BABYLON.RectPackingMap = RectPackingMap;
  40550. })(BABYLON || (BABYLON = {}));
  40551. //# sourceMappingURL=babylon.rectPackingMap.js.map
  40552. var BABYLON;
  40553. (function (BABYLON) {
  40554. var DynamicFloatArrayElementInfo = (function () {
  40555. function DynamicFloatArrayElementInfo() {
  40556. }
  40557. return DynamicFloatArrayElementInfo;
  40558. }());
  40559. BABYLON.DynamicFloatArrayElementInfo = DynamicFloatArrayElementInfo;
  40560. /**
  40561. * 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.
  40562. * The intent is to maintain through time data that will be bound to a WebGlBuffer with the ability to change add/remove elements.
  40563. * It was first built to efficiently maintain the WebGlBuffer that contain instancing based data.
  40564. * 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.
  40565. * 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.
  40566. * 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".
  40567. */
  40568. var DynamicFloatArray = (function () {
  40569. /**
  40570. * Construct an instance of the dynamic float array
  40571. * @param stride size of one element in float (i.e. not bytes!)
  40572. * @param initialElementCount the number of available entries at construction
  40573. */
  40574. function DynamicFloatArray(stride, initialElementCount) {
  40575. this.compareValueOffset = null;
  40576. this.sortingAscending = true;
  40577. this._stride = stride;
  40578. this.buffer = new Float32Array(stride * initialElementCount);
  40579. this._lastUsed = 0;
  40580. this._firstFree = 0;
  40581. this._allEntries = new Array(initialElementCount);
  40582. this._freeEntries = new Array(initialElementCount);
  40583. for (var i = 0; i < initialElementCount; i++) {
  40584. var element = new DynamicFloatArrayElementInfo();
  40585. element.offset = i * stride;
  40586. this._allEntries[i] = element;
  40587. this._freeEntries[initialElementCount - i - 1] = element;
  40588. }
  40589. }
  40590. /**
  40591. * Allocate an element in the array.
  40592. * @return the element info instance that contains the offset into the main buffer of the element's location.
  40593. * Beware, this offset may change when you call pack()
  40594. */
  40595. DynamicFloatArray.prototype.allocElement = function () {
  40596. if (this._freeEntries.length === 0) {
  40597. this._growBuffer();
  40598. }
  40599. var el = this._freeEntries.pop();
  40600. this._lastUsed = Math.max(el.offset, this._lastUsed);
  40601. if (el.offset === this._firstFree) {
  40602. if (this._freeEntries.length > 0) {
  40603. this._firstFree = this._freeEntries[this._freeEntries.length - 1].offset;
  40604. }
  40605. else {
  40606. this._firstFree += this._stride;
  40607. }
  40608. }
  40609. return el;
  40610. };
  40611. /**
  40612. * Free the element corresponding to the given element info
  40613. * @param elInfo the element that describe the allocated element
  40614. */
  40615. DynamicFloatArray.prototype.freeElement = function (elInfo) {
  40616. this._firstFree = Math.min(elInfo.offset, this._firstFree);
  40617. this._freeEntries.push(elInfo);
  40618. };
  40619. /**
  40620. * This method will pack all the used elements into a linear sequence and put all the free space at the end.
  40621. * 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().
  40622. * @return the subArray that is the view of the used elements area, you can use it as a source to update a WebGLBuffer
  40623. */
  40624. DynamicFloatArray.prototype.pack = function () {
  40625. // no free slot? no need to pack
  40626. if (this._freeEntries.length === 0) {
  40627. return this.buffer;
  40628. }
  40629. // If the buffer is already packed the last used will always be lower than the first free
  40630. // 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.
  40631. if (this._lastUsed < this._firstFree) {
  40632. var elementsBuffer_1 = this.buffer.subarray(0, this._lastUsed + this._stride);
  40633. return elementsBuffer_1;
  40634. }
  40635. var s = this._stride;
  40636. // 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
  40637. var lastFree = new DynamicFloatArrayElementInfo();
  40638. lastFree.offset = this.totalElementCount * s;
  40639. this._freeEntries.push(lastFree);
  40640. var sortedFree = this._freeEntries.sort(function (a, b) { return a.offset - b.offset; });
  40641. var sortedAll = this._allEntries.sort(function (a, b) { return a.offset - b.offset; });
  40642. var firstFreeSlotOffset = sortedFree[0].offset;
  40643. var freeZoneSize = 1;
  40644. var occupiedZoneSize = (this.usedElementCount + 1) * s;
  40645. var prevOffset = sortedFree[0].offset;
  40646. for (var i = 1; i < sortedFree.length; i++) {
  40647. // 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
  40648. if (firstFreeSlotOffset >= occupiedZoneSize) {
  40649. break;
  40650. }
  40651. var curFree = sortedFree[i];
  40652. var curOffset = curFree.offset;
  40653. // Compute the distance between this offset and the previous
  40654. var distance = curOffset - prevOffset;
  40655. // If the distance is the stride size, they are adjacent, it good, move to the next
  40656. if (distance === s) {
  40657. // Free zone is one element bigger
  40658. ++freeZoneSize;
  40659. // as we're about to iterate to the next, the cur becomes the previous...
  40660. prevOffset = curOffset;
  40661. continue;
  40662. }
  40663. // Distance is bigger, which means there's x element between the previous free and this one
  40664. var usedRange = (distance / s) - 1;
  40665. // Two cases the free zone is smaller than the data to move or bigger
  40666. // Copy what can fit in the free zone
  40667. var curMoveOffset = curOffset - s;
  40668. var copyCount = Math.min(freeZoneSize, usedRange);
  40669. for (var j = 0; j < copyCount; j++) {
  40670. var freeI = firstFreeSlotOffset / s;
  40671. var curI = curMoveOffset / s;
  40672. var moveEl = sortedAll[curI];
  40673. this._moveElement(moveEl, firstFreeSlotOffset);
  40674. var replacedEl = sortedAll[freeI];
  40675. // set the offset of the element we replaced with a value that will make it discard at the end of the method
  40676. replacedEl.offset = curMoveOffset;
  40677. // Swap the element we moved and the one it replaced in the sorted array to reflect the action we've made
  40678. sortedAll[freeI] = moveEl;
  40679. sortedAll[curI] = replacedEl;
  40680. curMoveOffset -= s;
  40681. firstFreeSlotOffset += s;
  40682. }
  40683. // Free Zone is smaller or equal so it's no longer a free zone, set the new one to the current location
  40684. if (freeZoneSize <= usedRange) {
  40685. firstFreeSlotOffset = curMoveOffset + s;
  40686. freeZoneSize = 1 + copyCount;
  40687. }
  40688. else {
  40689. freeZoneSize = ((curOffset - firstFreeSlotOffset) / s) + 1;
  40690. }
  40691. // as we're about to iterate to the next, the cur becomes the previous...
  40692. prevOffset = curOffset;
  40693. }
  40694. var elementsBuffer = this.buffer.subarray(0, firstFreeSlotOffset);
  40695. this._lastUsed = firstFreeSlotOffset - s;
  40696. this._firstFree = firstFreeSlotOffset;
  40697. sortedFree.pop(); // Remove the last free because that's the one we added at the start of the method
  40698. this._freeEntries = sortedFree.sort(function (a, b) { return b.offset - a.offset; });
  40699. this._allEntries = sortedAll;
  40700. return elementsBuffer;
  40701. };
  40702. DynamicFloatArray.prototype._moveElement = function (element, destOffset) {
  40703. for (var i = 0; i < this._stride; i++) {
  40704. this.buffer[destOffset + i] = this.buffer[element.offset + i];
  40705. }
  40706. element.offset = destOffset;
  40707. };
  40708. DynamicFloatArray.prototype._growBuffer = function () {
  40709. // Allocate the new buffer with 50% more entries, copy the content of the current one
  40710. var newElCount = Math.floor(this.totalElementCount * 1.5);
  40711. var newBuffer = new Float32Array(newElCount * this._stride);
  40712. newBuffer.set(this.buffer);
  40713. var curCount = this.totalElementCount;
  40714. var addedCount = newElCount - this.totalElementCount;
  40715. for (var i = 0; i < addedCount; i++) {
  40716. var element = new DynamicFloatArrayElementInfo();
  40717. element.offset = (curCount + i) * this.stride;
  40718. this._allEntries.push(element);
  40719. this._freeEntries[addedCount - i - 1] = element;
  40720. }
  40721. this._firstFree = curCount * this.stride;
  40722. this.buffer = newBuffer;
  40723. };
  40724. Object.defineProperty(DynamicFloatArray.prototype, "totalElementCount", {
  40725. /**
  40726. * Get the total count of entries that can fit in the current buffer
  40727. * @returns the elements count
  40728. */
  40729. get: function () {
  40730. return this._allEntries.length;
  40731. },
  40732. enumerable: true,
  40733. configurable: true
  40734. });
  40735. Object.defineProperty(DynamicFloatArray.prototype, "freeElementCount", {
  40736. /**
  40737. * Get the count of free entries that can still be allocated without resizing the buffer
  40738. * @returns the free elements count
  40739. */
  40740. get: function () {
  40741. return this._freeEntries.length;
  40742. },
  40743. enumerable: true,
  40744. configurable: true
  40745. });
  40746. Object.defineProperty(DynamicFloatArray.prototype, "usedElementCount", {
  40747. /**
  40748. * Get the count of allocated elements
  40749. * @returns the allocated elements count
  40750. */
  40751. get: function () {
  40752. return this._allEntries.length - this._freeEntries.length;
  40753. },
  40754. enumerable: true,
  40755. configurable: true
  40756. });
  40757. Object.defineProperty(DynamicFloatArray.prototype, "stride", {
  40758. /**
  40759. * Return the size of one element in float
  40760. * @returns the size in float
  40761. */
  40762. get: function () {
  40763. return this._stride;
  40764. },
  40765. enumerable: true,
  40766. configurable: true
  40767. });
  40768. DynamicFloatArray.prototype.sort = function () {
  40769. var _this = this;
  40770. if (!this.compareValueOffset) {
  40771. throw new Error("The DynamicFloatArray.sort() method needs a valid 'compareValueOffset' property");
  40772. }
  40773. var count = this.usedElementCount;
  40774. // Do we have to (re)create the sort table?
  40775. if (!this._sortTable || this._sortTable.length < count) {
  40776. // 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...
  40777. var newCount = Math.min(this.totalElementCount, count * 2);
  40778. this._sortTable = new Array(newCount);
  40779. }
  40780. if (!this._sortedTable || this._sortedTable.length !== count) {
  40781. this._sortedTable = new Array(count);
  40782. }
  40783. // Because, you know...
  40784. this.pack();
  40785. //let stride = this.stride;
  40786. //for (let i = 0; i < count; i++) {
  40787. // let si = this._sortTable[i];
  40788. // if (!si) {
  40789. // si = new SortInfo();
  40790. // this._sortTable[i] = si;
  40791. // }
  40792. // si.entry = this._allEntries[i];
  40793. // si.compareData = this.buffer[si.entry.offset + this.compareValueOffset];
  40794. // si.swapedOffset = null;
  40795. // this._sortedTable[i] = si;
  40796. //}
  40797. var curOffset = 0;
  40798. var stride = this.stride;
  40799. for (var i = 0; i < count; i++, curOffset += stride) {
  40800. var si = this._sortTable[i];
  40801. if (!si) {
  40802. si = new SortInfo();
  40803. this._sortTable[i] = si;
  40804. }
  40805. si.compareData = this.buffer[curOffset + this.compareValueOffset];
  40806. si.offset = curOffset;
  40807. si.swapedOffset = null;
  40808. this._sortedTable[i] = si;
  40809. }
  40810. // Let's sort the sorted table, we want to keep a track of the original one (that's why we have two buffers)
  40811. if (this.sortingAscending) {
  40812. this._sortedTable.sort(function (a, b) { return a.compareData - b.compareData; });
  40813. }
  40814. else {
  40815. this._sortedTable.sort(function (a, b) { return b.compareData - a.compareData; });
  40816. }
  40817. var swapElements = function (src, dst) {
  40818. for (var i = 0; i < stride; i++) {
  40819. var tps = _this.buffer[dst + i];
  40820. _this.buffer[dst + i] = _this.buffer[src + i];
  40821. _this.buffer[src + i] = tps;
  40822. }
  40823. };
  40824. // 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:
  40825. // 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),
  40826. // and I still want something with a good algorithm complexity.
  40827. // 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,
  40828. // we need sortTable for that, it contains the original layout of SortInfo object, not the sorted one.
  40829. // The best way is to use an extra field in SortInfo, because potentially every element can be replaced.
  40830. // 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
  40831. // until we find a SortInfo object without a swapedOffset which means we got the right location
  40832. // 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
  40833. // than a double allocation of the whole float32Array or a O(n²/2) typical algorithm.
  40834. for (var i = 0; i < count; i++) {
  40835. // Get the element to move
  40836. var sourceSI = this._sortedTable[i];
  40837. var destSI = this._sortTable[i];
  40838. var sourceOff = sourceSI.offset;
  40839. // If the source changed location, find the new one
  40840. if (sourceSI.swapedOffset) {
  40841. // Follow the swapedOffset until there's none, it will mean that curSI contains the new location in its offset member
  40842. var curSI = sourceSI;
  40843. while (curSI.swapedOffset) {
  40844. curSI = this._sortTable[curSI.swapedOffset / stride];
  40845. }
  40846. // Finally get the right location
  40847. sourceOff = curSI.offset;
  40848. }
  40849. // Tag the element being replaced with its new location
  40850. destSI.swapedOffset = sourceOff;
  40851. // Swap elements (only if needed)
  40852. if (sourceOff !== destSI.offset) {
  40853. swapElements(sourceOff, destSI.offset);
  40854. }
  40855. // Update the offset in the corresponding DFAE
  40856. //sourceSI.entry.offset = destSI.entry.offset;
  40857. this._allEntries[sourceSI.offset / stride].offset = destSI.offset;
  40858. }
  40859. this._allEntries.sort(function (a, b) { return a.offset - b.offset; });
  40860. return true;
  40861. };
  40862. return DynamicFloatArray;
  40863. }());
  40864. BABYLON.DynamicFloatArray = DynamicFloatArray;
  40865. var SortInfo = (function () {
  40866. function SortInfo() {
  40867. this.compareData = this.offset = this.swapedOffset = null;
  40868. }
  40869. return SortInfo;
  40870. }());
  40871. })(BABYLON || (BABYLON = {}));
  40872. //# sourceMappingURL=babylon.dynamicFloatArray.js.map
  40873. var BABYLON;
  40874. (function (BABYLON) {
  40875. var MapTexture = (function (_super) {
  40876. __extends(MapTexture, _super);
  40877. function MapTexture(name, scene, size, samplingMode, useMipMap) {
  40878. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  40879. if (useMipMap === void 0) { useMipMap = false; }
  40880. var _this = _super.call(this, null, scene, !useMipMap, false, samplingMode) || this;
  40881. _this.name = name;
  40882. _this._size = size;
  40883. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  40884. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  40885. // Create the rectPackMap that will allocate portion of the texture
  40886. _this._rectPackingMap = new BABYLON.RectPackingMap(new BABYLON.Size(size.width, size.height));
  40887. // Create the texture that will store the content
  40888. _this._texture = scene.getEngine().createRenderTargetTexture(size, { generateMipMaps: !_this.noMipmap, type: BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT });
  40889. return _this;
  40890. }
  40891. /**
  40892. * Allocate a rectangle of a given size in the texture map
  40893. * @param size the size of the rectangle to allocation
  40894. * @return the PackedRect instance corresponding to the allocated rect or null is there was not enough space to allocate it.
  40895. */
  40896. MapTexture.prototype.allocateRect = function (size) {
  40897. return this._rectPackingMap.addRect(size);
  40898. };
  40899. /**
  40900. * Free a given rectangle from the texture map
  40901. * @param rectInfo the instance corresponding to the rect to free.
  40902. */
  40903. MapTexture.prototype.freeRect = function (rectInfo) {
  40904. if (rectInfo) {
  40905. rectInfo.freeContent();
  40906. }
  40907. };
  40908. Object.defineProperty(MapTexture.prototype, "freeSpace", {
  40909. /**
  40910. * Return the available space in the range of [O;1]. 0 being not space left at all, 1 being an empty texture map.
  40911. * This is the cumulated space, not the biggest available surface. Due to fragmentation you may not allocate a rect corresponding to this surface.
  40912. * @returns {}
  40913. */
  40914. get: function () {
  40915. return this._rectPackingMap.freeSpace;
  40916. },
  40917. enumerable: true,
  40918. configurable: true
  40919. });
  40920. /**
  40921. * Bind the texture to the rendering engine to render in the zone of a given rectangle.
  40922. * 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.
  40923. * Don't forget to call unbindTexture when you're done rendering
  40924. * @param rect the zone to render to
  40925. * @param clear true to clear the portion's color/depth data
  40926. */
  40927. MapTexture.prototype.bindTextureForRect = function (rect, clear) {
  40928. return this.bindTextureForPosSize(rect.pos, rect.contentSize, clear);
  40929. };
  40930. /**
  40931. * Bind the texture to the rendering engine to render in the zone of the given size at the given position.
  40932. * 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.
  40933. * Don't forget to call unbindTexture when you're done rendering
  40934. * @param pos the position into the texture
  40935. * @param size the portion to fit the clip space to
  40936. * @param clear true to clear the portion's color/depth data
  40937. */
  40938. MapTexture.prototype.bindTextureForPosSize = function (pos, size, clear) {
  40939. var engine = this.getScene().getEngine();
  40940. engine.bindFramebuffer(this._texture);
  40941. this._replacedViewport = engine.setDirectViewport(pos.x, pos.y, size.width, size.height);
  40942. if (clear) {
  40943. // We only want to clear the part of the texture we're binding to, only the scissor can help us to achieve that
  40944. engine.scissorClear(pos.x, pos.y, size.width, size.height, new BABYLON.Color4(0, 0, 0, 0));
  40945. }
  40946. };
  40947. /**
  40948. * Unbind the texture map from the rendering engine.
  40949. * Call this method when you're done rendering. A previous call to bindTextureForRect has to be made.
  40950. * @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.
  40951. */
  40952. MapTexture.prototype.unbindTexture = function (dumpForDebug) {
  40953. // Dump ?
  40954. if (dumpForDebug) {
  40955. BABYLON.Tools.DumpFramebuffer(this._size.width, this._size.height, this.getScene().getEngine());
  40956. }
  40957. var engine = this.getScene().getEngine();
  40958. if (this._replacedViewport) {
  40959. engine.setViewport(this._replacedViewport);
  40960. this._replacedViewport = null;
  40961. }
  40962. engine.unBindFramebuffer(this._texture);
  40963. };
  40964. Object.defineProperty(MapTexture.prototype, "canRescale", {
  40965. get: function () {
  40966. return false;
  40967. },
  40968. enumerable: true,
  40969. configurable: true
  40970. });
  40971. // Note, I don't know what behavior this method should have: clone the underlying texture/rectPackingMap or just reference them?
  40972. // Anyway, there's not much point to use this method for this kind of texture I guess
  40973. MapTexture.prototype.clone = function () {
  40974. return null;
  40975. };
  40976. return MapTexture;
  40977. }(BABYLON.Texture));
  40978. BABYLON.MapTexture = MapTexture;
  40979. })(BABYLON || (BABYLON = {}));
  40980. //# sourceMappingURL=babylon.mapTexture.js.map
  40981. var BABYLON;
  40982. (function (BABYLON) {
  40983. var ShaderMaterial = (function (_super) {
  40984. __extends(ShaderMaterial, _super);
  40985. function ShaderMaterial(name, scene, shaderPath, options) {
  40986. var _this = _super.call(this, name, scene) || this;
  40987. _this._textures = {};
  40988. _this._textureArrays = {};
  40989. _this._floats = {};
  40990. _this._floatsArrays = {};
  40991. _this._colors3 = {};
  40992. _this._colors4 = {};
  40993. _this._vectors2 = {};
  40994. _this._vectors3 = {};
  40995. _this._vectors4 = {};
  40996. _this._matrices = {};
  40997. _this._matrices3x3 = {};
  40998. _this._matrices2x2 = {};
  40999. _this._vectors3Arrays = {};
  41000. _this._cachedWorldViewMatrix = new BABYLON.Matrix();
  41001. _this._shaderPath = shaderPath;
  41002. options.needAlphaBlending = options.needAlphaBlending || false;
  41003. options.needAlphaTesting = options.needAlphaTesting || false;
  41004. options.attributes = options.attributes || ["position", "normal", "uv"];
  41005. options.uniforms = options.uniforms || ["worldViewProjection"];
  41006. options.samplers = options.samplers || [];
  41007. options.defines = options.defines || [];
  41008. _this._options = options;
  41009. return _this;
  41010. }
  41011. ShaderMaterial.prototype.getClassName = function () {
  41012. return "ShaderMaterial";
  41013. };
  41014. ShaderMaterial.prototype.needAlphaBlending = function () {
  41015. return this._options.needAlphaBlending;
  41016. };
  41017. ShaderMaterial.prototype.needAlphaTesting = function () {
  41018. return this._options.needAlphaTesting;
  41019. };
  41020. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  41021. if (this._options.uniforms.indexOf(uniformName) === -1) {
  41022. this._options.uniforms.push(uniformName);
  41023. }
  41024. };
  41025. ShaderMaterial.prototype.setTexture = function (name, texture) {
  41026. if (this._options.samplers.indexOf(name) === -1) {
  41027. this._options.samplers.push(name);
  41028. }
  41029. this._textures[name] = texture;
  41030. return this;
  41031. };
  41032. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  41033. if (this._options.samplers.indexOf(name) === -1) {
  41034. this._options.samplers.push(name);
  41035. }
  41036. this._checkUniform(name);
  41037. this._textureArrays[name] = textures;
  41038. return this;
  41039. };
  41040. ShaderMaterial.prototype.setFloat = function (name, value) {
  41041. this._checkUniform(name);
  41042. this._floats[name] = value;
  41043. return this;
  41044. };
  41045. ShaderMaterial.prototype.setFloats = function (name, value) {
  41046. this._checkUniform(name);
  41047. this._floatsArrays[name] = value;
  41048. return this;
  41049. };
  41050. ShaderMaterial.prototype.setColor3 = function (name, value) {
  41051. this._checkUniform(name);
  41052. this._colors3[name] = value;
  41053. return this;
  41054. };
  41055. ShaderMaterial.prototype.setColor4 = function (name, value) {
  41056. this._checkUniform(name);
  41057. this._colors4[name] = value;
  41058. return this;
  41059. };
  41060. ShaderMaterial.prototype.setVector2 = function (name, value) {
  41061. this._checkUniform(name);
  41062. this._vectors2[name] = value;
  41063. return this;
  41064. };
  41065. ShaderMaterial.prototype.setVector3 = function (name, value) {
  41066. this._checkUniform(name);
  41067. this._vectors3[name] = value;
  41068. return this;
  41069. };
  41070. ShaderMaterial.prototype.setVector4 = function (name, value) {
  41071. this._checkUniform(name);
  41072. this._vectors4[name] = value;
  41073. return this;
  41074. };
  41075. ShaderMaterial.prototype.setMatrix = function (name, value) {
  41076. this._checkUniform(name);
  41077. this._matrices[name] = value;
  41078. return this;
  41079. };
  41080. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  41081. this._checkUniform(name);
  41082. this._matrices3x3[name] = value;
  41083. return this;
  41084. };
  41085. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  41086. this._checkUniform(name);
  41087. this._matrices2x2[name] = value;
  41088. return this;
  41089. };
  41090. ShaderMaterial.prototype.setArray3 = function (name, value) {
  41091. this._checkUniform(name);
  41092. this._vectors3Arrays[name] = value;
  41093. return this;
  41094. };
  41095. ShaderMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  41096. if (!mesh) {
  41097. return true;
  41098. }
  41099. if (this._effect && (this._effect.defines.indexOf("#define INSTANCES") !== -1) !== useInstances) {
  41100. return false;
  41101. }
  41102. return false;
  41103. };
  41104. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  41105. var scene = this.getScene();
  41106. var engine = scene.getEngine();
  41107. if (!this.checkReadyOnEveryCall) {
  41108. if (this._renderId === scene.getRenderId()) {
  41109. if (this._checkCache(scene, mesh, useInstances)) {
  41110. return true;
  41111. }
  41112. }
  41113. }
  41114. // Instances
  41115. var defines = [];
  41116. var fallbacks = new BABYLON.EffectFallbacks();
  41117. if (useInstances) {
  41118. defines.push("#define INSTANCES");
  41119. }
  41120. for (var index = 0; index < this._options.defines.length; index++) {
  41121. defines.push(this._options.defines[index]);
  41122. }
  41123. // Bones
  41124. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  41125. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  41126. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  41127. fallbacks.addCPUSkinningFallback(0, mesh);
  41128. }
  41129. // Alpha test
  41130. if (engine.getAlphaTesting()) {
  41131. defines.push("#define ALPHATEST");
  41132. }
  41133. var previousEffect = this._effect;
  41134. var join = defines.join("\n");
  41135. this._effect = engine.createEffect(this._shaderPath, this._options.attributes, this._options.uniforms, this._options.samplers, join, fallbacks, this.onCompiled, this.onError);
  41136. if (!this._effect.isReady()) {
  41137. return false;
  41138. }
  41139. if (previousEffect !== this._effect) {
  41140. scene.resetCachedMaterial();
  41141. }
  41142. this._renderId = scene.getRenderId();
  41143. return true;
  41144. };
  41145. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  41146. var scene = this.getScene();
  41147. if (this._options.uniforms.indexOf("world") !== -1) {
  41148. this._effect.setMatrix("world", world);
  41149. }
  41150. if (this._options.uniforms.indexOf("worldView") !== -1) {
  41151. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  41152. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  41153. }
  41154. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  41155. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  41156. }
  41157. };
  41158. ShaderMaterial.prototype.bind = function (world, mesh) {
  41159. // Std values
  41160. this.bindOnlyWorldMatrix(world);
  41161. if (this.getScene().getCachedMaterial() !== this) {
  41162. if (this._options.uniforms.indexOf("view") !== -1) {
  41163. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  41164. }
  41165. if (this._options.uniforms.indexOf("projection") !== -1) {
  41166. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  41167. }
  41168. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  41169. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  41170. }
  41171. // Bones
  41172. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  41173. var name;
  41174. // Texture
  41175. for (name in this._textures) {
  41176. this._effect.setTexture(name, this._textures[name]);
  41177. }
  41178. // Texture arrays
  41179. for (name in this._textureArrays) {
  41180. this._effect.setTextureArray(name, this._textureArrays[name]);
  41181. }
  41182. // Float
  41183. for (name in this._floats) {
  41184. this._effect.setFloat(name, this._floats[name]);
  41185. }
  41186. // Float s
  41187. for (name in this._floatsArrays) {
  41188. this._effect.setArray(name, this._floatsArrays[name]);
  41189. }
  41190. // Color3
  41191. for (name in this._colors3) {
  41192. this._effect.setColor3(name, this._colors3[name]);
  41193. }
  41194. // Color4
  41195. for (name in this._colors4) {
  41196. var color = this._colors4[name];
  41197. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  41198. }
  41199. // Vector2
  41200. for (name in this._vectors2) {
  41201. this._effect.setVector2(name, this._vectors2[name]);
  41202. }
  41203. // Vector3
  41204. for (name in this._vectors3) {
  41205. this._effect.setVector3(name, this._vectors3[name]);
  41206. }
  41207. // Vector4
  41208. for (name in this._vectors4) {
  41209. this._effect.setVector4(name, this._vectors4[name]);
  41210. }
  41211. // Matrix
  41212. for (name in this._matrices) {
  41213. this._effect.setMatrix(name, this._matrices[name]);
  41214. }
  41215. // Matrix 3x3
  41216. for (name in this._matrices3x3) {
  41217. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  41218. }
  41219. // Matrix 2x2
  41220. for (name in this._matrices2x2) {
  41221. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  41222. }
  41223. // Vector3Array
  41224. for (name in this._vectors3Arrays) {
  41225. this._effect.setArray3(name, this._vectors3Arrays[name]);
  41226. }
  41227. }
  41228. _super.prototype.bind.call(this, world, mesh);
  41229. };
  41230. ShaderMaterial.prototype.clone = function (name) {
  41231. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  41232. return newShaderMaterial;
  41233. };
  41234. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  41235. if (forceDisposeTextures) {
  41236. var name;
  41237. for (name in this._textures) {
  41238. this._textures[name].dispose();
  41239. }
  41240. for (name in this._textureArrays) {
  41241. var array = this._textureArrays[name];
  41242. for (var index = 0; index < array.length; index++) {
  41243. array[index].dispose();
  41244. }
  41245. }
  41246. }
  41247. this._textures = {};
  41248. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  41249. };
  41250. ShaderMaterial.prototype.serialize = function () {
  41251. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  41252. serializationObject.customType = "BABYLON.ShaderMaterial";
  41253. serializationObject.options = this._options;
  41254. serializationObject.shaderPath = this._shaderPath;
  41255. var name;
  41256. // Texture
  41257. serializationObject.textures = {};
  41258. for (name in this._textures) {
  41259. serializationObject.textures[name] = this._textures[name].serialize();
  41260. }
  41261. // Texture arrays
  41262. serializationObject.textureArrays = {};
  41263. for (name in this._textureArrays) {
  41264. serializationObject.textureArrays[name] = [];
  41265. var array = this._textureArrays[name];
  41266. for (var index = 0; index < array.length; index++) {
  41267. serializationObject.textureArrays[name].push(array[index].serialize());
  41268. }
  41269. }
  41270. // Float
  41271. serializationObject.floats = {};
  41272. for (name in this._floats) {
  41273. serializationObject.floats[name] = this._floats[name];
  41274. }
  41275. // Float s
  41276. serializationObject.floatArrays = {};
  41277. for (name in this._floatsArrays) {
  41278. serializationObject.floatArrays[name] = this._floatsArrays[name];
  41279. }
  41280. // Color3
  41281. serializationObject.colors3 = {};
  41282. for (name in this._colors3) {
  41283. serializationObject.colors3[name] = this._colors3[name].asArray();
  41284. }
  41285. // Color4
  41286. serializationObject.colors4 = {};
  41287. for (name in this._colors4) {
  41288. serializationObject.colors4[name] = this._colors4[name].asArray();
  41289. }
  41290. // Vector2
  41291. serializationObject.vectors2 = {};
  41292. for (name in this._vectors2) {
  41293. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  41294. }
  41295. // Vector3
  41296. serializationObject.vectors3 = {};
  41297. for (name in this._vectors3) {
  41298. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  41299. }
  41300. // Vector4
  41301. serializationObject.vectors4 = {};
  41302. for (name in this._vectors4) {
  41303. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  41304. }
  41305. // Matrix
  41306. serializationObject.matrices = {};
  41307. for (name in this._matrices) {
  41308. serializationObject.matrices[name] = this._matrices[name].asArray();
  41309. }
  41310. // Matrix 3x3
  41311. serializationObject.matrices3x3 = {};
  41312. for (name in this._matrices3x3) {
  41313. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  41314. }
  41315. // Matrix 2x2
  41316. serializationObject.matrices2x2 = {};
  41317. for (name in this._matrices2x2) {
  41318. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  41319. }
  41320. // Vector3Array
  41321. serializationObject.vectors3Arrays = {};
  41322. for (name in this._vectors3Arrays) {
  41323. serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];
  41324. }
  41325. return serializationObject;
  41326. };
  41327. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  41328. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  41329. var name;
  41330. // Texture
  41331. for (name in source.textures) {
  41332. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  41333. }
  41334. // Texture arrays
  41335. for (name in source.textureArrays) {
  41336. var array = source.textureArrays[name];
  41337. var textureArray = new Array();
  41338. for (var index = 0; index < array.length; index++) {
  41339. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  41340. }
  41341. material.setTextureArray(name, textureArray);
  41342. }
  41343. // Float
  41344. for (name in source.floats) {
  41345. material.setFloat(name, source.floats[name]);
  41346. }
  41347. // Float s
  41348. for (name in source.floatsArrays) {
  41349. material.setFloats(name, source.floatsArrays[name]);
  41350. }
  41351. // Color3
  41352. for (name in source.colors3) {
  41353. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  41354. }
  41355. // Color4
  41356. for (name in source.colors4) {
  41357. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  41358. }
  41359. // Vector2
  41360. for (name in source.vectors2) {
  41361. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  41362. }
  41363. // Vector3
  41364. for (name in source.vectors3) {
  41365. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  41366. }
  41367. // Vector4
  41368. for (name in source.vectors4) {
  41369. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  41370. }
  41371. // Matrix
  41372. for (name in source.matrices) {
  41373. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  41374. }
  41375. // Matrix 3x3
  41376. for (name in source.matrices3x3) {
  41377. material.setMatrix3x3(name, source.matrices3x3[name]);
  41378. }
  41379. // Matrix 2x2
  41380. for (name in source.matrices2x2) {
  41381. material.setMatrix2x2(name, source.matrices2x2[name]);
  41382. }
  41383. // Vector3Array
  41384. for (name in source.vectors3Arrays) {
  41385. material.setArray3(name, source.vectors3Arrays[name]);
  41386. }
  41387. return material;
  41388. };
  41389. return ShaderMaterial;
  41390. }(BABYLON.Material));
  41391. BABYLON.ShaderMaterial = ShaderMaterial;
  41392. })(BABYLON || (BABYLON = {}));
  41393. //# sourceMappingURL=babylon.shaderMaterial.js.map
  41394. var BABYLON;
  41395. (function (BABYLON) {
  41396. var Internals;
  41397. (function (Internals) {
  41398. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  41399. // All values and structures referenced from:
  41400. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  41401. var DDS_MAGIC = 0x20534444;
  41402. 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;
  41403. var DDSCAPS_COMPLEX = 0x8, DDSCAPS_MIPMAP = 0x400000, DDSCAPS_TEXTURE = 0x1000;
  41404. 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;
  41405. var DDPF_ALPHAPIXELS = 0x1, DDPF_ALPHA = 0x2, DDPF_FOURCC = 0x4, DDPF_RGB = 0x40, DDPF_YUV = 0x200, DDPF_LUMINANCE = 0x20000;
  41406. function FourCCToInt32(value) {
  41407. return value.charCodeAt(0) +
  41408. (value.charCodeAt(1) << 8) +
  41409. (value.charCodeAt(2) << 16) +
  41410. (value.charCodeAt(3) << 24);
  41411. }
  41412. function Int32ToFourCC(value) {
  41413. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  41414. }
  41415. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  41416. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  41417. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  41418. var headerLengthInt = 31; // The header length in 32 bit ints
  41419. // Offsets into the header array
  41420. var off_magic = 0;
  41421. var off_size = 1;
  41422. var off_flags = 2;
  41423. var off_height = 3;
  41424. var off_width = 4;
  41425. var off_mipmapCount = 7;
  41426. var off_pfFlags = 20;
  41427. var off_pfFourCC = 21;
  41428. var off_RGBbpp = 22;
  41429. var off_RMask = 23;
  41430. var off_GMask = 24;
  41431. var off_BMask = 25;
  41432. var off_AMask = 26;
  41433. var off_caps1 = 27;
  41434. var off_caps2 = 28;
  41435. ;
  41436. var DDSTools = (function () {
  41437. function DDSTools() {
  41438. }
  41439. DDSTools.GetDDSInfo = function (arrayBuffer) {
  41440. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  41441. var mipmapCount = 1;
  41442. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  41443. mipmapCount = Math.max(1, header[off_mipmapCount]);
  41444. }
  41445. return {
  41446. width: header[off_width],
  41447. height: header[off_height],
  41448. mipmapCount: mipmapCount,
  41449. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  41450. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  41451. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  41452. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP
  41453. };
  41454. };
  41455. DDSTools.GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  41456. var byteArray = new Uint8Array(dataLength);
  41457. var srcData = new Uint8Array(arrayBuffer);
  41458. var index = 0;
  41459. for (var y = height - 1; y >= 0; y--) {
  41460. for (var x = 0; x < width; x++) {
  41461. var srcPos = dataOffset + (x + y * width) * 4;
  41462. byteArray[index + 2] = srcData[srcPos];
  41463. byteArray[index + 1] = srcData[srcPos + 1];
  41464. byteArray[index] = srcData[srcPos + 2];
  41465. byteArray[index + 3] = srcData[srcPos + 3];
  41466. index += 4;
  41467. }
  41468. }
  41469. return byteArray;
  41470. };
  41471. DDSTools.GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  41472. var byteArray = new Uint8Array(dataLength);
  41473. var srcData = new Uint8Array(arrayBuffer);
  41474. var index = 0;
  41475. for (var y = height - 1; y >= 0; y--) {
  41476. for (var x = 0; x < width; x++) {
  41477. var srcPos = dataOffset + (x + y * width) * 3;
  41478. byteArray[index + 2] = srcData[srcPos];
  41479. byteArray[index + 1] = srcData[srcPos + 1];
  41480. byteArray[index] = srcData[srcPos + 2];
  41481. index += 3;
  41482. }
  41483. }
  41484. return byteArray;
  41485. };
  41486. DDSTools.GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  41487. var byteArray = new Uint8Array(dataLength);
  41488. var srcData = new Uint8Array(arrayBuffer);
  41489. var index = 0;
  41490. for (var y = height - 1; y >= 0; y--) {
  41491. for (var x = 0; x < width; x++) {
  41492. var srcPos = dataOffset + (x + y * width);
  41493. byteArray[index] = srcData[srcPos];
  41494. index++;
  41495. }
  41496. }
  41497. return byteArray;
  41498. };
  41499. DDSTools.UploadDDSLevels = function (gl, ext, arrayBuffer, info, loadMipmaps, faces) {
  41500. var header = new Int32Array(arrayBuffer, 0, headerLengthInt), fourCC, blockBytes, internalFormat, width, height, dataLength, dataOffset, byteArray, mipmapCount, i;
  41501. if (header[off_magic] != DDS_MAGIC) {
  41502. BABYLON.Tools.Error("Invalid magic number in DDS header");
  41503. return;
  41504. }
  41505. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  41506. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  41507. return;
  41508. }
  41509. if (info.isFourCC) {
  41510. fourCC = header[off_pfFourCC];
  41511. switch (fourCC) {
  41512. case FOURCC_DXT1:
  41513. blockBytes = 8;
  41514. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  41515. break;
  41516. case FOURCC_DXT3:
  41517. blockBytes = 16;
  41518. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  41519. break;
  41520. case FOURCC_DXT5:
  41521. blockBytes = 16;
  41522. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  41523. break;
  41524. default:
  41525. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  41526. return;
  41527. }
  41528. }
  41529. mipmapCount = 1;
  41530. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  41531. mipmapCount = Math.max(1, header[off_mipmapCount]);
  41532. }
  41533. var bpp = header[off_RGBbpp];
  41534. for (var face = 0; face < faces; face++) {
  41535. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  41536. width = header[off_width];
  41537. height = header[off_height];
  41538. dataOffset = header[off_size] + 4;
  41539. for (i = 0; i < mipmapCount; ++i) {
  41540. if (info.isRGB) {
  41541. if (bpp === 24) {
  41542. dataLength = width * height * 3;
  41543. byteArray = DDSTools.GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  41544. gl.texImage2D(sampler, i, gl.RGB, width, height, 0, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  41545. }
  41546. else {
  41547. dataLength = width * height * 4;
  41548. byteArray = DDSTools.GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  41549. gl.texImage2D(sampler, i, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  41550. }
  41551. }
  41552. else if (info.isLuminance) {
  41553. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  41554. var unpaddedRowSize = width;
  41555. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  41556. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  41557. byteArray = DDSTools.GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  41558. gl.texImage2D(sampler, i, gl.LUMINANCE, width, height, 0, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  41559. }
  41560. else {
  41561. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  41562. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  41563. gl.compressedTexImage2D(sampler, i, internalFormat, width, height, 0, byteArray);
  41564. }
  41565. dataOffset += dataLength;
  41566. width *= 0.5;
  41567. height *= 0.5;
  41568. width = Math.max(1.0, width);
  41569. height = Math.max(1.0, height);
  41570. }
  41571. }
  41572. };
  41573. return DDSTools;
  41574. }());
  41575. Internals.DDSTools = DDSTools;
  41576. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  41577. })(BABYLON || (BABYLON = {}));
  41578. //# sourceMappingURL=babylon.tools.dds.js.map
  41579. var BABYLON;
  41580. (function (BABYLON) {
  41581. var Internals;
  41582. (function (Internals) {
  41583. /**
  41584. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  41585. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  41586. */
  41587. var KhronosTextureContainer = (function () {
  41588. /**
  41589. * @param {ArrayBuffer} arrayBuffer- contents of the KTX container file
  41590. * @param {number} facesExpected- should be either 1 or 6, based whether a cube texture or or
  41591. * @param {boolean} threeDExpected- provision for indicating that data should be a 3D texture, not implemented
  41592. * @param {boolean} textureArrayExpected- provision for indicating that data should be a texture array, not implemented
  41593. */
  41594. function KhronosTextureContainer(arrayBuffer, facesExpected, threeDExpected, textureArrayExpected) {
  41595. this.arrayBuffer = arrayBuffer;
  41596. // Test that it is a ktx formatted file, based on the first 12 bytes, character representation is:
  41597. // '�', 'K', 'T', 'X', ' ', '1', '1', '�', '\r', '\n', '\x1A', '\n'
  41598. // 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A
  41599. var identifier = new Uint8Array(this.arrayBuffer, 0, 12);
  41600. if (identifier[0] !== 0xAB || identifier[1] !== 0x4B || identifier[2] !== 0x54 || identifier[3] !== 0x58 || identifier[4] !== 0x20 || identifier[5] !== 0x31 ||
  41601. identifier[6] !== 0x31 || identifier[7] !== 0xBB || identifier[8] !== 0x0D || identifier[9] !== 0x0A || identifier[10] !== 0x1A || identifier[11] !== 0x0A) {
  41602. BABYLON.Tools.Error("texture missing KTX identifier");
  41603. return;
  41604. }
  41605. // load the reset of the header in native 32 bit int
  41606. var header = new Int32Array(this.arrayBuffer, 12, 13);
  41607. // determine of the remaining header values are recorded in the opposite endianness & require conversion
  41608. var oppositeEndianess = header[0] === 0x01020304;
  41609. // read all the header elements in order they exist in the file, without modification (sans endainness)
  41610. this.glType = oppositeEndianess ? this.switchEndainness(header[1]) : header[1]; // must be 0 for compressed textures
  41611. this.glTypeSize = oppositeEndianess ? this.switchEndainness(header[2]) : header[2]; // must be 1 for compressed textures
  41612. this.glFormat = oppositeEndianess ? this.switchEndainness(header[3]) : header[3]; // must be 0 for compressed textures
  41613. this.glInternalFormat = oppositeEndianess ? this.switchEndainness(header[4]) : header[4]; // the value of arg passed to gl.compressedTexImage2D(,,x,,,,)
  41614. this.glBaseInternalFormat = oppositeEndianess ? this.switchEndainness(header[5]) : header[5]; // specify GL_RGB, GL_RGBA, GL_ALPHA, etc (un-compressed only)
  41615. this.pixelWidth = oppositeEndianess ? this.switchEndainness(header[6]) : header[6]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,x,,,)
  41616. this.pixelHeight = oppositeEndianess ? this.switchEndainness(header[7]) : header[7]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,,x,,)
  41617. this.pixelDepth = oppositeEndianess ? this.switchEndainness(header[8]) : header[8]; // level 0 value of arg passed to gl.compressedTexImage3D(,,,,,x,,)
  41618. this.numberOfArrayElements = oppositeEndianess ? this.switchEndainness(header[9]) : header[9]; // used for texture arrays
  41619. this.numberOfFaces = oppositeEndianess ? this.switchEndainness(header[10]) : header[10]; // used for cubemap textures, should either be 1 or 6
  41620. this.numberOfMipmapLevels = oppositeEndianess ? this.switchEndainness(header[11]) : header[11]; // number of levels; disregard possibility of 0 for compressed textures
  41621. this.bytesOfKeyValueData = oppositeEndianess ? this.switchEndainness(header[12]) : header[12]; // the amount of space after the header for meta-data
  41622. // Make sure we have a compressed type. Not only reduces work, but probably better to let dev know they are not compressing.
  41623. if (this.glType !== 0) {
  41624. BABYLON.Tools.Error("only compressed formats currently supported");
  41625. return;
  41626. }
  41627. else {
  41628. // value of zero is an indication to generate mipmaps @ runtime. Not usually allowed for compressed, so disregard.
  41629. this.numberOfMipmapLevels = Math.max(1, this.numberOfMipmapLevels);
  41630. }
  41631. if (this.pixelHeight === 0 || this.pixelDepth !== 0) {
  41632. BABYLON.Tools.Error("only 2D textures currently supported");
  41633. return;
  41634. }
  41635. if (this.numberOfArrayElements !== 0) {
  41636. BABYLON.Tools.Error("texture arrays not currently supported");
  41637. return;
  41638. }
  41639. if (this.numberOfFaces !== facesExpected) {
  41640. BABYLON.Tools.Error("number of faces expected" + facesExpected + ", but found " + this.numberOfFaces);
  41641. return;
  41642. }
  41643. // we now have a completely validated file, so could use existence of loadType as success
  41644. // would need to make this more elaborate & adjust checks above to support more than one load type
  41645. this.loadType = KhronosTextureContainer.COMPRESSED_2D;
  41646. }
  41647. // not as fast hardware based, but will probably never need to use
  41648. KhronosTextureContainer.prototype.switchEndainness = function (val) {
  41649. return ((val & 0xFF) << 24)
  41650. | ((val & 0xFF00) << 8)
  41651. | ((val >> 8) & 0xFF00)
  41652. | ((val >> 24) & 0xFF);
  41653. };
  41654. /**
  41655. * It is assumed that the texture has already been created & is currently bound
  41656. */
  41657. KhronosTextureContainer.prototype.uploadLevels = function (gl, loadMipmaps) {
  41658. switch (this.loadType) {
  41659. case KhronosTextureContainer.COMPRESSED_2D:
  41660. this._upload2DCompressedLevels(gl, loadMipmaps);
  41661. break;
  41662. case KhronosTextureContainer.TEX_2D:
  41663. case KhronosTextureContainer.COMPRESSED_3D:
  41664. case KhronosTextureContainer.TEX_3D:
  41665. }
  41666. };
  41667. KhronosTextureContainer.prototype._upload2DCompressedLevels = function (gl, loadMipmaps) {
  41668. // initialize width & height for level 1
  41669. var dataOffset = KhronosTextureContainer.HEADER_LEN + this.bytesOfKeyValueData;
  41670. var width = this.pixelWidth;
  41671. var height = this.pixelHeight;
  41672. var mipmapCount = loadMipmaps ? this.numberOfMipmapLevels : 1;
  41673. for (var level = 0; level < mipmapCount; level++) {
  41674. var imageSize = new Int32Array(this.arrayBuffer, dataOffset, 1)[0]; // size per face, since not supporting array cubemaps
  41675. for (var face = 0; face < this.numberOfFaces; face++) {
  41676. var sampler = this.numberOfFaces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  41677. var byteArray = new Uint8Array(this.arrayBuffer, dataOffset + 4, imageSize);
  41678. gl.compressedTexImage2D(sampler, level, this.glInternalFormat, width, height, 0, byteArray);
  41679. dataOffset += imageSize + 4; // size of the image + 4 for the imageSize field
  41680. dataOffset += 3 - ((imageSize + 3) % 4); // add padding for odd sized image
  41681. }
  41682. width = Math.max(1.0, width * 0.5);
  41683. height = Math.max(1.0, height * 0.5);
  41684. }
  41685. };
  41686. return KhronosTextureContainer;
  41687. }());
  41688. KhronosTextureContainer.HEADER_LEN = 12 + (13 * 4); // identifier + header elements (not including key value meta-data pairs)
  41689. // load types
  41690. KhronosTextureContainer.COMPRESSED_2D = 0; // uses a gl.compressedTexImage2D()
  41691. KhronosTextureContainer.COMPRESSED_3D = 1; // uses a gl.compressedTexImage3D()
  41692. KhronosTextureContainer.TEX_2D = 2; // uses a gl.texImage2D()
  41693. KhronosTextureContainer.TEX_3D = 3; // uses a gl.texImage3D()
  41694. Internals.KhronosTextureContainer = KhronosTextureContainer;
  41695. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  41696. })(BABYLON || (BABYLON = {}));
  41697. //# sourceMappingURL=babylon.khronosTextureContainer.js.map
  41698. var BABYLON;
  41699. (function (BABYLON) {
  41700. var CannonJSPlugin = (function () {
  41701. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  41702. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  41703. if (iterations === void 0) { iterations = 10; }
  41704. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  41705. this.name = "CannonJSPlugin";
  41706. this._physicsMaterials = [];
  41707. this._fixedTimeStep = 1 / 60;
  41708. //See https://github.com/schteppe/cannon.js/blob/gh-pages/demos/collisionFilter.html
  41709. this._currentCollisionGroup = 2;
  41710. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  41711. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  41712. this._tmpPosition = BABYLON.Vector3.Zero();
  41713. this._tmpQuaternion = new BABYLON.Quaternion();
  41714. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  41715. this._tmpDeltaRotation = new BABYLON.Quaternion();
  41716. this._tmpUnityRotation = new BABYLON.Quaternion();
  41717. if (!this.isSupported()) {
  41718. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  41719. return;
  41720. }
  41721. this.world = new CANNON.World();
  41722. this.world.broadphase = new CANNON.NaiveBroadphase();
  41723. this.world.solver.iterations = iterations;
  41724. }
  41725. CannonJSPlugin.prototype.setGravity = function (gravity) {
  41726. this.world.gravity.copy(gravity);
  41727. };
  41728. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  41729. this._fixedTimeStep = timeStep;
  41730. };
  41731. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  41732. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta * 1000 : 0, 3);
  41733. };
  41734. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  41735. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  41736. var impulse = new CANNON.Vec3(force.x, force.y, force.z);
  41737. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  41738. };
  41739. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  41740. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  41741. var impulse = new CANNON.Vec3(force.x, force.y, force.z);
  41742. impostor.physicsBody.applyForce(impulse, worldPoint);
  41743. };
  41744. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  41745. //parent-child relationship. Does this impostor has a parent impostor?
  41746. if (impostor.parent) {
  41747. if (impostor.physicsBody) {
  41748. this.removePhysicsBody(impostor);
  41749. //TODO is that needed?
  41750. impostor.forceUpdate();
  41751. }
  41752. return;
  41753. }
  41754. //should a new body be created for this impostor?
  41755. if (impostor.isBodyInitRequired()) {
  41756. var shape = this._createShape(impostor);
  41757. //unregister events, if body is being changed
  41758. var oldBody = impostor.physicsBody;
  41759. if (oldBody) {
  41760. this.removePhysicsBody(impostor);
  41761. }
  41762. //create the body and material
  41763. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  41764. var bodyCreationObject = {
  41765. mass: impostor.getParam("mass"),
  41766. material: material
  41767. };
  41768. // A simple extend, in case native options were used.
  41769. var nativeOptions = impostor.getParam("nativeOptions");
  41770. for (var key in nativeOptions) {
  41771. if (nativeOptions.hasOwnProperty(key)) {
  41772. bodyCreationObject[key] = nativeOptions[key];
  41773. }
  41774. }
  41775. impostor.physicsBody = new CANNON.Body(bodyCreationObject);
  41776. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  41777. this.world.addEventListener("preStep", impostor.beforeStep);
  41778. this.world.addEventListener("postStep", impostor.afterStep);
  41779. impostor.physicsBody.addShape(shape);
  41780. this.world.add(impostor.physicsBody);
  41781. //try to keep the body moving in the right direction by taking old properties.
  41782. //Should be tested!
  41783. if (oldBody) {
  41784. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  41785. impostor.physicsBody[param].copy(oldBody[param]);
  41786. });
  41787. }
  41788. this._processChildMeshes(impostor);
  41789. }
  41790. //now update the body's transformation
  41791. this._updatePhysicsBodyTransformation(impostor);
  41792. };
  41793. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  41794. var _this = this;
  41795. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes() : [];
  41796. if (meshChildren.length) {
  41797. var processMesh = function (localPosition, mesh) {
  41798. var childImpostor = mesh.getPhysicsImpostor();
  41799. if (childImpostor) {
  41800. var parent = childImpostor.parent;
  41801. if (parent !== mainImpostor) {
  41802. var localPosition = mesh.position;
  41803. if (childImpostor.physicsBody) {
  41804. _this.removePhysicsBody(childImpostor);
  41805. childImpostor.physicsBody = null;
  41806. }
  41807. childImpostor.parent = mainImpostor;
  41808. childImpostor.resetUpdateFlags();
  41809. mainImpostor.physicsBody.addShape(_this._createShape(childImpostor), new CANNON.Vec3(localPosition.x, localPosition.y, localPosition.z));
  41810. //Add the mass of the children.
  41811. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  41812. }
  41813. }
  41814. mesh.getChildMeshes().forEach(processMesh.bind(_this, mesh.position));
  41815. };
  41816. meshChildren.forEach(processMesh.bind(this, BABYLON.Vector3.Zero()));
  41817. }
  41818. };
  41819. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  41820. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  41821. this.world.removeEventListener("preStep", impostor.beforeStep);
  41822. this.world.removeEventListener("postStep", impostor.afterStep);
  41823. this.world.remove(impostor.physicsBody);
  41824. };
  41825. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  41826. var mainBody = impostorJoint.mainImpostor.physicsBody;
  41827. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  41828. if (!mainBody || !connectedBody) {
  41829. return;
  41830. }
  41831. var constraint;
  41832. var jointData = impostorJoint.joint.jointData;
  41833. //TODO - https://github.com/schteppe/cannon.js/blob/gh-pages/demos/collisionFilter.html
  41834. var constraintData = {
  41835. pivotA: jointData.mainPivot ? new CANNON.Vec3().copy(jointData.mainPivot) : null,
  41836. pivotB: jointData.connectedPivot ? new CANNON.Vec3().copy(jointData.connectedPivot) : null,
  41837. axisA: jointData.mainAxis ? new CANNON.Vec3().copy(jointData.mainAxis) : null,
  41838. axisB: jointData.connectedAxis ? new CANNON.Vec3().copy(jointData.connectedAxis) : null,
  41839. maxForce: jointData.nativeParams.maxForce,
  41840. collideConnected: !!jointData.collision
  41841. };
  41842. switch (impostorJoint.joint.type) {
  41843. case BABYLON.PhysicsJoint.HingeJoint:
  41844. case BABYLON.PhysicsJoint.Hinge2Joint:
  41845. constraint = new CANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  41846. break;
  41847. case BABYLON.PhysicsJoint.DistanceJoint:
  41848. constraint = new CANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  41849. break;
  41850. case BABYLON.PhysicsJoint.SpringJoint:
  41851. var springData = jointData;
  41852. constraint = new CANNON.Spring(mainBody, connectedBody, {
  41853. restLength: springData.length,
  41854. stiffness: springData.stiffness,
  41855. damping: springData.damping,
  41856. localAnchorA: constraintData.pivotA,
  41857. localAnchorB: constraintData.pivotB
  41858. });
  41859. break;
  41860. case BABYLON.PhysicsJoint.LockJoint:
  41861. constraint = new CANNON.LockConstraint(mainBody, connectedBody, constraintData);
  41862. break;
  41863. case BABYLON.PhysicsJoint.PointToPointJoint:
  41864. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  41865. default:
  41866. constraint = new CANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  41867. break;
  41868. }
  41869. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  41870. constraint.collideConnected = !!jointData.collision;
  41871. impostorJoint.joint.physicsJoint = constraint;
  41872. //don't add spring as constraint, as it is not one.
  41873. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  41874. this.world.addConstraint(constraint);
  41875. }
  41876. else {
  41877. impostorJoint.mainImpostor.registerAfterPhysicsStep(function () {
  41878. constraint.applyForce();
  41879. });
  41880. }
  41881. };
  41882. CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
  41883. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  41884. };
  41885. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  41886. var index;
  41887. var mat;
  41888. for (index = 0; index < this._physicsMaterials.length; index++) {
  41889. mat = this._physicsMaterials[index];
  41890. if (mat.friction === friction && mat.restitution === restitution) {
  41891. return mat;
  41892. }
  41893. }
  41894. var currentMat = new CANNON.Material(name);
  41895. currentMat.friction = friction;
  41896. currentMat.restitution = restitution;
  41897. this._physicsMaterials.push(currentMat);
  41898. return currentMat;
  41899. };
  41900. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  41901. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  41902. };
  41903. CannonJSPlugin.prototype._createShape = function (impostor) {
  41904. var object = impostor.object;
  41905. var returnValue;
  41906. var extendSize = impostor.getObjectExtendSize();
  41907. switch (impostor.type) {
  41908. case BABYLON.PhysicsEngine.SphereImpostor:
  41909. var radiusX = extendSize.x;
  41910. var radiusY = extendSize.y;
  41911. var radiusZ = extendSize.z;
  41912. returnValue = new CANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  41913. break;
  41914. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  41915. case BABYLON.PhysicsImpostor.CylinderImpostor:
  41916. returnValue = new CANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  41917. break;
  41918. case BABYLON.PhysicsImpostor.BoxImpostor:
  41919. var box = extendSize.scale(0.5);
  41920. returnValue = new CANNON.Box(new CANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  41921. break;
  41922. case BABYLON.PhysicsImpostor.PlaneImpostor:
  41923. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  41924. returnValue = new CANNON.Plane();
  41925. break;
  41926. case BABYLON.PhysicsImpostor.MeshImpostor:
  41927. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  41928. var rawFaces = object.getIndices ? object.getIndices() : [];
  41929. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  41930. returnValue = new CANNON.Trimesh(rawVerts, rawFaces);
  41931. break;
  41932. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  41933. returnValue = this._createHeightmap(object);
  41934. break;
  41935. case BABYLON.PhysicsImpostor.ParticleImpostor:
  41936. returnValue = new CANNON.Particle();
  41937. break;
  41938. }
  41939. return returnValue;
  41940. };
  41941. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  41942. var pos = object.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  41943. var matrix = [];
  41944. //For now pointDepth will not be used and will be automatically calculated.
  41945. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  41946. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  41947. var dim = Math.min(object.getBoundingInfo().boundingBox.extendSize.x, object.getBoundingInfo().boundingBox.extendSize.z);
  41948. var elementSize = dim * 2 / arraySize;
  41949. var minY = object.getBoundingInfo().boundingBox.extendSize.y;
  41950. for (var i = 0; i < pos.length; i = i + 3) {
  41951. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  41952. var z = Math.round(((pos[i + 2]) / elementSize - arraySize / 2) * -1);
  41953. var y = pos[i + 1] + minY;
  41954. if (!matrix[x]) {
  41955. matrix[x] = [];
  41956. }
  41957. if (!matrix[x][z]) {
  41958. matrix[x][z] = y;
  41959. }
  41960. matrix[x][z] = Math.max(y, matrix[x][z]);
  41961. }
  41962. for (var x = 0; x <= arraySize; ++x) {
  41963. if (!matrix[x]) {
  41964. var loc = 1;
  41965. while (!matrix[(x + loc) % arraySize]) {
  41966. loc++;
  41967. }
  41968. matrix[x] = matrix[(x + loc) % arraySize].slice();
  41969. }
  41970. for (var z = 0; z <= arraySize; ++z) {
  41971. if (!matrix[x][z]) {
  41972. var loc = 1;
  41973. var newValue;
  41974. while (newValue === undefined) {
  41975. newValue = matrix[x][(z + loc++) % arraySize];
  41976. }
  41977. matrix[x][z] = newValue;
  41978. }
  41979. }
  41980. }
  41981. var shape = new CANNON.Heightfield(matrix, {
  41982. elementSize: elementSize
  41983. });
  41984. //For future reference, needed for body transformation
  41985. shape.minY = minY;
  41986. return shape;
  41987. };
  41988. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  41989. var object = impostor.object;
  41990. //make sure it is updated...
  41991. object.computeWorldMatrix && object.computeWorldMatrix(true);
  41992. // The delta between the mesh position and the mesh bounding box center
  41993. var center = impostor.getObjectCenter();
  41994. var extendSize = impostor.getObjectExtendSize();
  41995. this._tmpDeltaPosition.copyFrom(object.position.subtract(center));
  41996. this._tmpPosition.copyFrom(center);
  41997. var quaternion = object.rotationQuaternion;
  41998. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  41999. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  42000. //-90 DEG in X, precalculated
  42001. quaternion = quaternion.multiply(this._minus90X);
  42002. //Invert! (Precalculated, 90 deg in X)
  42003. //No need to clone. this will never change.
  42004. impostor.setDeltaRotation(this._plus90X);
  42005. }
  42006. //If it is a heightfield, if should be centered.
  42007. if (impostor.type === BABYLON.PhysicsEngine.HeightmapImpostor) {
  42008. var mesh = object;
  42009. //calculate the correct body position:
  42010. var rotationQuaternion = mesh.rotationQuaternion;
  42011. mesh.rotationQuaternion = this._tmpUnityRotation;
  42012. mesh.computeWorldMatrix(true);
  42013. //get original center with no rotation
  42014. var c = center.clone();
  42015. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  42016. //rotation is back
  42017. mesh.rotationQuaternion = rotationQuaternion;
  42018. //calculate the new center using a pivot (since Cannon.js doesn't center height maps)
  42019. var p = BABYLON.Matrix.Translation(mesh.getBoundingInfo().boundingBox.extendSize.x, 0, -mesh.getBoundingInfo().boundingBox.extendSize.z);
  42020. mesh.setPivotMatrix(p);
  42021. mesh.computeWorldMatrix(true);
  42022. //calculate the translation
  42023. var translation = mesh.getBoundingInfo().boundingBox.center.subtract(center).subtract(mesh.position).negate();
  42024. this._tmpPosition.copyFromFloats(translation.x, translation.y - mesh.getBoundingInfo().boundingBox.extendSize.y, translation.z);
  42025. //add it inverted to the delta
  42026. this._tmpDeltaPosition.copyFrom(mesh.getBoundingInfo().boundingBox.center.subtract(c));
  42027. this._tmpDeltaPosition.y += mesh.getBoundingInfo().boundingBox.extendSize.y;
  42028. mesh.setPivotMatrix(oldPivot);
  42029. mesh.computeWorldMatrix(true);
  42030. }
  42031. else if (impostor.type === BABYLON.PhysicsEngine.MeshImpostor) {
  42032. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  42033. this._tmpPosition.copyFrom(object.position);
  42034. }
  42035. impostor.setDeltaPosition(this._tmpDeltaPosition);
  42036. //Now update the impostor object
  42037. impostor.physicsBody.position.copy(this._tmpPosition);
  42038. impostor.physicsBody.quaternion.copy(quaternion);
  42039. };
  42040. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  42041. impostor.object.position.copyFrom(impostor.physicsBody.position);
  42042. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  42043. };
  42044. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  42045. impostor.physicsBody.position.copy(newPosition);
  42046. impostor.physicsBody.quaternion.copy(newRotation);
  42047. };
  42048. CannonJSPlugin.prototype.isSupported = function () {
  42049. return window.CANNON !== undefined;
  42050. };
  42051. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  42052. impostor.physicsBody.velocity.copy(velocity);
  42053. };
  42054. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  42055. impostor.physicsBody.angularVelocity.copy(velocity);
  42056. };
  42057. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  42058. var v = impostor.physicsBody.velocity;
  42059. if (!v)
  42060. return null;
  42061. return new BABYLON.Vector3(v.x, v.y, v.z);
  42062. };
  42063. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  42064. var v = impostor.physicsBody.angularVelocity;
  42065. if (!v)
  42066. return null;
  42067. return new BABYLON.Vector3(v.x, v.y, v.z);
  42068. };
  42069. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  42070. impostor.physicsBody.mass = mass;
  42071. impostor.physicsBody.updateMassProperties();
  42072. };
  42073. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  42074. impostor.physicsBody.sleep();
  42075. };
  42076. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  42077. impostor.physicsBody.wakeUp();
  42078. };
  42079. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  42080. joint.physicsJoint.distance = maxDistance;
  42081. };
  42082. CannonJSPlugin.prototype.enableMotor = function (joint, motorIndex) {
  42083. if (!motorIndex) {
  42084. joint.physicsJoint.enableMotor();
  42085. }
  42086. };
  42087. CannonJSPlugin.prototype.disableMotor = function (joint, motorIndex) {
  42088. if (!motorIndex) {
  42089. joint.physicsJoint.disableMotor();
  42090. }
  42091. };
  42092. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  42093. if (!motorIndex) {
  42094. joint.physicsJoint.enableMotor();
  42095. joint.physicsJoint.setMotorSpeed(speed);
  42096. if (maxForce) {
  42097. this.setLimit(joint, maxForce);
  42098. }
  42099. }
  42100. };
  42101. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  42102. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  42103. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  42104. };
  42105. CannonJSPlugin.prototype.dispose = function () {
  42106. //nothing to do, actually.
  42107. };
  42108. return CannonJSPlugin;
  42109. }());
  42110. BABYLON.CannonJSPlugin = CannonJSPlugin;
  42111. })(BABYLON || (BABYLON = {}));
  42112. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  42113. var BABYLON;
  42114. (function (BABYLON) {
  42115. var OimoJSPlugin = (function () {
  42116. function OimoJSPlugin(iterations) {
  42117. this.name = "OimoJSPlugin";
  42118. this._tmpImpostorsArray = [];
  42119. this._tmpPositionVector = BABYLON.Vector3.Zero();
  42120. this.world = new OIMO.World(1 / 60, 2, iterations, true);
  42121. this.world.worldscale(1);
  42122. this.world.clear();
  42123. //making sure no stats are calculated
  42124. this.world.isNoStat = true;
  42125. }
  42126. OimoJSPlugin.prototype.setGravity = function (gravity) {
  42127. this.world.gravity.copy(gravity);
  42128. };
  42129. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  42130. this.world.timeStep = timeStep;
  42131. };
  42132. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  42133. var _this = this;
  42134. impostors.forEach(function (impostor) {
  42135. impostor.beforeStep();
  42136. });
  42137. this.world.step();
  42138. impostors.forEach(function (impostor) {
  42139. impostor.afterStep();
  42140. //update the ordered impostors array
  42141. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  42142. });
  42143. //check for collisions
  42144. var contact = this.world.contacts;
  42145. while (contact !== null) {
  42146. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  42147. contact = contact.next;
  42148. continue;
  42149. }
  42150. //is this body colliding with any other? get the impostor
  42151. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  42152. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  42153. if (!mainImpostor || !collidingImpostor) {
  42154. contact = contact.next;
  42155. continue;
  42156. }
  42157. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  42158. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  42159. contact = contact.next;
  42160. }
  42161. };
  42162. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  42163. var mass = impostor.physicsBody.massInfo.mass;
  42164. impostor.physicsBody.applyImpulse(contactPoint.scale(OIMO.INV_SCALE), force.scale(OIMO.INV_SCALE * mass));
  42165. };
  42166. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  42167. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  42168. this.applyImpulse(impostor, force, contactPoint);
  42169. };
  42170. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  42171. var _this = this;
  42172. //parent-child relationship. Does this impostor has a parent impostor?
  42173. if (impostor.parent) {
  42174. if (impostor.physicsBody) {
  42175. this.removePhysicsBody(impostor);
  42176. //TODO is that needed?
  42177. impostor.forceUpdate();
  42178. }
  42179. return;
  42180. }
  42181. if (impostor.isBodyInitRequired()) {
  42182. var bodyConfig = {
  42183. name: impostor.uniqueId,
  42184. //Oimo must have mass, also for static objects.
  42185. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  42186. size: [],
  42187. type: [],
  42188. pos: [],
  42189. rot: [],
  42190. move: impostor.getParam("mass") !== 0,
  42191. //Supporting older versions of Oimo
  42192. world: this.world
  42193. };
  42194. var impostors = [impostor];
  42195. var addToArray = function (parent) {
  42196. if (!parent.getChildMeshes)
  42197. return;
  42198. parent.getChildMeshes().forEach(function (m) {
  42199. if (m.physicsImpostor) {
  42200. impostors.push(m.physicsImpostor);
  42201. m.physicsImpostor._init();
  42202. }
  42203. });
  42204. };
  42205. addToArray(impostor.object);
  42206. var checkWithEpsilon_1 = function (value) {
  42207. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  42208. };
  42209. impostors.forEach(function (i) {
  42210. //get the correct bounding box
  42211. var oldQuaternion = i.object.rotationQuaternion;
  42212. var rot = new OIMO.Euler().setFromQuaternion({
  42213. x: impostor.object.rotationQuaternion.x,
  42214. y: impostor.object.rotationQuaternion.y,
  42215. z: impostor.object.rotationQuaternion.z,
  42216. s: impostor.object.rotationQuaternion.w
  42217. });
  42218. var extendSize = i.getObjectExtendSize();
  42219. if (i === impostor) {
  42220. var center = impostor.getObjectCenter();
  42221. impostor.object.position.subtractToRef(center, _this._tmpPositionVector);
  42222. //Can also use Array.prototype.push.apply
  42223. bodyConfig.pos.push(center.x);
  42224. bodyConfig.pos.push(center.y);
  42225. bodyConfig.pos.push(center.z);
  42226. //tmp solution
  42227. bodyConfig.rot.push(rot.x / (OIMO.degtorad || OIMO.TO_RAD));
  42228. bodyConfig.rot.push(rot.y / (OIMO.degtorad || OIMO.TO_RAD));
  42229. bodyConfig.rot.push(rot.z / (OIMO.degtorad || OIMO.TO_RAD));
  42230. }
  42231. else {
  42232. bodyConfig.pos.push(i.object.position.x);
  42233. bodyConfig.pos.push(i.object.position.y);
  42234. bodyConfig.pos.push(i.object.position.z);
  42235. //tmp solution until https://github.com/lo-th/Oimo.js/pull/37 is merged
  42236. bodyConfig.rot.push(0);
  42237. bodyConfig.rot.push(0);
  42238. bodyConfig.rot.push(0);
  42239. }
  42240. // register mesh
  42241. switch (i.type) {
  42242. case BABYLON.PhysicsImpostor.ParticleImpostor:
  42243. BABYLON.Tools.Warn("No Particle support in Oimo.js. using SphereImpostor instead");
  42244. case BABYLON.PhysicsImpostor.SphereImpostor:
  42245. var radiusX = extendSize.x;
  42246. var radiusY = extendSize.y;
  42247. var radiusZ = extendSize.z;
  42248. var size = Math.max(checkWithEpsilon_1(radiusX), checkWithEpsilon_1(radiusY), checkWithEpsilon_1(radiusZ)) / 2;
  42249. bodyConfig.type.push('sphere');
  42250. //due to the way oimo works with compounds, add 3 times
  42251. bodyConfig.size.push(size);
  42252. bodyConfig.size.push(size);
  42253. bodyConfig.size.push(size);
  42254. break;
  42255. case BABYLON.PhysicsImpostor.CylinderImpostor:
  42256. var sizeX = checkWithEpsilon_1(extendSize.x) / 2;
  42257. var sizeY = checkWithEpsilon_1(extendSize.y);
  42258. bodyConfig.type.push('cylinder');
  42259. bodyConfig.size.push(sizeX);
  42260. bodyConfig.size.push(sizeY);
  42261. //due to the way oimo works with compounds, add one more value.
  42262. bodyConfig.size.push(sizeY);
  42263. break;
  42264. case BABYLON.PhysicsImpostor.PlaneImpostor:
  42265. case BABYLON.PhysicsImpostor.BoxImpostor:
  42266. default:
  42267. var sizeX = checkWithEpsilon_1(extendSize.x);
  42268. var sizeY = checkWithEpsilon_1(extendSize.y);
  42269. var sizeZ = checkWithEpsilon_1(extendSize.z);
  42270. bodyConfig.type.push('box');
  42271. bodyConfig.size.push(sizeX);
  42272. bodyConfig.size.push(sizeY);
  42273. bodyConfig.size.push(sizeZ);
  42274. break;
  42275. }
  42276. //actually not needed, but hey...
  42277. i.object.rotationQuaternion = oldQuaternion;
  42278. });
  42279. impostor.physicsBody = new OIMO.Body(bodyConfig).body; //this.world.add(bodyConfig);
  42280. }
  42281. else {
  42282. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  42283. }
  42284. impostor.setDeltaPosition(this._tmpPositionVector);
  42285. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  42286. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  42287. };
  42288. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  42289. //impostor.physicsBody.dispose();
  42290. //Same as : (older oimo versions)
  42291. this.world.removeRigidBody(impostor.physicsBody);
  42292. };
  42293. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  42294. var mainBody = impostorJoint.mainImpostor.physicsBody;
  42295. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  42296. if (!mainBody || !connectedBody) {
  42297. return;
  42298. }
  42299. var jointData = impostorJoint.joint.jointData;
  42300. var options = jointData.nativeParams || {};
  42301. var type;
  42302. var nativeJointData = {
  42303. body1: mainBody,
  42304. body2: connectedBody,
  42305. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  42306. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  42307. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  42308. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  42309. min: options.min,
  42310. max: options.max,
  42311. collision: options.collision || jointData.collision,
  42312. spring: options.spring,
  42313. //supporting older version of Oimo
  42314. world: this.world
  42315. };
  42316. switch (impostorJoint.joint.type) {
  42317. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  42318. type = "jointBall";
  42319. break;
  42320. case BABYLON.PhysicsJoint.SpringJoint:
  42321. BABYLON.Tools.Warn("Oimo.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  42322. var springData = jointData;
  42323. nativeJointData.min = springData.length || nativeJointData.min;
  42324. //Max should also be set, just make sure it is at least min
  42325. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  42326. case BABYLON.PhysicsJoint.DistanceJoint:
  42327. type = "jointDistance";
  42328. nativeJointData.max = jointData.maxDistance;
  42329. break;
  42330. case BABYLON.PhysicsJoint.PrismaticJoint:
  42331. type = "jointPrisme";
  42332. break;
  42333. case BABYLON.PhysicsJoint.SliderJoint:
  42334. type = "jointSlide";
  42335. break;
  42336. case BABYLON.PhysicsJoint.WheelJoint:
  42337. type = "jointWheel";
  42338. break;
  42339. case BABYLON.PhysicsJoint.HingeJoint:
  42340. default:
  42341. type = "jointHinge";
  42342. break;
  42343. }
  42344. nativeJointData.type = type;
  42345. impostorJoint.joint.physicsJoint = new OIMO.Link(nativeJointData).joint; //this.world.add(nativeJointData);
  42346. };
  42347. OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
  42348. //Bug in Oimo prevents us from disposing a joint in the playground
  42349. //joint.joint.physicsJoint.dispose();
  42350. //So we will bruteforce it!
  42351. try {
  42352. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  42353. }
  42354. catch (e) {
  42355. BABYLON.Tools.Warn(e);
  42356. }
  42357. };
  42358. OimoJSPlugin.prototype.isSupported = function () {
  42359. return OIMO !== undefined;
  42360. };
  42361. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  42362. if (!impostor.physicsBody.sleeping) {
  42363. //TODO check that
  42364. if (impostor.physicsBody.shapes.next) {
  42365. var parentShape = this._getLastShape(impostor.physicsBody);
  42366. impostor.object.position.x = parentShape.position.x * OIMO.WORLD_SCALE;
  42367. impostor.object.position.y = parentShape.position.y * OIMO.WORLD_SCALE;
  42368. impostor.object.position.z = parentShape.position.z * OIMO.WORLD_SCALE;
  42369. }
  42370. else {
  42371. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  42372. }
  42373. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  42374. impostor.object.rotationQuaternion.normalize();
  42375. }
  42376. };
  42377. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  42378. var body = impostor.physicsBody;
  42379. body.position.init(newPosition.x * OIMO.INV_SCALE, newPosition.y * OIMO.INV_SCALE, newPosition.z * OIMO.INV_SCALE);
  42380. body.orientation.init(newRotation.w, newRotation.x, newRotation.y, newRotation.z);
  42381. body.syncShapes();
  42382. body.awake();
  42383. };
  42384. OimoJSPlugin.prototype._getLastShape = function (body) {
  42385. var lastShape = body.shapes;
  42386. while (lastShape.next) {
  42387. lastShape = lastShape.next;
  42388. }
  42389. return lastShape;
  42390. };
  42391. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  42392. impostor.physicsBody.linearVelocity.init(velocity.x, velocity.y, velocity.z);
  42393. };
  42394. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  42395. impostor.physicsBody.angularVelocity.init(velocity.x, velocity.y, velocity.z);
  42396. };
  42397. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  42398. var v = impostor.physicsBody.linearVelocity;
  42399. if (!v)
  42400. return null;
  42401. return new BABYLON.Vector3(v.x, v.y, v.z);
  42402. };
  42403. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  42404. var v = impostor.physicsBody.angularVelocity;
  42405. if (!v)
  42406. return null;
  42407. return new BABYLON.Vector3(v.x, v.y, v.z);
  42408. };
  42409. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  42410. var staticBody = mass === 0;
  42411. //this will actually set the body's density and not its mass.
  42412. //But this is how oimo treats the mass variable.
  42413. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  42414. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  42415. };
  42416. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  42417. impostor.physicsBody.sleep();
  42418. };
  42419. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  42420. impostor.physicsBody.awake();
  42421. };
  42422. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  42423. joint.physicsJoint.limitMotor.upperLimit = maxDistance;
  42424. if (minDistance !== void 0) {
  42425. joint.physicsJoint.limitMotor.lowerLimit = minDistance;
  42426. }
  42427. };
  42428. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  42429. //TODO separate rotational and transational motors.
  42430. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  42431. if (motor) {
  42432. motor.setMotor(speed, maxForce);
  42433. }
  42434. };
  42435. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  42436. //TODO separate rotational and transational motors.
  42437. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  42438. if (motor) {
  42439. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  42440. }
  42441. };
  42442. OimoJSPlugin.prototype.dispose = function () {
  42443. this.world.clear();
  42444. };
  42445. return OimoJSPlugin;
  42446. }());
  42447. BABYLON.OimoJSPlugin = OimoJSPlugin;
  42448. })(BABYLON || (BABYLON = {}));
  42449. //# sourceMappingURL=babylon.oimoJSPlugin.js.map
  42450. var BABYLON;
  42451. (function (BABYLON) {
  42452. var DisplayPassPostProcess = (function (_super) {
  42453. __extends(DisplayPassPostProcess, _super);
  42454. function DisplayPassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  42455. return _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], options, camera, samplingMode, engine, reusable) || this;
  42456. }
  42457. return DisplayPassPostProcess;
  42458. }(BABYLON.PostProcess));
  42459. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  42460. })(BABYLON || (BABYLON = {}));
  42461. //# sourceMappingURL=babylon.displayPassPostProcess.js.map
  42462. var BABYLON;
  42463. (function (BABYLON) {
  42464. var SimplificationSettings = (function () {
  42465. function SimplificationSettings(quality, distance, optimizeMesh) {
  42466. this.quality = quality;
  42467. this.distance = distance;
  42468. this.optimizeMesh = optimizeMesh;
  42469. }
  42470. return SimplificationSettings;
  42471. }());
  42472. BABYLON.SimplificationSettings = SimplificationSettings;
  42473. var SimplificationQueue = (function () {
  42474. function SimplificationQueue() {
  42475. this.running = false;
  42476. this._simplificationArray = [];
  42477. }
  42478. SimplificationQueue.prototype.addTask = function (task) {
  42479. this._simplificationArray.push(task);
  42480. };
  42481. SimplificationQueue.prototype.executeNext = function () {
  42482. var task = this._simplificationArray.pop();
  42483. if (task) {
  42484. this.running = true;
  42485. this.runSimplification(task);
  42486. }
  42487. else {
  42488. this.running = false;
  42489. }
  42490. };
  42491. SimplificationQueue.prototype.runSimplification = function (task) {
  42492. var _this = this;
  42493. if (task.parallelProcessing) {
  42494. //parallel simplifier
  42495. task.settings.forEach(function (setting) {
  42496. var simplifier = _this.getSimplifier(task);
  42497. simplifier.simplify(setting, function (newMesh) {
  42498. task.mesh.addLODLevel(setting.distance, newMesh);
  42499. newMesh.isVisible = true;
  42500. //check if it is the last
  42501. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  42502. //all done, run the success callback.
  42503. task.successCallback();
  42504. }
  42505. _this.executeNext();
  42506. });
  42507. });
  42508. }
  42509. else {
  42510. //single simplifier.
  42511. var simplifier = this.getSimplifier(task);
  42512. var runDecimation = function (setting, callback) {
  42513. simplifier.simplify(setting, function (newMesh) {
  42514. task.mesh.addLODLevel(setting.distance, newMesh);
  42515. newMesh.isVisible = true;
  42516. //run the next quality level
  42517. callback();
  42518. });
  42519. };
  42520. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  42521. runDecimation(task.settings[loop.index], function () {
  42522. loop.executeNext();
  42523. });
  42524. }, function () {
  42525. //execution ended, run the success callback.
  42526. if (task.successCallback) {
  42527. task.successCallback();
  42528. }
  42529. _this.executeNext();
  42530. });
  42531. }
  42532. };
  42533. SimplificationQueue.prototype.getSimplifier = function (task) {
  42534. switch (task.simplificationType) {
  42535. case SimplificationType.QUADRATIC:
  42536. default:
  42537. return new QuadraticErrorSimplification(task.mesh);
  42538. }
  42539. };
  42540. return SimplificationQueue;
  42541. }());
  42542. BABYLON.SimplificationQueue = SimplificationQueue;
  42543. /**
  42544. * The implemented types of simplification.
  42545. * At the moment only Quadratic Error Decimation is implemented.
  42546. */
  42547. var SimplificationType;
  42548. (function (SimplificationType) {
  42549. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  42550. })(SimplificationType = BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  42551. var DecimationTriangle = (function () {
  42552. function DecimationTriangle(vertices) {
  42553. this.vertices = vertices;
  42554. this.error = new Array(4);
  42555. this.deleted = false;
  42556. this.isDirty = false;
  42557. this.deletePending = false;
  42558. this.borderFactor = 0;
  42559. }
  42560. return DecimationTriangle;
  42561. }());
  42562. BABYLON.DecimationTriangle = DecimationTriangle;
  42563. var DecimationVertex = (function () {
  42564. function DecimationVertex(position, id) {
  42565. this.position = position;
  42566. this.id = id;
  42567. this.isBorder = true;
  42568. this.q = new QuadraticMatrix();
  42569. this.triangleCount = 0;
  42570. this.triangleStart = 0;
  42571. this.originalOffsets = [];
  42572. }
  42573. DecimationVertex.prototype.updatePosition = function (newPosition) {
  42574. this.position.copyFrom(newPosition);
  42575. };
  42576. return DecimationVertex;
  42577. }());
  42578. BABYLON.DecimationVertex = DecimationVertex;
  42579. var QuadraticMatrix = (function () {
  42580. function QuadraticMatrix(data) {
  42581. this.data = new Array(10);
  42582. for (var i = 0; i < 10; ++i) {
  42583. if (data && data[i]) {
  42584. this.data[i] = data[i];
  42585. }
  42586. else {
  42587. this.data[i] = 0;
  42588. }
  42589. }
  42590. }
  42591. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  42592. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  42593. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  42594. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  42595. return det;
  42596. };
  42597. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  42598. for (var i = 0; i < 10; ++i) {
  42599. this.data[i] += matrix.data[i];
  42600. }
  42601. };
  42602. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  42603. for (var i = 0; i < 10; ++i) {
  42604. this.data[i] += data[i];
  42605. }
  42606. };
  42607. QuadraticMatrix.prototype.add = function (matrix) {
  42608. var m = new QuadraticMatrix();
  42609. for (var i = 0; i < 10; ++i) {
  42610. m.data[i] = this.data[i] + matrix.data[i];
  42611. }
  42612. return m;
  42613. };
  42614. QuadraticMatrix.FromData = function (a, b, c, d) {
  42615. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  42616. };
  42617. //returning an array to avoid garbage collection
  42618. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  42619. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  42620. };
  42621. return QuadraticMatrix;
  42622. }());
  42623. BABYLON.QuadraticMatrix = QuadraticMatrix;
  42624. var Reference = (function () {
  42625. function Reference(vertexId, triangleId) {
  42626. this.vertexId = vertexId;
  42627. this.triangleId = triangleId;
  42628. }
  42629. return Reference;
  42630. }());
  42631. BABYLON.Reference = Reference;
  42632. /**
  42633. * An implementation of the Quadratic Error simplification algorithm.
  42634. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  42635. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  42636. * @author RaananW
  42637. */
  42638. var QuadraticErrorSimplification = (function () {
  42639. function QuadraticErrorSimplification(_mesh) {
  42640. this._mesh = _mesh;
  42641. this.initialized = false;
  42642. this.syncIterations = 5000;
  42643. this.aggressiveness = 7;
  42644. this.decimationIterations = 100;
  42645. this.boundingBoxEpsilon = BABYLON.Epsilon;
  42646. }
  42647. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  42648. var _this = this;
  42649. this.initDecimatedMesh();
  42650. //iterating through the submeshes array, one after the other.
  42651. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  42652. _this.initWithMesh(loop.index, function () {
  42653. _this.runDecimation(settings, loop.index, function () {
  42654. loop.executeNext();
  42655. });
  42656. }, settings.optimizeMesh);
  42657. }, function () {
  42658. setTimeout(function () {
  42659. successCallback(_this._reconstructedMesh);
  42660. }, 0);
  42661. });
  42662. };
  42663. QuadraticErrorSimplification.prototype.isTriangleOnBoundingBox = function (triangle) {
  42664. var _this = this;
  42665. var gCount = 0;
  42666. triangle.vertices.forEach(function (vertex) {
  42667. var count = 0;
  42668. var vPos = vertex.position;
  42669. var bbox = _this._mesh.getBoundingInfo().boundingBox;
  42670. if (bbox.maximum.x - vPos.x < _this.boundingBoxEpsilon || vPos.x - bbox.minimum.x > _this.boundingBoxEpsilon)
  42671. ++count;
  42672. if (bbox.maximum.y === vPos.y || vPos.y === bbox.minimum.y)
  42673. ++count;
  42674. if (bbox.maximum.z === vPos.z || vPos.z === bbox.minimum.z)
  42675. ++count;
  42676. if (count > 1) {
  42677. ++gCount;
  42678. }
  42679. ;
  42680. });
  42681. if (gCount > 1) {
  42682. console.log(triangle, gCount);
  42683. }
  42684. return gCount > 1;
  42685. };
  42686. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  42687. var _this = this;
  42688. var targetCount = ~~(this.triangles.length * settings.quality);
  42689. var deletedTriangles = 0;
  42690. var triangleCount = this.triangles.length;
  42691. var iterationFunction = function (iteration, callback) {
  42692. setTimeout(function () {
  42693. if (iteration % 5 === 0) {
  42694. _this.updateMesh(iteration === 0);
  42695. }
  42696. for (var i = 0; i < _this.triangles.length; ++i) {
  42697. _this.triangles[i].isDirty = false;
  42698. }
  42699. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  42700. var trianglesIterator = function (i) {
  42701. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  42702. var t = _this.triangles[tIdx];
  42703. if (!t)
  42704. return;
  42705. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  42706. return;
  42707. }
  42708. for (var j = 0; j < 3; ++j) {
  42709. if (t.error[j] < threshold) {
  42710. var deleted0 = [];
  42711. var deleted1 = [];
  42712. var v0 = t.vertices[j];
  42713. var v1 = t.vertices[(j + 1) % 3];
  42714. if (v0.isBorder || v1.isBorder)
  42715. continue;
  42716. var p = BABYLON.Vector3.Zero();
  42717. var n = BABYLON.Vector3.Zero();
  42718. var uv = BABYLON.Vector2.Zero();
  42719. var color = new BABYLON.Color4(0, 0, 0, 1);
  42720. _this.calculateError(v0, v1, p, n, uv, color);
  42721. var delTr = [];
  42722. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  42723. continue;
  42724. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  42725. continue;
  42726. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  42727. continue;
  42728. var uniqueArray = [];
  42729. delTr.forEach(function (deletedT) {
  42730. if (uniqueArray.indexOf(deletedT) === -1) {
  42731. deletedT.deletePending = true;
  42732. uniqueArray.push(deletedT);
  42733. }
  42734. });
  42735. if (uniqueArray.length % 2 !== 0) {
  42736. continue;
  42737. }
  42738. v0.q = v1.q.add(v0.q);
  42739. v0.updatePosition(p);
  42740. var tStart = _this.references.length;
  42741. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  42742. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  42743. var tCount = _this.references.length - tStart;
  42744. if (tCount <= v0.triangleCount) {
  42745. if (tCount) {
  42746. for (var c = 0; c < tCount; c++) {
  42747. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  42748. }
  42749. }
  42750. }
  42751. else {
  42752. v0.triangleStart = tStart;
  42753. }
  42754. v0.triangleCount = tCount;
  42755. break;
  42756. }
  42757. }
  42758. };
  42759. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  42760. }, 0);
  42761. };
  42762. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  42763. if (triangleCount - deletedTriangles <= targetCount)
  42764. loop.breakLoop();
  42765. else {
  42766. iterationFunction(loop.index, function () {
  42767. loop.executeNext();
  42768. });
  42769. }
  42770. }, function () {
  42771. setTimeout(function () {
  42772. //reconstruct this part of the mesh
  42773. _this.reconstructMesh(submeshIndex);
  42774. successCallback();
  42775. }, 0);
  42776. });
  42777. };
  42778. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  42779. var _this = this;
  42780. this.vertices = [];
  42781. this.triangles = [];
  42782. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  42783. var indices = this._mesh.getIndices();
  42784. var submesh = this._mesh.subMeshes[submeshIndex];
  42785. var findInVertices = function (positionToSearch) {
  42786. if (optimizeMesh) {
  42787. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  42788. if (_this.vertices[ii].position.equals(positionToSearch)) {
  42789. return _this.vertices[ii];
  42790. }
  42791. }
  42792. }
  42793. return null;
  42794. };
  42795. var vertexReferences = [];
  42796. var vertexInit = function (i) {
  42797. var offset = i + submesh.verticesStart;
  42798. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  42799. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  42800. vertex.originalOffsets.push(offset);
  42801. if (vertex.id === _this.vertices.length) {
  42802. _this.vertices.push(vertex);
  42803. }
  42804. vertexReferences.push(vertex.id);
  42805. };
  42806. //var totalVertices = mesh.getTotalVertices();
  42807. var totalVertices = submesh.verticesCount;
  42808. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  42809. var indicesInit = function (i) {
  42810. var offset = (submesh.indexStart / 3) + i;
  42811. var pos = (offset * 3);
  42812. var i0 = indices[pos + 0];
  42813. var i1 = indices[pos + 1];
  42814. var i2 = indices[pos + 2];
  42815. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  42816. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  42817. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  42818. var triangle = new DecimationTriangle([v0, v1, v2]);
  42819. triangle.originalOffset = pos;
  42820. _this.triangles.push(triangle);
  42821. };
  42822. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  42823. _this.init(callback);
  42824. });
  42825. });
  42826. };
  42827. QuadraticErrorSimplification.prototype.init = function (callback) {
  42828. var _this = this;
  42829. var triangleInit1 = function (i) {
  42830. var t = _this.triangles[i];
  42831. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  42832. for (var j = 0; j < 3; j++) {
  42833. 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))));
  42834. }
  42835. };
  42836. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  42837. var triangleInit2 = function (i) {
  42838. var t = _this.triangles[i];
  42839. for (var j = 0; j < 3; ++j) {
  42840. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  42841. }
  42842. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  42843. };
  42844. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  42845. _this.initialized = true;
  42846. callback();
  42847. });
  42848. });
  42849. };
  42850. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  42851. var newTriangles = [];
  42852. var i;
  42853. for (i = 0; i < this.vertices.length; ++i) {
  42854. this.vertices[i].triangleCount = 0;
  42855. }
  42856. var t;
  42857. var j;
  42858. for (i = 0; i < this.triangles.length; ++i) {
  42859. if (!this.triangles[i].deleted) {
  42860. t = this.triangles[i];
  42861. for (j = 0; j < 3; ++j) {
  42862. t.vertices[j].triangleCount = 1;
  42863. }
  42864. newTriangles.push(t);
  42865. }
  42866. }
  42867. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  42868. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  42869. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  42870. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  42871. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  42872. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  42873. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  42874. var vertexCount = 0;
  42875. for (i = 0; i < this.vertices.length; ++i) {
  42876. var vertex = this.vertices[i];
  42877. vertex.id = vertexCount;
  42878. if (vertex.triangleCount) {
  42879. vertex.originalOffsets.forEach(function (originalOffset) {
  42880. newPositionData.push(vertex.position.x);
  42881. newPositionData.push(vertex.position.y);
  42882. newPositionData.push(vertex.position.z);
  42883. newNormalData.push(normalData[originalOffset * 3]);
  42884. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  42885. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  42886. if (uvs && uvs.length) {
  42887. newUVsData.push(uvs[(originalOffset * 2)]);
  42888. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  42889. }
  42890. else if (colorsData && colorsData.length) {
  42891. newColorsData.push(colorsData[(originalOffset * 4)]);
  42892. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  42893. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  42894. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  42895. }
  42896. ++vertexCount;
  42897. });
  42898. }
  42899. }
  42900. var startingIndex = this._reconstructedMesh.getTotalIndices();
  42901. var startingVertex = this._reconstructedMesh.getTotalVertices();
  42902. var submeshesArray = this._reconstructedMesh.subMeshes;
  42903. this._reconstructedMesh.subMeshes = [];
  42904. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  42905. var originalIndices = this._mesh.getIndices();
  42906. for (i = 0; i < newTriangles.length; ++i) {
  42907. t = newTriangles[i]; //now get the new referencing point for each vertex
  42908. [0, 1, 2].forEach(function (idx) {
  42909. var id = originalIndices[t.originalOffset + idx];
  42910. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  42911. if (offset < 0)
  42912. offset = 0;
  42913. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  42914. });
  42915. }
  42916. //overwriting the old vertex buffers and indices.
  42917. this._reconstructedMesh.setIndices(newIndicesArray);
  42918. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  42919. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  42920. if (newUVsData.length > 0)
  42921. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  42922. if (newColorsData.length > 0)
  42923. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  42924. //create submesh
  42925. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  42926. if (submeshIndex > 0) {
  42927. this._reconstructedMesh.subMeshes = [];
  42928. submeshesArray.forEach(function (submesh) {
  42929. new BABYLON.SubMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  42930. });
  42931. var newSubmesh = new BABYLON.SubMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  42932. }
  42933. };
  42934. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  42935. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  42936. this._reconstructedMesh.material = this._mesh.material;
  42937. this._reconstructedMesh.parent = this._mesh.parent;
  42938. this._reconstructedMesh.isVisible = false;
  42939. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  42940. };
  42941. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  42942. for (var i = 0; i < vertex1.triangleCount; ++i) {
  42943. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  42944. if (t.deleted)
  42945. continue;
  42946. var s = this.references[vertex1.triangleStart + i].vertexId;
  42947. var v1 = t.vertices[(s + 1) % 3];
  42948. var v2 = t.vertices[(s + 2) % 3];
  42949. if ((v1 === vertex2 || v2 === vertex2) /* && !this.isTriangleOnBoundingBox(t)*/) {
  42950. deletedArray[i] = true;
  42951. delTr.push(t);
  42952. continue;
  42953. }
  42954. var d1 = v1.position.subtract(point);
  42955. d1 = d1.normalize();
  42956. var d2 = v2.position.subtract(point);
  42957. d2 = d2.normalize();
  42958. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  42959. return true;
  42960. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  42961. deletedArray[i] = false;
  42962. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  42963. return true;
  42964. }
  42965. return false;
  42966. };
  42967. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  42968. var newDeleted = deletedTriangles;
  42969. for (var i = 0; i < vertex.triangleCount; ++i) {
  42970. var ref = this.references[vertex.triangleStart + i];
  42971. var t = this.triangles[ref.triangleId];
  42972. if (t.deleted)
  42973. continue;
  42974. if (deletedArray[i] && t.deletePending) {
  42975. t.deleted = true;
  42976. newDeleted++;
  42977. continue;
  42978. }
  42979. t.vertices[ref.vertexId] = origVertex;
  42980. t.isDirty = true;
  42981. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  42982. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  42983. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  42984. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  42985. this.references.push(ref);
  42986. }
  42987. return newDeleted;
  42988. };
  42989. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  42990. for (var i = 0; i < this.vertices.length; ++i) {
  42991. var vCount = [];
  42992. var vId = [];
  42993. var v = this.vertices[i];
  42994. var j;
  42995. for (j = 0; j < v.triangleCount; ++j) {
  42996. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  42997. for (var ii = 0; ii < 3; ii++) {
  42998. var ofs = 0;
  42999. var vv = triangle.vertices[ii];
  43000. while (ofs < vCount.length) {
  43001. if (vId[ofs] === vv.id)
  43002. break;
  43003. ++ofs;
  43004. }
  43005. if (ofs === vCount.length) {
  43006. vCount.push(1);
  43007. vId.push(vv.id);
  43008. }
  43009. else {
  43010. vCount[ofs]++;
  43011. }
  43012. }
  43013. }
  43014. for (j = 0; j < vCount.length; ++j) {
  43015. if (vCount[j] === 1) {
  43016. this.vertices[vId[j]].isBorder = true;
  43017. }
  43018. else {
  43019. this.vertices[vId[j]].isBorder = false;
  43020. }
  43021. }
  43022. }
  43023. };
  43024. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  43025. if (identifyBorders === void 0) { identifyBorders = false; }
  43026. var i;
  43027. if (!identifyBorders) {
  43028. var newTrianglesVector = [];
  43029. for (i = 0; i < this.triangles.length; ++i) {
  43030. if (!this.triangles[i].deleted) {
  43031. newTrianglesVector.push(this.triangles[i]);
  43032. }
  43033. }
  43034. this.triangles = newTrianglesVector;
  43035. }
  43036. for (i = 0; i < this.vertices.length; ++i) {
  43037. this.vertices[i].triangleCount = 0;
  43038. this.vertices[i].triangleStart = 0;
  43039. }
  43040. var t;
  43041. var j;
  43042. var v;
  43043. for (i = 0; i < this.triangles.length; ++i) {
  43044. t = this.triangles[i];
  43045. for (j = 0; j < 3; ++j) {
  43046. v = t.vertices[j];
  43047. v.triangleCount++;
  43048. }
  43049. }
  43050. var tStart = 0;
  43051. for (i = 0; i < this.vertices.length; ++i) {
  43052. this.vertices[i].triangleStart = tStart;
  43053. tStart += this.vertices[i].triangleCount;
  43054. this.vertices[i].triangleCount = 0;
  43055. }
  43056. var newReferences = new Array(this.triangles.length * 3);
  43057. for (i = 0; i < this.triangles.length; ++i) {
  43058. t = this.triangles[i];
  43059. for (j = 0; j < 3; ++j) {
  43060. v = t.vertices[j];
  43061. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  43062. v.triangleCount++;
  43063. }
  43064. }
  43065. this.references = newReferences;
  43066. if (identifyBorders) {
  43067. this.identifyBorder();
  43068. }
  43069. };
  43070. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  43071. var x = point.x;
  43072. var y = point.y;
  43073. var z = point.z;
  43074. 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
  43075. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  43076. };
  43077. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  43078. var q = vertex1.q.add(vertex2.q);
  43079. var border = vertex1.isBorder && vertex2.isBorder;
  43080. var error = 0;
  43081. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  43082. if (qDet !== 0 && !border) {
  43083. if (!pointResult) {
  43084. pointResult = BABYLON.Vector3.Zero();
  43085. }
  43086. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  43087. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  43088. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  43089. error = this.vertexError(q, pointResult);
  43090. }
  43091. else {
  43092. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  43093. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  43094. var error1 = this.vertexError(q, vertex1.position);
  43095. var error2 = this.vertexError(q, vertex2.position);
  43096. var error3 = this.vertexError(q, p3);
  43097. error = Math.min(error1, error2, error3);
  43098. if (error === error1) {
  43099. if (pointResult) {
  43100. pointResult.copyFrom(vertex1.position);
  43101. }
  43102. }
  43103. else if (error === error2) {
  43104. if (pointResult) {
  43105. pointResult.copyFrom(vertex2.position);
  43106. }
  43107. }
  43108. else {
  43109. if (pointResult) {
  43110. pointResult.copyFrom(p3);
  43111. }
  43112. }
  43113. }
  43114. return error;
  43115. };
  43116. return QuadraticErrorSimplification;
  43117. }());
  43118. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  43119. })(BABYLON || (BABYLON = {}));
  43120. //# sourceMappingURL=babylon.meshSimplification.js.map
  43121. var BABYLON;
  43122. (function (BABYLON) {
  43123. var serializedGeometries = [];
  43124. var serializeGeometry = function (geometry, serializationGeometries) {
  43125. if (serializedGeometries[geometry.id]) {
  43126. return;
  43127. }
  43128. if (geometry.doNotSerialize) {
  43129. return;
  43130. }
  43131. if (geometry instanceof BABYLON.Geometry.Primitives.Box) {
  43132. serializationGeometries.boxes.push(geometry.serialize());
  43133. }
  43134. else if (geometry instanceof BABYLON.Geometry.Primitives.Sphere) {
  43135. serializationGeometries.spheres.push(geometry.serialize());
  43136. }
  43137. else if (geometry instanceof BABYLON.Geometry.Primitives.Cylinder) {
  43138. serializationGeometries.cylinders.push(geometry.serialize());
  43139. }
  43140. else if (geometry instanceof BABYLON.Geometry.Primitives.Torus) {
  43141. serializationGeometries.toruses.push(geometry.serialize());
  43142. }
  43143. else if (geometry instanceof BABYLON.Geometry.Primitives.Ground) {
  43144. serializationGeometries.grounds.push(geometry.serialize());
  43145. }
  43146. else if (geometry instanceof BABYLON.Geometry.Primitives.Plane) {
  43147. serializationGeometries.planes.push(geometry.serialize());
  43148. }
  43149. else if (geometry instanceof BABYLON.Geometry.Primitives.TorusKnot) {
  43150. serializationGeometries.torusKnots.push(geometry.serialize());
  43151. }
  43152. else if (geometry instanceof BABYLON.Geometry.Primitives._Primitive) {
  43153. throw new Error("Unknown primitive type");
  43154. }
  43155. else {
  43156. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  43157. }
  43158. serializedGeometries[geometry.id] = true;
  43159. };
  43160. var serializeMesh = function (mesh, serializationScene) {
  43161. var serializationObject = {};
  43162. serializationObject.name = mesh.name;
  43163. serializationObject.id = mesh.id;
  43164. if (BABYLON.Tags.HasTags(mesh)) {
  43165. serializationObject.tags = BABYLON.Tags.GetTags(mesh);
  43166. }
  43167. serializationObject.position = mesh.position.asArray();
  43168. if (mesh.rotationQuaternion) {
  43169. serializationObject.rotationQuaternion = mesh.rotationQuaternion.asArray();
  43170. }
  43171. else if (mesh.rotation) {
  43172. serializationObject.rotation = mesh.rotation.asArray();
  43173. }
  43174. serializationObject.scaling = mesh.scaling.asArray();
  43175. serializationObject.localMatrix = mesh.getPivotMatrix().asArray();
  43176. serializationObject.isEnabled = mesh.isEnabled();
  43177. serializationObject.isVisible = mesh.isVisible;
  43178. serializationObject.infiniteDistance = mesh.infiniteDistance;
  43179. serializationObject.pickable = mesh.isPickable;
  43180. serializationObject.receiveShadows = mesh.receiveShadows;
  43181. serializationObject.billboardMode = mesh.billboardMode;
  43182. serializationObject.visibility = mesh.visibility;
  43183. serializationObject.checkCollisions = mesh.checkCollisions;
  43184. serializationObject.isBlocker = mesh.isBlocker;
  43185. // Parent
  43186. if (mesh.parent) {
  43187. serializationObject.parentId = mesh.parent.id;
  43188. }
  43189. // Geometry
  43190. var geometry = mesh._geometry;
  43191. if (geometry) {
  43192. var geometryId = geometry.id;
  43193. serializationObject.geometryId = geometryId;
  43194. if (!mesh.getScene().getGeometryByID(geometryId)) {
  43195. // 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
  43196. serializeGeometry(geometry, serializationScene.geometries);
  43197. }
  43198. // SubMeshes
  43199. serializationObject.subMeshes = [];
  43200. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  43201. var subMesh = mesh.subMeshes[subIndex];
  43202. serializationObject.subMeshes.push({
  43203. materialIndex: subMesh.materialIndex,
  43204. verticesStart: subMesh.verticesStart,
  43205. verticesCount: subMesh.verticesCount,
  43206. indexStart: subMesh.indexStart,
  43207. indexCount: subMesh.indexCount
  43208. });
  43209. }
  43210. }
  43211. // Material
  43212. if (mesh.material) {
  43213. serializationObject.materialId = mesh.material.id;
  43214. }
  43215. else {
  43216. mesh.material = null;
  43217. }
  43218. // Skeleton
  43219. if (mesh.skeleton) {
  43220. serializationObject.skeletonId = mesh.skeleton.id;
  43221. }
  43222. // Physics
  43223. //TODO implement correct serialization for physics impostors.
  43224. if (mesh.getPhysicsImpostor()) {
  43225. serializationObject.physicsMass = mesh.getPhysicsMass();
  43226. serializationObject.physicsFriction = mesh.getPhysicsFriction();
  43227. serializationObject.physicsRestitution = mesh.getPhysicsRestitution();
  43228. serializationObject.physicsImpostor = mesh.getPhysicsImpostor().type;
  43229. }
  43230. // Metadata
  43231. if (mesh.metadata) {
  43232. serializationObject.metadata = mesh.metadata;
  43233. }
  43234. // Instances
  43235. serializationObject.instances = [];
  43236. for (var index = 0; index < mesh.instances.length; index++) {
  43237. var instance = mesh.instances[index];
  43238. var serializationInstance = {
  43239. name: instance.name,
  43240. position: instance.position.asArray(),
  43241. scaling: instance.scaling.asArray()
  43242. };
  43243. if (instance.rotationQuaternion) {
  43244. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  43245. }
  43246. else if (instance.rotation) {
  43247. serializationInstance.rotation = instance.rotation.asArray();
  43248. }
  43249. serializationObject.instances.push(serializationInstance);
  43250. // Animations
  43251. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  43252. serializationInstance.ranges = instance.serializeAnimationRanges();
  43253. }
  43254. // Animations
  43255. BABYLON.Animation.AppendSerializedAnimations(mesh, serializationObject);
  43256. serializationObject.ranges = mesh.serializeAnimationRanges();
  43257. // Layer mask
  43258. serializationObject.layerMask = mesh.layerMask;
  43259. // Alpha
  43260. serializationObject.alphaIndex = mesh.alphaIndex;
  43261. serializationObject.hasVertexAlpha = mesh.hasVertexAlpha;
  43262. // Overlay
  43263. serializationObject.overlayAlpha = mesh.overlayAlpha;
  43264. serializationObject.overlayColor = mesh.overlayColor.asArray();
  43265. serializationObject.renderOverlay = mesh.renderOverlay;
  43266. // Fog
  43267. serializationObject.applyFog = mesh.applyFog;
  43268. // Action Manager
  43269. if (mesh.actionManager) {
  43270. serializationObject.actions = mesh.actionManager.serialize(mesh.name);
  43271. }
  43272. return serializationObject;
  43273. };
  43274. var finalizeSingleMesh = function (mesh, serializationObject) {
  43275. //only works if the mesh is already loaded
  43276. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  43277. //serialize material
  43278. if (mesh.material) {
  43279. if (mesh.material instanceof BABYLON.StandardMaterial) {
  43280. serializationObject.materials = serializationObject.materials || [];
  43281. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  43282. serializationObject.materials.push(mesh.material.serialize());
  43283. }
  43284. }
  43285. else if (mesh.material instanceof BABYLON.MultiMaterial) {
  43286. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  43287. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  43288. serializationObject.multiMaterials.push(mesh.material.serialize());
  43289. }
  43290. }
  43291. }
  43292. //serialize geometry
  43293. var geometry = mesh._geometry;
  43294. if (geometry) {
  43295. if (!serializationObject.geometries) {
  43296. serializationObject.geometries = {};
  43297. serializationObject.geometries.boxes = [];
  43298. serializationObject.geometries.spheres = [];
  43299. serializationObject.geometries.cylinders = [];
  43300. serializationObject.geometries.toruses = [];
  43301. serializationObject.geometries.grounds = [];
  43302. serializationObject.geometries.planes = [];
  43303. serializationObject.geometries.torusKnots = [];
  43304. serializationObject.geometries.vertexData = [];
  43305. }
  43306. serializeGeometry(geometry, serializationObject.geometries);
  43307. }
  43308. // Skeletons
  43309. if (mesh.skeleton) {
  43310. serializationObject.skeletons = serializationObject.skeletons || [];
  43311. serializationObject.skeletons.push(mesh.skeleton.serialize());
  43312. }
  43313. //serialize the actual mesh
  43314. serializationObject.meshes = serializationObject.meshes || [];
  43315. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  43316. }
  43317. };
  43318. var SceneSerializer = (function () {
  43319. function SceneSerializer() {
  43320. }
  43321. SceneSerializer.ClearCache = function () {
  43322. serializedGeometries = [];
  43323. };
  43324. SceneSerializer.Serialize = function (scene) {
  43325. var serializationObject = {};
  43326. // Scene
  43327. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  43328. serializationObject.autoClear = scene.autoClear;
  43329. serializationObject.clearColor = scene.clearColor.asArray();
  43330. serializationObject.ambientColor = scene.ambientColor.asArray();
  43331. serializationObject.gravity = scene.gravity.asArray();
  43332. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  43333. serializationObject.workerCollisions = scene.workerCollisions;
  43334. // Fog
  43335. if (scene.fogMode && scene.fogMode !== 0) {
  43336. serializationObject.fogMode = scene.fogMode;
  43337. serializationObject.fogColor = scene.fogColor.asArray();
  43338. serializationObject.fogStart = scene.fogStart;
  43339. serializationObject.fogEnd = scene.fogEnd;
  43340. serializationObject.fogDensity = scene.fogDensity;
  43341. }
  43342. //Physics
  43343. if (scene.isPhysicsEnabled()) {
  43344. serializationObject.physicsEnabled = true;
  43345. serializationObject.physicsGravity = scene.getPhysicsEngine().gravity.asArray();
  43346. serializationObject.physicsEngine = scene.getPhysicsEngine().getPhysicsPluginName();
  43347. }
  43348. // Metadata
  43349. if (scene.metadata) {
  43350. serializationObject.metadata = scene.metadata;
  43351. }
  43352. // Lights
  43353. serializationObject.lights = [];
  43354. var index;
  43355. var light;
  43356. for (index = 0; index < scene.lights.length; index++) {
  43357. light = scene.lights[index];
  43358. if (!light.doNotSerialize) {
  43359. serializationObject.lights.push(light.serialize());
  43360. }
  43361. }
  43362. // Cameras
  43363. serializationObject.cameras = [];
  43364. for (index = 0; index < scene.cameras.length; index++) {
  43365. var camera = scene.cameras[index];
  43366. if (!camera.doNotSerialize) {
  43367. serializationObject.cameras.push(camera.serialize());
  43368. }
  43369. }
  43370. if (scene.activeCamera) {
  43371. serializationObject.activeCameraID = scene.activeCamera.id;
  43372. }
  43373. // Animations
  43374. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  43375. // Materials
  43376. serializationObject.materials = [];
  43377. serializationObject.multiMaterials = [];
  43378. var material;
  43379. for (index = 0; index < scene.materials.length; index++) {
  43380. material = scene.materials[index];
  43381. if (!material.doNotSerialize) {
  43382. serializationObject.materials.push(material.serialize());
  43383. }
  43384. }
  43385. // MultiMaterials
  43386. serializationObject.multiMaterials = [];
  43387. for (index = 0; index < scene.multiMaterials.length; index++) {
  43388. var multiMaterial = scene.multiMaterials[index];
  43389. serializationObject.multiMaterials.push(multiMaterial.serialize());
  43390. }
  43391. // Skeletons
  43392. serializationObject.skeletons = [];
  43393. for (index = 0; index < scene.skeletons.length; index++) {
  43394. serializationObject.skeletons.push(scene.skeletons[index].serialize());
  43395. }
  43396. // Geometries
  43397. serializationObject.geometries = {};
  43398. serializationObject.geometries.boxes = [];
  43399. serializationObject.geometries.spheres = [];
  43400. serializationObject.geometries.cylinders = [];
  43401. serializationObject.geometries.toruses = [];
  43402. serializationObject.geometries.grounds = [];
  43403. serializationObject.geometries.planes = [];
  43404. serializationObject.geometries.torusKnots = [];
  43405. serializationObject.geometries.vertexData = [];
  43406. serializedGeometries = [];
  43407. var geometries = scene.getGeometries();
  43408. for (index = 0; index < geometries.length; index++) {
  43409. var geometry = geometries[index];
  43410. if (geometry.isReady()) {
  43411. serializeGeometry(geometry, serializationObject.geometries);
  43412. }
  43413. }
  43414. // Meshes
  43415. serializationObject.meshes = [];
  43416. for (index = 0; index < scene.meshes.length; index++) {
  43417. var abstractMesh = scene.meshes[index];
  43418. if (abstractMesh instanceof BABYLON.Mesh) {
  43419. var mesh = abstractMesh;
  43420. if (!mesh.doNotSerialize) {
  43421. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  43422. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  43423. }
  43424. }
  43425. }
  43426. }
  43427. // Particles Systems
  43428. serializationObject.particleSystems = [];
  43429. for (index = 0; index < scene.particleSystems.length; index++) {
  43430. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  43431. }
  43432. // Lens flares
  43433. serializationObject.lensFlareSystems = [];
  43434. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  43435. serializationObject.lensFlareSystems.push(scene.lensFlareSystems[index].serialize());
  43436. }
  43437. // Shadows
  43438. serializationObject.shadowGenerators = [];
  43439. for (index = 0; index < scene.lights.length; index++) {
  43440. light = scene.lights[index];
  43441. var shadowGenerator = light.getShadowGenerator();
  43442. // Only support serialization for official generator so far.
  43443. if (shadowGenerator && shadowGenerator instanceof BABYLON.ShadowGenerator) {
  43444. serializationObject.shadowGenerators.push(shadowGenerator.serialize());
  43445. }
  43446. }
  43447. // Action Manager
  43448. if (scene.actionManager) {
  43449. serializationObject.actions = scene.actionManager.serialize("scene");
  43450. }
  43451. // Audio
  43452. serializationObject.sounds = [];
  43453. for (index = 0; index < scene.soundTracks.length; index++) {
  43454. var soundtrack = scene.soundTracks[index];
  43455. for (var soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) {
  43456. serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize());
  43457. }
  43458. }
  43459. return serializationObject;
  43460. };
  43461. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  43462. if (withParents === void 0) { withParents = false; }
  43463. if (withChildren === void 0) { withChildren = false; }
  43464. var serializationObject = {};
  43465. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  43466. if (withParents || withChildren) {
  43467. //deliberate for loop! not for each, appended should be processed as well.
  43468. for (var i = 0; i < toSerialize.length; ++i) {
  43469. if (withChildren) {
  43470. toSerialize[i].getDescendants().forEach(function (node) {
  43471. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  43472. toSerialize.push(node);
  43473. }
  43474. });
  43475. }
  43476. //make sure the array doesn't contain the object already
  43477. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  43478. toSerialize.push(toSerialize[i].parent);
  43479. }
  43480. }
  43481. }
  43482. toSerialize.forEach(function (mesh) {
  43483. finalizeSingleMesh(mesh, serializationObject);
  43484. });
  43485. return serializationObject;
  43486. };
  43487. return SceneSerializer;
  43488. }());
  43489. BABYLON.SceneSerializer = SceneSerializer;
  43490. })(BABYLON || (BABYLON = {}));
  43491. //# sourceMappingURL=babylon.sceneSerializer.js.map
  43492. // All the credit goes to this project and the guy who's behind it https://github.com/mapbox/earcut
  43493. // Huge respect for a such great lib.
  43494. // Earcut license:
  43495. // Copyright (c) 2016, Mapbox
  43496. //
  43497. // Permission to use, copy, modify, and/or distribute this software for any purpose
  43498. // with or without fee is hereby granted, provided that the above copyright notice
  43499. // and this permission notice appear in all copies.
  43500. //
  43501. // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
  43502. // REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
  43503. // FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
  43504. // INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
  43505. // OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
  43506. // TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
  43507. // THIS SOFTWARE.
  43508. var Earcut;
  43509. (function (Earcut) {
  43510. /**
  43511. * The fastest and smallest JavaScript polygon triangulation library for your WebGL apps
  43512. * @param data is a flat array of vertice coordinates like [x0, y0, x1, y1, x2, y2, ...].
  43513. * @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).
  43514. * @param dim is the number of coordinates per vertice in the input array (2 by default).
  43515. */
  43516. function earcut(data, holeIndices, dim) {
  43517. dim = dim || 2;
  43518. var hasHoles = holeIndices && holeIndices.length, outerLen = hasHoles ? holeIndices[0] * dim : data.length, outerNode = linkedList(data, 0, outerLen, dim, true), triangles = [];
  43519. if (!outerNode)
  43520. return triangles;
  43521. var minX, minY, maxX, maxY, x, y, size;
  43522. if (hasHoles)
  43523. outerNode = eliminateHoles(data, holeIndices, outerNode, dim);
  43524. // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
  43525. if (data.length > 80 * dim) {
  43526. minX = maxX = data[0];
  43527. minY = maxY = data[1];
  43528. for (var i = dim; i < outerLen; i += dim) {
  43529. x = data[i];
  43530. y = data[i + 1];
  43531. if (x < minX)
  43532. minX = x;
  43533. if (y < minY)
  43534. minY = y;
  43535. if (x > maxX)
  43536. maxX = x;
  43537. if (y > maxY)
  43538. maxY = y;
  43539. }
  43540. // minX, minY and size are later used to transform coords into integers for z-order calculation
  43541. size = Math.max(maxX - minX, maxY - minY);
  43542. }
  43543. earcutLinked(outerNode, triangles, dim, minX, minY, size, undefined);
  43544. return triangles;
  43545. }
  43546. Earcut.earcut = earcut;
  43547. // create a circular doubly linked list from polygon points in the specified winding order
  43548. function linkedList(data, start, end, dim, clockwise) {
  43549. var i, last;
  43550. if (clockwise === (signedArea(data, start, end, dim) > 0)) {
  43551. for (i = start; i < end; i += dim)
  43552. last = insertNode(i, data[i], data[i + 1], last);
  43553. }
  43554. else {
  43555. for (i = end - dim; i >= start; i -= dim)
  43556. last = insertNode(i, data[i], data[i + 1], last);
  43557. }
  43558. if (last && equals(last, last.next)) {
  43559. removeNode(last);
  43560. last = last.next;
  43561. }
  43562. return last;
  43563. }
  43564. // eliminate colinear or duplicate points
  43565. function filterPoints(start, end) {
  43566. if (!start)
  43567. return start;
  43568. if (!end)
  43569. end = start;
  43570. var p = start, again;
  43571. do {
  43572. again = false;
  43573. if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) {
  43574. removeNode(p);
  43575. p = end = p.prev;
  43576. if (p === p.next)
  43577. return null;
  43578. again = true;
  43579. }
  43580. else {
  43581. p = p.next;
  43582. }
  43583. } while (again || p !== end);
  43584. return end;
  43585. }
  43586. // main ear slicing loop which triangulates a polygon (given as a linked list)
  43587. function earcutLinked(ear, triangles, dim, minX, minY, size, pass) {
  43588. if (!ear)
  43589. return;
  43590. // interlink polygon nodes in z-order
  43591. if (!pass && size)
  43592. indexCurve(ear, minX, minY, size);
  43593. var stop = ear, prev, next;
  43594. // iterate through ears, slicing them one by one
  43595. while (ear.prev !== ear.next) {
  43596. prev = ear.prev;
  43597. next = ear.next;
  43598. if (size ? isEarHashed(ear, minX, minY, size) : isEar(ear)) {
  43599. // cut off the triangle
  43600. triangles.push(prev.i / dim);
  43601. triangles.push(ear.i / dim);
  43602. triangles.push(next.i / dim);
  43603. removeNode(ear);
  43604. // skipping the next vertice leads to less sliver triangles
  43605. ear = next.next;
  43606. stop = next.next;
  43607. continue;
  43608. }
  43609. ear = next;
  43610. // if we looped through the whole remaining polygon and can't find any more ears
  43611. if (ear === stop) {
  43612. // try filtering points and slicing again
  43613. if (!pass) {
  43614. earcutLinked(filterPoints(ear, undefined), triangles, dim, minX, minY, size, 1);
  43615. }
  43616. else if (pass === 1) {
  43617. ear = cureLocalIntersections(ear, triangles, dim);
  43618. earcutLinked(ear, triangles, dim, minX, minY, size, 2);
  43619. }
  43620. else if (pass === 2) {
  43621. splitEarcut(ear, triangles, dim, minX, minY, size);
  43622. }
  43623. break;
  43624. }
  43625. }
  43626. }
  43627. // check whether a polygon node forms a valid ear with adjacent nodes
  43628. function isEar(ear) {
  43629. var a = ear.prev, b = ear, c = ear.next;
  43630. if (area(a, b, c) >= 0)
  43631. return false; // reflex, can't be an ear
  43632. // now make sure we don't have other points inside the potential ear
  43633. var p = ear.next.next;
  43634. while (p !== ear.prev) {
  43635. if (pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  43636. area(p.prev, p, p.next) >= 0)
  43637. return false;
  43638. p = p.next;
  43639. }
  43640. return true;
  43641. }
  43642. function isEarHashed(ear, minX, minY, size) {
  43643. var a = ear.prev, b = ear, c = ear.next;
  43644. if (area(a, b, c) >= 0)
  43645. return false; // reflex, can't be an ear
  43646. // triangle bbox; min & max are calculated like this for speed
  43647. 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);
  43648. // z-order range for the current triangle bbox;
  43649. var minZ = zOrder(minTX, minTY, minX, minY, size), maxZ = zOrder(maxTX, maxTY, minX, minY, size);
  43650. // first look for points inside the triangle in increasing z-order
  43651. var p = ear.nextZ;
  43652. while (p && p.z <= maxZ) {
  43653. if (p !== ear.prev &&
  43654. p !== ear.next &&
  43655. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  43656. area(p.prev, p, p.next) >= 0)
  43657. return false;
  43658. p = p.nextZ;
  43659. }
  43660. // then look for points in decreasing z-order
  43661. p = ear.prevZ;
  43662. while (p && p.z >= minZ) {
  43663. if (p !== ear.prev &&
  43664. p !== ear.next &&
  43665. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  43666. area(p.prev, p, p.next) >= 0)
  43667. return false;
  43668. p = p.prevZ;
  43669. }
  43670. return true;
  43671. }
  43672. // go through all polygon nodes and cure small local self-intersections
  43673. function cureLocalIntersections(start, triangles, dim) {
  43674. var p = start;
  43675. do {
  43676. var a = p.prev, b = p.next.next;
  43677. if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) {
  43678. triangles.push(a.i / dim);
  43679. triangles.push(p.i / dim);
  43680. triangles.push(b.i / dim);
  43681. // remove two nodes involved
  43682. removeNode(p);
  43683. removeNode(p.next);
  43684. p = start = b;
  43685. }
  43686. p = p.next;
  43687. } while (p !== start);
  43688. return p;
  43689. }
  43690. // try splitting polygon into two and triangulate them independently
  43691. function splitEarcut(start, triangles, dim, minX, minY, size) {
  43692. // look for a valid diagonal that divides the polygon into two
  43693. var a = start;
  43694. do {
  43695. var b = a.next.next;
  43696. while (b !== a.prev) {
  43697. if (a.i !== b.i && isValidDiagonal(a, b)) {
  43698. // split the polygon in two by the diagonal
  43699. var c = splitPolygon(a, b);
  43700. // filter colinear points around the cuts
  43701. a = filterPoints(a, a.next);
  43702. c = filterPoints(c, c.next);
  43703. // run earcut on each half
  43704. earcutLinked(a, triangles, dim, minX, minY, size, undefined);
  43705. earcutLinked(c, triangles, dim, minX, minY, size, undefined);
  43706. return;
  43707. }
  43708. b = b.next;
  43709. }
  43710. a = a.next;
  43711. } while (a !== start);
  43712. }
  43713. // link every hole into the outer loop, producing a single-ring polygon without holes
  43714. function eliminateHoles(data, holeIndices, outerNode, dim) {
  43715. var queue = [], i, len, start, end, list;
  43716. for (i = 0, len = holeIndices.length; i < len; i++) {
  43717. start = holeIndices[i] * dim;
  43718. end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  43719. list = linkedList(data, start, end, dim, false);
  43720. if (list === list.next)
  43721. list.steiner = true;
  43722. queue.push(getLeftmost(list));
  43723. }
  43724. queue.sort(compareX);
  43725. // process holes from left to right
  43726. for (i = 0; i < queue.length; i++) {
  43727. eliminateHole(queue[i], outerNode);
  43728. outerNode = filterPoints(outerNode, outerNode.next);
  43729. }
  43730. return outerNode;
  43731. }
  43732. function compareX(a, b) {
  43733. return a.x - b.x;
  43734. }
  43735. // find a bridge between vertices that connects hole with an outer ring and and link it
  43736. function eliminateHole(hole, outerNode) {
  43737. outerNode = findHoleBridge(hole, outerNode);
  43738. if (outerNode) {
  43739. var b = splitPolygon(outerNode, hole);
  43740. filterPoints(b, b.next);
  43741. }
  43742. }
  43743. // David Eberly's algorithm for finding a bridge between hole and outer polygon
  43744. function findHoleBridge(hole, outerNode) {
  43745. var p = outerNode, hx = hole.x, hy = hole.y, qx = -Infinity, m;
  43746. // find a segment intersected by a ray from the hole's leftmost point to the left;
  43747. // segment's endpoint with lesser x will be potential connection point
  43748. do {
  43749. if (hy <= p.y && hy >= p.next.y) {
  43750. var x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y);
  43751. if (x <= hx && x > qx) {
  43752. qx = x;
  43753. if (x === hx) {
  43754. if (hy === p.y)
  43755. return p;
  43756. if (hy === p.next.y)
  43757. return p.next;
  43758. }
  43759. m = p.x < p.next.x ? p : p.next;
  43760. }
  43761. }
  43762. p = p.next;
  43763. } while (p !== outerNode);
  43764. if (!m)
  43765. return null;
  43766. if (hx === qx)
  43767. return m.prev; // hole touches outer segment; pick lower endpoint
  43768. // look for points inside the triangle of hole point, segment intersection and endpoint;
  43769. // if there are no points found, we have a valid connection;
  43770. // otherwise choose the point of the minimum angle with the ray as connection point
  43771. var stop = m, mx = m.x, my = m.y, tanMin = Infinity, tan;
  43772. p = m.next;
  43773. while (p !== stop) {
  43774. if (hx >= p.x &&
  43775. p.x >= mx &&
  43776. pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y)) {
  43777. tan = Math.abs(hy - p.y) / (hx - p.x); // tangential
  43778. if ((tan < tanMin || (tan === tanMin && p.x > m.x)) && locallyInside(p, hole)) {
  43779. m = p;
  43780. tanMin = tan;
  43781. }
  43782. }
  43783. p = p.next;
  43784. }
  43785. return m;
  43786. }
  43787. // interlink polygon nodes in z-order
  43788. function indexCurve(start, minX, minY, size) {
  43789. var p = start;
  43790. do {
  43791. if (p.z === null)
  43792. p.z = zOrder(p.x, p.y, minX, minY, size);
  43793. p.prevZ = p.prev;
  43794. p.nextZ = p.next;
  43795. p = p.next;
  43796. } while (p !== start);
  43797. p.prevZ.nextZ = null;
  43798. p.prevZ = null;
  43799. sortLinked(p);
  43800. }
  43801. // Simon Tatham's linked list merge sort algorithm
  43802. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  43803. function sortLinked(list) {
  43804. var i, p, q, e, tail, numMerges, pSize, qSize, inSize = 1;
  43805. do {
  43806. p = list;
  43807. list = null;
  43808. tail = null;
  43809. numMerges = 0;
  43810. while (p) {
  43811. numMerges++;
  43812. q = p;
  43813. pSize = 0;
  43814. for (i = 0; i < inSize; i++) {
  43815. pSize++;
  43816. q = q.nextZ;
  43817. if (!q)
  43818. break;
  43819. }
  43820. qSize = inSize;
  43821. while (pSize > 0 || (qSize > 0 && q)) {
  43822. if (pSize === 0) {
  43823. e = q;
  43824. q = q.nextZ;
  43825. qSize--;
  43826. }
  43827. else if (qSize === 0 || !q) {
  43828. e = p;
  43829. p = p.nextZ;
  43830. pSize--;
  43831. }
  43832. else if (p.z <= q.z) {
  43833. e = p;
  43834. p = p.nextZ;
  43835. pSize--;
  43836. }
  43837. else {
  43838. e = q;
  43839. q = q.nextZ;
  43840. qSize--;
  43841. }
  43842. if (tail)
  43843. tail.nextZ = e;
  43844. else
  43845. list = e;
  43846. e.prevZ = tail;
  43847. tail = e;
  43848. }
  43849. p = q;
  43850. }
  43851. tail.nextZ = null;
  43852. inSize *= 2;
  43853. } while (numMerges > 1);
  43854. return list;
  43855. }
  43856. // z-order of a point given coords and size of the data bounding box
  43857. function zOrder(x, y, minX, minY, size) {
  43858. // coords are transformed into non-negative 15-bit integer range
  43859. x = 32767 * (x - minX) / size;
  43860. y = 32767 * (y - minY) / size;
  43861. x = (x | (x << 8)) & 0x00FF00FF;
  43862. x = (x | (x << 4)) & 0x0F0F0F0F;
  43863. x = (x | (x << 2)) & 0x33333333;
  43864. x = (x | (x << 1)) & 0x55555555;
  43865. y = (y | (y << 8)) & 0x00FF00FF;
  43866. y = (y | (y << 4)) & 0x0F0F0F0F;
  43867. y = (y | (y << 2)) & 0x33333333;
  43868. y = (y | (y << 1)) & 0x55555555;
  43869. return x | (y << 1);
  43870. }
  43871. // find the leftmost node of a polygon ring
  43872. function getLeftmost(start) {
  43873. var p = start, leftmost = start;
  43874. do {
  43875. if (p.x < leftmost.x)
  43876. leftmost = p;
  43877. p = p.next;
  43878. } while (p !== start);
  43879. return leftmost;
  43880. }
  43881. // check if a point lies within a convex triangle
  43882. function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) {
  43883. return (cx - px) * (ay - py) - (ax - px) * (cy - py) >= 0 &&
  43884. (ax - px) * (by - py) - (bx - px) * (ay - py) >= 0 &&
  43885. (bx - px) * (cy - py) - (cx - px) * (by - py) >= 0;
  43886. }
  43887. // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  43888. function isValidDiagonal(a, b) {
  43889. return a.next.i !== b.i &&
  43890. a.prev.i !== b.i &&
  43891. !intersectsPolygon(a, b) &&
  43892. locallyInside(a, b) &&
  43893. locallyInside(b, a) &&
  43894. middleInside(a, b);
  43895. }
  43896. // signed area of a triangle
  43897. function area(p, q, r) {
  43898. return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);
  43899. }
  43900. // check if two points are equal
  43901. function equals(p1, p2) {
  43902. return p1.x === p2.x && p1.y === p2.y;
  43903. }
  43904. // check if two segments intersect
  43905. function intersects(p1, q1, p2, q2) {
  43906. if ((equals(p1, q1) && equals(p2, q2)) ||
  43907. (equals(p1, q2) && equals(p2, q1)))
  43908. return true;
  43909. return area(p1, q1, p2) > 0 !== area(p1, q1, q2) > 0 &&
  43910. area(p2, q2, p1) > 0 !== area(p2, q2, q1) > 0;
  43911. }
  43912. // check if a polygon diagonal intersects any polygon segments
  43913. function intersectsPolygon(a, b) {
  43914. var p = a;
  43915. do {
  43916. if (p.i !== a.i &&
  43917. p.next.i !== a.i &&
  43918. p.i !== b.i &&
  43919. p.next.i !== b.i &&
  43920. intersects(p, p.next, a, b))
  43921. return true;
  43922. p = p.next;
  43923. } while (p !== a);
  43924. return false;
  43925. }
  43926. // check if a polygon diagonal is locally inside the polygon
  43927. function locallyInside(a, b) {
  43928. return area(a.prev, a, a.next) < 0
  43929. ? area(a, b, a.next) >= 0 && area(a, a.prev, b) >= 0
  43930. : area(a, b, a.prev) < 0 || area(a, a.next, b) < 0;
  43931. }
  43932. // check if the middle point of a polygon diagonal is inside the polygon
  43933. function middleInside(a, b) {
  43934. var p = a, inside = false, px = (a.x + b.x) / 2, py = (a.y + b.y) / 2;
  43935. do {
  43936. if (((p.y > py) !== (p.next.y > py)) && (px < (p.next.x - p.x) * (py - p.y) / (p.next.y - p.y) + p.x))
  43937. inside = !inside;
  43938. p = p.next;
  43939. } while (p !== a);
  43940. return inside;
  43941. }
  43942. // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  43943. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  43944. function splitPolygon(a, b) {
  43945. 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;
  43946. a.next = b;
  43947. b.prev = a;
  43948. a2.next = an;
  43949. an.prev = a2;
  43950. b2.next = a2;
  43951. a2.prev = b2;
  43952. bp.next = b2;
  43953. b2.prev = bp;
  43954. return b2;
  43955. }
  43956. // create a node and optionally link it with previous one (in a circular doubly linked list)
  43957. function insertNode(i, x, y, last) {
  43958. var p = new Node(i, x, y);
  43959. if (!last) {
  43960. p.prev = p;
  43961. p.next = p;
  43962. }
  43963. else {
  43964. p.next = last.next;
  43965. p.prev = last;
  43966. last.next.prev = p;
  43967. last.next = p;
  43968. }
  43969. return p;
  43970. }
  43971. function removeNode(p) {
  43972. p.next.prev = p.prev;
  43973. p.prev.next = p.next;
  43974. if (p.prevZ)
  43975. p.prevZ.nextZ = p.nextZ;
  43976. if (p.nextZ)
  43977. p.nextZ.prevZ = p.prevZ;
  43978. }
  43979. function Node(i, x, y) {
  43980. // vertice index in coordinates array
  43981. this.i = i;
  43982. // vertex coordinates
  43983. this.x = x;
  43984. this.y = y;
  43985. // previous and next vertice nodes in a polygon ring
  43986. this.prev = null;
  43987. this.next = null;
  43988. // z-order curve value
  43989. this.z = null;
  43990. // previous and next nodes in z-order
  43991. this.prevZ = null;
  43992. this.nextZ = null;
  43993. // indicates whether this is a steiner point
  43994. this.steiner = false;
  43995. }
  43996. /**
  43997. * return a percentage difference between the polygon area and its triangulation area;
  43998. * used to verify correctness of triangulation
  43999. */
  44000. function deviation(data, holeIndices, dim, triangles) {
  44001. var hasHoles = holeIndices && holeIndices.length;
  44002. var outerLen = hasHoles ? holeIndices[0] * dim : data.length;
  44003. var polygonArea = Math.abs(signedArea(data, 0, outerLen, dim));
  44004. if (hasHoles) {
  44005. for (var i = 0, len = holeIndices.length; i < len; i++) {
  44006. var start = holeIndices[i] * dim;
  44007. var end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  44008. polygonArea -= Math.abs(signedArea(data, start, end, dim));
  44009. }
  44010. }
  44011. var trianglesArea = 0;
  44012. for (i = 0; i < triangles.length; i += 3) {
  44013. var a = triangles[i] * dim;
  44014. var b = triangles[i + 1] * dim;
  44015. var c = triangles[i + 2] * dim;
  44016. trianglesArea += Math.abs((data[a] - data[c]) * (data[b + 1] - data[a + 1]) -
  44017. (data[a] - data[b]) * (data[c + 1] - data[a + 1]));
  44018. }
  44019. return polygonArea === 0 && trianglesArea === 0 ? 0 : Math.abs((trianglesArea - polygonArea) / polygonArea);
  44020. }
  44021. Earcut.deviation = deviation;
  44022. ;
  44023. function signedArea(data, start, end, dim) {
  44024. var sum = 0;
  44025. for (var i = start, j = end - dim; i < end; i += dim) {
  44026. sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]);
  44027. j = i;
  44028. }
  44029. return sum;
  44030. }
  44031. /**
  44032. * turn a polygon in a multi-dimensional array form (e.g. as in GeoJSON) into a form Earcut accepts
  44033. */
  44034. function flatten(data) {
  44035. var dim = data[0][0].length, result = { vertices: [], holes: [], dimensions: dim }, holeIndex = 0;
  44036. for (var i = 0; i < data.length; i++) {
  44037. for (var j = 0; j < data[i].length; j++) {
  44038. for (var d = 0; d < dim; d++)
  44039. result.vertices.push(data[i][j][d]);
  44040. }
  44041. if (i > 0) {
  44042. holeIndex += data[i - 1].length;
  44043. result.holes.push(holeIndex);
  44044. }
  44045. }
  44046. return result;
  44047. }
  44048. Earcut.flatten = flatten;
  44049. ;
  44050. })(Earcut || (Earcut = {}));
  44051. //# sourceMappingURL=babylon.earcut.js.map
  44052. var BABYLON;
  44053. (function (BABYLON) {
  44054. // Unique ID when we import meshes from Babylon to CSG
  44055. var currentCSGMeshId = 0;
  44056. // # class Vertex
  44057. // Represents a vertex of a polygon. Use your own vertex class instead of this
  44058. // one to provide additional features like texture coordinates and vertex
  44059. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  44060. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  44061. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  44062. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  44063. // is not used anywhere else.
  44064. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  44065. var Vertex = (function () {
  44066. function Vertex(pos, normal, uv) {
  44067. this.pos = pos;
  44068. this.normal = normal;
  44069. this.uv = uv;
  44070. }
  44071. Vertex.prototype.clone = function () {
  44072. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  44073. };
  44074. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  44075. // orientation of a polygon is flipped.
  44076. Vertex.prototype.flip = function () {
  44077. this.normal = this.normal.scale(-1);
  44078. };
  44079. // Create a new vertex between this vertex and `other` by linearly
  44080. // interpolating all properties using a parameter of `t`. Subclasses should
  44081. // override this to interpolate additional properties.
  44082. Vertex.prototype.interpolate = function (other, t) {
  44083. 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));
  44084. };
  44085. return Vertex;
  44086. }());
  44087. // # class Plane
  44088. // Represents a plane in 3D space.
  44089. var Plane = (function () {
  44090. function Plane(normal, w) {
  44091. this.normal = normal;
  44092. this.w = w;
  44093. }
  44094. Plane.FromPoints = function (a, b, c) {
  44095. var v0 = c.subtract(a);
  44096. var v1 = b.subtract(a);
  44097. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  44098. return null;
  44099. }
  44100. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  44101. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  44102. };
  44103. Plane.prototype.clone = function () {
  44104. return new Plane(this.normal.clone(), this.w);
  44105. };
  44106. Plane.prototype.flip = function () {
  44107. this.normal.scaleInPlace(-1);
  44108. this.w = -this.w;
  44109. };
  44110. // Split `polygon` by this plane if needed, then put the polygon or polygon
  44111. // fragments in the appropriate lists. Coplanar polygons go into either
  44112. // `coplanarFront` or `coplanarBack` depending on their orientation with
  44113. // respect to this plane. Polygons in front or in back of this plane go into
  44114. // either `front` or `back`.
  44115. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  44116. var COPLANAR = 0;
  44117. var FRONT = 1;
  44118. var BACK = 2;
  44119. var SPANNING = 3;
  44120. // Classify each point as well as the entire polygon into one of the above
  44121. // four classes.
  44122. var polygonType = 0;
  44123. var types = [];
  44124. var i;
  44125. var t;
  44126. for (i = 0; i < polygon.vertices.length; i++) {
  44127. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  44128. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  44129. polygonType |= type;
  44130. types.push(type);
  44131. }
  44132. // Put the polygon in the correct list, splitting it when necessary.
  44133. switch (polygonType) {
  44134. case COPLANAR:
  44135. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  44136. break;
  44137. case FRONT:
  44138. front.push(polygon);
  44139. break;
  44140. case BACK:
  44141. back.push(polygon);
  44142. break;
  44143. case SPANNING:
  44144. var f = [], b = [];
  44145. for (i = 0; i < polygon.vertices.length; i++) {
  44146. var j = (i + 1) % polygon.vertices.length;
  44147. var ti = types[i], tj = types[j];
  44148. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  44149. if (ti !== BACK)
  44150. f.push(vi);
  44151. if (ti !== FRONT)
  44152. b.push(ti !== BACK ? vi.clone() : vi);
  44153. if ((ti | tj) === SPANNING) {
  44154. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  44155. var v = vi.interpolate(vj, t);
  44156. f.push(v);
  44157. b.push(v.clone());
  44158. }
  44159. }
  44160. var poly;
  44161. if (f.length >= 3) {
  44162. poly = new Polygon(f, polygon.shared);
  44163. if (poly.plane)
  44164. front.push(poly);
  44165. }
  44166. if (b.length >= 3) {
  44167. poly = new Polygon(b, polygon.shared);
  44168. if (poly.plane)
  44169. back.push(poly);
  44170. }
  44171. break;
  44172. }
  44173. };
  44174. return Plane;
  44175. }());
  44176. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  44177. // point is on the plane.
  44178. Plane.EPSILON = 1e-5;
  44179. // # class Polygon
  44180. // Represents a convex polygon. The vertices used to initialize a polygon must
  44181. // be coplanar and form a convex loop.
  44182. //
  44183. // Each convex polygon has a `shared` property, which is shared between all
  44184. // polygons that are clones of each other or were split from the same polygon.
  44185. // This can be used to define per-polygon properties (such as surface color).
  44186. var Polygon = (function () {
  44187. function Polygon(vertices, shared) {
  44188. this.vertices = vertices;
  44189. this.shared = shared;
  44190. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  44191. }
  44192. Polygon.prototype.clone = function () {
  44193. var vertices = this.vertices.map(function (v) { return v.clone(); });
  44194. return new Polygon(vertices, this.shared);
  44195. };
  44196. Polygon.prototype.flip = function () {
  44197. this.vertices.reverse().map(function (v) { v.flip(); });
  44198. this.plane.flip();
  44199. };
  44200. return Polygon;
  44201. }());
  44202. // # class Node
  44203. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  44204. // by picking a polygon to split along. That polygon (and all other coplanar
  44205. // polygons) are added directly to that node and the other polygons are added to
  44206. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  44207. // no distinction between internal and leaf nodes.
  44208. var Node = (function () {
  44209. function Node(polygons) {
  44210. this.plane = null;
  44211. this.front = null;
  44212. this.back = null;
  44213. this.polygons = [];
  44214. if (polygons) {
  44215. this.build(polygons);
  44216. }
  44217. }
  44218. Node.prototype.clone = function () {
  44219. var node = new Node();
  44220. node.plane = this.plane && this.plane.clone();
  44221. node.front = this.front && this.front.clone();
  44222. node.back = this.back && this.back.clone();
  44223. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  44224. return node;
  44225. };
  44226. // Convert solid space to empty space and empty space to solid space.
  44227. Node.prototype.invert = function () {
  44228. for (var i = 0; i < this.polygons.length; i++) {
  44229. this.polygons[i].flip();
  44230. }
  44231. if (this.plane) {
  44232. this.plane.flip();
  44233. }
  44234. if (this.front) {
  44235. this.front.invert();
  44236. }
  44237. if (this.back) {
  44238. this.back.invert();
  44239. }
  44240. var temp = this.front;
  44241. this.front = this.back;
  44242. this.back = temp;
  44243. };
  44244. // Recursively remove all polygons in `polygons` that are inside this BSP
  44245. // tree.
  44246. Node.prototype.clipPolygons = function (polygons) {
  44247. if (!this.plane)
  44248. return polygons.slice();
  44249. var front = [], back = [];
  44250. for (var i = 0; i < polygons.length; i++) {
  44251. this.plane.splitPolygon(polygons[i], front, back, front, back);
  44252. }
  44253. if (this.front) {
  44254. front = this.front.clipPolygons(front);
  44255. }
  44256. if (this.back) {
  44257. back = this.back.clipPolygons(back);
  44258. }
  44259. else {
  44260. back = [];
  44261. }
  44262. return front.concat(back);
  44263. };
  44264. // Remove all polygons in this BSP tree that are inside the other BSP tree
  44265. // `bsp`.
  44266. Node.prototype.clipTo = function (bsp) {
  44267. this.polygons = bsp.clipPolygons(this.polygons);
  44268. if (this.front)
  44269. this.front.clipTo(bsp);
  44270. if (this.back)
  44271. this.back.clipTo(bsp);
  44272. };
  44273. // Return a list of all polygons in this BSP tree.
  44274. Node.prototype.allPolygons = function () {
  44275. var polygons = this.polygons.slice();
  44276. if (this.front)
  44277. polygons = polygons.concat(this.front.allPolygons());
  44278. if (this.back)
  44279. polygons = polygons.concat(this.back.allPolygons());
  44280. return polygons;
  44281. };
  44282. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  44283. // new polygons are filtered down to the bottom of the tree and become new
  44284. // nodes there. Each set of polygons is partitioned using the first polygon
  44285. // (no heuristic is used to pick a good split).
  44286. Node.prototype.build = function (polygons) {
  44287. if (!polygons.length)
  44288. return;
  44289. if (!this.plane)
  44290. this.plane = polygons[0].plane.clone();
  44291. var front = [], back = [];
  44292. for (var i = 0; i < polygons.length; i++) {
  44293. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  44294. }
  44295. if (front.length) {
  44296. if (!this.front)
  44297. this.front = new Node();
  44298. this.front.build(front);
  44299. }
  44300. if (back.length) {
  44301. if (!this.back)
  44302. this.back = new Node();
  44303. this.back.build(back);
  44304. }
  44305. };
  44306. return Node;
  44307. }());
  44308. var CSG = (function () {
  44309. function CSG() {
  44310. this.polygons = new Array();
  44311. }
  44312. // Convert BABYLON.Mesh to BABYLON.CSG
  44313. CSG.FromMesh = function (mesh) {
  44314. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  44315. var matrix, meshPosition, meshRotation, meshRotationQuaternion, meshScaling;
  44316. if (mesh instanceof BABYLON.Mesh) {
  44317. mesh.computeWorldMatrix(true);
  44318. matrix = mesh.getWorldMatrix();
  44319. meshPosition = mesh.position.clone();
  44320. meshRotation = mesh.rotation.clone();
  44321. if (mesh.rotationQuaternion) {
  44322. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  44323. }
  44324. meshScaling = mesh.scaling.clone();
  44325. }
  44326. else {
  44327. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  44328. }
  44329. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  44330. var subMeshes = mesh.subMeshes;
  44331. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  44332. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  44333. vertices = [];
  44334. for (var j = 0; j < 3; j++) {
  44335. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  44336. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  44337. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  44338. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  44339. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  44340. vertex = new Vertex(position, normal, uv);
  44341. vertices.push(vertex);
  44342. }
  44343. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  44344. // To handle the case of degenerated triangle
  44345. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  44346. if (polygon.plane)
  44347. polygons.push(polygon);
  44348. }
  44349. }
  44350. var csg = CSG.FromPolygons(polygons);
  44351. csg.matrix = matrix;
  44352. csg.position = meshPosition;
  44353. csg.rotation = meshRotation;
  44354. csg.scaling = meshScaling;
  44355. csg.rotationQuaternion = meshRotationQuaternion;
  44356. currentCSGMeshId++;
  44357. return csg;
  44358. };
  44359. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  44360. CSG.FromPolygons = function (polygons) {
  44361. var csg = new CSG();
  44362. csg.polygons = polygons;
  44363. return csg;
  44364. };
  44365. CSG.prototype.clone = function () {
  44366. var csg = new CSG();
  44367. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  44368. csg.copyTransformAttributes(this);
  44369. return csg;
  44370. };
  44371. CSG.prototype.toPolygons = function () {
  44372. return this.polygons;
  44373. };
  44374. CSG.prototype.union = function (csg) {
  44375. var a = new Node(this.clone().polygons);
  44376. var b = new Node(csg.clone().polygons);
  44377. a.clipTo(b);
  44378. b.clipTo(a);
  44379. b.invert();
  44380. b.clipTo(a);
  44381. b.invert();
  44382. a.build(b.allPolygons());
  44383. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  44384. };
  44385. CSG.prototype.unionInPlace = function (csg) {
  44386. var a = new Node(this.polygons);
  44387. var b = new Node(csg.polygons);
  44388. a.clipTo(b);
  44389. b.clipTo(a);
  44390. b.invert();
  44391. b.clipTo(a);
  44392. b.invert();
  44393. a.build(b.allPolygons());
  44394. this.polygons = a.allPolygons();
  44395. };
  44396. CSG.prototype.subtract = function (csg) {
  44397. var a = new Node(this.clone().polygons);
  44398. var b = new Node(csg.clone().polygons);
  44399. a.invert();
  44400. a.clipTo(b);
  44401. b.clipTo(a);
  44402. b.invert();
  44403. b.clipTo(a);
  44404. b.invert();
  44405. a.build(b.allPolygons());
  44406. a.invert();
  44407. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  44408. };
  44409. CSG.prototype.subtractInPlace = function (csg) {
  44410. var a = new Node(this.polygons);
  44411. var b = new Node(csg.polygons);
  44412. a.invert();
  44413. a.clipTo(b);
  44414. b.clipTo(a);
  44415. b.invert();
  44416. b.clipTo(a);
  44417. b.invert();
  44418. a.build(b.allPolygons());
  44419. a.invert();
  44420. this.polygons = a.allPolygons();
  44421. };
  44422. CSG.prototype.intersect = function (csg) {
  44423. var a = new Node(this.clone().polygons);
  44424. var b = new Node(csg.clone().polygons);
  44425. a.invert();
  44426. b.clipTo(a);
  44427. b.invert();
  44428. a.clipTo(b);
  44429. b.clipTo(a);
  44430. a.build(b.allPolygons());
  44431. a.invert();
  44432. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  44433. };
  44434. CSG.prototype.intersectInPlace = function (csg) {
  44435. var a = new Node(this.polygons);
  44436. var b = new Node(csg.polygons);
  44437. a.invert();
  44438. b.clipTo(a);
  44439. b.invert();
  44440. a.clipTo(b);
  44441. b.clipTo(a);
  44442. a.build(b.allPolygons());
  44443. a.invert();
  44444. this.polygons = a.allPolygons();
  44445. };
  44446. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  44447. // not modified.
  44448. CSG.prototype.inverse = function () {
  44449. var csg = this.clone();
  44450. csg.inverseInPlace();
  44451. return csg;
  44452. };
  44453. CSG.prototype.inverseInPlace = function () {
  44454. this.polygons.map(function (p) { p.flip(); });
  44455. };
  44456. // This is used to keep meshes transformations so they can be restored
  44457. // when we build back a Babylon Mesh
  44458. // NB : All CSG operations are performed in world coordinates
  44459. CSG.prototype.copyTransformAttributes = function (csg) {
  44460. this.matrix = csg.matrix;
  44461. this.position = csg.position;
  44462. this.rotation = csg.rotation;
  44463. this.scaling = csg.scaling;
  44464. this.rotationQuaternion = csg.rotationQuaternion;
  44465. return this;
  44466. };
  44467. // Build Raw mesh from CSG
  44468. // Coordinates here are in world space
  44469. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  44470. var matrix = this.matrix.clone();
  44471. matrix.invert();
  44472. 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;
  44473. if (keepSubMeshes) {
  44474. // Sort Polygons, since subMeshes are indices range
  44475. polygons.sort(function (a, b) {
  44476. if (a.shared.meshId === b.shared.meshId) {
  44477. return a.shared.subMeshId - b.shared.subMeshId;
  44478. }
  44479. else {
  44480. return a.shared.meshId - b.shared.meshId;
  44481. }
  44482. });
  44483. }
  44484. for (var i = 0, il = polygons.length; i < il; i++) {
  44485. polygon = polygons[i];
  44486. // Building SubMeshes
  44487. if (!subMesh_dict[polygon.shared.meshId]) {
  44488. subMesh_dict[polygon.shared.meshId] = {};
  44489. }
  44490. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  44491. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  44492. indexStart: +Infinity,
  44493. indexEnd: -Infinity,
  44494. materialIndex: polygon.shared.materialIndex
  44495. };
  44496. }
  44497. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  44498. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  44499. polygonIndices[0] = 0;
  44500. polygonIndices[1] = j - 1;
  44501. polygonIndices[2] = j;
  44502. for (var k = 0; k < 3; k++) {
  44503. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  44504. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  44505. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  44506. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  44507. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  44508. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  44509. // Check if 2 points can be merged
  44510. if (!(typeof vertex_idx !== 'undefined' &&
  44511. normals[vertex_idx * 3] === localNormal.x &&
  44512. normals[vertex_idx * 3 + 1] === localNormal.y &&
  44513. normals[vertex_idx * 3 + 2] === localNormal.z &&
  44514. uvs[vertex_idx * 2] === uv.x &&
  44515. uvs[vertex_idx * 2 + 1] === uv.y)) {
  44516. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  44517. uvs.push(uv.x, uv.y);
  44518. normals.push(normal.x, normal.y, normal.z);
  44519. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  44520. }
  44521. indices.push(vertex_idx);
  44522. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  44523. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  44524. currentIndex++;
  44525. }
  44526. }
  44527. }
  44528. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  44529. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  44530. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  44531. mesh.setIndices(indices);
  44532. if (keepSubMeshes) {
  44533. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  44534. var materialIndexOffset = 0, materialMaxIndex;
  44535. mesh.subMeshes = new Array();
  44536. for (var m in subMesh_dict) {
  44537. materialMaxIndex = -1;
  44538. for (var sm in subMesh_dict[m]) {
  44539. subMesh_obj = subMesh_dict[m][sm];
  44540. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  44541. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  44542. }
  44543. materialIndexOffset += ++materialMaxIndex;
  44544. }
  44545. }
  44546. return mesh;
  44547. };
  44548. // Build Mesh from CSG taking material and transforms into account
  44549. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  44550. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  44551. mesh.material = material;
  44552. mesh.position.copyFrom(this.position);
  44553. mesh.rotation.copyFrom(this.rotation);
  44554. if (this.rotationQuaternion) {
  44555. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  44556. }
  44557. mesh.scaling.copyFrom(this.scaling);
  44558. mesh.computeWorldMatrix(true);
  44559. return mesh;
  44560. };
  44561. return CSG;
  44562. }());
  44563. BABYLON.CSG = CSG;
  44564. })(BABYLON || (BABYLON = {}));
  44565. //# sourceMappingURL=babylon.csg.js.map
  44566. var BABYLON;
  44567. (function (BABYLON) {
  44568. var VRDistortionCorrectionPostProcess = (function (_super) {
  44569. __extends(VRDistortionCorrectionPostProcess, _super);
  44570. //ANY
  44571. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  44572. var _this = _super.call(this, name, "vrDistortionCorrection", [
  44573. 'LensCenter',
  44574. 'Scale',
  44575. 'ScaleIn',
  44576. 'HmdWarpParam'
  44577. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE, null, null) || this;
  44578. _this._isRightEye = isRightEye;
  44579. _this._distortionFactors = vrMetrics.distortionK;
  44580. _this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  44581. _this._lensCenterOffset = vrMetrics.lensCenterOffset;
  44582. _this.onSizeChangedObservable.add(function () {
  44583. _this.aspectRatio = _this.width * .5 / _this.height;
  44584. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  44585. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  44586. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  44587. });
  44588. _this.onApplyObservable.add(function (effect) {
  44589. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  44590. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  44591. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  44592. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  44593. });
  44594. return _this;
  44595. }
  44596. return VRDistortionCorrectionPostProcess;
  44597. }(BABYLON.PostProcess));
  44598. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  44599. })(BABYLON || (BABYLON = {}));
  44600. //# sourceMappingURL=babylon.vrDistortionCorrectionPostProcess.js.map
  44601. // Mainly based on these 2 articles :
  44602. // 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
  44603. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  44604. var BABYLON;
  44605. (function (BABYLON) {
  44606. var JoystickAxis;
  44607. (function (JoystickAxis) {
  44608. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  44609. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  44610. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  44611. })(JoystickAxis = BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  44612. var VirtualJoystick = (function () {
  44613. function VirtualJoystick(leftJoystick) {
  44614. var _this = this;
  44615. if (leftJoystick) {
  44616. this._leftJoystick = true;
  44617. }
  44618. else {
  44619. this._leftJoystick = false;
  44620. }
  44621. this._joystickIndex = VirtualJoystick._globalJoystickIndex;
  44622. VirtualJoystick._globalJoystickIndex++;
  44623. // By default left & right arrow keys are moving the X
  44624. // and up & down keys are moving the Y
  44625. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  44626. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  44627. this.reverseLeftRight = false;
  44628. this.reverseUpDown = false;
  44629. // collections of pointers
  44630. this._touches = new BABYLON.StringDictionary();
  44631. this.deltaPosition = BABYLON.Vector3.Zero();
  44632. this._joystickSensibility = 25;
  44633. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  44634. this._rotationSpeed = 25;
  44635. this._inverseRotationSpeed = 1 / (this._rotationSpeed / 1000);
  44636. this._rotateOnAxisRelativeToMesh = false;
  44637. this._onResize = function (evt) {
  44638. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  44639. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  44640. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  44641. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  44642. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  44643. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvasHeight / 2;
  44644. };
  44645. // injecting a canvas element on top of the canvas 3D game
  44646. if (!VirtualJoystick.vjCanvas) {
  44647. window.addEventListener("resize", this._onResize, false);
  44648. VirtualJoystick.vjCanvas = document.createElement("canvas");
  44649. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  44650. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  44651. VirtualJoystick.vjCanvas.width = window.innerWidth;
  44652. VirtualJoystick.vjCanvas.height = window.innerHeight;
  44653. VirtualJoystick.vjCanvas.style.width = "100%";
  44654. VirtualJoystick.vjCanvas.style.height = "100%";
  44655. VirtualJoystick.vjCanvas.style.position = "absolute";
  44656. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  44657. VirtualJoystick.vjCanvas.style.top = "0px";
  44658. VirtualJoystick.vjCanvas.style.left = "0px";
  44659. VirtualJoystick.vjCanvas.style.zIndex = "5";
  44660. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  44661. // Support for jQuery PEP polyfill
  44662. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  44663. VirtualJoystick.vjCanvasContext = VirtualJoystick.vjCanvas.getContext('2d');
  44664. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  44665. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  44666. document.body.appendChild(VirtualJoystick.vjCanvas);
  44667. }
  44668. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  44669. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvas.height / 2;
  44670. this.pressed = false;
  44671. // default joystick color
  44672. this._joystickColor = "cyan";
  44673. this._joystickPointerID = -1;
  44674. // current joystick position
  44675. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  44676. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  44677. // origin joystick position
  44678. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  44679. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  44680. this._onPointerDownHandlerRef = function (evt) {
  44681. _this._onPointerDown(evt);
  44682. };
  44683. this._onPointerMoveHandlerRef = function (evt) {
  44684. _this._onPointerMove(evt);
  44685. };
  44686. this._onPointerOutHandlerRef = function (evt) {
  44687. _this._onPointerUp(evt);
  44688. };
  44689. this._onPointerUpHandlerRef = function (evt) {
  44690. _this._onPointerUp(evt);
  44691. };
  44692. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  44693. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  44694. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  44695. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  44696. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  44697. evt.preventDefault(); // Disables system menu
  44698. }, false);
  44699. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  44700. }
  44701. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  44702. this._joystickSensibility = newJoystickSensibility;
  44703. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  44704. };
  44705. VirtualJoystick.prototype._onPointerDown = function (e) {
  44706. var positionOnScreenCondition;
  44707. e.preventDefault();
  44708. if (this._leftJoystick === true) {
  44709. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  44710. }
  44711. else {
  44712. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  44713. }
  44714. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  44715. // First contact will be dedicated to the virtual joystick
  44716. this._joystickPointerID = e.pointerId;
  44717. this._joystickPointerStartPos.x = e.clientX;
  44718. this._joystickPointerStartPos.y = e.clientY;
  44719. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  44720. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  44721. this._deltaJoystickVector.x = 0;
  44722. this._deltaJoystickVector.y = 0;
  44723. this.pressed = true;
  44724. this._touches.add(e.pointerId.toString(), e);
  44725. }
  44726. else {
  44727. // You can only trigger the action buttons with a joystick declared
  44728. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  44729. this._action();
  44730. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  44731. }
  44732. }
  44733. };
  44734. VirtualJoystick.prototype._onPointerMove = function (e) {
  44735. // If the current pointer is the one associated to the joystick (first touch contact)
  44736. if (this._joystickPointerID == e.pointerId) {
  44737. this._joystickPointerPos.x = e.clientX;
  44738. this._joystickPointerPos.y = e.clientY;
  44739. this._deltaJoystickVector = this._joystickPointerPos.clone();
  44740. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  44741. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  44742. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  44743. switch (this._axisTargetedByLeftAndRight) {
  44744. case JoystickAxis.X:
  44745. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  44746. break;
  44747. case JoystickAxis.Y:
  44748. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  44749. break;
  44750. case JoystickAxis.Z:
  44751. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  44752. break;
  44753. }
  44754. var directionUpDown = this.reverseUpDown ? 1 : -1;
  44755. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  44756. switch (this._axisTargetedByUpAndDown) {
  44757. case JoystickAxis.X:
  44758. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  44759. break;
  44760. case JoystickAxis.Y:
  44761. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  44762. break;
  44763. case JoystickAxis.Z:
  44764. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  44765. break;
  44766. }
  44767. }
  44768. else {
  44769. var data = this._touches.get(e.pointerId.toString());
  44770. if (data) {
  44771. data.x = e.clientX;
  44772. data.y = e.clientY;
  44773. }
  44774. }
  44775. };
  44776. VirtualJoystick.prototype._onPointerUp = function (e) {
  44777. if (this._joystickPointerID == e.pointerId) {
  44778. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 64, this._joystickPointerStartPos.y - 64, 128, 128);
  44779. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 42, this._joystickPreviousPointerPos.y - 42, 84, 84);
  44780. this._joystickPointerID = -1;
  44781. this.pressed = false;
  44782. }
  44783. else {
  44784. var touch = this._touches.get(e.pointerId.toString());
  44785. if (touch) {
  44786. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  44787. }
  44788. }
  44789. this._deltaJoystickVector.x = 0;
  44790. this._deltaJoystickVector.y = 0;
  44791. this._touches.remove(e.pointerId.toString());
  44792. };
  44793. /**
  44794. * Change the color of the virtual joystick
  44795. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  44796. */
  44797. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  44798. this._joystickColor = newColor;
  44799. };
  44800. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  44801. this._action = action;
  44802. };
  44803. // Define which axis you'd like to control for left & right
  44804. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  44805. switch (axis) {
  44806. case JoystickAxis.X:
  44807. case JoystickAxis.Y:
  44808. case JoystickAxis.Z:
  44809. this._axisTargetedByLeftAndRight = axis;
  44810. break;
  44811. default:
  44812. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  44813. break;
  44814. }
  44815. };
  44816. // Define which axis you'd like to control for up & down
  44817. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  44818. switch (axis) {
  44819. case JoystickAxis.X:
  44820. case JoystickAxis.Y:
  44821. case JoystickAxis.Z:
  44822. this._axisTargetedByUpAndDown = axis;
  44823. break;
  44824. default:
  44825. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  44826. break;
  44827. }
  44828. };
  44829. VirtualJoystick.prototype._clearCanvas = function () {
  44830. if (this._leftJoystick) {
  44831. VirtualJoystick.vjCanvasContext.clearRect(0, 0, VirtualJoystick.vjCanvasWidth / 2, VirtualJoystick.vjCanvasHeight);
  44832. }
  44833. else {
  44834. VirtualJoystick.vjCanvasContext.clearRect(VirtualJoystick.vjCanvasWidth / 2, 0, VirtualJoystick.vjCanvasWidth, VirtualJoystick.vjCanvasHeight);
  44835. }
  44836. };
  44837. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  44838. var _this = this;
  44839. if (this.pressed) {
  44840. this._touches.forEach(function (key, touch) {
  44841. if (touch.pointerId === _this._joystickPointerID) {
  44842. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 64, _this._joystickPointerStartPos.y - 64, 128, 128);
  44843. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 42, _this._joystickPreviousPointerPos.y - 42, 84, 84);
  44844. VirtualJoystick.vjCanvasContext.beginPath();
  44845. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  44846. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  44847. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  44848. VirtualJoystick.vjCanvasContext.stroke();
  44849. VirtualJoystick.vjCanvasContext.closePath();
  44850. VirtualJoystick.vjCanvasContext.beginPath();
  44851. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  44852. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  44853. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  44854. VirtualJoystick.vjCanvasContext.stroke();
  44855. VirtualJoystick.vjCanvasContext.closePath();
  44856. VirtualJoystick.vjCanvasContext.beginPath();
  44857. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  44858. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  44859. VirtualJoystick.vjCanvasContext.stroke();
  44860. VirtualJoystick.vjCanvasContext.closePath();
  44861. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  44862. }
  44863. else {
  44864. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  44865. VirtualJoystick.vjCanvasContext.beginPath();
  44866. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  44867. VirtualJoystick.vjCanvasContext.beginPath();
  44868. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  44869. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  44870. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  44871. VirtualJoystick.vjCanvasContext.stroke();
  44872. VirtualJoystick.vjCanvasContext.closePath();
  44873. touch.prevX = touch.x;
  44874. touch.prevY = touch.y;
  44875. }
  44876. ;
  44877. });
  44878. }
  44879. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  44880. };
  44881. VirtualJoystick.prototype.releaseCanvas = function () {
  44882. if (VirtualJoystick.vjCanvas) {
  44883. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  44884. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  44885. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  44886. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  44887. window.removeEventListener("resize", this._onResize);
  44888. document.body.removeChild(VirtualJoystick.vjCanvas);
  44889. VirtualJoystick.vjCanvas = null;
  44890. }
  44891. };
  44892. return VirtualJoystick;
  44893. }());
  44894. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  44895. VirtualJoystick._globalJoystickIndex = 0;
  44896. BABYLON.VirtualJoystick = VirtualJoystick;
  44897. })(BABYLON || (BABYLON = {}));
  44898. //# sourceMappingURL=babylon.virtualJoystick.js.map
  44899. var BABYLON;
  44900. (function (BABYLON) {
  44901. // We're mainly based on the logic defined into the FreeCamera code
  44902. var VirtualJoysticksCamera = (function (_super) {
  44903. __extends(VirtualJoysticksCamera, _super);
  44904. function VirtualJoysticksCamera(name, position, scene) {
  44905. var _this = _super.call(this, name, position, scene) || this;
  44906. _this.inputs.addVirtualJoystick();
  44907. return _this;
  44908. }
  44909. VirtualJoysticksCamera.prototype.getClassName = function () {
  44910. return "VirtualJoysticksCamera";
  44911. };
  44912. return VirtualJoysticksCamera;
  44913. }(BABYLON.FreeCamera));
  44914. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  44915. })(BABYLON || (BABYLON = {}));
  44916. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  44917. var BABYLON;
  44918. (function (BABYLON) {
  44919. var FreeCameraVirtualJoystickInput = (function () {
  44920. function FreeCameraVirtualJoystickInput() {
  44921. }
  44922. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  44923. return this._leftjoystick;
  44924. };
  44925. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  44926. return this._rightjoystick;
  44927. };
  44928. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  44929. if (this._leftjoystick) {
  44930. var camera = this.camera;
  44931. var speed = camera._computeLocalCameraSpeed() * 50;
  44932. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  44933. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  44934. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  44935. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  44936. if (!this._leftjoystick.pressed) {
  44937. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  44938. }
  44939. if (!this._rightjoystick.pressed) {
  44940. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  44941. }
  44942. }
  44943. };
  44944. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  44945. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  44946. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  44947. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  44948. this._leftjoystick.setJoystickSensibility(0.15);
  44949. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  44950. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  44951. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  44952. this._rightjoystick.reverseUpDown = true;
  44953. this._rightjoystick.setJoystickSensibility(0.05);
  44954. this._rightjoystick.setJoystickColor("yellow");
  44955. };
  44956. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  44957. this._leftjoystick.releaseCanvas();
  44958. this._rightjoystick.releaseCanvas();
  44959. };
  44960. FreeCameraVirtualJoystickInput.prototype.getTypeName = function () {
  44961. return "FreeCameraVirtualJoystickInput";
  44962. };
  44963. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  44964. return "virtualJoystick";
  44965. };
  44966. return FreeCameraVirtualJoystickInput;
  44967. }());
  44968. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  44969. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  44970. })(BABYLON || (BABYLON = {}));
  44971. //# sourceMappingURL=babylon.freecamera.input.virtualjoystick.js.map
  44972. var BABYLON;
  44973. (function (BABYLON) {
  44974. var AnaglyphPostProcess = (function (_super) {
  44975. __extends(AnaglyphPostProcess, _super);
  44976. function AnaglyphPostProcess(name, options, rigCameras, samplingMode, engine, reusable) {
  44977. var _this = _super.call(this, name, "anaglyph", null, ["leftSampler"], options, rigCameras[1], samplingMode, engine, reusable) || this;
  44978. _this._passedProcess = rigCameras[0]._rigPostProcess;
  44979. _this.onApplyObservable.add(function (effect) {
  44980. effect.setTextureFromPostProcess("leftSampler", _this._passedProcess);
  44981. });
  44982. return _this;
  44983. }
  44984. return AnaglyphPostProcess;
  44985. }(BABYLON.PostProcess));
  44986. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  44987. })(BABYLON || (BABYLON = {}));
  44988. //# sourceMappingURL=babylon.anaglyphPostProcess.js.map
  44989. var BABYLON;
  44990. (function (BABYLON) {
  44991. var OutlineRenderer = (function () {
  44992. function OutlineRenderer(scene) {
  44993. this._scene = scene;
  44994. }
  44995. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  44996. var _this = this;
  44997. if (useOverlay === void 0) { useOverlay = false; }
  44998. var scene = this._scene;
  44999. var engine = this._scene.getEngine();
  45000. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  45001. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  45002. return;
  45003. }
  45004. var mesh = subMesh.getRenderingMesh();
  45005. var material = subMesh.getMaterial();
  45006. engine.enableEffect(this._effect);
  45007. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  45008. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : 1.0);
  45009. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  45010. // Bones
  45011. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  45012. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  45013. }
  45014. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  45015. // Alpha test
  45016. if (material && material.needAlphaTesting()) {
  45017. var alphaTexture = material.getAlphaTestTexture();
  45018. this._effect.setTexture("diffuseSampler", alphaTexture);
  45019. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  45020. }
  45021. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  45022. };
  45023. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  45024. var defines = [];
  45025. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  45026. var mesh = subMesh.getMesh();
  45027. var material = subMesh.getMaterial();
  45028. // Alpha test
  45029. if (material && material.needAlphaTesting()) {
  45030. defines.push("#define ALPHATEST");
  45031. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  45032. attribs.push(BABYLON.VertexBuffer.UVKind);
  45033. defines.push("#define UV1");
  45034. }
  45035. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  45036. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  45037. defines.push("#define UV2");
  45038. }
  45039. }
  45040. // Bones
  45041. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  45042. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  45043. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  45044. if (mesh.numBoneInfluencers > 4) {
  45045. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  45046. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  45047. }
  45048. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  45049. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  45050. }
  45051. else {
  45052. defines.push("#define NUM_BONE_INFLUENCERS 0");
  45053. }
  45054. // Instances
  45055. if (useInstances) {
  45056. defines.push("#define INSTANCES");
  45057. attribs.push("world0");
  45058. attribs.push("world1");
  45059. attribs.push("world2");
  45060. attribs.push("world3");
  45061. }
  45062. // Get correct effect
  45063. var join = defines.join("\n");
  45064. if (this._cachedDefines !== join) {
  45065. this._cachedDefines = join;
  45066. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color"], ["diffuseSampler"], join);
  45067. }
  45068. return this._effect.isReady();
  45069. };
  45070. return OutlineRenderer;
  45071. }());
  45072. BABYLON.OutlineRenderer = OutlineRenderer;
  45073. })(BABYLON || (BABYLON = {}));
  45074. //# sourceMappingURL=babylon.outlineRenderer.js.map
  45075. var BABYLON;
  45076. (function (BABYLON) {
  45077. var MeshAssetTask = (function () {
  45078. function MeshAssetTask(name, meshesNames, rootUrl, sceneFilename) {
  45079. this.name = name;
  45080. this.meshesNames = meshesNames;
  45081. this.rootUrl = rootUrl;
  45082. this.sceneFilename = sceneFilename;
  45083. this.isCompleted = false;
  45084. }
  45085. MeshAssetTask.prototype.run = function (scene, onSuccess, onError) {
  45086. var _this = this;
  45087. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  45088. _this.loadedMeshes = meshes;
  45089. _this.loadedParticleSystems = particleSystems;
  45090. _this.loadedSkeletons = skeletons;
  45091. _this.isCompleted = true;
  45092. if (_this.onSuccess) {
  45093. _this.onSuccess(_this);
  45094. }
  45095. onSuccess();
  45096. }, null, function () {
  45097. if (_this.onError) {
  45098. _this.onError(_this);
  45099. }
  45100. onError();
  45101. });
  45102. };
  45103. return MeshAssetTask;
  45104. }());
  45105. BABYLON.MeshAssetTask = MeshAssetTask;
  45106. var TextFileAssetTask = (function () {
  45107. function TextFileAssetTask(name, url) {
  45108. this.name = name;
  45109. this.url = url;
  45110. this.isCompleted = false;
  45111. }
  45112. TextFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  45113. var _this = this;
  45114. BABYLON.Tools.LoadFile(this.url, function (data) {
  45115. _this.text = data;
  45116. _this.isCompleted = true;
  45117. if (_this.onSuccess) {
  45118. _this.onSuccess(_this);
  45119. }
  45120. onSuccess();
  45121. }, null, scene.database, false, function () {
  45122. if (_this.onError) {
  45123. _this.onError(_this);
  45124. }
  45125. onError();
  45126. });
  45127. };
  45128. return TextFileAssetTask;
  45129. }());
  45130. BABYLON.TextFileAssetTask = TextFileAssetTask;
  45131. var BinaryFileAssetTask = (function () {
  45132. function BinaryFileAssetTask(name, url) {
  45133. this.name = name;
  45134. this.url = url;
  45135. this.isCompleted = false;
  45136. }
  45137. BinaryFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  45138. var _this = this;
  45139. BABYLON.Tools.LoadFile(this.url, function (data) {
  45140. _this.data = data;
  45141. _this.isCompleted = true;
  45142. if (_this.onSuccess) {
  45143. _this.onSuccess(_this);
  45144. }
  45145. onSuccess();
  45146. }, null, scene.database, true, function () {
  45147. if (_this.onError) {
  45148. _this.onError(_this);
  45149. }
  45150. onError();
  45151. });
  45152. };
  45153. return BinaryFileAssetTask;
  45154. }());
  45155. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  45156. var ImageAssetTask = (function () {
  45157. function ImageAssetTask(name, url) {
  45158. this.name = name;
  45159. this.url = url;
  45160. this.isCompleted = false;
  45161. }
  45162. ImageAssetTask.prototype.run = function (scene, onSuccess, onError) {
  45163. var _this = this;
  45164. var img = new Image();
  45165. BABYLON.Tools.SetCorsBehavior(this.url, img);
  45166. img.onload = function () {
  45167. _this.image = img;
  45168. _this.isCompleted = true;
  45169. if (_this.onSuccess) {
  45170. _this.onSuccess(_this);
  45171. }
  45172. onSuccess();
  45173. };
  45174. img.onerror = function () {
  45175. if (_this.onError) {
  45176. _this.onError(_this);
  45177. }
  45178. onError();
  45179. };
  45180. img.src = this.url;
  45181. };
  45182. return ImageAssetTask;
  45183. }());
  45184. BABYLON.ImageAssetTask = ImageAssetTask;
  45185. var TextureAssetTask = (function () {
  45186. function TextureAssetTask(name, url, noMipmap, invertY, samplingMode) {
  45187. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  45188. this.name = name;
  45189. this.url = url;
  45190. this.noMipmap = noMipmap;
  45191. this.invertY = invertY;
  45192. this.samplingMode = samplingMode;
  45193. this.isCompleted = false;
  45194. }
  45195. TextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  45196. var _this = this;
  45197. var onload = function () {
  45198. _this.isCompleted = true;
  45199. if (_this.onSuccess) {
  45200. _this.onSuccess(_this);
  45201. }
  45202. onSuccess();
  45203. };
  45204. var onerror = function () {
  45205. if (_this.onError) {
  45206. _this.onError(_this);
  45207. }
  45208. onError();
  45209. };
  45210. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  45211. };
  45212. return TextureAssetTask;
  45213. }());
  45214. BABYLON.TextureAssetTask = TextureAssetTask;
  45215. var CubeTextureAssetTask = (function () {
  45216. function CubeTextureAssetTask(name, url, extensions, noMipmap, files) {
  45217. this.name = name;
  45218. this.url = url;
  45219. this.extensions = extensions;
  45220. this.noMipmap = noMipmap;
  45221. this.files = files;
  45222. this.isCompleted = false;
  45223. }
  45224. CubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  45225. var _this = this;
  45226. var onload = function () {
  45227. _this.isCompleted = true;
  45228. if (_this.onSuccess) {
  45229. _this.onSuccess(_this);
  45230. }
  45231. onSuccess();
  45232. };
  45233. var onerror = function () {
  45234. if (_this.onError) {
  45235. _this.onError(_this);
  45236. }
  45237. onError();
  45238. };
  45239. this.texture = new BABYLON.CubeTexture(this.url, scene, this.extensions, this.noMipmap, this.files, onload, onerror);
  45240. };
  45241. return CubeTextureAssetTask;
  45242. }());
  45243. BABYLON.CubeTextureAssetTask = CubeTextureAssetTask;
  45244. var AssetsManager = (function () {
  45245. function AssetsManager(scene) {
  45246. this.tasks = new Array();
  45247. this.waitingTasksCount = 0;
  45248. this.useDefaultLoadingScreen = true;
  45249. this._scene = scene;
  45250. }
  45251. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  45252. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  45253. this.tasks.push(task);
  45254. return task;
  45255. };
  45256. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  45257. var task = new TextFileAssetTask(taskName, url);
  45258. this.tasks.push(task);
  45259. return task;
  45260. };
  45261. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  45262. var task = new BinaryFileAssetTask(taskName, url);
  45263. this.tasks.push(task);
  45264. return task;
  45265. };
  45266. AssetsManager.prototype.addImageTask = function (taskName, url) {
  45267. var task = new ImageAssetTask(taskName, url);
  45268. this.tasks.push(task);
  45269. return task;
  45270. };
  45271. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  45272. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  45273. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  45274. this.tasks.push(task);
  45275. return task;
  45276. };
  45277. AssetsManager.prototype._decreaseWaitingTasksCount = function () {
  45278. this.waitingTasksCount--;
  45279. if (this.waitingTasksCount === 0) {
  45280. if (this.onFinish) {
  45281. this.onFinish(this.tasks);
  45282. }
  45283. this._scene.getEngine().hideLoadingUI();
  45284. }
  45285. };
  45286. AssetsManager.prototype._runTask = function (task) {
  45287. var _this = this;
  45288. task.run(this._scene, function () {
  45289. if (_this.onTaskSuccess) {
  45290. _this.onTaskSuccess(task);
  45291. }
  45292. _this._decreaseWaitingTasksCount();
  45293. }, function () {
  45294. if (_this.onTaskError) {
  45295. _this.onTaskError(task);
  45296. }
  45297. _this._decreaseWaitingTasksCount();
  45298. });
  45299. };
  45300. AssetsManager.prototype.reset = function () {
  45301. this.tasks = new Array();
  45302. return this;
  45303. };
  45304. AssetsManager.prototype.load = function () {
  45305. this.waitingTasksCount = this.tasks.length;
  45306. if (this.waitingTasksCount === 0) {
  45307. if (this.onFinish) {
  45308. this.onFinish(this.tasks);
  45309. }
  45310. return this;
  45311. }
  45312. if (this.useDefaultLoadingScreen) {
  45313. this._scene.getEngine().displayLoadingUI();
  45314. }
  45315. for (var index = 0; index < this.tasks.length; index++) {
  45316. var task = this.tasks[index];
  45317. this._runTask(task);
  45318. }
  45319. return this;
  45320. };
  45321. return AssetsManager;
  45322. }());
  45323. BABYLON.AssetsManager = AssetsManager;
  45324. })(BABYLON || (BABYLON = {}));
  45325. //# sourceMappingURL=babylon.assetsManager.js.map
  45326. var BABYLON;
  45327. (function (BABYLON) {
  45328. var VRCameraMetrics = (function () {
  45329. function VRCameraMetrics() {
  45330. this.compensateDistortion = true;
  45331. }
  45332. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  45333. get: function () {
  45334. return this.hResolution / (2 * this.vResolution);
  45335. },
  45336. enumerable: true,
  45337. configurable: true
  45338. });
  45339. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  45340. get: function () {
  45341. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  45342. },
  45343. enumerable: true,
  45344. configurable: true
  45345. });
  45346. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  45347. get: function () {
  45348. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  45349. var h = (4 * meters) / this.hScreenSize;
  45350. return BABYLON.Matrix.Translation(h, 0, 0);
  45351. },
  45352. enumerable: true,
  45353. configurable: true
  45354. });
  45355. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  45356. get: function () {
  45357. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  45358. var h = (4 * meters) / this.hScreenSize;
  45359. return BABYLON.Matrix.Translation(-h, 0, 0);
  45360. },
  45361. enumerable: true,
  45362. configurable: true
  45363. });
  45364. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  45365. get: function () {
  45366. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  45367. },
  45368. enumerable: true,
  45369. configurable: true
  45370. });
  45371. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  45372. get: function () {
  45373. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  45374. },
  45375. enumerable: true,
  45376. configurable: true
  45377. });
  45378. VRCameraMetrics.GetDefault = function () {
  45379. var result = new VRCameraMetrics();
  45380. result.hResolution = 1280;
  45381. result.vResolution = 800;
  45382. result.hScreenSize = 0.149759993;
  45383. result.vScreenSize = 0.0935999975;
  45384. result.vScreenCenter = 0.0467999987;
  45385. result.eyeToScreenDistance = 0.0410000011;
  45386. result.lensSeparationDistance = 0.0635000020;
  45387. result.interpupillaryDistance = 0.0640000030;
  45388. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  45389. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  45390. result.postProcessScaleFactor = 1.714605507808412;
  45391. result.lensCenterOffset = 0.151976421;
  45392. return result;
  45393. };
  45394. return VRCameraMetrics;
  45395. }());
  45396. BABYLON.VRCameraMetrics = VRCameraMetrics;
  45397. })(BABYLON || (BABYLON = {}));
  45398. //# sourceMappingURL=babylon.vrCameraMetrics.js.map
  45399. var BABYLON;
  45400. (function (BABYLON) {
  45401. var WebVRFreeCamera = (function (_super) {
  45402. __extends(WebVRFreeCamera, _super);
  45403. function WebVRFreeCamera(name, position, scene, compensateDistortion, webVROptions) {
  45404. if (compensateDistortion === void 0) { compensateDistortion = false; }
  45405. if (webVROptions === void 0) { webVROptions = {}; }
  45406. var _this = _super.call(this, name, position, scene) || this;
  45407. _this.webVROptions = webVROptions;
  45408. _this._vrDevice = null;
  45409. _this._cacheState = null;
  45410. _this._vrEnabled = false;
  45411. _this._attached = false;
  45412. //using the position provided as the current position offset
  45413. _this._positionOffset = position;
  45414. //enable VR
  45415. _this.getEngine().initWebVR();
  45416. if (!_this.getEngine().vrDisplaysPromise) {
  45417. BABYLON.Tools.Error("WebVR is not enabled on your browser");
  45418. }
  45419. else {
  45420. //TODO get the metrics updated using the device's eye parameters!
  45421. //TODO also check that the device has the right capabilities!
  45422. _this._frameData = new VRFrameData();
  45423. _this.getEngine().vrDisplaysPromise.then(function (devices) {
  45424. if (devices.length > 0) {
  45425. _this._vrEnabled = true;
  45426. if (_this.webVROptions.displayName) {
  45427. var found = devices.some(function (device) {
  45428. if (device.displayName === _this.webVROptions.displayName) {
  45429. _this._vrDevice = device;
  45430. return true;
  45431. }
  45432. else {
  45433. return false;
  45434. }
  45435. });
  45436. if (!found) {
  45437. _this._vrDevice = devices[0];
  45438. BABYLON.Tools.Warn("Display " + _this.webVROptions.displayName + " was not found. Using " + _this._vrDevice.displayName);
  45439. }
  45440. }
  45441. else {
  45442. //choose the first one
  45443. _this._vrDevice = devices[0];
  45444. }
  45445. //reset the rig parameters.
  45446. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_WEBVR, { vrDisplay: _this._vrDevice, frameData: _this._frameData });
  45447. if (_this._attached) {
  45448. _this.getEngine().enableVR(_this._vrDevice);
  45449. }
  45450. }
  45451. else {
  45452. BABYLON.Tools.Error("No WebVR devices found!");
  45453. }
  45454. });
  45455. }
  45456. _this.rotationQuaternion = new BABYLON.Quaternion();
  45457. _this._quaternionCache = new BABYLON.Quaternion();
  45458. return _this;
  45459. }
  45460. WebVRFreeCamera.prototype._checkInputs = function () {
  45461. if (this._vrEnabled && this._vrDevice.getFrameData(this._frameData)) {
  45462. var currentPost = this._frameData.pose;
  45463. //make sure we have data
  45464. if (currentPost && currentPost.orientation) {
  45465. this._cacheState = currentPost;
  45466. this.rotationQuaternion.copyFromFloats(this._cacheState.orientation[0], this._cacheState.orientation[1], -this._cacheState.orientation[2], -this._cacheState.orientation[3]);
  45467. if (this.webVROptions.trackPosition && this._cacheState.position) {
  45468. this.position.copyFromFloats(this._cacheState.position[0], this._cacheState.position[1], -this._cacheState.position[2]);
  45469. //scale the position accordingly
  45470. this.webVROptions.positionScale && this.position.scaleInPlace(this.webVROptions.positionScale);
  45471. //add the position offset
  45472. this.position.addInPlace(this._positionOffset);
  45473. }
  45474. }
  45475. }
  45476. _super.prototype._checkInputs.call(this);
  45477. };
  45478. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  45479. _super.prototype.attachControl.call(this, element, noPreventDefault);
  45480. this._attached = true;
  45481. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  45482. if (this._vrEnabled) {
  45483. this.getEngine().enableVR(this._vrDevice);
  45484. }
  45485. };
  45486. WebVRFreeCamera.prototype.detachControl = function (element) {
  45487. _super.prototype.detachControl.call(this, element);
  45488. this._vrEnabled = false;
  45489. this._attached = false;
  45490. this.getEngine().disableVR();
  45491. };
  45492. WebVRFreeCamera.prototype.requestVRFullscreen = function (requestPointerlock) {
  45493. //Backwards comp.
  45494. BABYLON.Tools.Warn("requestVRFullscreen is deprecated. call attachControl() to start sending frames to the VR display.");
  45495. //this.getEngine().switchFullscreen(requestPointerlock);
  45496. };
  45497. WebVRFreeCamera.prototype.getClassName = function () {
  45498. return "WebVRFreeCamera";
  45499. };
  45500. WebVRFreeCamera.prototype.resetToCurrentRotation = function () {
  45501. //uses the vrDisplay's "resetPose()".
  45502. //pitch and roll won't be affected.
  45503. this._vrDevice.resetPose();
  45504. };
  45505. /**
  45506. *
  45507. * Set the position offset of the VR camera
  45508. * The offset will be added to the WebVR pose, after scaling it (if set).
  45509. *
  45510. * @param {Vector3} [newPosition] an optional new position. if not provided, the current camera position will be used.
  45511. *
  45512. * @memberOf WebVRFreeCamera
  45513. */
  45514. WebVRFreeCamera.prototype.setPositionOffset = function (newPosition) {
  45515. if (newPosition) {
  45516. this._positionOffset = newPosition;
  45517. }
  45518. else {
  45519. this._positionOffset.copyFrom(this.position);
  45520. }
  45521. };
  45522. return WebVRFreeCamera;
  45523. }(BABYLON.FreeCamera));
  45524. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  45525. })(BABYLON || (BABYLON = {}));
  45526. //# sourceMappingURL=babylon.webVRCamera.js.map
  45527. var BABYLON;
  45528. (function (BABYLON) {
  45529. // Standard optimizations
  45530. var SceneOptimization = (function () {
  45531. function SceneOptimization(priority) {
  45532. if (priority === void 0) { priority = 0; }
  45533. this.priority = priority;
  45534. this.apply = function (scene) {
  45535. return true; // Return true if everything that can be done was applied
  45536. };
  45537. }
  45538. return SceneOptimization;
  45539. }());
  45540. BABYLON.SceneOptimization = SceneOptimization;
  45541. var TextureOptimization = (function (_super) {
  45542. __extends(TextureOptimization, _super);
  45543. function TextureOptimization(priority, maximumSize) {
  45544. if (priority === void 0) { priority = 0; }
  45545. if (maximumSize === void 0) { maximumSize = 1024; }
  45546. var _this = _super.call(this, priority) || this;
  45547. _this.priority = priority;
  45548. _this.maximumSize = maximumSize;
  45549. _this.apply = function (scene) {
  45550. var allDone = true;
  45551. for (var index = 0; index < scene.textures.length; index++) {
  45552. var texture = scene.textures[index];
  45553. if (!texture.canRescale) {
  45554. continue;
  45555. }
  45556. var currentSize = texture.getSize();
  45557. var maxDimension = Math.max(currentSize.width, currentSize.height);
  45558. if (maxDimension > _this.maximumSize) {
  45559. texture.scale(0.5);
  45560. allDone = false;
  45561. }
  45562. }
  45563. return allDone;
  45564. };
  45565. return _this;
  45566. }
  45567. return TextureOptimization;
  45568. }(SceneOptimization));
  45569. BABYLON.TextureOptimization = TextureOptimization;
  45570. var HardwareScalingOptimization = (function (_super) {
  45571. __extends(HardwareScalingOptimization, _super);
  45572. function HardwareScalingOptimization(priority, maximumScale) {
  45573. if (priority === void 0) { priority = 0; }
  45574. if (maximumScale === void 0) { maximumScale = 2; }
  45575. var _this = _super.call(this, priority) || this;
  45576. _this.priority = priority;
  45577. _this.maximumScale = maximumScale;
  45578. _this._currentScale = 1;
  45579. _this.apply = function (scene) {
  45580. _this._currentScale++;
  45581. scene.getEngine().setHardwareScalingLevel(_this._currentScale);
  45582. return _this._currentScale >= _this.maximumScale;
  45583. };
  45584. return _this;
  45585. }
  45586. return HardwareScalingOptimization;
  45587. }(SceneOptimization));
  45588. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  45589. var ShadowsOptimization = (function (_super) {
  45590. __extends(ShadowsOptimization, _super);
  45591. function ShadowsOptimization() {
  45592. var _this = _super.apply(this, arguments) || this;
  45593. _this.apply = function (scene) {
  45594. scene.shadowsEnabled = false;
  45595. return true;
  45596. };
  45597. return _this;
  45598. }
  45599. return ShadowsOptimization;
  45600. }(SceneOptimization));
  45601. BABYLON.ShadowsOptimization = ShadowsOptimization;
  45602. var PostProcessesOptimization = (function (_super) {
  45603. __extends(PostProcessesOptimization, _super);
  45604. function PostProcessesOptimization() {
  45605. var _this = _super.apply(this, arguments) || this;
  45606. _this.apply = function (scene) {
  45607. scene.postProcessesEnabled = false;
  45608. return true;
  45609. };
  45610. return _this;
  45611. }
  45612. return PostProcessesOptimization;
  45613. }(SceneOptimization));
  45614. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  45615. var LensFlaresOptimization = (function (_super) {
  45616. __extends(LensFlaresOptimization, _super);
  45617. function LensFlaresOptimization() {
  45618. var _this = _super.apply(this, arguments) || this;
  45619. _this.apply = function (scene) {
  45620. scene.lensFlaresEnabled = false;
  45621. return true;
  45622. };
  45623. return _this;
  45624. }
  45625. return LensFlaresOptimization;
  45626. }(SceneOptimization));
  45627. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  45628. var ParticlesOptimization = (function (_super) {
  45629. __extends(ParticlesOptimization, _super);
  45630. function ParticlesOptimization() {
  45631. var _this = _super.apply(this, arguments) || this;
  45632. _this.apply = function (scene) {
  45633. scene.particlesEnabled = false;
  45634. return true;
  45635. };
  45636. return _this;
  45637. }
  45638. return ParticlesOptimization;
  45639. }(SceneOptimization));
  45640. BABYLON.ParticlesOptimization = ParticlesOptimization;
  45641. var RenderTargetsOptimization = (function (_super) {
  45642. __extends(RenderTargetsOptimization, _super);
  45643. function RenderTargetsOptimization() {
  45644. var _this = _super.apply(this, arguments) || this;
  45645. _this.apply = function (scene) {
  45646. scene.renderTargetsEnabled = false;
  45647. return true;
  45648. };
  45649. return _this;
  45650. }
  45651. return RenderTargetsOptimization;
  45652. }(SceneOptimization));
  45653. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  45654. var MergeMeshesOptimization = (function (_super) {
  45655. __extends(MergeMeshesOptimization, _super);
  45656. function MergeMeshesOptimization() {
  45657. var _this = _super.apply(this, arguments) || this;
  45658. _this._canBeMerged = function (abstractMesh) {
  45659. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  45660. return false;
  45661. }
  45662. var mesh = abstractMesh;
  45663. if (!mesh.isVisible || !mesh.isEnabled()) {
  45664. return false;
  45665. }
  45666. if (mesh.instances.length > 0) {
  45667. return false;
  45668. }
  45669. if (mesh.skeleton || mesh.hasLODLevels) {
  45670. return false;
  45671. }
  45672. if (mesh.parent) {
  45673. return false;
  45674. }
  45675. return true;
  45676. };
  45677. _this.apply = function (scene, updateSelectionTree) {
  45678. var globalPool = scene.meshes.slice(0);
  45679. var globalLength = globalPool.length;
  45680. for (var index = 0; index < globalLength; index++) {
  45681. var currentPool = new Array();
  45682. var current = globalPool[index];
  45683. // Checks
  45684. if (!_this._canBeMerged(current)) {
  45685. continue;
  45686. }
  45687. currentPool.push(current);
  45688. // Find compatible meshes
  45689. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  45690. var otherMesh = globalPool[subIndex];
  45691. if (!_this._canBeMerged(otherMesh)) {
  45692. continue;
  45693. }
  45694. if (otherMesh.material !== current.material) {
  45695. continue;
  45696. }
  45697. if (otherMesh.checkCollisions !== current.checkCollisions) {
  45698. continue;
  45699. }
  45700. currentPool.push(otherMesh);
  45701. globalLength--;
  45702. globalPool.splice(subIndex, 1);
  45703. subIndex--;
  45704. }
  45705. if (currentPool.length < 2) {
  45706. continue;
  45707. }
  45708. // Merge meshes
  45709. BABYLON.Mesh.MergeMeshes(currentPool);
  45710. }
  45711. if (updateSelectionTree != undefined) {
  45712. if (updateSelectionTree) {
  45713. scene.createOrUpdateSelectionOctree();
  45714. }
  45715. }
  45716. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  45717. scene.createOrUpdateSelectionOctree();
  45718. }
  45719. return true;
  45720. };
  45721. return _this;
  45722. }
  45723. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  45724. get: function () {
  45725. return MergeMeshesOptimization._UpdateSelectionTree;
  45726. },
  45727. set: function (value) {
  45728. MergeMeshesOptimization._UpdateSelectionTree = value;
  45729. },
  45730. enumerable: true,
  45731. configurable: true
  45732. });
  45733. return MergeMeshesOptimization;
  45734. }(SceneOptimization));
  45735. MergeMeshesOptimization._UpdateSelectionTree = false;
  45736. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  45737. // Options
  45738. var SceneOptimizerOptions = (function () {
  45739. function SceneOptimizerOptions(targetFrameRate, trackerDuration) {
  45740. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  45741. if (trackerDuration === void 0) { trackerDuration = 2000; }
  45742. this.targetFrameRate = targetFrameRate;
  45743. this.trackerDuration = trackerDuration;
  45744. this.optimizations = new Array();
  45745. }
  45746. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  45747. var result = new SceneOptimizerOptions(targetFrameRate);
  45748. var priority = 0;
  45749. result.optimizations.push(new MergeMeshesOptimization(priority));
  45750. result.optimizations.push(new ShadowsOptimization(priority));
  45751. result.optimizations.push(new LensFlaresOptimization(priority));
  45752. // Next priority
  45753. priority++;
  45754. result.optimizations.push(new PostProcessesOptimization(priority));
  45755. result.optimizations.push(new ParticlesOptimization(priority));
  45756. // Next priority
  45757. priority++;
  45758. result.optimizations.push(new TextureOptimization(priority, 1024));
  45759. return result;
  45760. };
  45761. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  45762. var result = new SceneOptimizerOptions(targetFrameRate);
  45763. var priority = 0;
  45764. result.optimizations.push(new MergeMeshesOptimization(priority));
  45765. result.optimizations.push(new ShadowsOptimization(priority));
  45766. result.optimizations.push(new LensFlaresOptimization(priority));
  45767. // Next priority
  45768. priority++;
  45769. result.optimizations.push(new PostProcessesOptimization(priority));
  45770. result.optimizations.push(new ParticlesOptimization(priority));
  45771. // Next priority
  45772. priority++;
  45773. result.optimizations.push(new TextureOptimization(priority, 512));
  45774. // Next priority
  45775. priority++;
  45776. result.optimizations.push(new RenderTargetsOptimization(priority));
  45777. // Next priority
  45778. priority++;
  45779. result.optimizations.push(new HardwareScalingOptimization(priority, 2));
  45780. return result;
  45781. };
  45782. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  45783. var result = new SceneOptimizerOptions(targetFrameRate);
  45784. var priority = 0;
  45785. result.optimizations.push(new MergeMeshesOptimization(priority));
  45786. result.optimizations.push(new ShadowsOptimization(priority));
  45787. result.optimizations.push(new LensFlaresOptimization(priority));
  45788. // Next priority
  45789. priority++;
  45790. result.optimizations.push(new PostProcessesOptimization(priority));
  45791. result.optimizations.push(new ParticlesOptimization(priority));
  45792. // Next priority
  45793. priority++;
  45794. result.optimizations.push(new TextureOptimization(priority, 256));
  45795. // Next priority
  45796. priority++;
  45797. result.optimizations.push(new RenderTargetsOptimization(priority));
  45798. // Next priority
  45799. priority++;
  45800. result.optimizations.push(new HardwareScalingOptimization(priority, 4));
  45801. return result;
  45802. };
  45803. return SceneOptimizerOptions;
  45804. }());
  45805. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  45806. // Scene optimizer tool
  45807. var SceneOptimizer = (function () {
  45808. function SceneOptimizer() {
  45809. }
  45810. SceneOptimizer._CheckCurrentState = function (scene, options, currentPriorityLevel, onSuccess, onFailure) {
  45811. // TODO: add an epsilon
  45812. if (scene.getEngine().getFps() >= options.targetFrameRate) {
  45813. if (onSuccess) {
  45814. onSuccess();
  45815. }
  45816. return;
  45817. }
  45818. // Apply current level of optimizations
  45819. var allDone = true;
  45820. var noOptimizationApplied = true;
  45821. for (var index = 0; index < options.optimizations.length; index++) {
  45822. var optimization = options.optimizations[index];
  45823. if (optimization.priority === currentPriorityLevel) {
  45824. noOptimizationApplied = false;
  45825. allDone = allDone && optimization.apply(scene);
  45826. }
  45827. }
  45828. // If no optimization was applied, this is a failure :(
  45829. if (noOptimizationApplied) {
  45830. if (onFailure) {
  45831. onFailure();
  45832. }
  45833. return;
  45834. }
  45835. // If all optimizations were done, move to next level
  45836. if (allDone) {
  45837. currentPriorityLevel++;
  45838. }
  45839. // Let's the system running for a specific amount of time before checking FPS
  45840. scene.executeWhenReady(function () {
  45841. setTimeout(function () {
  45842. SceneOptimizer._CheckCurrentState(scene, options, currentPriorityLevel, onSuccess, onFailure);
  45843. }, options.trackerDuration);
  45844. });
  45845. };
  45846. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  45847. if (!options) {
  45848. options = SceneOptimizerOptions.ModerateDegradationAllowed();
  45849. }
  45850. // Let's the system running for a specific amount of time before checking FPS
  45851. scene.executeWhenReady(function () {
  45852. setTimeout(function () {
  45853. SceneOptimizer._CheckCurrentState(scene, options, 0, onSuccess, onFailure);
  45854. }, options.trackerDuration);
  45855. });
  45856. };
  45857. return SceneOptimizer;
  45858. }());
  45859. BABYLON.SceneOptimizer = SceneOptimizer;
  45860. })(BABYLON || (BABYLON = {}));
  45861. //# sourceMappingURL=babylon.sceneOptimizer.js.map
  45862. var BABYLON;
  45863. (function (BABYLON) {
  45864. var Internals;
  45865. (function (Internals) {
  45866. var MeshLODLevel = (function () {
  45867. function MeshLODLevel(distance, mesh) {
  45868. this.distance = distance;
  45869. this.mesh = mesh;
  45870. }
  45871. return MeshLODLevel;
  45872. }());
  45873. Internals.MeshLODLevel = MeshLODLevel;
  45874. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  45875. })(BABYLON || (BABYLON = {}));
  45876. //# sourceMappingURL=babylon.meshLODLevel.js.map
  45877. var BABYLON;
  45878. (function (BABYLON) {
  45879. var RawTexture = (function (_super) {
  45880. __extends(RawTexture, _super);
  45881. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode) {
  45882. if (generateMipMaps === void 0) { generateMipMaps = true; }
  45883. if (invertY === void 0) { invertY = false; }
  45884. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  45885. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  45886. _this.format = format;
  45887. _this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode);
  45888. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  45889. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  45890. return _this;
  45891. }
  45892. RawTexture.prototype.update = function (data) {
  45893. this.getScene().getEngine().updateRawTexture(this._texture, data, this.format, this._invertY);
  45894. };
  45895. // Statics
  45896. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  45897. if (generateMipMaps === void 0) { generateMipMaps = true; }
  45898. if (invertY === void 0) { invertY = false; }
  45899. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  45900. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  45901. };
  45902. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  45903. if (generateMipMaps === void 0) { generateMipMaps = true; }
  45904. if (invertY === void 0) { invertY = false; }
  45905. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  45906. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  45907. };
  45908. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  45909. if (generateMipMaps === void 0) { generateMipMaps = true; }
  45910. if (invertY === void 0) { invertY = false; }
  45911. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  45912. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  45913. };
  45914. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  45915. if (generateMipMaps === void 0) { generateMipMaps = true; }
  45916. if (invertY === void 0) { invertY = false; }
  45917. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  45918. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode);
  45919. };
  45920. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  45921. if (generateMipMaps === void 0) { generateMipMaps = true; }
  45922. if (invertY === void 0) { invertY = false; }
  45923. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  45924. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode);
  45925. };
  45926. return RawTexture;
  45927. }(BABYLON.Texture));
  45928. BABYLON.RawTexture = RawTexture;
  45929. })(BABYLON || (BABYLON = {}));
  45930. //# sourceMappingURL=babylon.rawTexture.js.map
  45931. var BABYLON;
  45932. (function (BABYLON) {
  45933. var IndexedVector2 = (function (_super) {
  45934. __extends(IndexedVector2, _super);
  45935. function IndexedVector2(original, index) {
  45936. var _this = _super.call(this, original.x, original.y) || this;
  45937. _this.index = index;
  45938. return _this;
  45939. }
  45940. return IndexedVector2;
  45941. }(BABYLON.Vector2));
  45942. var PolygonPoints = (function () {
  45943. function PolygonPoints() {
  45944. this.elements = new Array();
  45945. }
  45946. PolygonPoints.prototype.add = function (originalPoints) {
  45947. var _this = this;
  45948. var result = new Array();
  45949. originalPoints.forEach(function (point) {
  45950. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  45951. var newPoint = new IndexedVector2(point, _this.elements.length);
  45952. result.push(newPoint);
  45953. _this.elements.push(newPoint);
  45954. }
  45955. });
  45956. return result;
  45957. };
  45958. PolygonPoints.prototype.computeBounds = function () {
  45959. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  45960. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  45961. this.elements.forEach(function (point) {
  45962. // x
  45963. if (point.x < lmin.x) {
  45964. lmin.x = point.x;
  45965. }
  45966. else if (point.x > lmax.x) {
  45967. lmax.x = point.x;
  45968. }
  45969. // y
  45970. if (point.y < lmin.y) {
  45971. lmin.y = point.y;
  45972. }
  45973. else if (point.y > lmax.y) {
  45974. lmax.y = point.y;
  45975. }
  45976. });
  45977. return {
  45978. min: lmin,
  45979. max: lmax,
  45980. width: lmax.x - lmin.x,
  45981. height: lmax.y - lmin.y
  45982. };
  45983. };
  45984. return PolygonPoints;
  45985. }());
  45986. var Polygon = (function () {
  45987. function Polygon() {
  45988. }
  45989. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  45990. return [
  45991. new BABYLON.Vector2(xmin, ymin),
  45992. new BABYLON.Vector2(xmax, ymin),
  45993. new BABYLON.Vector2(xmax, ymax),
  45994. new BABYLON.Vector2(xmin, ymax)
  45995. ];
  45996. };
  45997. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  45998. if (cx === void 0) { cx = 0; }
  45999. if (cy === void 0) { cy = 0; }
  46000. if (numberOfSides === void 0) { numberOfSides = 32; }
  46001. var result = new Array();
  46002. var angle = 0;
  46003. var increment = (Math.PI * 2) / numberOfSides;
  46004. for (var i = 0; i < numberOfSides; i++) {
  46005. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  46006. angle -= increment;
  46007. }
  46008. return result;
  46009. };
  46010. Polygon.Parse = function (input) {
  46011. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  46012. var i, result = [];
  46013. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  46014. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  46015. }
  46016. return result;
  46017. };
  46018. Polygon.StartingAt = function (x, y) {
  46019. return BABYLON.Path2.StartingAt(x, y);
  46020. };
  46021. return Polygon;
  46022. }());
  46023. BABYLON.Polygon = Polygon;
  46024. var PolygonMeshBuilder = (function () {
  46025. function PolygonMeshBuilder(name, contours, scene) {
  46026. this._points = new PolygonPoints();
  46027. this._outlinepoints = new PolygonPoints();
  46028. this._holes = [];
  46029. this._epoints = new Array();
  46030. this._eholes = new Array();
  46031. this._name = name;
  46032. this._scene = scene;
  46033. var points;
  46034. if (contours instanceof BABYLON.Path2) {
  46035. points = contours.getPoints();
  46036. }
  46037. else {
  46038. points = contours;
  46039. }
  46040. this._addToepoint(points);
  46041. this._points.add(points);
  46042. this._outlinepoints.add(points);
  46043. }
  46044. PolygonMeshBuilder.prototype._addToepoint = function (points) {
  46045. for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {
  46046. var p = points_1[_i];
  46047. this._epoints.push(p.x, p.y);
  46048. }
  46049. };
  46050. PolygonMeshBuilder.prototype.addHole = function (hole) {
  46051. this._points.add(hole);
  46052. var holepoints = new PolygonPoints();
  46053. holepoints.add(hole);
  46054. this._holes.push(holepoints);
  46055. this._eholes.push(this._epoints.length / 2);
  46056. this._addToepoint(hole);
  46057. return this;
  46058. };
  46059. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  46060. var _this = this;
  46061. if (updatable === void 0) { updatable = false; }
  46062. var result = new BABYLON.Mesh(this._name, this._scene);
  46063. var normals = [];
  46064. var positions = [];
  46065. var uvs = [];
  46066. var bounds = this._points.computeBounds();
  46067. this._points.elements.forEach(function (p) {
  46068. normals.push(0, 1.0, 0);
  46069. positions.push(p.x, 0, p.y);
  46070. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  46071. });
  46072. var indices = [];
  46073. var res = Earcut.earcut(this._epoints, this._eholes, 2);
  46074. for (var i = 0; i < res.length; i++) {
  46075. indices.push(res[i]);
  46076. }
  46077. if (depth > 0) {
  46078. var positionscount = (positions.length / 3); //get the current pointcount
  46079. this._points.elements.forEach(function (p) {
  46080. normals.push(0, -1.0, 0);
  46081. positions.push(p.x, -depth, p.y);
  46082. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  46083. });
  46084. var totalCount = indices.length;
  46085. for (var i = 0; i < totalCount; i += 3) {
  46086. var i0 = indices[i + 0];
  46087. var i1 = indices[i + 1];
  46088. var i2 = indices[i + 2];
  46089. indices.push(i2 + positionscount);
  46090. indices.push(i1 + positionscount);
  46091. indices.push(i0 + positionscount);
  46092. }
  46093. //Add the sides
  46094. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  46095. this._holes.forEach(function (hole) {
  46096. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  46097. });
  46098. }
  46099. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  46100. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  46101. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  46102. result.setIndices(indices);
  46103. return result;
  46104. };
  46105. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  46106. var StartIndex = positions.length / 3;
  46107. var ulength = 0;
  46108. for (var i = 0; i < points.elements.length; i++) {
  46109. var p = points.elements[i];
  46110. var p1;
  46111. if ((i + 1) > points.elements.length - 1) {
  46112. p1 = points.elements[0];
  46113. }
  46114. else {
  46115. p1 = points.elements[i + 1];
  46116. }
  46117. positions.push(p.x, 0, p.y);
  46118. positions.push(p.x, -depth, p.y);
  46119. positions.push(p1.x, 0, p1.y);
  46120. positions.push(p1.x, -depth, p1.y);
  46121. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  46122. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  46123. var v3 = v2.subtract(v1);
  46124. var v4 = new BABYLON.Vector3(0, 1, 0);
  46125. var vn = BABYLON.Vector3.Cross(v3, v4);
  46126. vn = vn.normalize();
  46127. uvs.push(ulength / bounds.width, 0);
  46128. uvs.push(ulength / bounds.width, 1);
  46129. ulength += v3.length();
  46130. uvs.push((ulength / bounds.width), 0);
  46131. uvs.push((ulength / bounds.width), 1);
  46132. if (!flip) {
  46133. normals.push(-vn.x, -vn.y, -vn.z);
  46134. normals.push(-vn.x, -vn.y, -vn.z);
  46135. normals.push(-vn.x, -vn.y, -vn.z);
  46136. normals.push(-vn.x, -vn.y, -vn.z);
  46137. indices.push(StartIndex);
  46138. indices.push(StartIndex + 1);
  46139. indices.push(StartIndex + 2);
  46140. indices.push(StartIndex + 1);
  46141. indices.push(StartIndex + 3);
  46142. indices.push(StartIndex + 2);
  46143. }
  46144. else {
  46145. normals.push(vn.x, vn.y, vn.z);
  46146. normals.push(vn.x, vn.y, vn.z);
  46147. normals.push(vn.x, vn.y, vn.z);
  46148. normals.push(vn.x, vn.y, vn.z);
  46149. indices.push(StartIndex);
  46150. indices.push(StartIndex + 2);
  46151. indices.push(StartIndex + 1);
  46152. indices.push(StartIndex + 1);
  46153. indices.push(StartIndex + 2);
  46154. indices.push(StartIndex + 3);
  46155. }
  46156. StartIndex += 4;
  46157. }
  46158. ;
  46159. };
  46160. return PolygonMeshBuilder;
  46161. }());
  46162. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  46163. })(BABYLON || (BABYLON = {}));
  46164. //# sourceMappingURL=babylon.polygonMesh.js.map
  46165. var BABYLON;
  46166. (function (BABYLON) {
  46167. var Octree = (function () {
  46168. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  46169. if (maxDepth === void 0) { maxDepth = 2; }
  46170. this.maxDepth = maxDepth;
  46171. this.dynamicContent = new Array();
  46172. this._maxBlockCapacity = maxBlockCapacity || 64;
  46173. this._selectionContent = new BABYLON.SmartArray(1024);
  46174. this._creationFunc = creationFunc;
  46175. }
  46176. // Methods
  46177. Octree.prototype.update = function (worldMin, worldMax, entries) {
  46178. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  46179. };
  46180. Octree.prototype.addMesh = function (entry) {
  46181. for (var index = 0; index < this.blocks.length; index++) {
  46182. var block = this.blocks[index];
  46183. block.addEntry(entry);
  46184. }
  46185. };
  46186. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  46187. this._selectionContent.reset();
  46188. for (var index = 0; index < this.blocks.length; index++) {
  46189. var block = this.blocks[index];
  46190. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  46191. }
  46192. if (allowDuplicate) {
  46193. this._selectionContent.concat(this.dynamicContent);
  46194. }
  46195. else {
  46196. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  46197. }
  46198. return this._selectionContent;
  46199. };
  46200. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  46201. this._selectionContent.reset();
  46202. for (var index = 0; index < this.blocks.length; index++) {
  46203. var block = this.blocks[index];
  46204. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  46205. }
  46206. if (allowDuplicate) {
  46207. this._selectionContent.concat(this.dynamicContent);
  46208. }
  46209. else {
  46210. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  46211. }
  46212. return this._selectionContent;
  46213. };
  46214. Octree.prototype.intersectsRay = function (ray) {
  46215. this._selectionContent.reset();
  46216. for (var index = 0; index < this.blocks.length; index++) {
  46217. var block = this.blocks[index];
  46218. block.intersectsRay(ray, this._selectionContent);
  46219. }
  46220. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  46221. return this._selectionContent;
  46222. };
  46223. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  46224. target.blocks = new Array();
  46225. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  46226. // Segmenting space
  46227. for (var x = 0; x < 2; x++) {
  46228. for (var y = 0; y < 2; y++) {
  46229. for (var z = 0; z < 2; z++) {
  46230. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  46231. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  46232. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  46233. block.addEntries(entries);
  46234. target.blocks.push(block);
  46235. }
  46236. }
  46237. }
  46238. };
  46239. return Octree;
  46240. }());
  46241. Octree.CreationFuncForMeshes = function (entry, block) {
  46242. if (!entry.isBlocked && entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  46243. block.entries.push(entry);
  46244. }
  46245. };
  46246. Octree.CreationFuncForSubMeshes = function (entry, block) {
  46247. if (entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  46248. block.entries.push(entry);
  46249. }
  46250. };
  46251. BABYLON.Octree = Octree;
  46252. })(BABYLON || (BABYLON = {}));
  46253. //# sourceMappingURL=babylon.octree.js.map
  46254. var BABYLON;
  46255. (function (BABYLON) {
  46256. var OctreeBlock = (function () {
  46257. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  46258. this.entries = new Array();
  46259. this._boundingVectors = new Array();
  46260. this._capacity = capacity;
  46261. this._depth = depth;
  46262. this._maxDepth = maxDepth;
  46263. this._creationFunc = creationFunc;
  46264. this._minPoint = minPoint;
  46265. this._maxPoint = maxPoint;
  46266. this._boundingVectors.push(minPoint.clone());
  46267. this._boundingVectors.push(maxPoint.clone());
  46268. this._boundingVectors.push(minPoint.clone());
  46269. this._boundingVectors[2].x = maxPoint.x;
  46270. this._boundingVectors.push(minPoint.clone());
  46271. this._boundingVectors[3].y = maxPoint.y;
  46272. this._boundingVectors.push(minPoint.clone());
  46273. this._boundingVectors[4].z = maxPoint.z;
  46274. this._boundingVectors.push(maxPoint.clone());
  46275. this._boundingVectors[5].z = minPoint.z;
  46276. this._boundingVectors.push(maxPoint.clone());
  46277. this._boundingVectors[6].x = minPoint.x;
  46278. this._boundingVectors.push(maxPoint.clone());
  46279. this._boundingVectors[7].y = minPoint.y;
  46280. }
  46281. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  46282. // Property
  46283. get: function () {
  46284. return this._capacity;
  46285. },
  46286. enumerable: true,
  46287. configurable: true
  46288. });
  46289. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  46290. get: function () {
  46291. return this._minPoint;
  46292. },
  46293. enumerable: true,
  46294. configurable: true
  46295. });
  46296. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  46297. get: function () {
  46298. return this._maxPoint;
  46299. },
  46300. enumerable: true,
  46301. configurable: true
  46302. });
  46303. // Methods
  46304. OctreeBlock.prototype.addEntry = function (entry) {
  46305. if (this.blocks) {
  46306. for (var index = 0; index < this.blocks.length; index++) {
  46307. var block = this.blocks[index];
  46308. block.addEntry(entry);
  46309. }
  46310. return;
  46311. }
  46312. this._creationFunc(entry, this);
  46313. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  46314. this.createInnerBlocks();
  46315. }
  46316. };
  46317. OctreeBlock.prototype.addEntries = function (entries) {
  46318. for (var index = 0; index < entries.length; index++) {
  46319. var mesh = entries[index];
  46320. this.addEntry(mesh);
  46321. }
  46322. };
  46323. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  46324. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  46325. if (this.blocks) {
  46326. for (var index = 0; index < this.blocks.length; index++) {
  46327. var block = this.blocks[index];
  46328. block.select(frustumPlanes, selection, allowDuplicate);
  46329. }
  46330. return;
  46331. }
  46332. if (allowDuplicate) {
  46333. selection.concat(this.entries);
  46334. }
  46335. else {
  46336. selection.concatWithNoDuplicate(this.entries);
  46337. }
  46338. }
  46339. };
  46340. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  46341. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  46342. if (this.blocks) {
  46343. for (var index = 0; index < this.blocks.length; index++) {
  46344. var block = this.blocks[index];
  46345. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  46346. }
  46347. return;
  46348. }
  46349. if (allowDuplicate) {
  46350. selection.concat(this.entries);
  46351. }
  46352. else {
  46353. selection.concatWithNoDuplicate(this.entries);
  46354. }
  46355. }
  46356. };
  46357. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  46358. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  46359. if (this.blocks) {
  46360. for (var index = 0; index < this.blocks.length; index++) {
  46361. var block = this.blocks[index];
  46362. block.intersectsRay(ray, selection);
  46363. }
  46364. return;
  46365. }
  46366. selection.concatWithNoDuplicate(this.entries);
  46367. }
  46368. };
  46369. OctreeBlock.prototype.createInnerBlocks = function () {
  46370. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  46371. };
  46372. return OctreeBlock;
  46373. }());
  46374. BABYLON.OctreeBlock = OctreeBlock;
  46375. })(BABYLON || (BABYLON = {}));
  46376. //# sourceMappingURL=babylon.octreeBlock.js.map
  46377. var BABYLON;
  46378. (function (BABYLON) {
  46379. var BlurPostProcess = (function (_super) {
  46380. __extends(BlurPostProcess, _super);
  46381. function BlurPostProcess(name, direction, blurWidth, options, camera, samplingMode, engine, reusable) {
  46382. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  46383. var _this = _super.call(this, name, "blur", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable) || this;
  46384. _this.direction = direction;
  46385. _this.blurWidth = blurWidth;
  46386. _this.onApplyObservable.add(function (effect) {
  46387. effect.setFloat2("screenSize", _this.width, _this.height);
  46388. effect.setVector2("direction", _this.direction);
  46389. effect.setFloat("blurWidth", _this.blurWidth);
  46390. });
  46391. return _this;
  46392. }
  46393. return BlurPostProcess;
  46394. }(BABYLON.PostProcess));
  46395. BABYLON.BlurPostProcess = BlurPostProcess;
  46396. })(BABYLON || (BABYLON = {}));
  46397. //# sourceMappingURL=babylon.blurPostProcess.js.map
  46398. var BABYLON;
  46399. (function (BABYLON) {
  46400. var RefractionPostProcess = (function (_super) {
  46401. __extends(RefractionPostProcess, _super);
  46402. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, options, camera, samplingMode, engine, reusable) {
  46403. var _this = _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], options, camera, samplingMode, engine, reusable) || this;
  46404. _this.color = color;
  46405. _this.depth = depth;
  46406. _this.colorLevel = colorLevel;
  46407. _this.onActivateObservable.add(function (cam) {
  46408. _this._refRexture = _this._refRexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  46409. });
  46410. _this.onApplyObservable.add(function (effect) {
  46411. effect.setColor3("baseColor", _this.color);
  46412. effect.setFloat("depth", _this.depth);
  46413. effect.setFloat("colorLevel", _this.colorLevel);
  46414. effect.setTexture("refractionSampler", _this._refRexture);
  46415. });
  46416. return _this;
  46417. }
  46418. // Methods
  46419. RefractionPostProcess.prototype.dispose = function (camera) {
  46420. if (this._refRexture) {
  46421. this._refRexture.dispose();
  46422. }
  46423. _super.prototype.dispose.call(this, camera);
  46424. };
  46425. return RefractionPostProcess;
  46426. }(BABYLON.PostProcess));
  46427. BABYLON.RefractionPostProcess = RefractionPostProcess;
  46428. })(BABYLON || (BABYLON = {}));
  46429. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  46430. var BABYLON;
  46431. (function (BABYLON) {
  46432. var BlackAndWhitePostProcess = (function (_super) {
  46433. __extends(BlackAndWhitePostProcess, _super);
  46434. function BlackAndWhitePostProcess(name, options, camera, samplingMode, engine, reusable) {
  46435. return _super.call(this, name, "blackAndWhite", null, null, options, camera, samplingMode, engine, reusable) || this;
  46436. }
  46437. return BlackAndWhitePostProcess;
  46438. }(BABYLON.PostProcess));
  46439. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  46440. })(BABYLON || (BABYLON = {}));
  46441. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  46442. var BABYLON;
  46443. (function (BABYLON) {
  46444. var ConvolutionPostProcess = (function (_super) {
  46445. __extends(ConvolutionPostProcess, _super);
  46446. function ConvolutionPostProcess(name, kernel, options, camera, samplingMode, engine, reusable) {
  46447. var _this = _super.call(this, name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable) || this;
  46448. _this.kernel = kernel;
  46449. _this.onApply = function (effect) {
  46450. effect.setFloat2("screenSize", _this.width, _this.height);
  46451. effect.setArray("kernel", _this.kernel);
  46452. };
  46453. return _this;
  46454. }
  46455. return ConvolutionPostProcess;
  46456. }(BABYLON.PostProcess));
  46457. // Statics
  46458. // Based on http://en.wikipedia.org/wiki/Kernel_(image_processing)
  46459. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  46460. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  46461. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  46462. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  46463. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  46464. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  46465. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  46466. })(BABYLON || (BABYLON = {}));
  46467. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  46468. var BABYLON;
  46469. (function (BABYLON) {
  46470. var FilterPostProcess = (function (_super) {
  46471. __extends(FilterPostProcess, _super);
  46472. function FilterPostProcess(name, kernelMatrix, options, camera, samplingMode, engine, reusable) {
  46473. var _this = _super.call(this, name, "filter", ["kernelMatrix"], null, options, camera, samplingMode, engine, reusable) || this;
  46474. _this.kernelMatrix = kernelMatrix;
  46475. _this.onApply = function (effect) {
  46476. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  46477. };
  46478. return _this;
  46479. }
  46480. return FilterPostProcess;
  46481. }(BABYLON.PostProcess));
  46482. BABYLON.FilterPostProcess = FilterPostProcess;
  46483. })(BABYLON || (BABYLON = {}));
  46484. //# sourceMappingURL=babylon.filterPostProcess.js.map
  46485. var BABYLON;
  46486. (function (BABYLON) {
  46487. var FxaaPostProcess = (function (_super) {
  46488. __extends(FxaaPostProcess, _super);
  46489. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable) {
  46490. var _this = _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode, engine, reusable) || this;
  46491. _this.onSizeChangedObservable.add(function () {
  46492. _this.texelWidth = 1.0 / _this.width;
  46493. _this.texelHeight = 1.0 / _this.height;
  46494. });
  46495. _this.onApplyObservable.add(function (effect) {
  46496. effect.setFloat2("texelSize", _this.texelWidth, _this.texelHeight);
  46497. });
  46498. return _this;
  46499. }
  46500. return FxaaPostProcess;
  46501. }(BABYLON.PostProcess));
  46502. BABYLON.FxaaPostProcess = FxaaPostProcess;
  46503. })(BABYLON || (BABYLON = {}));
  46504. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  46505. var BABYLON;
  46506. (function (BABYLON) {
  46507. var StereoscopicInterlacePostProcess = (function (_super) {
  46508. __extends(StereoscopicInterlacePostProcess, _super);
  46509. function StereoscopicInterlacePostProcess(name, rigCameras, isStereoscopicHoriz, samplingMode, engine, reusable) {
  46510. var _this = _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined) || this;
  46511. _this._passedProcess = rigCameras[0]._rigPostProcess;
  46512. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  46513. _this.onSizeChangedObservable.add(function () {
  46514. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  46515. });
  46516. _this.onApplyObservable.add(function (effect) {
  46517. effect.setTextureFromPostProcess("camASampler", _this._passedProcess);
  46518. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  46519. });
  46520. return _this;
  46521. }
  46522. return StereoscopicInterlacePostProcess;
  46523. }(BABYLON.PostProcess));
  46524. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  46525. })(BABYLON || (BABYLON = {}));
  46526. //# sourceMappingURL=babylon.stereoscopicInterlacePostProcess.js.map
  46527. var BABYLON;
  46528. (function (BABYLON) {
  46529. var LensFlare = (function () {
  46530. function LensFlare(size, position, color, imgUrl, system) {
  46531. this.size = size;
  46532. this.position = position;
  46533. this.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  46534. this.dispose = function () {
  46535. if (this.texture) {
  46536. this.texture.dispose();
  46537. }
  46538. // Remove from scene
  46539. var index = this._system.lensFlares.indexOf(this);
  46540. this._system.lensFlares.splice(index, 1);
  46541. };
  46542. this.color = color || new BABYLON.Color3(1, 1, 1);
  46543. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  46544. this._system = system;
  46545. system.lensFlares.push(this);
  46546. }
  46547. return LensFlare;
  46548. }());
  46549. BABYLON.LensFlare = LensFlare;
  46550. })(BABYLON || (BABYLON = {}));
  46551. //# sourceMappingURL=babylon.lensFlare.js.map
  46552. var BABYLON;
  46553. (function (BABYLON) {
  46554. var LensFlareSystem = (function () {
  46555. function LensFlareSystem(name, emitter, scene) {
  46556. this.name = name;
  46557. this.lensFlares = new Array();
  46558. this.borderLimit = 300;
  46559. this.viewportBorder = 0;
  46560. this.layerMask = 0x0FFFFFFF;
  46561. this._vertexBuffers = {};
  46562. this._isEnabled = true;
  46563. this._scene = scene;
  46564. this._emitter = emitter;
  46565. this.id = name;
  46566. scene.lensFlareSystems.push(this);
  46567. this.meshesSelectionPredicate = function (m) { return m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0); };
  46568. var engine = scene.getEngine();
  46569. // VBO
  46570. var vertices = [];
  46571. vertices.push(1, 1);
  46572. vertices.push(-1, 1);
  46573. vertices.push(-1, -1);
  46574. vertices.push(1, -1);
  46575. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  46576. // Indices
  46577. var indices = [];
  46578. indices.push(0);
  46579. indices.push(1);
  46580. indices.push(2);
  46581. indices.push(0);
  46582. indices.push(2);
  46583. indices.push(3);
  46584. this._indexBuffer = engine.createIndexBuffer(indices);
  46585. // Effects
  46586. this._effect = engine.createEffect("lensFlare", [BABYLON.VertexBuffer.PositionKind], ["color", "viewportMatrix"], ["textureSampler"], "");
  46587. }
  46588. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  46589. get: function () {
  46590. return this._isEnabled;
  46591. },
  46592. set: function (value) {
  46593. this._isEnabled = value;
  46594. },
  46595. enumerable: true,
  46596. configurable: true
  46597. });
  46598. LensFlareSystem.prototype.getScene = function () {
  46599. return this._scene;
  46600. };
  46601. LensFlareSystem.prototype.getEmitter = function () {
  46602. return this._emitter;
  46603. };
  46604. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  46605. this._emitter = newEmitter;
  46606. };
  46607. LensFlareSystem.prototype.getEmitterPosition = function () {
  46608. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  46609. };
  46610. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  46611. var position = this.getEmitterPosition();
  46612. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  46613. this._positionX = position.x;
  46614. this._positionY = position.y;
  46615. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  46616. if (this.viewportBorder > 0) {
  46617. globalViewport.x -= this.viewportBorder;
  46618. globalViewport.y -= this.viewportBorder;
  46619. globalViewport.width += this.viewportBorder * 2;
  46620. globalViewport.height += this.viewportBorder * 2;
  46621. position.x += this.viewportBorder;
  46622. position.y += this.viewportBorder;
  46623. this._positionX += this.viewportBorder;
  46624. this._positionY += this.viewportBorder;
  46625. }
  46626. if (position.z > 0) {
  46627. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  46628. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  46629. return true;
  46630. }
  46631. return true;
  46632. }
  46633. return false;
  46634. };
  46635. LensFlareSystem.prototype._isVisible = function () {
  46636. if (!this._isEnabled) {
  46637. return false;
  46638. }
  46639. var emitterPosition = this.getEmitterPosition();
  46640. var direction = emitterPosition.subtract(this._scene.activeCamera.globalPosition);
  46641. var distance = direction.length();
  46642. direction.normalize();
  46643. var ray = new BABYLON.Ray(this._scene.activeCamera.globalPosition, direction);
  46644. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  46645. return !pickInfo.hit || pickInfo.distance > distance;
  46646. };
  46647. LensFlareSystem.prototype.render = function () {
  46648. if (!this._effect.isReady())
  46649. return false;
  46650. var engine = this._scene.getEngine();
  46651. var viewport = this._scene.activeCamera.viewport;
  46652. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  46653. // Position
  46654. if (!this.computeEffectivePosition(globalViewport)) {
  46655. return false;
  46656. }
  46657. // Visibility
  46658. if (!this._isVisible()) {
  46659. return false;
  46660. }
  46661. // Intensity
  46662. var awayX;
  46663. var awayY;
  46664. if (this._positionX < this.borderLimit + globalViewport.x) {
  46665. awayX = this.borderLimit + globalViewport.x - this._positionX;
  46666. }
  46667. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  46668. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  46669. }
  46670. else {
  46671. awayX = 0;
  46672. }
  46673. if (this._positionY < this.borderLimit + globalViewport.y) {
  46674. awayY = this.borderLimit + globalViewport.y - this._positionY;
  46675. }
  46676. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  46677. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  46678. }
  46679. else {
  46680. awayY = 0;
  46681. }
  46682. var away = (awayX > awayY) ? awayX : awayY;
  46683. away -= this.viewportBorder;
  46684. if (away > this.borderLimit) {
  46685. away = this.borderLimit;
  46686. }
  46687. var intensity = 1.0 - (away / this.borderLimit);
  46688. if (intensity < 0) {
  46689. return false;
  46690. }
  46691. if (intensity > 1.0) {
  46692. intensity = 1.0;
  46693. }
  46694. if (this.viewportBorder > 0) {
  46695. globalViewport.x += this.viewportBorder;
  46696. globalViewport.y += this.viewportBorder;
  46697. globalViewport.width -= this.viewportBorder * 2;
  46698. globalViewport.height -= this.viewportBorder * 2;
  46699. this._positionX -= this.viewportBorder;
  46700. this._positionY -= this.viewportBorder;
  46701. }
  46702. // Position
  46703. var centerX = globalViewport.x + globalViewport.width / 2;
  46704. var centerY = globalViewport.y + globalViewport.height / 2;
  46705. var distX = centerX - this._positionX;
  46706. var distY = centerY - this._positionY;
  46707. // Effects
  46708. engine.enableEffect(this._effect);
  46709. engine.setState(false);
  46710. engine.setDepthBuffer(false);
  46711. // VBOs
  46712. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  46713. // Flares
  46714. for (var index = 0; index < this.lensFlares.length; index++) {
  46715. var flare = this.lensFlares[index];
  46716. engine.setAlphaMode(flare.alphaMode);
  46717. var x = centerX - (distX * flare.position);
  46718. var y = centerY - (distY * flare.position);
  46719. var cw = flare.size;
  46720. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  46721. var cx = 2 * (x / (globalViewport.width + globalViewport.x * 2)) - 1.0;
  46722. var cy = 1.0 - 2 * (y / (globalViewport.height + globalViewport.y * 2));
  46723. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  46724. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  46725. // Texture
  46726. this._effect.setTexture("textureSampler", flare.texture);
  46727. // Color
  46728. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  46729. // Draw order
  46730. engine.draw(true, 0, 6);
  46731. }
  46732. engine.setDepthBuffer(true);
  46733. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  46734. return true;
  46735. };
  46736. LensFlareSystem.prototype.dispose = function () {
  46737. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  46738. if (vertexBuffer) {
  46739. vertexBuffer.dispose();
  46740. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  46741. }
  46742. if (this._indexBuffer) {
  46743. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  46744. this._indexBuffer = null;
  46745. }
  46746. while (this.lensFlares.length) {
  46747. this.lensFlares[0].dispose();
  46748. }
  46749. // Remove from scene
  46750. var index = this._scene.lensFlareSystems.indexOf(this);
  46751. this._scene.lensFlareSystems.splice(index, 1);
  46752. };
  46753. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  46754. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  46755. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  46756. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  46757. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  46758. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  46759. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  46760. var parsedFlare = parsedLensFlareSystem.flares[index];
  46761. var flare = new BABYLON.LensFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), rootUrl + parsedFlare.textureName, lensFlareSystem);
  46762. }
  46763. return lensFlareSystem;
  46764. };
  46765. LensFlareSystem.prototype.serialize = function () {
  46766. var serializationObject = {};
  46767. serializationObject.id = this.id;
  46768. serializationObject.name = this.name;
  46769. serializationObject.emitterId = this.getEmitter().id;
  46770. serializationObject.borderLimit = this.borderLimit;
  46771. serializationObject.flares = [];
  46772. for (var index = 0; index < this.lensFlares.length; index++) {
  46773. var flare = this.lensFlares[index];
  46774. serializationObject.flares.push({
  46775. size: flare.size,
  46776. position: flare.position,
  46777. color: flare.color.asArray(),
  46778. textureName: BABYLON.Tools.GetFilename(flare.texture.name)
  46779. });
  46780. }
  46781. return serializationObject;
  46782. };
  46783. return LensFlareSystem;
  46784. }());
  46785. BABYLON.LensFlareSystem = LensFlareSystem;
  46786. })(BABYLON || (BABYLON = {}));
  46787. //# sourceMappingURL=babylon.lensFlareSystem.js.map
  46788. var BABYLON;
  46789. (function (BABYLON) {
  46790. // We're mainly based on the logic defined into the FreeCamera code
  46791. var DeviceOrientationCamera = (function (_super) {
  46792. __extends(DeviceOrientationCamera, _super);
  46793. function DeviceOrientationCamera(name, position, scene) {
  46794. var _this = _super.call(this, name, position, scene) || this;
  46795. _this._quaternionCache = new BABYLON.Quaternion();
  46796. _this.inputs.addDeviceOrientation();
  46797. return _this;
  46798. }
  46799. DeviceOrientationCamera.prototype.getClassName = function () {
  46800. return "DeviceOrientationCamera";
  46801. };
  46802. DeviceOrientationCamera.prototype._checkInputs = function () {
  46803. _super.prototype._checkInputs.call(this);
  46804. this._quaternionCache.copyFrom(this.rotationQuaternion);
  46805. if (this._initialQuaternion) {
  46806. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  46807. }
  46808. };
  46809. DeviceOrientationCamera.prototype.resetToCurrentRotation = function (axis) {
  46810. var _this = this;
  46811. if (axis === void 0) { axis = BABYLON.Axis.Y; }
  46812. //can only work if this camera has a rotation quaternion already.
  46813. if (!this.rotationQuaternion)
  46814. return;
  46815. if (!this._initialQuaternion) {
  46816. this._initialQuaternion = new BABYLON.Quaternion();
  46817. }
  46818. this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion);
  46819. ['x', 'y', 'z'].forEach(function (axisName) {
  46820. if (!axis[axisName]) {
  46821. _this._initialQuaternion[axisName] = 0;
  46822. }
  46823. else {
  46824. _this._initialQuaternion[axisName] *= -1;
  46825. }
  46826. });
  46827. this._initialQuaternion.normalize();
  46828. //force rotation update
  46829. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  46830. };
  46831. return DeviceOrientationCamera;
  46832. }(BABYLON.FreeCamera));
  46833. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  46834. })(BABYLON || (BABYLON = {}));
  46835. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  46836. var BABYLON;
  46837. (function (BABYLON) {
  46838. var VRDeviceOrientationFreeCamera = (function (_super) {
  46839. __extends(VRDeviceOrientationFreeCamera, _super);
  46840. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  46841. if (compensateDistortion === void 0) { compensateDistortion = true; }
  46842. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  46843. var _this = _super.call(this, name, position, scene) || this;
  46844. vrCameraMetrics.compensateDistortion = compensateDistortion;
  46845. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  46846. return _this;
  46847. }
  46848. VRDeviceOrientationFreeCamera.prototype.getClassName = function () {
  46849. return "VRDeviceOrientationFreeCamera";
  46850. };
  46851. return VRDeviceOrientationFreeCamera;
  46852. }(BABYLON.DeviceOrientationCamera));
  46853. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  46854. var VRDeviceOrientationGamepadCamera = (function (_super) {
  46855. __extends(VRDeviceOrientationGamepadCamera, _super);
  46856. function VRDeviceOrientationGamepadCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  46857. if (compensateDistortion === void 0) { compensateDistortion = true; }
  46858. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  46859. var _this = _super.call(this, name, position, scene, compensateDistortion, vrCameraMetrics) || this;
  46860. _this.inputs.addGamepad();
  46861. return _this;
  46862. }
  46863. VRDeviceOrientationGamepadCamera.prototype.getClassName = function () {
  46864. return "VRDeviceOrientationGamepadCamera";
  46865. };
  46866. return VRDeviceOrientationGamepadCamera;
  46867. }(VRDeviceOrientationFreeCamera));
  46868. BABYLON.VRDeviceOrientationGamepadCamera = VRDeviceOrientationGamepadCamera;
  46869. var VRDeviceOrientationArcRotateCamera = (function (_super) {
  46870. __extends(VRDeviceOrientationArcRotateCamera, _super);
  46871. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion, vrCameraMetrics) {
  46872. if (compensateDistortion === void 0) { compensateDistortion = true; }
  46873. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  46874. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  46875. vrCameraMetrics.compensateDistortion = compensateDistortion;
  46876. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  46877. _this.inputs.addVRDeviceOrientation();
  46878. return _this;
  46879. }
  46880. VRDeviceOrientationArcRotateCamera.prototype.getClassName = function () {
  46881. return "VRDeviceOrientationArcRotateCamera";
  46882. };
  46883. return VRDeviceOrientationArcRotateCamera;
  46884. }(BABYLON.ArcRotateCamera));
  46885. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  46886. })(BABYLON || (BABYLON = {}));
  46887. //# sourceMappingURL=babylon.vrDeviceOrientationCamera.js.map
  46888. var BABYLON;
  46889. (function (BABYLON) {
  46890. // We're mainly based on the logic defined into the FreeCamera code
  46891. var UniversalCamera = (function (_super) {
  46892. __extends(UniversalCamera, _super);
  46893. //-- end properties for backward compatibility for inputs
  46894. function UniversalCamera(name, position, scene) {
  46895. var _this = _super.call(this, name, position, scene) || this;
  46896. _this.inputs.addGamepad();
  46897. return _this;
  46898. }
  46899. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  46900. //-- Begin properties for backward compatibility for inputs
  46901. get: function () {
  46902. var gamepad = this.inputs.attached["gamepad"];
  46903. if (gamepad)
  46904. return gamepad.gamepadAngularSensibility;
  46905. },
  46906. set: function (value) {
  46907. var gamepad = this.inputs.attached["gamepad"];
  46908. if (gamepad)
  46909. gamepad.gamepadAngularSensibility = value;
  46910. },
  46911. enumerable: true,
  46912. configurable: true
  46913. });
  46914. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  46915. get: function () {
  46916. var gamepad = this.inputs.attached["gamepad"];
  46917. if (gamepad)
  46918. return gamepad.gamepadMoveSensibility;
  46919. },
  46920. set: function (value) {
  46921. var gamepad = this.inputs.attached["gamepad"];
  46922. if (gamepad)
  46923. gamepad.gamepadMoveSensibility = value;
  46924. },
  46925. enumerable: true,
  46926. configurable: true
  46927. });
  46928. UniversalCamera.prototype.getClassName = function () {
  46929. return "UniversalCamera";
  46930. };
  46931. return UniversalCamera;
  46932. }(BABYLON.TouchCamera));
  46933. BABYLON.UniversalCamera = UniversalCamera;
  46934. })(BABYLON || (BABYLON = {}));
  46935. //# sourceMappingURL=babylon.universalCamera.js.map
  46936. var BABYLON;
  46937. (function (BABYLON) {
  46938. var Gamepads = (function () {
  46939. function Gamepads(ongamedpadconnected) {
  46940. var _this = this;
  46941. this.babylonGamepads = [];
  46942. this.oneGamepadConnected = false;
  46943. this.isMonitoring = false;
  46944. this.gamepadEventSupported = 'GamepadEvent' in window;
  46945. this.gamepadSupportAvailable = (navigator.getGamepads ||
  46946. !!navigator.webkitGetGamepads || !!navigator.msGetGamepads || !!navigator.webkitGamepads);
  46947. this._callbackGamepadConnected = ongamedpadconnected;
  46948. if (this.gamepadSupportAvailable) {
  46949. // Checking if the gamepad connected event is supported (like in Firefox)
  46950. if (this.gamepadEventSupported) {
  46951. this._onGamepadConnectedEvent = function (evt) {
  46952. _this._onGamepadConnected(evt);
  46953. };
  46954. this._onGamepadDisonnectedEvent = function (evt) {
  46955. _this._onGamepadDisconnected(evt);
  46956. };
  46957. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  46958. window.addEventListener('gamepaddisconnected', this._onGamepadDisonnectedEvent, false);
  46959. }
  46960. else {
  46961. this._startMonitoringGamepads();
  46962. }
  46963. }
  46964. }
  46965. Gamepads.prototype.dispose = function () {
  46966. if (Gamepads.gamepadDOMInfo) {
  46967. document.body.removeChild(Gamepads.gamepadDOMInfo);
  46968. }
  46969. if (this._onGamepadConnectedEvent) {
  46970. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  46971. window.removeEventListener('gamepaddisconnected', this._onGamepadDisonnectedEvent, false);
  46972. this._onGamepadConnectedEvent = null;
  46973. this._onGamepadDisonnectedEvent = null;
  46974. }
  46975. };
  46976. Gamepads.prototype._onGamepadConnected = function (evt) {
  46977. var newGamepad = this._addNewGamepad(evt.gamepad);
  46978. if (this._callbackGamepadConnected)
  46979. this._callbackGamepadConnected(newGamepad);
  46980. this._startMonitoringGamepads();
  46981. };
  46982. Gamepads.prototype._addNewGamepad = function (gamepad) {
  46983. if (!this.oneGamepadConnected) {
  46984. this.oneGamepadConnected = true;
  46985. if (Gamepads.gamepadDOMInfo) {
  46986. document.body.removeChild(Gamepads.gamepadDOMInfo);
  46987. Gamepads.gamepadDOMInfo = null;
  46988. }
  46989. }
  46990. var newGamepad;
  46991. var xboxOne = (gamepad.id.search("Xbox One") !== -1);
  46992. if (xboxOne || gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  46993. newGamepad = new Xbox360Pad(gamepad.id, gamepad.index, gamepad, xboxOne);
  46994. }
  46995. else {
  46996. newGamepad = new GenericPad(gamepad.id, gamepad.index, gamepad);
  46997. }
  46998. this.babylonGamepads.push(newGamepad);
  46999. return newGamepad;
  47000. };
  47001. Gamepads.prototype._onGamepadDisconnected = function (evt) {
  47002. // Remove the gamepad from the list of gamepads to monitor.
  47003. for (var i in this.babylonGamepads) {
  47004. if (this.babylonGamepads[i].index == evt.gamepad.index) {
  47005. this.babylonGamepads.splice(+i, 1);
  47006. break;
  47007. }
  47008. }
  47009. // If no gamepads are left, stop the polling loop.
  47010. if (this.babylonGamepads.length == 0) {
  47011. this._stopMonitoringGamepads();
  47012. }
  47013. };
  47014. Gamepads.prototype._startMonitoringGamepads = function () {
  47015. if (!this.isMonitoring) {
  47016. this.isMonitoring = true;
  47017. this._checkGamepadsStatus();
  47018. }
  47019. };
  47020. Gamepads.prototype._stopMonitoringGamepads = function () {
  47021. this.isMonitoring = false;
  47022. };
  47023. Gamepads.prototype._checkGamepadsStatus = function () {
  47024. var _this = this;
  47025. // updating gamepad objects
  47026. this._updateGamepadObjects();
  47027. for (var i in this.babylonGamepads) {
  47028. this.babylonGamepads[i].update();
  47029. }
  47030. if (this.isMonitoring) {
  47031. if (window.requestAnimationFrame) {
  47032. window.requestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  47033. }
  47034. else if (window.mozRequestAnimationFrame) {
  47035. window.mozRequestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  47036. }
  47037. else if (window.webkitRequestAnimationFrame) {
  47038. window.webkitRequestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  47039. }
  47040. }
  47041. };
  47042. // This function is called only on Chrome, which does not yet support
  47043. // connection/disconnection events, but requires you to monitor
  47044. // an array for changes.
  47045. Gamepads.prototype._updateGamepadObjects = function () {
  47046. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  47047. for (var i = 0; i < gamepads.length; i++) {
  47048. if (gamepads[i]) {
  47049. if (!(gamepads[i].index in this.babylonGamepads)) {
  47050. var newGamepad = this._addNewGamepad(gamepads[i]);
  47051. if (this._callbackGamepadConnected) {
  47052. this._callbackGamepadConnected(newGamepad);
  47053. }
  47054. }
  47055. else {
  47056. this.babylonGamepads[i].browserGamepad = gamepads[i];
  47057. }
  47058. }
  47059. }
  47060. };
  47061. return Gamepads;
  47062. }());
  47063. BABYLON.Gamepads = Gamepads;
  47064. var StickValues = (function () {
  47065. function StickValues(x, y) {
  47066. this.x = x;
  47067. this.y = y;
  47068. }
  47069. return StickValues;
  47070. }());
  47071. BABYLON.StickValues = StickValues;
  47072. var Gamepad = (function () {
  47073. function Gamepad(id, index, browserGamepad, leftStickX, leftStickY, rightStickX, rightStickY) {
  47074. if (leftStickX === void 0) { leftStickX = 0; }
  47075. if (leftStickY === void 0) { leftStickY = 1; }
  47076. if (rightStickX === void 0) { rightStickX = 2; }
  47077. if (rightStickY === void 0) { rightStickY = 3; }
  47078. this.id = id;
  47079. this.index = index;
  47080. this.browserGamepad = browserGamepad;
  47081. this._leftStickAxisX = leftStickX;
  47082. this._leftStickAxisY = leftStickY;
  47083. this._rightStickAxisX = rightStickX;
  47084. this._rightStickAxisY = rightStickY;
  47085. if (this.browserGamepad.axes.length >= 2) {
  47086. this._leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  47087. }
  47088. if (this.browserGamepad.axes.length >= 4) {
  47089. this._rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  47090. }
  47091. }
  47092. Gamepad.prototype.onleftstickchanged = function (callback) {
  47093. this._onleftstickchanged = callback;
  47094. };
  47095. Gamepad.prototype.onrightstickchanged = function (callback) {
  47096. this._onrightstickchanged = callback;
  47097. };
  47098. Object.defineProperty(Gamepad.prototype, "leftStick", {
  47099. get: function () {
  47100. return this._leftStick;
  47101. },
  47102. set: function (newValues) {
  47103. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  47104. this._onleftstickchanged(newValues);
  47105. }
  47106. this._leftStick = newValues;
  47107. },
  47108. enumerable: true,
  47109. configurable: true
  47110. });
  47111. Object.defineProperty(Gamepad.prototype, "rightStick", {
  47112. get: function () {
  47113. return this._rightStick;
  47114. },
  47115. set: function (newValues) {
  47116. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  47117. this._onrightstickchanged(newValues);
  47118. }
  47119. this._rightStick = newValues;
  47120. },
  47121. enumerable: true,
  47122. configurable: true
  47123. });
  47124. Gamepad.prototype.update = function () {
  47125. if (this._leftStick) {
  47126. this.leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  47127. }
  47128. if (this._rightStick) {
  47129. this.rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  47130. }
  47131. };
  47132. return Gamepad;
  47133. }());
  47134. BABYLON.Gamepad = Gamepad;
  47135. var GenericPad = (function (_super) {
  47136. __extends(GenericPad, _super);
  47137. function GenericPad(id, index, gamepad) {
  47138. var _this = _super.call(this, id, index, gamepad) || this;
  47139. _this.id = id;
  47140. _this.index = index;
  47141. _this.gamepad = gamepad;
  47142. _this._buttons = new Array(gamepad.buttons.length);
  47143. return _this;
  47144. }
  47145. GenericPad.prototype.onbuttondown = function (callback) {
  47146. this._onbuttondown = callback;
  47147. };
  47148. GenericPad.prototype.onbuttonup = function (callback) {
  47149. this._onbuttonup = callback;
  47150. };
  47151. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  47152. if (newValue !== currentValue) {
  47153. if (this._onbuttondown && newValue === 1) {
  47154. this._onbuttondown(buttonIndex);
  47155. }
  47156. if (this._onbuttonup && newValue === 0) {
  47157. this._onbuttonup(buttonIndex);
  47158. }
  47159. }
  47160. return newValue;
  47161. };
  47162. GenericPad.prototype.update = function () {
  47163. _super.prototype.update.call(this);
  47164. for (var index = 0; index < this._buttons.length; index++) {
  47165. this._buttons[index] = this._setButtonValue(this.gamepad.buttons[index].value, this._buttons[index], index);
  47166. }
  47167. };
  47168. return GenericPad;
  47169. }(Gamepad));
  47170. BABYLON.GenericPad = GenericPad;
  47171. var Xbox360Button;
  47172. (function (Xbox360Button) {
  47173. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  47174. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  47175. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  47176. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  47177. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  47178. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  47179. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  47180. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  47181. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  47182. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  47183. })(Xbox360Button = BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  47184. var Xbox360Dpad;
  47185. (function (Xbox360Dpad) {
  47186. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  47187. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  47188. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  47189. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  47190. })(Xbox360Dpad = BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  47191. var Xbox360Pad = (function (_super) {
  47192. __extends(Xbox360Pad, _super);
  47193. function Xbox360Pad(id, index, gamepad, xboxOne) {
  47194. if (xboxOne === void 0) { xboxOne = false; }
  47195. var _this = _super.call(this, id, index, gamepad, 0, 1, (xboxOne ? 3 : 2), (xboxOne ? 4 : 3)) || this;
  47196. _this._leftTrigger = 0;
  47197. _this._rightTrigger = 0;
  47198. _this._buttonA = 0;
  47199. _this._buttonB = 0;
  47200. _this._buttonX = 0;
  47201. _this._buttonY = 0;
  47202. _this._buttonBack = 0;
  47203. _this._buttonStart = 0;
  47204. _this._buttonLB = 0;
  47205. _this._buttonRB = 0;
  47206. _this._buttonLeftStick = 0;
  47207. _this._buttonRightStick = 0;
  47208. _this._dPadUp = 0;
  47209. _this._dPadDown = 0;
  47210. _this._dPadLeft = 0;
  47211. _this._dPadRight = 0;
  47212. _this._isXboxOnePad = false;
  47213. _this._isXboxOnePad = xboxOne;
  47214. return _this;
  47215. }
  47216. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  47217. this._onlefttriggerchanged = callback;
  47218. };
  47219. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  47220. this._onrighttriggerchanged = callback;
  47221. };
  47222. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  47223. get: function () {
  47224. return this._leftTrigger;
  47225. },
  47226. set: function (newValue) {
  47227. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  47228. this._onlefttriggerchanged(newValue);
  47229. }
  47230. this._leftTrigger = newValue;
  47231. },
  47232. enumerable: true,
  47233. configurable: true
  47234. });
  47235. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  47236. get: function () {
  47237. return this._rightTrigger;
  47238. },
  47239. set: function (newValue) {
  47240. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  47241. this._onrighttriggerchanged(newValue);
  47242. }
  47243. this._rightTrigger = newValue;
  47244. },
  47245. enumerable: true,
  47246. configurable: true
  47247. });
  47248. Xbox360Pad.prototype.onbuttondown = function (callback) {
  47249. this._onbuttondown = callback;
  47250. };
  47251. Xbox360Pad.prototype.onbuttonup = function (callback) {
  47252. this._onbuttonup = callback;
  47253. };
  47254. Xbox360Pad.prototype.ondpaddown = function (callback) {
  47255. this._ondpaddown = callback;
  47256. };
  47257. Xbox360Pad.prototype.ondpadup = function (callback) {
  47258. this._ondpadup = callback;
  47259. };
  47260. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  47261. if (newValue !== currentValue) {
  47262. if (this._onbuttondown && newValue === 1) {
  47263. this._onbuttondown(buttonType);
  47264. }
  47265. if (this._onbuttonup && newValue === 0) {
  47266. this._onbuttonup(buttonType);
  47267. }
  47268. }
  47269. return newValue;
  47270. };
  47271. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  47272. if (newValue !== currentValue) {
  47273. if (this._ondpaddown && newValue === 1) {
  47274. this._ondpaddown(buttonType);
  47275. }
  47276. if (this._ondpadup && newValue === 0) {
  47277. this._ondpadup(buttonType);
  47278. }
  47279. }
  47280. return newValue;
  47281. };
  47282. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  47283. get: function () {
  47284. return this._buttonA;
  47285. },
  47286. set: function (value) {
  47287. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  47288. },
  47289. enumerable: true,
  47290. configurable: true
  47291. });
  47292. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  47293. get: function () {
  47294. return this._buttonB;
  47295. },
  47296. set: function (value) {
  47297. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  47298. },
  47299. enumerable: true,
  47300. configurable: true
  47301. });
  47302. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  47303. get: function () {
  47304. return this._buttonX;
  47305. },
  47306. set: function (value) {
  47307. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  47308. },
  47309. enumerable: true,
  47310. configurable: true
  47311. });
  47312. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  47313. get: function () {
  47314. return this._buttonY;
  47315. },
  47316. set: function (value) {
  47317. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  47318. },
  47319. enumerable: true,
  47320. configurable: true
  47321. });
  47322. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  47323. get: function () {
  47324. return this._buttonStart;
  47325. },
  47326. set: function (value) {
  47327. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  47328. },
  47329. enumerable: true,
  47330. configurable: true
  47331. });
  47332. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  47333. get: function () {
  47334. return this._buttonBack;
  47335. },
  47336. set: function (value) {
  47337. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  47338. },
  47339. enumerable: true,
  47340. configurable: true
  47341. });
  47342. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  47343. get: function () {
  47344. return this._buttonLB;
  47345. },
  47346. set: function (value) {
  47347. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  47348. },
  47349. enumerable: true,
  47350. configurable: true
  47351. });
  47352. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  47353. get: function () {
  47354. return this._buttonRB;
  47355. },
  47356. set: function (value) {
  47357. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  47358. },
  47359. enumerable: true,
  47360. configurable: true
  47361. });
  47362. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  47363. get: function () {
  47364. return this._buttonLeftStick;
  47365. },
  47366. set: function (value) {
  47367. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  47368. },
  47369. enumerable: true,
  47370. configurable: true
  47371. });
  47372. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  47373. get: function () {
  47374. return this._buttonRightStick;
  47375. },
  47376. set: function (value) {
  47377. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  47378. },
  47379. enumerable: true,
  47380. configurable: true
  47381. });
  47382. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  47383. get: function () {
  47384. return this._dPadUp;
  47385. },
  47386. set: function (value) {
  47387. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  47388. },
  47389. enumerable: true,
  47390. configurable: true
  47391. });
  47392. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  47393. get: function () {
  47394. return this._dPadDown;
  47395. },
  47396. set: function (value) {
  47397. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  47398. },
  47399. enumerable: true,
  47400. configurable: true
  47401. });
  47402. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  47403. get: function () {
  47404. return this._dPadLeft;
  47405. },
  47406. set: function (value) {
  47407. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  47408. },
  47409. enumerable: true,
  47410. configurable: true
  47411. });
  47412. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  47413. get: function () {
  47414. return this._dPadRight;
  47415. },
  47416. set: function (value) {
  47417. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  47418. },
  47419. enumerable: true,
  47420. configurable: true
  47421. });
  47422. Xbox360Pad.prototype.update = function () {
  47423. _super.prototype.update.call(this);
  47424. if (this._isXboxOnePad) {
  47425. this.buttonA = this.browserGamepad.buttons[0].value;
  47426. this.buttonB = this.browserGamepad.buttons[1].value;
  47427. this.buttonX = this.browserGamepad.buttons[2].value;
  47428. this.buttonY = this.browserGamepad.buttons[3].value;
  47429. this.buttonLB = this.browserGamepad.buttons[4].value;
  47430. this.buttonRB = this.browserGamepad.buttons[5].value;
  47431. this.leftTrigger = this.browserGamepad.axes[2];
  47432. this.rightTrigger = this.browserGamepad.axes[5];
  47433. this.buttonBack = this.browserGamepad.buttons[9].value;
  47434. this.buttonStart = this.browserGamepad.buttons[8].value;
  47435. this.buttonLeftStick = this.browserGamepad.buttons[6].value;
  47436. this.buttonRightStick = this.browserGamepad.buttons[7].value;
  47437. this.dPadUp = this.browserGamepad.buttons[11].value;
  47438. this.dPadDown = this.browserGamepad.buttons[12].value;
  47439. this.dPadLeft = this.browserGamepad.buttons[13].value;
  47440. this.dPadRight = this.browserGamepad.buttons[14].value;
  47441. }
  47442. else {
  47443. this.buttonA = this.browserGamepad.buttons[0].value;
  47444. this.buttonB = this.browserGamepad.buttons[1].value;
  47445. this.buttonX = this.browserGamepad.buttons[2].value;
  47446. this.buttonY = this.browserGamepad.buttons[3].value;
  47447. this.buttonLB = this.browserGamepad.buttons[4].value;
  47448. this.buttonRB = this.browserGamepad.buttons[5].value;
  47449. this.leftTrigger = this.browserGamepad.buttons[6].value;
  47450. this.rightTrigger = this.browserGamepad.buttons[7].value;
  47451. this.buttonBack = this.browserGamepad.buttons[8].value;
  47452. this.buttonStart = this.browserGamepad.buttons[9].value;
  47453. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  47454. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  47455. this.dPadUp = this.browserGamepad.buttons[12].value;
  47456. this.dPadDown = this.browserGamepad.buttons[13].value;
  47457. this.dPadLeft = this.browserGamepad.buttons[14].value;
  47458. this.dPadRight = this.browserGamepad.buttons[15].value;
  47459. }
  47460. };
  47461. return Xbox360Pad;
  47462. }(Gamepad));
  47463. BABYLON.Xbox360Pad = Xbox360Pad;
  47464. })(BABYLON || (BABYLON = {}));
  47465. //# sourceMappingURL=babylon.gamepads.js.map
  47466. var BABYLON;
  47467. (function (BABYLON) {
  47468. // We're mainly based on the logic defined into the FreeCamera code
  47469. var GamepadCamera = (function (_super) {
  47470. __extends(GamepadCamera, _super);
  47471. //-- end properties for backward compatibility for inputs
  47472. function GamepadCamera(name, position, scene) {
  47473. var _this;
  47474. BABYLON.Tools.Warn("Deprecated. Please use Universal Camera instead.");
  47475. _this = _super.call(this, name, position, scene) || this;
  47476. return _this;
  47477. }
  47478. Object.defineProperty(GamepadCamera.prototype, "gamepadAngularSensibility", {
  47479. //-- Begin properties for backward compatibility for inputs
  47480. get: function () {
  47481. var gamepad = this.inputs.attached["gamepad"];
  47482. if (gamepad)
  47483. return gamepad.gamepadAngularSensibility;
  47484. },
  47485. set: function (value) {
  47486. var gamepad = this.inputs.attached["gamepad"];
  47487. if (gamepad)
  47488. gamepad.gamepadAngularSensibility = value;
  47489. },
  47490. enumerable: true,
  47491. configurable: true
  47492. });
  47493. Object.defineProperty(GamepadCamera.prototype, "gamepadMoveSensibility", {
  47494. get: function () {
  47495. var gamepad = this.inputs.attached["gamepad"];
  47496. if (gamepad)
  47497. return gamepad.gamepadMoveSensibility;
  47498. },
  47499. set: function (value) {
  47500. var gamepad = this.inputs.attached["gamepad"];
  47501. if (gamepad)
  47502. gamepad.gamepadMoveSensibility = value;
  47503. },
  47504. enumerable: true,
  47505. configurable: true
  47506. });
  47507. GamepadCamera.prototype.getClassName = function () {
  47508. return "GamepadCamera";
  47509. };
  47510. return GamepadCamera;
  47511. }(BABYLON.UniversalCamera));
  47512. BABYLON.GamepadCamera = GamepadCamera;
  47513. })(BABYLON || (BABYLON = {}));
  47514. //# sourceMappingURL=babylon.gamepadCamera.js.map
  47515. var BABYLON;
  47516. (function (BABYLON) {
  47517. var Analyser = (function () {
  47518. function Analyser(scene) {
  47519. this.SMOOTHING = 0.75;
  47520. this.FFT_SIZE = 512;
  47521. this.BARGRAPHAMPLITUDE = 256;
  47522. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  47523. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  47524. this._scene = scene;
  47525. this._audioEngine = BABYLON.Engine.audioEngine;
  47526. if (this._audioEngine.canUseWebAudio) {
  47527. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  47528. this._webAudioAnalyser.minDecibels = -140;
  47529. this._webAudioAnalyser.maxDecibels = 0;
  47530. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  47531. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  47532. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  47533. }
  47534. }
  47535. Analyser.prototype.getFrequencyBinCount = function () {
  47536. if (this._audioEngine.canUseWebAudio) {
  47537. return this._webAudioAnalyser.frequencyBinCount;
  47538. }
  47539. else {
  47540. return 0;
  47541. }
  47542. };
  47543. Analyser.prototype.getByteFrequencyData = function () {
  47544. if (this._audioEngine.canUseWebAudio) {
  47545. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  47546. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  47547. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  47548. }
  47549. return this._byteFreqs;
  47550. };
  47551. Analyser.prototype.getByteTimeDomainData = function () {
  47552. if (this._audioEngine.canUseWebAudio) {
  47553. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  47554. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  47555. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  47556. }
  47557. return this._byteTime;
  47558. };
  47559. Analyser.prototype.getFloatFrequencyData = function () {
  47560. if (this._audioEngine.canUseWebAudio) {
  47561. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  47562. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  47563. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  47564. }
  47565. return this._floatFreqs;
  47566. };
  47567. Analyser.prototype.drawDebugCanvas = function () {
  47568. var _this = this;
  47569. if (this._audioEngine.canUseWebAudio) {
  47570. if (!this._debugCanvas) {
  47571. this._debugCanvas = document.createElement("canvas");
  47572. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  47573. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  47574. this._debugCanvas.style.position = "absolute";
  47575. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  47576. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  47577. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  47578. document.body.appendChild(this._debugCanvas);
  47579. this._registerFunc = function () {
  47580. _this.drawDebugCanvas();
  47581. };
  47582. this._scene.registerBeforeRender(this._registerFunc);
  47583. }
  47584. if (this._registerFunc) {
  47585. var workingArray = this.getByteFrequencyData();
  47586. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  47587. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  47588. // Draw the frequency domain chart.
  47589. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  47590. var value = workingArray[i];
  47591. var percent = value / this.BARGRAPHAMPLITUDE;
  47592. var height = this.DEBUGCANVASSIZE.height * percent;
  47593. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  47594. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  47595. var hue = i / this.getFrequencyBinCount() * 360;
  47596. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  47597. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  47598. }
  47599. }
  47600. }
  47601. };
  47602. Analyser.prototype.stopDebugCanvas = function () {
  47603. if (this._debugCanvas) {
  47604. this._scene.unregisterBeforeRender(this._registerFunc);
  47605. this._registerFunc = null;
  47606. document.body.removeChild(this._debugCanvas);
  47607. this._debugCanvas = null;
  47608. this._debugCanvasContext = null;
  47609. }
  47610. };
  47611. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  47612. if (this._audioEngine.canUseWebAudio) {
  47613. inputAudioNode.connect(this._webAudioAnalyser);
  47614. this._webAudioAnalyser.connect(outputAudioNode);
  47615. }
  47616. };
  47617. Analyser.prototype.dispose = function () {
  47618. if (this._audioEngine.canUseWebAudio) {
  47619. this._webAudioAnalyser.disconnect();
  47620. }
  47621. };
  47622. return Analyser;
  47623. }());
  47624. BABYLON.Analyser = Analyser;
  47625. })(BABYLON || (BABYLON = {}));
  47626. //# sourceMappingURL=babylon.analyser.js.map
  47627. var BABYLON;
  47628. (function (BABYLON) {
  47629. var DepthRenderer = (function () {
  47630. function DepthRenderer(scene, type) {
  47631. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  47632. var _this = this;
  47633. this._viewMatrix = BABYLON.Matrix.Zero();
  47634. this._projectionMatrix = BABYLON.Matrix.Zero();
  47635. this._transformMatrix = BABYLON.Matrix.Zero();
  47636. this._worldViewProjection = BABYLON.Matrix.Zero();
  47637. this._scene = scene;
  47638. var engine = scene.getEngine();
  47639. // Render target
  47640. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  47641. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  47642. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  47643. this._depthMap.refreshRate = 1;
  47644. this._depthMap.renderParticles = false;
  47645. this._depthMap.renderList = null;
  47646. // set default depth value to 1.0 (far away)
  47647. this._depthMap.onClearObservable.add(function (engine) {
  47648. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  47649. });
  47650. // Custom render function
  47651. var renderSubMesh = function (subMesh) {
  47652. var mesh = subMesh.getRenderingMesh();
  47653. var scene = _this._scene;
  47654. var engine = scene.getEngine();
  47655. // Culling
  47656. engine.setState(subMesh.getMaterial().backFaceCulling);
  47657. // Managing instances
  47658. var batch = mesh._getInstancesRenderList(subMesh._id);
  47659. if (batch.mustReturn) {
  47660. return;
  47661. }
  47662. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  47663. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  47664. engine.enableEffect(_this._effect);
  47665. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  47666. var material = subMesh.getMaterial();
  47667. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  47668. _this._effect.setFloat("far", scene.activeCamera.maxZ);
  47669. // Alpha test
  47670. if (material && material.needAlphaTesting()) {
  47671. var alphaTexture = material.getAlphaTestTexture();
  47672. _this._effect.setTexture("diffuseSampler", alphaTexture);
  47673. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  47674. }
  47675. // Bones
  47676. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  47677. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  47678. }
  47679. // Draw
  47680. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  47681. }
  47682. };
  47683. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes) {
  47684. var index;
  47685. for (index = 0; index < opaqueSubMeshes.length; index++) {
  47686. renderSubMesh(opaqueSubMeshes.data[index]);
  47687. }
  47688. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  47689. renderSubMesh(alphaTestSubMeshes.data[index]);
  47690. }
  47691. };
  47692. }
  47693. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  47694. var material = subMesh.getMaterial();
  47695. if (material.disableDepthWrite) {
  47696. return false;
  47697. }
  47698. var defines = [];
  47699. var attribs = [BABYLON.VertexBuffer.PositionKind];
  47700. var mesh = subMesh.getMesh();
  47701. var scene = mesh.getScene();
  47702. // Alpha test
  47703. if (material && material.needAlphaTesting()) {
  47704. defines.push("#define ALPHATEST");
  47705. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  47706. attribs.push(BABYLON.VertexBuffer.UVKind);
  47707. defines.push("#define UV1");
  47708. }
  47709. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  47710. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  47711. defines.push("#define UV2");
  47712. }
  47713. }
  47714. // Bones
  47715. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  47716. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  47717. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  47718. if (mesh.numBoneInfluencers > 4) {
  47719. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  47720. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  47721. }
  47722. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  47723. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  47724. }
  47725. else {
  47726. defines.push("#define NUM_BONE_INFLUENCERS 0");
  47727. }
  47728. // Instances
  47729. if (useInstances) {
  47730. defines.push("#define INSTANCES");
  47731. attribs.push("world0");
  47732. attribs.push("world1");
  47733. attribs.push("world2");
  47734. attribs.push("world3");
  47735. }
  47736. // Get correct effect
  47737. var join = defines.join("\n");
  47738. if (this._cachedDefines !== join) {
  47739. this._cachedDefines = join;
  47740. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "far"], ["diffuseSampler"], join);
  47741. }
  47742. return this._effect.isReady();
  47743. };
  47744. DepthRenderer.prototype.getDepthMap = function () {
  47745. return this._depthMap;
  47746. };
  47747. // Methods
  47748. DepthRenderer.prototype.dispose = function () {
  47749. this._depthMap.dispose();
  47750. };
  47751. return DepthRenderer;
  47752. }());
  47753. BABYLON.DepthRenderer = DepthRenderer;
  47754. })(BABYLON || (BABYLON = {}));
  47755. //# sourceMappingURL=babylon.depthRenderer.js.map
  47756. var BABYLON;
  47757. (function (BABYLON) {
  47758. var SSAORenderingPipeline = (function (_super) {
  47759. __extends(SSAORenderingPipeline, _super);
  47760. /**
  47761. * @constructor
  47762. * @param {string} name - The rendering pipeline name
  47763. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  47764. * @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 }
  47765. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  47766. */
  47767. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  47768. var _this = _super.call(this, scene.getEngine(), name) || this;
  47769. // Members
  47770. /**
  47771. * The PassPostProcess id in the pipeline that contains the original scene color
  47772. * @type {string}
  47773. */
  47774. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  47775. /**
  47776. * The SSAO PostProcess id in the pipeline
  47777. * @type {string}
  47778. */
  47779. _this.SSAORenderEffect = "SSAORenderEffect";
  47780. /**
  47781. * The horizontal blur PostProcess id in the pipeline
  47782. * @type {string}
  47783. */
  47784. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  47785. /**
  47786. * The vertical blur PostProcess id in the pipeline
  47787. * @type {string}
  47788. */
  47789. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  47790. /**
  47791. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  47792. * @type {string}
  47793. */
  47794. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  47795. /**
  47796. * The output strength of the SSAO post-process. Default value is 1.0.
  47797. * @type {number}
  47798. */
  47799. _this.totalStrength = 1.0;
  47800. /**
  47801. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  47802. * @type {number}
  47803. */
  47804. _this.radius = 0.0001;
  47805. /**
  47806. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  47807. * Must not be equal to fallOff and superior to fallOff.
  47808. * Default value is 0.975
  47809. * @type {number}
  47810. */
  47811. _this.area = 0.0075;
  47812. /**
  47813. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  47814. * Must not be equal to area and inferior to area.
  47815. * Default value is 0.0
  47816. * @type {number}
  47817. */
  47818. _this.fallOff = 0.000001;
  47819. /**
  47820. * The base color of the SSAO post-process
  47821. * The final result is "base + ssao" between [0, 1]
  47822. * @type {number}
  47823. */
  47824. _this.base = 0.5;
  47825. _this._firstUpdate = true;
  47826. _this._scene = scene;
  47827. // Set up assets
  47828. _this._createRandomTexture();
  47829. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  47830. var ssaoRatio = ratio.ssaoRatio || ratio;
  47831. var combineRatio = ratio.combineRatio || ratio;
  47832. _this._ratio = {
  47833. ssaoRatio: ssaoRatio,
  47834. combineRatio: combineRatio
  47835. };
  47836. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  47837. _this._createSSAOPostProcess(ssaoRatio);
  47838. _this._createBlurPostProcess(ssaoRatio);
  47839. _this._createSSAOCombinePostProcess(combineRatio);
  47840. // Set up pipeline
  47841. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  47842. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  47843. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  47844. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  47845. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  47846. // Finish
  47847. scene.postProcessRenderPipelineManager.addPipeline(_this);
  47848. if (cameras)
  47849. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  47850. return _this;
  47851. }
  47852. // Public Methods
  47853. /**
  47854. * Returns the horizontal blur PostProcess
  47855. * @return {BABYLON.BlurPostProcess} The horizontal blur post-process
  47856. */
  47857. SSAORenderingPipeline.prototype.getBlurHPostProcess = function () {
  47858. BABYLON.Tools.Error("SSAORenderinPipeline.getBlurHPostProcess() is deprecated, no more blur post-process exists");
  47859. return null;
  47860. };
  47861. /**
  47862. * Returns the vertical blur PostProcess
  47863. * @return {BABYLON.BlurPostProcess} The vertical blur post-process
  47864. */
  47865. SSAORenderingPipeline.prototype.getBlurVPostProcess = function () {
  47866. BABYLON.Tools.Error("SSAORenderinPipeline.getBlurVPostProcess() is deprecated, no more blur post-process exists");
  47867. return null;
  47868. };
  47869. /**
  47870. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  47871. */
  47872. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  47873. if (disableDepthRender === void 0) { disableDepthRender = false; }
  47874. for (var i = 0; i < this._scene.cameras.length; i++) {
  47875. var camera = this._scene.cameras[i];
  47876. this._originalColorPostProcess.dispose(camera);
  47877. this._ssaoPostProcess.dispose(camera);
  47878. this._blurHPostProcess.dispose(camera);
  47879. this._blurVPostProcess.dispose(camera);
  47880. this._ssaoCombinePostProcess.dispose(camera);
  47881. }
  47882. this._randomTexture.dispose();
  47883. if (disableDepthRender)
  47884. this._scene.disableDepthRenderer();
  47885. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  47886. _super.prototype.dispose.call(this);
  47887. };
  47888. // Private Methods
  47889. SSAORenderingPipeline.prototype._createBlurPostProcess = function (ratio) {
  47890. var _this = this;
  47891. /*
  47892. var samplerOffsets = [
  47893. -8.0, -6.0, -4.0, -2.0,
  47894. 0.0,
  47895. 2.0, 4.0, 6.0, 8.0
  47896. ];
  47897. */
  47898. var samples = 16;
  47899. var samplerOffsets = [];
  47900. for (var i = -8; i < 8; i++) {
  47901. samplerOffsets.push(i * 2);
  47902. }
  47903. 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");
  47904. this._blurHPostProcess.onApply = function (effect) {
  47905. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width);
  47906. effect.setTexture("depthSampler", _this._depthTexture);
  47907. if (_this._firstUpdate) {
  47908. effect.setArray("samplerOffsets", samplerOffsets);
  47909. }
  47910. };
  47911. 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");
  47912. this._blurVPostProcess.onApply = function (effect) {
  47913. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height);
  47914. effect.setTexture("depthSampler", _this._depthTexture);
  47915. if (_this._firstUpdate) {
  47916. effect.setArray("samplerOffsets", samplerOffsets);
  47917. _this._firstUpdate = false;
  47918. }
  47919. };
  47920. };
  47921. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  47922. var _this = this;
  47923. var numSamples = 16;
  47924. var sampleSphere = [
  47925. 0.5381, 0.1856, -0.4319,
  47926. 0.1379, 0.2486, 0.4430,
  47927. 0.3371, 0.5679, -0.0057,
  47928. -0.6999, -0.0451, -0.0019,
  47929. 0.0689, -0.1598, -0.8547,
  47930. 0.0560, 0.0069, -0.1843,
  47931. -0.0146, 0.1402, 0.0762,
  47932. 0.0100, -0.1924, -0.0344,
  47933. -0.3577, -0.5301, -0.4358,
  47934. -0.3169, 0.1063, 0.0158,
  47935. 0.0103, -0.5869, 0.0046,
  47936. -0.0897, -0.4940, 0.3287,
  47937. 0.7119, -0.0154, -0.0918,
  47938. -0.0533, 0.0596, -0.5411,
  47939. 0.0352, -0.0631, 0.5460,
  47940. -0.4776, 0.2847, -0.0271
  47941. ];
  47942. var samplesFactor = 1.0 / numSamples;
  47943. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  47944. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  47945. "area", "fallOff", "base", "range", "viewport"
  47946. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  47947. var viewport = new BABYLON.Vector2(0, 0);
  47948. this._ssaoPostProcess.onApply = function (effect) {
  47949. if (_this._firstUpdate) {
  47950. effect.setArray3("sampleSphere", sampleSphere);
  47951. effect.setFloat("samplesFactor", samplesFactor);
  47952. effect.setFloat("randTextureTiles", 4.0);
  47953. }
  47954. effect.setFloat("totalStrength", _this.totalStrength);
  47955. effect.setFloat("radius", _this.radius);
  47956. effect.setFloat("area", _this.area);
  47957. effect.setFloat("fallOff", _this.fallOff);
  47958. effect.setFloat("base", _this.base);
  47959. effect.setTexture("textureSampler", _this._depthTexture);
  47960. effect.setTexture("randomSampler", _this._randomTexture);
  47961. };
  47962. };
  47963. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  47964. var _this = this;
  47965. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  47966. this._ssaoCombinePostProcess.onApply = function (effect) {
  47967. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  47968. };
  47969. };
  47970. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  47971. var size = 512;
  47972. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  47973. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  47974. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  47975. var context = this._randomTexture.getContext();
  47976. var rand = function (min, max) {
  47977. return Math.random() * (max - min) + min;
  47978. };
  47979. var randVector = BABYLON.Vector3.Zero();
  47980. for (var x = 0; x < size; x++) {
  47981. for (var y = 0; y < size; y++) {
  47982. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  47983. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  47984. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  47985. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  47986. context.fillRect(x, y, 1, 1);
  47987. }
  47988. }
  47989. this._randomTexture.update(false);
  47990. };
  47991. return SSAORenderingPipeline;
  47992. }(BABYLON.PostProcessRenderPipeline));
  47993. __decorate([
  47994. BABYLON.serialize()
  47995. ], SSAORenderingPipeline.prototype, "totalStrength", void 0);
  47996. __decorate([
  47997. BABYLON.serialize()
  47998. ], SSAORenderingPipeline.prototype, "radius", void 0);
  47999. __decorate([
  48000. BABYLON.serialize()
  48001. ], SSAORenderingPipeline.prototype, "area", void 0);
  48002. __decorate([
  48003. BABYLON.serialize()
  48004. ], SSAORenderingPipeline.prototype, "fallOff", void 0);
  48005. __decorate([
  48006. BABYLON.serialize()
  48007. ], SSAORenderingPipeline.prototype, "base", void 0);
  48008. __decorate([
  48009. BABYLON.serialize()
  48010. ], SSAORenderingPipeline.prototype, "_ratio", void 0);
  48011. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  48012. })(BABYLON || (BABYLON = {}));
  48013. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  48014. var BABYLON;
  48015. (function (BABYLON) {
  48016. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  48017. var VolumetricLightScatteringPostProcess = (function (_super) {
  48018. __extends(VolumetricLightScatteringPostProcess, _super);
  48019. /**
  48020. * @constructor
  48021. * @param {string} name - The post-process name
  48022. * @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)
  48023. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  48024. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  48025. * @param {number} samples - The post-process quality, default 100
  48026. * @param {number} samplingMode - The post-process filtering mode
  48027. * @param {BABYLON.Engine} engine - The babylon engine
  48028. * @param {boolean} reusable - If the post-process is reusable
  48029. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  48030. */
  48031. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  48032. if (samples === void 0) { samples = 100; }
  48033. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  48034. 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;
  48035. _this._screenCoordinates = BABYLON.Vector2.Zero();
  48036. /**
  48037. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  48038. * @type {Vector3}
  48039. */
  48040. _this.customMeshPosition = BABYLON.Vector3.Zero();
  48041. /**
  48042. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  48043. * @type {boolean}
  48044. */
  48045. _this.useCustomMeshPosition = false;
  48046. /**
  48047. * If the post-process should inverse the light scattering direction
  48048. * @type {boolean}
  48049. */
  48050. _this.invert = true;
  48051. /**
  48052. * Array containing the excluded meshes not rendered in the internal pass
  48053. */
  48054. _this.excludedMeshes = new Array();
  48055. /**
  48056. * Controls the overall intensity of the post-process
  48057. * @type {number}
  48058. */
  48059. _this.exposure = 0.3;
  48060. /**
  48061. * Dissipates each sample's contribution in range [0, 1]
  48062. * @type {number}
  48063. */
  48064. _this.decay = 0.96815;
  48065. /**
  48066. * Controls the overall intensity of each sample
  48067. * @type {number}
  48068. */
  48069. _this.weight = 0.58767;
  48070. /**
  48071. * Controls the density of each sample
  48072. * @type {number}
  48073. */
  48074. _this.density = 0.926;
  48075. scene = (camera === null) ? scene : camera.getScene(); // parameter "scene" can be null.
  48076. var engine = scene.getEngine();
  48077. _this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  48078. // Configure mesh
  48079. _this.mesh = (mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene);
  48080. // Configure
  48081. _this._createPass(scene, ratio.passRatio || ratio);
  48082. _this.onActivate = function (camera) {
  48083. if (!_this.isSupported) {
  48084. _this.dispose(camera);
  48085. }
  48086. _this.onActivate = null;
  48087. };
  48088. _this.onApplyObservable.add(function (effect) {
  48089. _this._updateMeshScreenCoordinates(scene);
  48090. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  48091. effect.setFloat("exposure", _this.exposure);
  48092. effect.setFloat("decay", _this.decay);
  48093. effect.setFloat("weight", _this.weight);
  48094. effect.setFloat("density", _this.density);
  48095. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  48096. });
  48097. return _this;
  48098. }
  48099. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  48100. get: function () {
  48101. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  48102. return false;
  48103. },
  48104. set: function (useDiffuseColor) {
  48105. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  48106. },
  48107. enumerable: true,
  48108. configurable: true
  48109. });
  48110. VolumetricLightScatteringPostProcess.prototype.isReady = function (subMesh, useInstances) {
  48111. var mesh = subMesh.getMesh();
  48112. // Render this.mesh as default
  48113. if (mesh === this.mesh) {
  48114. return mesh.material.isReady(mesh);
  48115. }
  48116. var defines = [];
  48117. var attribs = [BABYLON.VertexBuffer.PositionKind];
  48118. var material = subMesh.getMaterial();
  48119. var needUV = false;
  48120. // Alpha test
  48121. if (material) {
  48122. if (material.needAlphaTesting()) {
  48123. defines.push("#define ALPHATEST");
  48124. }
  48125. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  48126. attribs.push(BABYLON.VertexBuffer.UVKind);
  48127. defines.push("#define UV1");
  48128. }
  48129. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  48130. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  48131. defines.push("#define UV2");
  48132. }
  48133. }
  48134. // Bones
  48135. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  48136. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  48137. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  48138. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  48139. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  48140. }
  48141. else {
  48142. defines.push("#define NUM_BONE_INFLUENCERS 0");
  48143. }
  48144. // Instances
  48145. if (useInstances) {
  48146. defines.push("#define INSTANCES");
  48147. attribs.push("world0");
  48148. attribs.push("world1");
  48149. attribs.push("world2");
  48150. attribs.push("world3");
  48151. }
  48152. // Get correct effect
  48153. var join = defines.join("\n");
  48154. if (this._cachedDefines !== join) {
  48155. this._cachedDefines = join;
  48156. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  48157. }
  48158. return this._volumetricLightScatteringPass.isReady();
  48159. };
  48160. /**
  48161. * Sets the new light position for light scattering effect
  48162. * @param {BABYLON.Vector3} The new custom light position
  48163. */
  48164. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  48165. this.customMeshPosition = position;
  48166. };
  48167. /**
  48168. * Returns the light position for light scattering effect
  48169. * @return {BABYLON.Vector3} The custom light position
  48170. */
  48171. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  48172. return this.customMeshPosition;
  48173. };
  48174. /**
  48175. * Disposes the internal assets and detaches the post-process from the camera
  48176. */
  48177. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  48178. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  48179. if (rttIndex !== -1) {
  48180. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  48181. }
  48182. this._volumetricLightScatteringRTT.dispose();
  48183. _super.prototype.dispose.call(this, camera);
  48184. };
  48185. /**
  48186. * Returns the render target texture used by the post-process
  48187. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  48188. */
  48189. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  48190. return this._volumetricLightScatteringRTT;
  48191. };
  48192. // Private methods
  48193. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  48194. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  48195. return true;
  48196. }
  48197. return false;
  48198. };
  48199. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  48200. var _this = this;
  48201. var engine = scene.getEngine();
  48202. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  48203. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  48204. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  48205. this._volumetricLightScatteringRTT.renderList = null;
  48206. this._volumetricLightScatteringRTT.renderParticles = false;
  48207. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  48208. // Custom render function for submeshes
  48209. var renderSubMesh = function (subMesh) {
  48210. var mesh = subMesh.getRenderingMesh();
  48211. if (_this._meshExcluded(mesh)) {
  48212. return;
  48213. }
  48214. var scene = mesh.getScene();
  48215. var engine = scene.getEngine();
  48216. // Culling
  48217. engine.setState(subMesh.getMaterial().backFaceCulling);
  48218. // Managing instances
  48219. var batch = mesh._getInstancesRenderList(subMesh._id);
  48220. if (batch.mustReturn) {
  48221. return;
  48222. }
  48223. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  48224. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  48225. var effect = _this._volumetricLightScatteringPass;
  48226. if (mesh === _this.mesh) {
  48227. effect = subMesh.getMaterial().getEffect();
  48228. }
  48229. engine.enableEffect(effect);
  48230. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  48231. if (mesh === _this.mesh) {
  48232. subMesh.getMaterial().bind(mesh.getWorldMatrix(), mesh);
  48233. }
  48234. else {
  48235. var material = subMesh.getMaterial();
  48236. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  48237. // Alpha test
  48238. if (material && material.needAlphaTesting()) {
  48239. var alphaTexture = material.getAlphaTestTexture();
  48240. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  48241. if (alphaTexture) {
  48242. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  48243. }
  48244. }
  48245. // Bones
  48246. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  48247. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  48248. }
  48249. }
  48250. // Draw
  48251. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  48252. }
  48253. };
  48254. // Render target texture callbacks
  48255. var savedSceneClearColor;
  48256. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  48257. this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function () {
  48258. savedSceneClearColor = scene.clearColor;
  48259. scene.clearColor = sceneClearColor;
  48260. });
  48261. this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function () {
  48262. scene.clearColor = savedSceneClearColor;
  48263. });
  48264. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  48265. var engine = scene.getEngine();
  48266. var index;
  48267. for (index = 0; index < opaqueSubMeshes.length; index++) {
  48268. renderSubMesh(opaqueSubMeshes.data[index]);
  48269. }
  48270. engine.setAlphaTesting(true);
  48271. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  48272. renderSubMesh(alphaTestSubMeshes.data[index]);
  48273. }
  48274. engine.setAlphaTesting(false);
  48275. if (transparentSubMeshes.length) {
  48276. // Sort sub meshes
  48277. for (index = 0; index < transparentSubMeshes.length; index++) {
  48278. var submesh = transparentSubMeshes.data[index];
  48279. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  48280. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  48281. }
  48282. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  48283. sortedArray.sort(function (a, b) {
  48284. // Alpha index first
  48285. if (a._alphaIndex > b._alphaIndex) {
  48286. return 1;
  48287. }
  48288. if (a._alphaIndex < b._alphaIndex) {
  48289. return -1;
  48290. }
  48291. // Then distance to camera
  48292. if (a._distanceToCamera < b._distanceToCamera) {
  48293. return 1;
  48294. }
  48295. if (a._distanceToCamera > b._distanceToCamera) {
  48296. return -1;
  48297. }
  48298. return 0;
  48299. });
  48300. // Render sub meshes
  48301. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  48302. for (index = 0; index < sortedArray.length; index++) {
  48303. renderSubMesh(sortedArray[index]);
  48304. }
  48305. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  48306. }
  48307. };
  48308. };
  48309. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  48310. var transform = scene.getTransformMatrix();
  48311. var meshPosition;
  48312. if (this.useCustomMeshPosition) {
  48313. meshPosition = this.customMeshPosition;
  48314. }
  48315. else if (this.attachedNode) {
  48316. meshPosition = this.attachedNode.position;
  48317. }
  48318. else {
  48319. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  48320. }
  48321. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  48322. this._screenCoordinates.x = pos.x / this._viewPort.width;
  48323. this._screenCoordinates.y = pos.y / this._viewPort.height;
  48324. if (this.invert)
  48325. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  48326. };
  48327. // Static methods
  48328. /**
  48329. * Creates a default mesh for the Volumeric Light Scattering post-process
  48330. * @param {string} The mesh name
  48331. * @param {BABYLON.Scene} The scene where to create the mesh
  48332. * @return {BABYLON.Mesh} the default mesh
  48333. */
  48334. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  48335. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  48336. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  48337. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  48338. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  48339. mesh.material = material;
  48340. return mesh;
  48341. };
  48342. return VolumetricLightScatteringPostProcess;
  48343. }(BABYLON.PostProcess));
  48344. __decorate([
  48345. BABYLON.serializeAsVector3()
  48346. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  48347. __decorate([
  48348. BABYLON.serialize()
  48349. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  48350. __decorate([
  48351. BABYLON.serialize()
  48352. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  48353. __decorate([
  48354. BABYLON.serializeAsMeshReference()
  48355. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  48356. __decorate([
  48357. BABYLON.serialize()
  48358. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  48359. __decorate([
  48360. BABYLON.serialize()
  48361. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  48362. __decorate([
  48363. BABYLON.serialize()
  48364. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  48365. __decorate([
  48366. BABYLON.serialize()
  48367. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  48368. __decorate([
  48369. BABYLON.serialize()
  48370. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  48371. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  48372. })(BABYLON || (BABYLON = {}));
  48373. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  48374. // BABYLON.JS Chromatic Aberration GLSL Shader
  48375. // Author: Olivier Guyot
  48376. // Separates very slightly R, G and B colors on the edges of the screen
  48377. // Inspired by Francois Tarlier & Martins Upitis
  48378. var BABYLON;
  48379. (function (BABYLON) {
  48380. var LensRenderingPipeline = (function (_super) {
  48381. __extends(LensRenderingPipeline, _super);
  48382. /**
  48383. * @constructor
  48384. *
  48385. * Effect parameters are as follow:
  48386. * {
  48387. * chromatic_aberration: number; // from 0 to x (1 for realism)
  48388. * edge_blur: number; // from 0 to x (1 for realism)
  48389. * distortion: number; // from 0 to x (1 for realism)
  48390. * grain_amount: number; // from 0 to 1
  48391. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  48392. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  48393. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  48394. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  48395. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  48396. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  48397. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  48398. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  48399. * }
  48400. * Note: if an effect parameter is unset, effect is disabled
  48401. *
  48402. * @param {string} name - The rendering pipeline name
  48403. * @param {object} parameters - An object containing all parameters (see above)
  48404. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  48405. * @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)
  48406. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  48407. */
  48408. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  48409. if (ratio === void 0) { ratio = 1.0; }
  48410. var _this = _super.call(this, scene.getEngine(), name) || this;
  48411. // Lens effects can be of the following:
  48412. // - chromatic aberration (slight shift of RGB colors)
  48413. // - blur on the edge of the lens
  48414. // - lens distortion
  48415. // - depth-of-field blur & highlights enhancing
  48416. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  48417. // - grain effect (noise or custom texture)
  48418. // Two additional texture samplers are needed:
  48419. // - depth map (for depth-of-field)
  48420. // - grain texture
  48421. /**
  48422. * The chromatic aberration PostProcess id in the pipeline
  48423. * @type {string}
  48424. */
  48425. _this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  48426. /**
  48427. * The highlights enhancing PostProcess id in the pipeline
  48428. * @type {string}
  48429. */
  48430. _this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  48431. /**
  48432. * The depth-of-field PostProcess id in the pipeline
  48433. * @type {string}
  48434. */
  48435. _this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  48436. _this._scene = scene;
  48437. // Fetch texture samplers
  48438. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  48439. if (parameters.grain_texture) {
  48440. _this._grainTexture = parameters.grain_texture;
  48441. }
  48442. else {
  48443. _this._createGrainTexture();
  48444. }
  48445. // save parameters
  48446. _this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  48447. _this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  48448. _this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  48449. _this._distortion = parameters.distortion ? parameters.distortion : 0;
  48450. _this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  48451. _this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  48452. _this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  48453. _this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  48454. _this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  48455. _this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  48456. _this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  48457. // Create effects
  48458. _this._createChromaticAberrationPostProcess(ratio);
  48459. _this._createHighlightsPostProcess(ratio);
  48460. _this._createDepthOfFieldPostProcess(ratio / 4);
  48461. // Set up pipeline
  48462. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  48463. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  48464. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  48465. if (_this._highlightsGain === -1) {
  48466. _this._disableEffect(_this.HighlightsEnhancingEffect, null);
  48467. }
  48468. // Finish
  48469. scene.postProcessRenderPipelineManager.addPipeline(_this);
  48470. if (cameras) {
  48471. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  48472. }
  48473. return _this;
  48474. }
  48475. // public methods (self explanatory)
  48476. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  48477. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  48478. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  48479. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  48480. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  48481. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  48482. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  48483. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  48484. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  48485. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  48486. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  48487. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  48488. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  48489. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  48490. };
  48491. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  48492. this._highlightsPostProcess.updateEffect();
  48493. };
  48494. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  48495. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  48496. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  48497. this._highlightsGain = amount;
  48498. };
  48499. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  48500. if (this._highlightsGain === -1) {
  48501. this._highlightsGain = 1.0;
  48502. }
  48503. this._highlightsThreshold = amount;
  48504. };
  48505. LensRenderingPipeline.prototype.disableHighlights = function () {
  48506. this._highlightsGain = -1;
  48507. };
  48508. /**
  48509. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  48510. */
  48511. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  48512. if (disableDepthRender === void 0) { disableDepthRender = false; }
  48513. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  48514. this._chromaticAberrationPostProcess = undefined;
  48515. this._highlightsPostProcess = undefined;
  48516. this._depthOfFieldPostProcess = undefined;
  48517. this._grainTexture.dispose();
  48518. if (disableDepthRender)
  48519. this._scene.disableDepthRenderer();
  48520. };
  48521. // colors shifting and distortion
  48522. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  48523. var _this = this;
  48524. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height"], // uniforms
  48525. [], // samplers
  48526. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  48527. this._chromaticAberrationPostProcess.onApply = function (effect) {
  48528. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  48529. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  48530. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  48531. };
  48532. };
  48533. // highlights enhancing
  48534. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  48535. var _this = this;
  48536. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  48537. [], // samplers
  48538. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  48539. this._highlightsPostProcess.onApply = function (effect) {
  48540. effect.setFloat('gain', _this._highlightsGain);
  48541. effect.setFloat('threshold', _this._highlightsThreshold);
  48542. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  48543. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  48544. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  48545. };
  48546. };
  48547. // colors shifting and distortion
  48548. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  48549. var _this = this;
  48550. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  48551. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  48552. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  48553. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  48554. this._depthOfFieldPostProcess.onApply = function (effect) {
  48555. effect.setTexture("depthSampler", _this._depthTexture);
  48556. effect.setTexture("grainSampler", _this._grainTexture);
  48557. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  48558. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  48559. effect.setFloat('grain_amount', _this._grainAmount);
  48560. effect.setBool('blur_noise', _this._blurNoise);
  48561. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  48562. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  48563. effect.setFloat('distortion', _this._distortion);
  48564. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  48565. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  48566. effect.setFloat('aperture', _this._dofAperture);
  48567. effect.setFloat('darken', _this._dofDarken);
  48568. effect.setFloat('edge_blur', _this._edgeBlur);
  48569. effect.setBool('highlights', (_this._highlightsGain !== -1));
  48570. effect.setFloat('near', _this._scene.activeCamera.minZ);
  48571. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  48572. };
  48573. };
  48574. // creates a black and white random noise texture, 512x512
  48575. LensRenderingPipeline.prototype._createGrainTexture = function () {
  48576. var size = 512;
  48577. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  48578. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  48579. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  48580. var context = this._grainTexture.getContext();
  48581. var rand = function (min, max) {
  48582. return Math.random() * (max - min) + min;
  48583. };
  48584. var value;
  48585. for (var x = 0; x < size; x++) {
  48586. for (var y = 0; y < size; y++) {
  48587. value = Math.floor(rand(0.42, 0.58) * 255);
  48588. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  48589. context.fillRect(x, y, 1, 1);
  48590. }
  48591. }
  48592. this._grainTexture.update(false);
  48593. };
  48594. return LensRenderingPipeline;
  48595. }(BABYLON.PostProcessRenderPipeline));
  48596. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  48597. })(BABYLON || (BABYLON = {}));
  48598. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map
  48599. //
  48600. // This post-process allows the modification of rendered colors by using
  48601. // a 'look-up table' (LUT). This effect is also called Color Grading.
  48602. //
  48603. // The object needs to be provided an url to a texture containing the color
  48604. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  48605. // Use an image editing software to tweak the LUT to match your needs.
  48606. //
  48607. // For an example of a color LUT, see here:
  48608. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  48609. // For explanations on color grading, see here:
  48610. // http://udn.epicgames.com/Three/ColorGrading.html
  48611. //
  48612. var BABYLON;
  48613. (function (BABYLON) {
  48614. var ColorCorrectionPostProcess = (function (_super) {
  48615. __extends(ColorCorrectionPostProcess, _super);
  48616. function ColorCorrectionPostProcess(name, colorTableUrl, options, camera, samplingMode, engine, reusable) {
  48617. var _this = _super.call(this, name, 'colorCorrection', null, ['colorTable'], options, camera, samplingMode, engine, reusable) || this;
  48618. _this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  48619. _this._colorTableTexture.anisotropicFilteringLevel = 1;
  48620. _this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  48621. _this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  48622. _this.onApply = function (effect) {
  48623. effect.setTexture("colorTable", _this._colorTableTexture);
  48624. };
  48625. return _this;
  48626. }
  48627. return ColorCorrectionPostProcess;
  48628. }(BABYLON.PostProcess));
  48629. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  48630. })(BABYLON || (BABYLON = {}));
  48631. //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.map
  48632. var BABYLON;
  48633. (function (BABYLON) {
  48634. var AnaglyphFreeCamera = (function (_super) {
  48635. __extends(AnaglyphFreeCamera, _super);
  48636. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  48637. var _this = _super.call(this, name, position, scene) || this;
  48638. _this.interaxialDistance = interaxialDistance;
  48639. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  48640. return _this;
  48641. }
  48642. AnaglyphFreeCamera.prototype.getClassName = function () {
  48643. return "AnaglyphFreeCamera";
  48644. };
  48645. return AnaglyphFreeCamera;
  48646. }(BABYLON.FreeCamera));
  48647. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  48648. var AnaglyphArcRotateCamera = (function (_super) {
  48649. __extends(AnaglyphArcRotateCamera, _super);
  48650. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  48651. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  48652. _this.interaxialDistance = interaxialDistance;
  48653. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  48654. return _this;
  48655. }
  48656. AnaglyphArcRotateCamera.prototype.getClassName = function () {
  48657. return "AnaglyphArcRotateCamera";
  48658. };
  48659. return AnaglyphArcRotateCamera;
  48660. }(BABYLON.ArcRotateCamera));
  48661. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  48662. var AnaglyphGamepadCamera = (function (_super) {
  48663. __extends(AnaglyphGamepadCamera, _super);
  48664. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  48665. var _this = _super.call(this, name, position, scene) || this;
  48666. _this.interaxialDistance = interaxialDistance;
  48667. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  48668. return _this;
  48669. }
  48670. AnaglyphGamepadCamera.prototype.getClassName = function () {
  48671. return "AnaglyphGamepadCamera";
  48672. };
  48673. return AnaglyphGamepadCamera;
  48674. }(BABYLON.GamepadCamera));
  48675. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  48676. var AnaglyphUniversalCamera = (function (_super) {
  48677. __extends(AnaglyphUniversalCamera, _super);
  48678. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  48679. var _this = _super.call(this, name, position, scene) || this;
  48680. _this.interaxialDistance = interaxialDistance;
  48681. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  48682. return _this;
  48683. }
  48684. AnaglyphUniversalCamera.prototype.getClassName = function () {
  48685. return "AnaglyphUniversalCamera";
  48686. };
  48687. return AnaglyphUniversalCamera;
  48688. }(BABYLON.UniversalCamera));
  48689. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  48690. var StereoscopicFreeCamera = (function (_super) {
  48691. __extends(StereoscopicFreeCamera, _super);
  48692. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  48693. var _this = _super.call(this, name, position, scene) || this;
  48694. _this.interaxialDistance = interaxialDistance;
  48695. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  48696. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  48697. return _this;
  48698. }
  48699. StereoscopicFreeCamera.prototype.getClassName = function () {
  48700. return "StereoscopicFreeCamera";
  48701. };
  48702. return StereoscopicFreeCamera;
  48703. }(BABYLON.FreeCamera));
  48704. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  48705. var StereoscopicArcRotateCamera = (function (_super) {
  48706. __extends(StereoscopicArcRotateCamera, _super);
  48707. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  48708. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  48709. _this.interaxialDistance = interaxialDistance;
  48710. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  48711. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  48712. return _this;
  48713. }
  48714. StereoscopicArcRotateCamera.prototype.getClassName = function () {
  48715. return "StereoscopicArcRotateCamera";
  48716. };
  48717. return StereoscopicArcRotateCamera;
  48718. }(BABYLON.ArcRotateCamera));
  48719. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  48720. var StereoscopicGamepadCamera = (function (_super) {
  48721. __extends(StereoscopicGamepadCamera, _super);
  48722. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  48723. var _this = _super.call(this, name, position, scene) || this;
  48724. _this.interaxialDistance = interaxialDistance;
  48725. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  48726. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  48727. return _this;
  48728. }
  48729. StereoscopicGamepadCamera.prototype.getClassName = function () {
  48730. return "StereoscopicGamepadCamera";
  48731. };
  48732. return StereoscopicGamepadCamera;
  48733. }(BABYLON.GamepadCamera));
  48734. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  48735. var StereoscopicUniversalCamera = (function (_super) {
  48736. __extends(StereoscopicUniversalCamera, _super);
  48737. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  48738. var _this = _super.call(this, name, position, scene) || this;
  48739. _this.interaxialDistance = interaxialDistance;
  48740. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  48741. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  48742. return _this;
  48743. }
  48744. StereoscopicUniversalCamera.prototype.getClassName = function () {
  48745. return "StereoscopicUniversalCamera";
  48746. };
  48747. return StereoscopicUniversalCamera;
  48748. }(BABYLON.UniversalCamera));
  48749. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  48750. })(BABYLON || (BABYLON = {}));
  48751. //# sourceMappingURL=babylon.stereoscopicCameras.js.map
  48752. var BABYLON;
  48753. (function (BABYLON) {
  48754. var HolographicCamera = (function (_super) {
  48755. __extends(HolographicCamera, _super);
  48756. function HolographicCamera(name, scene) {
  48757. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  48758. scene.clearColor = new BABYLON.Color4(0, 0, 0, 0);
  48759. _this._holographicViewMatrix = new BABYLON.Matrix();
  48760. _this._identityProjection = BABYLON.Matrix.Identity();
  48761. _this._scriptProjection = BABYLON.Matrix.Transpose(BABYLON.Matrix.PerspectiveFovLH(30, window.innerWidth / window.innerHeight, 1, 20));
  48762. _this._scriptViewProjection = BABYLON.Matrix.Identity();
  48763. _this.fov = 30;
  48764. _this.minZ = 1.0;
  48765. _this.maxZ = 20;
  48766. _this.mode = BABYLON.Camera.PERSPECTIVE_CAMERA;
  48767. _this.isIntermediate = false;
  48768. _this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  48769. _this.layerMask = 0x0FFFFFFF;
  48770. _this.fovMode = BABYLON.Camera.FOVMODE_VERTICAL_FIXED;
  48771. _this.cameraRigMode = BABYLON.Camera.RIG_MODE_NONE;
  48772. var self = _this;
  48773. _this._onBeforeRenderObserver = scene.onBeforeRenderObservable.add(function (scene) {
  48774. self._holographicViewMatrix.m = window.getViewMatrix();
  48775. self.setViewMatrix(self._holographicViewMatrix);
  48776. var position = window.getCameraPositionVector();
  48777. self.position.copyFromFloats(-position[0], position[1], -position[2]);
  48778. });
  48779. _this._onBeforeCameraRenderObserver = scene.onBeforeCameraRenderObservable.add(function () {
  48780. if (scene.frustumPlanes) {
  48781. self.getFrustumPlanesToRef(scene.frustumPlanes);
  48782. }
  48783. });
  48784. scene.addCamera(_this);
  48785. if (!scene.activeCamera) {
  48786. scene.activeCamera = _this;
  48787. }
  48788. return _this;
  48789. }
  48790. HolographicCamera.prototype.getTypeName = function () {
  48791. return "HolographicCamera";
  48792. };
  48793. ;
  48794. HolographicCamera.prototype.getProjectionMatrix = function () {
  48795. return this._identityProjection;
  48796. };
  48797. ;
  48798. HolographicCamera.prototype.getViewMatrix = function () {
  48799. return this._holographicViewMatrix;
  48800. };
  48801. ;
  48802. HolographicCamera.prototype.setViewMatrix = function (view) {
  48803. this._holographicViewMatrix = view;
  48804. view.m[0] = -view.m[0];
  48805. view.m[1] = -view.m[1];
  48806. view.m[2] = -view.m[2];
  48807. view.m[3] = -view.m[3];
  48808. view.m[8] = -view.m[8];
  48809. view.m[9] = -view.m[9];
  48810. view.m[10] = -view.m[10];
  48811. view.m[11] = -view.m[11];
  48812. };
  48813. ;
  48814. HolographicCamera.prototype._initCache = function () { };
  48815. ;
  48816. HolographicCamera.prototype._updateCache = function () { };
  48817. ;
  48818. HolographicCamera.prototype._updateFromScene = function () { };
  48819. ;
  48820. // Synchronized
  48821. HolographicCamera.prototype._isSynchronizedViewMatrix = function () {
  48822. return true;
  48823. };
  48824. ;
  48825. HolographicCamera.prototype._isSynchronizedProjectionMatrix = function () {
  48826. return true;
  48827. };
  48828. ;
  48829. HolographicCamera.prototype.getFrustumPlanesToRef = function (result) {
  48830. this._holographicViewMatrix.multiplyToRef(this._scriptProjection, this._scriptViewProjection);
  48831. BABYLON.Frustum.GetPlanesToRef(this._scriptViewProjection, result);
  48832. return result;
  48833. };
  48834. ;
  48835. HolographicCamera.prototype.dispose = function () {
  48836. this.getScene().onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  48837. this.getScene().onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  48838. _super.prototype.dispose.call(this);
  48839. };
  48840. return HolographicCamera;
  48841. }(BABYLON.Camera));
  48842. BABYLON.HolographicCamera = HolographicCamera;
  48843. })(BABYLON || (BABYLON = {}));
  48844. //# sourceMappingURL=babylon.holographicCamera.js.map
  48845. var BABYLON;
  48846. (function (BABYLON) {
  48847. var HDRRenderingPipeline = (function (_super) {
  48848. __extends(HDRRenderingPipeline, _super);
  48849. /**
  48850. * @constructor
  48851. * @param {string} name - The rendering pipeline name
  48852. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  48853. * @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)
  48854. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  48855. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  48856. */
  48857. function HDRRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  48858. if (originalPostProcess === void 0) { originalPostProcess = null; }
  48859. var _this = _super.call(this, scene.getEngine(), name) || this;
  48860. /**
  48861. * Public members
  48862. */
  48863. // Gaussian Blur
  48864. /**
  48865. * Gaussian blur coefficient
  48866. * @type {number}
  48867. */
  48868. _this.gaussCoeff = 0.3;
  48869. /**
  48870. * Gaussian blur mean
  48871. * @type {number}
  48872. */
  48873. _this.gaussMean = 1.0;
  48874. /**
  48875. * Gaussian blur standard deviation
  48876. * @type {number}
  48877. */
  48878. _this.gaussStandDev = 0.8;
  48879. /**
  48880. * Gaussian blur multiplier. Multiplies the blur effect
  48881. * @type {number}
  48882. */
  48883. _this.gaussMultiplier = 4.0;
  48884. // HDR
  48885. /**
  48886. * Exposure, controls the overall intensity of the pipeline
  48887. * @type {number}
  48888. */
  48889. _this.exposure = 1.0;
  48890. /**
  48891. * Minimum luminance that the post-process can output. Luminance is >= 0
  48892. * @type {number}
  48893. */
  48894. _this.minimumLuminance = 1.0;
  48895. /**
  48896. * Maximum luminance that the post-process can output. Must be suprerior to minimumLuminance
  48897. * @type {number}
  48898. */
  48899. _this.maximumLuminance = 1e20;
  48900. /**
  48901. * Increase rate for luminance: eye adaptation speed to dark
  48902. * @type {number}
  48903. */
  48904. _this.luminanceIncreaserate = 0.5;
  48905. /**
  48906. * Decrease rate for luminance: eye adaptation speed to bright
  48907. * @type {number}
  48908. */
  48909. _this.luminanceDecreaseRate = 0.5;
  48910. // Bright pass
  48911. /**
  48912. * Minimum luminance needed to compute HDR
  48913. * @type {number}
  48914. */
  48915. _this.brightThreshold = 0.8;
  48916. _this._needUpdate = true;
  48917. _this._scene = scene;
  48918. // Bright pass
  48919. _this._createBrightPassPostProcess(scene, ratio);
  48920. // Down sample X4
  48921. _this._createDownSampleX4PostProcess(scene, ratio);
  48922. // Create gaussian blur post-processes
  48923. _this._createGaussianBlurPostProcess(scene, ratio);
  48924. // Texture adder
  48925. _this._createTextureAdderPostProcess(scene, ratio);
  48926. // Luminance generator
  48927. _this._createLuminanceGeneratorPostProcess(scene);
  48928. // HDR
  48929. _this._createHDRPostProcess(scene, ratio);
  48930. // Pass postprocess
  48931. if (originalPostProcess === null) {
  48932. _this._originalPostProcess = new BABYLON.PassPostProcess("hdr", ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  48933. }
  48934. else {
  48935. _this._originalPostProcess = originalPostProcess;
  48936. }
  48937. // Configure pipeline
  48938. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this._originalPostProcess; }, true));
  48939. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this._brightPassPostProcess; }, true));
  48940. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this._downSampleX4PostProcess; }, true));
  48941. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurH", function () { return _this._guassianBlurHPostProcess; }, true));
  48942. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurV", function () { return _this._guassianBlurVPostProcess; }, true));
  48943. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this._textureAdderPostProcess; }, true));
  48944. var addDownSamplerPostProcess = function (id) {
  48945. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampler" + id, function () { return _this._downSamplePostProcesses[id]; }, true));
  48946. };
  48947. for (var i = HDRRenderingPipeline.LUM_STEPS - 1; i >= 0; i--) {
  48948. addDownSamplerPostProcess(i);
  48949. }
  48950. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this._hdrPostProcess; }, true));
  48951. // Finish
  48952. scene.postProcessRenderPipelineManager.addPipeline(_this);
  48953. if (cameras !== null) {
  48954. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  48955. }
  48956. _this.update();
  48957. return _this;
  48958. }
  48959. /**
  48960. * Tells the pipeline to update its post-processes
  48961. */
  48962. HDRRenderingPipeline.prototype.update = function () {
  48963. this._needUpdate = true;
  48964. };
  48965. /**
  48966. * Returns the current calculated luminance
  48967. */
  48968. HDRRenderingPipeline.prototype.getCurrentLuminance = function () {
  48969. return this._hdrCurrentLuminance;
  48970. };
  48971. /**
  48972. * Returns the currently drawn luminance
  48973. */
  48974. HDRRenderingPipeline.prototype.getOutputLuminance = function () {
  48975. return this._hdrOutputLuminance;
  48976. };
  48977. /**
  48978. * Releases the rendering pipeline and its internal effects. Detaches pipeline from cameras
  48979. */
  48980. HDRRenderingPipeline.prototype.dispose = function () {
  48981. for (var i = 0; i < this._scene.cameras.length; i++) {
  48982. var camera = this._scene.cameras[i];
  48983. this._originalPostProcess.dispose(camera);
  48984. this._brightPassPostProcess.dispose(camera);
  48985. this._downSampleX4PostProcess.dispose(camera);
  48986. this._guassianBlurHPostProcess.dispose(camera);
  48987. this._guassianBlurVPostProcess.dispose(camera);
  48988. this._textureAdderPostProcess.dispose(camera);
  48989. for (var j = HDRRenderingPipeline.LUM_STEPS - 1; j >= 0; j--) {
  48990. this._downSamplePostProcesses[j].dispose(camera);
  48991. }
  48992. this._hdrPostProcess.dispose(camera);
  48993. }
  48994. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  48995. _super.prototype.dispose.call(this);
  48996. };
  48997. /**
  48998. * Creates the HDR post-process and computes the luminance adaptation
  48999. */
  49000. HDRRenderingPipeline.prototype._createHDRPostProcess = function (scene, ratio) {
  49001. var _this = this;
  49002. var hdrLastLuminance = 0.0;
  49003. this._hdrOutputLuminance = -1.0;
  49004. this._hdrCurrentLuminance = 1.0;
  49005. this._hdrPostProcess = new BABYLON.PostProcess("hdr", "hdr", ["exposure", "avgLuminance"], ["otherSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define HDR");
  49006. this._hdrPostProcess.onApply = function (effect) {
  49007. if (_this._hdrOutputLuminance < 0.0) {
  49008. _this._hdrOutputLuminance = _this._hdrCurrentLuminance;
  49009. }
  49010. else {
  49011. var dt = (hdrLastLuminance - (hdrLastLuminance + scene.getEngine().getDeltaTime())) / 1000.0;
  49012. if (_this._hdrCurrentLuminance < _this._hdrOutputLuminance + _this.luminanceDecreaseRate * dt) {
  49013. _this._hdrOutputLuminance += _this.luminanceDecreaseRate * dt;
  49014. }
  49015. else if (_this._hdrCurrentLuminance > _this._hdrOutputLuminance - _this.luminanceIncreaserate * dt) {
  49016. _this._hdrOutputLuminance -= _this.luminanceIncreaserate * dt;
  49017. }
  49018. else {
  49019. _this._hdrOutputLuminance = _this._hdrCurrentLuminance;
  49020. }
  49021. }
  49022. _this._hdrOutputLuminance = BABYLON.MathTools.Clamp(_this._hdrOutputLuminance, _this.minimumLuminance, _this.maximumLuminance);
  49023. hdrLastLuminance += scene.getEngine().getDeltaTime();
  49024. effect.setTextureFromPostProcess("textureSampler", _this._textureAdderPostProcess);
  49025. effect.setTextureFromPostProcess("otherSampler", _this._originalPostProcess);
  49026. effect.setFloat("exposure", _this.exposure);
  49027. effect.setFloat("avgLuminance", _this._hdrOutputLuminance);
  49028. _this._needUpdate = false;
  49029. };
  49030. };
  49031. /**
  49032. * Texture Adder post-process
  49033. */
  49034. HDRRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  49035. var _this = this;
  49036. this._textureAdderPostProcess = new BABYLON.PostProcess("hdr", "hdr", [], ["otherSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define TEXTURE_ADDER");
  49037. this._textureAdderPostProcess.onApply = function (effect) {
  49038. effect.setTextureFromPostProcess("otherSampler", _this._originalPostProcess);
  49039. };
  49040. };
  49041. /**
  49042. * Down sample X4 post-process
  49043. */
  49044. HDRRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  49045. var _this = this;
  49046. var downSampleX4Offsets = new Array(32);
  49047. this._downSampleX4PostProcess = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets"], [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define DOWN_SAMPLE_X4");
  49048. this._downSampleX4PostProcess.onApply = function (effect) {
  49049. if (_this._needUpdate) {
  49050. var id = 0;
  49051. for (var i = -2; i < 2; i++) {
  49052. for (var j = -2; j < 2; j++) {
  49053. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / _this._downSampleX4PostProcess.width);
  49054. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / _this._downSampleX4PostProcess.height);
  49055. id += 2;
  49056. }
  49057. }
  49058. }
  49059. effect.setArray2("dsOffsets", downSampleX4Offsets);
  49060. };
  49061. };
  49062. /**
  49063. * Bright pass post-process
  49064. */
  49065. HDRRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  49066. var _this = this;
  49067. var brightOffsets = new Array(8);
  49068. var brightPassCallback = function (effect) {
  49069. if (_this._needUpdate) {
  49070. var sU = (1.0 / _this._brightPassPostProcess.width);
  49071. var sV = (1.0 / _this._brightPassPostProcess.height);
  49072. brightOffsets[0] = -0.5 * sU;
  49073. brightOffsets[1] = 0.5 * sV;
  49074. brightOffsets[2] = 0.5 * sU;
  49075. brightOffsets[3] = 0.5 * sV;
  49076. brightOffsets[4] = -0.5 * sU;
  49077. brightOffsets[5] = -0.5 * sV;
  49078. brightOffsets[6] = 0.5 * sU;
  49079. brightOffsets[7] = -0.5 * sV;
  49080. }
  49081. effect.setArray2("dsOffsets", brightOffsets);
  49082. effect.setFloat("brightThreshold", _this.brightThreshold);
  49083. };
  49084. this._brightPassPostProcess = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets", "brightThreshold"], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define BRIGHT_PASS");
  49085. this._brightPassPostProcess.onApply = brightPassCallback;
  49086. };
  49087. /**
  49088. * Luminance generator. Creates the luminance post-process and down sample post-processes
  49089. */
  49090. HDRRenderingPipeline.prototype._createLuminanceGeneratorPostProcess = function (scene) {
  49091. var _this = this;
  49092. var lumSteps = HDRRenderingPipeline.LUM_STEPS;
  49093. var luminanceOffsets = new Array(8);
  49094. var downSampleOffsets = new Array(18);
  49095. var halfDestPixelSize;
  49096. this._downSamplePostProcesses = new Array(lumSteps);
  49097. // Utils for luminance
  49098. var luminanceUpdateSourceOffsets = function (width, height) {
  49099. var sU = (1.0 / width);
  49100. var sV = (1.0 / height);
  49101. luminanceOffsets[0] = -0.5 * sU;
  49102. luminanceOffsets[1] = 0.5 * sV;
  49103. luminanceOffsets[2] = 0.5 * sU;
  49104. luminanceOffsets[3] = 0.5 * sV;
  49105. luminanceOffsets[4] = -0.5 * sU;
  49106. luminanceOffsets[5] = -0.5 * sV;
  49107. luminanceOffsets[6] = 0.5 * sU;
  49108. luminanceOffsets[7] = -0.5 * sV;
  49109. };
  49110. var luminanceUpdateDestOffsets = function (width, height) {
  49111. var id = 0;
  49112. for (var x = -1; x < 2; x++) {
  49113. for (var y = -1; y < 2; y++) {
  49114. downSampleOffsets[id] = (x) / width;
  49115. downSampleOffsets[id + 1] = (y) / height;
  49116. id += 2;
  49117. }
  49118. }
  49119. };
  49120. // Luminance callback
  49121. var luminanceCallback = function (effect) {
  49122. if (_this._needUpdate) {
  49123. luminanceUpdateSourceOffsets(_this._textureAdderPostProcess.width, _this._textureAdderPostProcess.height);
  49124. }
  49125. effect.setTextureFromPostProcess("textureSampler", _this._textureAdderPostProcess);
  49126. effect.setArray2("lumOffsets", luminanceOffsets);
  49127. };
  49128. // Down sample callbacks
  49129. var downSampleCallback = function (indice) {
  49130. var i = indice;
  49131. return function (effect) {
  49132. luminanceUpdateSourceOffsets(_this._downSamplePostProcesses[i].width, _this._downSamplePostProcesses[i].height);
  49133. luminanceUpdateDestOffsets(_this._downSamplePostProcesses[i].width, _this._downSamplePostProcesses[i].height);
  49134. halfDestPixelSize = 0.5 / _this._downSamplePostProcesses[i].width;
  49135. effect.setTextureFromPostProcess("textureSampler", _this._downSamplePostProcesses[i + 1]);
  49136. effect.setFloat("halfDestPixelSize", halfDestPixelSize);
  49137. effect.setArray2("dsOffsets", downSampleOffsets);
  49138. };
  49139. };
  49140. var downSampleAfterRenderCallback = function (effect) {
  49141. // Unpack result
  49142. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  49143. 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);
  49144. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  49145. };
  49146. // Create luminance post-process
  49147. var ratio = { width: Math.pow(3, lumSteps - 1), height: Math.pow(3, lumSteps - 1) };
  49148. this._downSamplePostProcesses[lumSteps - 1] = new BABYLON.PostProcess("hdr", "hdr", ["lumOffsets"], [], ratio, null, BABYLON.Texture.NEAREST_SAMPLINGMODE, scene.getEngine(), false, "#define LUMINANCE_GENERATOR", BABYLON.Engine.TEXTURETYPE_FLOAT);
  49149. this._downSamplePostProcesses[lumSteps - 1].onApply = luminanceCallback;
  49150. // Create down sample post-processes
  49151. for (var i = lumSteps - 2; i >= 0; i--) {
  49152. var length = Math.pow(3, i);
  49153. ratio = { width: length, height: length };
  49154. var defines = "#define DOWN_SAMPLE\n";
  49155. if (i === 0) {
  49156. defines += "#define FINAL_DOWN_SAMPLE\n"; // To pack the result
  49157. }
  49158. this._downSamplePostProcesses[i] = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets", "halfDestPixelSize"], [], ratio, null, BABYLON.Texture.NEAREST_SAMPLINGMODE, scene.getEngine(), false, defines, BABYLON.Engine.TEXTURETYPE_FLOAT);
  49159. this._downSamplePostProcesses[i].onApply = downSampleCallback(i);
  49160. if (i === 0) {
  49161. this._downSamplePostProcesses[i].onAfterRender = downSampleAfterRenderCallback;
  49162. }
  49163. }
  49164. };
  49165. /**
  49166. * Gaussian blur post-processes. Horizontal and Vertical
  49167. */
  49168. HDRRenderingPipeline.prototype._createGaussianBlurPostProcess = function (scene, ratio) {
  49169. var _this = this;
  49170. var blurOffsetsW = new Array(9);
  49171. var blurOffsetsH = new Array(9);
  49172. var blurWeights = new Array(9);
  49173. var uniforms = ["blurOffsets", "blurWeights", "multiplier"];
  49174. // Utils for gaussian blur
  49175. var calculateBlurOffsets = function (height) {
  49176. var lastOutputDimensions = {
  49177. width: scene.getEngine().getRenderWidth(),
  49178. height: scene.getEngine().getRenderHeight()
  49179. };
  49180. for (var i = 0; i < 9; i++) {
  49181. var value = (i - 4.0) * (1.0 / (height === true ? lastOutputDimensions.height : lastOutputDimensions.width));
  49182. if (height) {
  49183. blurOffsetsH[i] = value;
  49184. }
  49185. else {
  49186. blurOffsetsW[i] = value;
  49187. }
  49188. }
  49189. };
  49190. var calculateWeights = function () {
  49191. var x = 0.0;
  49192. for (var i = 0; i < 9; i++) {
  49193. x = (i - 4.0) / 4.0;
  49194. blurWeights[i] = _this.gaussCoeff * (1.0 / Math.sqrt(2.0 * Math.PI * _this.gaussStandDev)) * Math.exp((-((x - _this.gaussMean) * (x - _this.gaussMean))) / (2.0 * _this.gaussStandDev * _this.gaussStandDev));
  49195. }
  49196. };
  49197. // Callback
  49198. var gaussianBlurCallback = function (height) {
  49199. return function (effect) {
  49200. if (_this._needUpdate) {
  49201. calculateWeights();
  49202. calculateBlurOffsets(height);
  49203. }
  49204. effect.setArray("blurOffsets", height ? blurOffsetsH : blurOffsetsW);
  49205. effect.setArray("blurWeights", blurWeights);
  49206. effect.setFloat("multiplier", _this.gaussMultiplier);
  49207. };
  49208. };
  49209. // Create horizontal gaussian blur post-processes
  49210. this._guassianBlurHPostProcess = new BABYLON.PostProcess("hdr", "hdr", uniforms, [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define GAUSSIAN_BLUR_H");
  49211. this._guassianBlurHPostProcess.onApply = gaussianBlurCallback(false);
  49212. // Create vertical gaussian blur post-process
  49213. this._guassianBlurVPostProcess = new BABYLON.PostProcess("hdr", "hdr", uniforms, [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define GAUSSIAN_BLUR_V");
  49214. this._guassianBlurVPostProcess.onApply = gaussianBlurCallback(true);
  49215. };
  49216. return HDRRenderingPipeline;
  49217. }(BABYLON.PostProcessRenderPipeline));
  49218. // Luminance generator
  49219. HDRRenderingPipeline.LUM_STEPS = 6;
  49220. BABYLON.HDRRenderingPipeline = HDRRenderingPipeline;
  49221. })(BABYLON || (BABYLON = {}));
  49222. //# sourceMappingURL=babylon.hdrRenderingPipeline.js.map
  49223. var BABYLON;
  49224. (function (BABYLON) {
  49225. var FaceAdjacencies = (function () {
  49226. function FaceAdjacencies() {
  49227. this.edges = new Array();
  49228. this.edgesConnectedCount = 0;
  49229. }
  49230. return FaceAdjacencies;
  49231. }());
  49232. var EdgesRenderer = (function () {
  49233. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  49234. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  49235. if (epsilon === void 0) { epsilon = 0.95; }
  49236. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  49237. this.edgesWidthScalerForOrthographic = 1000.0;
  49238. this.edgesWidthScalerForPerspective = 50.0;
  49239. this._linesPositions = new Array();
  49240. this._linesNormals = new Array();
  49241. this._linesIndices = new Array();
  49242. this._buffers = {};
  49243. this._checkVerticesInsteadOfIndices = false;
  49244. this._source = source;
  49245. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  49246. this._epsilon = epsilon;
  49247. this._prepareRessources();
  49248. this._generateEdgesLines();
  49249. }
  49250. EdgesRenderer.prototype._prepareRessources = function () {
  49251. if (this._lineShader) {
  49252. return;
  49253. }
  49254. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  49255. attributes: ["position", "normal"],
  49256. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  49257. });
  49258. this._lineShader.disableDepthWrite = true;
  49259. this._lineShader.backFaceCulling = false;
  49260. };
  49261. EdgesRenderer.prototype.dispose = function () {
  49262. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  49263. if (buffer) {
  49264. buffer.dispose();
  49265. this._buffers[BABYLON.VertexBuffer.PositionKind] = null;
  49266. }
  49267. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  49268. if (buffer) {
  49269. buffer.dispose();
  49270. this._buffers[BABYLON.VertexBuffer.NormalKind] = null;
  49271. }
  49272. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  49273. this._lineShader.dispose();
  49274. };
  49275. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  49276. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  49277. return 0;
  49278. }
  49279. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  49280. return 1;
  49281. }
  49282. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  49283. return 2;
  49284. }
  49285. return -1;
  49286. };
  49287. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  49288. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  49289. return 0;
  49290. }
  49291. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  49292. return 1;
  49293. }
  49294. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  49295. return 2;
  49296. }
  49297. return -1;
  49298. };
  49299. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  49300. var needToCreateLine;
  49301. if (edge === undefined) {
  49302. needToCreateLine = true;
  49303. }
  49304. else {
  49305. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  49306. needToCreateLine = dotProduct < this._epsilon;
  49307. }
  49308. if (needToCreateLine) {
  49309. var offset = this._linesPositions.length / 3;
  49310. var normal = p0.subtract(p1);
  49311. normal.normalize();
  49312. // Positions
  49313. this._linesPositions.push(p0.x);
  49314. this._linesPositions.push(p0.y);
  49315. this._linesPositions.push(p0.z);
  49316. this._linesPositions.push(p0.x);
  49317. this._linesPositions.push(p0.y);
  49318. this._linesPositions.push(p0.z);
  49319. this._linesPositions.push(p1.x);
  49320. this._linesPositions.push(p1.y);
  49321. this._linesPositions.push(p1.z);
  49322. this._linesPositions.push(p1.x);
  49323. this._linesPositions.push(p1.y);
  49324. this._linesPositions.push(p1.z);
  49325. // Normals
  49326. this._linesNormals.push(p1.x);
  49327. this._linesNormals.push(p1.y);
  49328. this._linesNormals.push(p1.z);
  49329. this._linesNormals.push(-1);
  49330. this._linesNormals.push(p1.x);
  49331. this._linesNormals.push(p1.y);
  49332. this._linesNormals.push(p1.z);
  49333. this._linesNormals.push(1);
  49334. this._linesNormals.push(p0.x);
  49335. this._linesNormals.push(p0.y);
  49336. this._linesNormals.push(p0.z);
  49337. this._linesNormals.push(-1);
  49338. this._linesNormals.push(p0.x);
  49339. this._linesNormals.push(p0.y);
  49340. this._linesNormals.push(p0.z);
  49341. this._linesNormals.push(1);
  49342. // Indices
  49343. this._linesIndices.push(offset);
  49344. this._linesIndices.push(offset + 1);
  49345. this._linesIndices.push(offset + 2);
  49346. this._linesIndices.push(offset);
  49347. this._linesIndices.push(offset + 2);
  49348. this._linesIndices.push(offset + 3);
  49349. }
  49350. };
  49351. EdgesRenderer.prototype._generateEdgesLines = function () {
  49352. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  49353. var indices = this._source.getIndices();
  49354. // First let's find adjacencies
  49355. var adjacencies = new Array();
  49356. var faceNormals = new Array();
  49357. var index;
  49358. var faceAdjacencies;
  49359. // Prepare faces
  49360. for (index = 0; index < indices.length; index += 3) {
  49361. faceAdjacencies = new FaceAdjacencies();
  49362. var p0Index = indices[index];
  49363. var p1Index = indices[index + 1];
  49364. var p2Index = indices[index + 2];
  49365. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  49366. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  49367. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  49368. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  49369. faceNormal.normalize();
  49370. faceNormals.push(faceNormal);
  49371. adjacencies.push(faceAdjacencies);
  49372. }
  49373. // Scan
  49374. for (index = 0; index < adjacencies.length; index++) {
  49375. faceAdjacencies = adjacencies[index];
  49376. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  49377. var otherFaceAdjacencies = adjacencies[otherIndex];
  49378. if (faceAdjacencies.edgesConnectedCount === 3) {
  49379. break;
  49380. }
  49381. if (otherFaceAdjacencies.edgesConnectedCount === 3) {
  49382. continue;
  49383. }
  49384. var otherP0 = indices[otherIndex * 3];
  49385. var otherP1 = indices[otherIndex * 3 + 1];
  49386. var otherP2 = indices[otherIndex * 3 + 2];
  49387. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  49388. var otherEdgeIndex;
  49389. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  49390. continue;
  49391. }
  49392. switch (edgeIndex) {
  49393. case 0:
  49394. if (this._checkVerticesInsteadOfIndices) {
  49395. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  49396. }
  49397. else {
  49398. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  49399. }
  49400. break;
  49401. case 1:
  49402. if (this._checkVerticesInsteadOfIndices) {
  49403. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  49404. }
  49405. else {
  49406. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  49407. }
  49408. break;
  49409. case 2:
  49410. if (this._checkVerticesInsteadOfIndices) {
  49411. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  49412. }
  49413. else {
  49414. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  49415. }
  49416. break;
  49417. }
  49418. if (otherEdgeIndex === -1) {
  49419. continue;
  49420. }
  49421. faceAdjacencies.edges[edgeIndex] = otherIndex;
  49422. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  49423. faceAdjacencies.edgesConnectedCount++;
  49424. otherFaceAdjacencies.edgesConnectedCount++;
  49425. if (faceAdjacencies.edgesConnectedCount === 3) {
  49426. break;
  49427. }
  49428. }
  49429. }
  49430. }
  49431. // Create lines
  49432. for (index = 0; index < adjacencies.length; index++) {
  49433. // 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
  49434. var current = adjacencies[index];
  49435. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  49436. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  49437. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  49438. }
  49439. // Merge into a single mesh
  49440. var engine = this._source.getScene().getEngine();
  49441. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  49442. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  49443. this._ib = engine.createIndexBuffer(this._linesIndices);
  49444. this._indicesCount = this._linesIndices.length;
  49445. };
  49446. EdgesRenderer.prototype.render = function () {
  49447. if (!this._lineShader.isReady()) {
  49448. return;
  49449. }
  49450. var scene = this._source.getScene();
  49451. var engine = scene.getEngine();
  49452. this._lineShader._preBind();
  49453. // VBOs
  49454. engine.bindBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  49455. scene.resetCachedMaterial();
  49456. this._lineShader.setColor4("color", this._source.edgesColor);
  49457. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  49458. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  49459. }
  49460. else {
  49461. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  49462. }
  49463. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  49464. this._lineShader.bind(this._source.getWorldMatrix());
  49465. // Draw order
  49466. engine.draw(true, 0, this._indicesCount);
  49467. this._lineShader.unbind();
  49468. engine.setDepthWrite(true);
  49469. };
  49470. return EdgesRenderer;
  49471. }());
  49472. BABYLON.EdgesRenderer = EdgesRenderer;
  49473. })(BABYLON || (BABYLON = {}));
  49474. //# sourceMappingURL=babylon.edgesRenderer.js.map
  49475. var BABYLON;
  49476. (function (BABYLON) {
  49477. var TonemappingOperator;
  49478. (function (TonemappingOperator) {
  49479. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  49480. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  49481. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  49482. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  49483. })(TonemappingOperator = BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  49484. ;
  49485. var TonemapPostProcess = (function (_super) {
  49486. __extends(TonemapPostProcess, _super);
  49487. function TonemapPostProcess(name, _operator, exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  49488. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  49489. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  49490. var _this = _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, defines, textureFormat) || this;
  49491. _this._operator = _operator;
  49492. _this.exposureAdjustment = exposureAdjustment;
  49493. var defines = "#define ";
  49494. if (_this._operator === TonemappingOperator.Hable)
  49495. defines += "HABLE_TONEMAPPING";
  49496. else if (_this._operator === TonemappingOperator.Reinhard)
  49497. defines += "REINHARD_TONEMAPPING";
  49498. else if (_this._operator === TonemappingOperator.HejiDawson)
  49499. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  49500. else if (_this._operator === TonemappingOperator.Photographic)
  49501. defines += "PHOTOGRAPHIC_TONEMAPPING";
  49502. //sadly a second call to create the effect.
  49503. _this.updateEffect(defines);
  49504. _this.onApply = function (effect) {
  49505. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  49506. };
  49507. return _this;
  49508. }
  49509. return TonemapPostProcess;
  49510. }(BABYLON.PostProcess));
  49511. BABYLON.TonemapPostProcess = TonemapPostProcess;
  49512. })(BABYLON || (BABYLON = {}));
  49513. //# sourceMappingURL=babylon.tonemapPostProcess.js.map
  49514. var BABYLON;
  49515. (function (BABYLON) {
  49516. var ReflectionProbe = (function () {
  49517. function ReflectionProbe(name, size, scene, generateMipMaps) {
  49518. if (generateMipMaps === void 0) { generateMipMaps = true; }
  49519. var _this = this;
  49520. this.name = name;
  49521. this._viewMatrix = BABYLON.Matrix.Identity();
  49522. this._target = BABYLON.Vector3.Zero();
  49523. this._add = BABYLON.Vector3.Zero();
  49524. this.invertYAxis = false;
  49525. this.position = BABYLON.Vector3.Zero();
  49526. this._scene = scene;
  49527. this._scene.reflectionProbes.push(this);
  49528. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  49529. this._renderTargetTexture.onBeforeRenderObservable.add(function (faceIndex) {
  49530. switch (faceIndex) {
  49531. case 0:
  49532. _this._add.copyFromFloats(1, 0, 0);
  49533. break;
  49534. case 1:
  49535. _this._add.copyFromFloats(-1, 0, 0);
  49536. break;
  49537. case 2:
  49538. _this._add.copyFromFloats(0, _this.invertYAxis ? 1 : -1, 0);
  49539. break;
  49540. case 3:
  49541. _this._add.copyFromFloats(0, _this.invertYAxis ? -1 : 1, 0);
  49542. break;
  49543. case 4:
  49544. _this._add.copyFromFloats(0, 0, 1);
  49545. break;
  49546. case 5:
  49547. _this._add.copyFromFloats(0, 0, -1);
  49548. break;
  49549. }
  49550. if (_this._attachedMesh) {
  49551. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  49552. }
  49553. _this.position.addToRef(_this._add, _this._target);
  49554. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  49555. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  49556. });
  49557. this._renderTargetTexture.onAfterUnbindObservable.add(function () {
  49558. scene.updateTransformMatrix(true);
  49559. });
  49560. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  49561. }
  49562. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  49563. get: function () {
  49564. return this._renderTargetTexture.refreshRate;
  49565. },
  49566. set: function (value) {
  49567. this._renderTargetTexture.refreshRate = value;
  49568. },
  49569. enumerable: true,
  49570. configurable: true
  49571. });
  49572. ReflectionProbe.prototype.getScene = function () {
  49573. return this._scene;
  49574. };
  49575. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  49576. get: function () {
  49577. return this._renderTargetTexture;
  49578. },
  49579. enumerable: true,
  49580. configurable: true
  49581. });
  49582. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  49583. get: function () {
  49584. return this._renderTargetTexture.renderList;
  49585. },
  49586. enumerable: true,
  49587. configurable: true
  49588. });
  49589. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  49590. this._attachedMesh = mesh;
  49591. };
  49592. ReflectionProbe.prototype.dispose = function () {
  49593. var index = this._scene.reflectionProbes.indexOf(this);
  49594. if (index !== -1) {
  49595. // Remove from the scene if found
  49596. this._scene.reflectionProbes.splice(index, 1);
  49597. }
  49598. if (this._renderTargetTexture) {
  49599. this._renderTargetTexture.dispose();
  49600. this._renderTargetTexture = null;
  49601. }
  49602. };
  49603. return ReflectionProbe;
  49604. }());
  49605. BABYLON.ReflectionProbe = ReflectionProbe;
  49606. })(BABYLON || (BABYLON = {}));
  49607. //# sourceMappingURL=babylon.reflectionProbe.js.map
  49608. var BABYLON;
  49609. (function (BABYLON) {
  49610. var SolidParticle = (function () {
  49611. /**
  49612. * Creates a Solid Particle object.
  49613. * Don't create particles manually, use instead the Solid Particle System internal tools like _addParticle()
  49614. * `particleIndex` (integer) is the particle index in the Solid Particle System pool. It's also the particle identifier.
  49615. * `positionIndex` (integer) is the starting index of the particle vertices in the SPS "positions" array.
  49616. * `model` (ModelShape) is a reference to the model shape on what the particle is designed.
  49617. * `shapeId` (integer) is the model shape identifier in the SPS.
  49618. * `idxInShape` (integer) is the index of the particle in the current model (ex: the 10th box of addShape(box, 30))
  49619. * `modelBoundingInfo` is the reference to the model BoundingInfo used for intersection computations.
  49620. */
  49621. function SolidParticle(particleIndex, positionIndex, model, shapeId, idxInShape, sps, modelBoundingInfo) {
  49622. this.idx = 0; // particle global index
  49623. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0); // color
  49624. this.position = BABYLON.Vector3.Zero(); // position
  49625. this.rotation = BABYLON.Vector3.Zero(); // rotation
  49626. this.scaling = new BABYLON.Vector3(1.0, 1.0, 1.0); // scaling
  49627. this.uvs = new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0); // uvs
  49628. this.velocity = BABYLON.Vector3.Zero(); // velocity
  49629. this.alive = true; // alive
  49630. this.isVisible = true; // visibility
  49631. this._pos = 0; // index of this particle in the global "positions" array
  49632. this.shapeId = 0; // model shape id
  49633. this.idxInShape = 0; // index of the particle in its shape id
  49634. this.idx = particleIndex;
  49635. this._pos = positionIndex;
  49636. this._model = model;
  49637. this.shapeId = shapeId;
  49638. this.idxInShape = idxInShape;
  49639. this._sps = sps;
  49640. if (modelBoundingInfo) {
  49641. this._modelBoundingInfo = modelBoundingInfo;
  49642. this._boundingInfo = new BABYLON.BoundingInfo(modelBoundingInfo.minimum, modelBoundingInfo.maximum);
  49643. }
  49644. }
  49645. Object.defineProperty(SolidParticle.prototype, "scale", {
  49646. /**
  49647. * legacy support, changed scale to scaling
  49648. */
  49649. get: function () {
  49650. return this.scaling;
  49651. },
  49652. set: function (scale) {
  49653. this.scaling = scale;
  49654. },
  49655. enumerable: true,
  49656. configurable: true
  49657. });
  49658. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  49659. /**
  49660. * legacy support, changed quaternion to rotationQuaternion
  49661. */
  49662. get: function () {
  49663. return this.rotationQuaternion;
  49664. },
  49665. set: function (q) {
  49666. this.rotationQuaternion = q;
  49667. },
  49668. enumerable: true,
  49669. configurable: true
  49670. });
  49671. /**
  49672. * Returns a boolean. True if the particle intersects another particle or another mesh, else false.
  49673. * The intersection is computed on the particle bounding sphere and Axis Aligned Bounding Box (AABB)
  49674. * `target` is the object (solid particle or mesh) what the intersection is computed against.
  49675. */
  49676. SolidParticle.prototype.intersectsMesh = function (target) {
  49677. if (!this._boundingInfo || !target._boundingInfo) {
  49678. return false;
  49679. }
  49680. if (this._sps._bSphereOnly) {
  49681. return BABYLON.BoundingSphere.Intersects(this._boundingInfo.boundingSphere, target._boundingInfo.boundingSphere);
  49682. }
  49683. return this._boundingInfo.intersects(target._boundingInfo, false);
  49684. };
  49685. return SolidParticle;
  49686. }());
  49687. BABYLON.SolidParticle = SolidParticle;
  49688. var ModelShape = (function () {
  49689. /**
  49690. * 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.
  49691. * SPS internal tool, don't use it manually.
  49692. */
  49693. function ModelShape(id, shape, shapeUV, posFunction, vtxFunction) {
  49694. this.shapeID = id;
  49695. this._shape = shape;
  49696. this._shapeUV = shapeUV;
  49697. this._positionFunction = posFunction;
  49698. this._vertexFunction = vtxFunction;
  49699. }
  49700. return ModelShape;
  49701. }());
  49702. BABYLON.ModelShape = ModelShape;
  49703. })(BABYLON || (BABYLON = {}));
  49704. //# sourceMappingURL=babylon.solidParticle.js.map
  49705. var BABYLON;
  49706. (function (BABYLON) {
  49707. /**
  49708. * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System
  49709. */
  49710. var SolidParticleSystem = (function () {
  49711. /**
  49712. * Creates a SPS (Solid Particle System) object.
  49713. * `name` (String) is the SPS name, this will be the underlying mesh name.
  49714. * `scene` (Scene) is the scene in which the SPS is added.
  49715. * `updatable` (optional boolean, default true) : if the SPS must be updatable or immutable.
  49716. * `isPickable` (optional boolean, default false) : if the solid particles must be pickable.
  49717. * `particleIntersection` (optional boolean, default false) : if the solid particle intersections must be computed.
  49718. * `boundingSphereOnly` (optional boolean, default false) : if the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster).
  49719. * `bSphereRadiusFactor` (optional float, default 1.0) : a number to multiply the boundind sphere radius by in order to reduce it for instance.
  49720. * Example : bSphereRadiusFactor = 1.0 / Math.sqrt(3.0) => the bounding sphere exactly matches a spherical mesh.
  49721. */
  49722. function SolidParticleSystem(name, scene, options) {
  49723. // public members
  49724. /**
  49725. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  49726. * Example : var p = SPS.particles[i];
  49727. */
  49728. this.particles = new Array();
  49729. /**
  49730. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  49731. */
  49732. this.nbParticles = 0;
  49733. /**
  49734. * If the particles must ever face the camera (default false). Useful for planar particles.
  49735. */
  49736. this.billboard = false;
  49737. /**
  49738. * Recompute normals when adding a shape
  49739. */
  49740. this.recomputeNormals = true;
  49741. /**
  49742. * This a counter ofr your own usage. It's not set by any SPS functions.
  49743. */
  49744. this.counter = 0;
  49745. /**
  49746. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  49747. * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns
  49748. */
  49749. this.vars = {};
  49750. this._positions = new Array();
  49751. this._indices = new Array();
  49752. this._normals = new Array();
  49753. this._colors = new Array();
  49754. this._uvs = new Array();
  49755. this._index = 0; // indices index
  49756. this._updatable = true;
  49757. this._pickable = false;
  49758. this._isVisibilityBoxLocked = false;
  49759. this._alwaysVisible = false;
  49760. this._shapeCounter = 0;
  49761. this._copy = new BABYLON.SolidParticle(null, null, null, null, null, null);
  49762. this._color = new BABYLON.Color4(0, 0, 0, 0);
  49763. this._computeParticleColor = true;
  49764. this._computeParticleTexture = true;
  49765. this._computeParticleRotation = true;
  49766. this._computeParticleVertex = false;
  49767. this._computeBoundingBox = false;
  49768. this._cam_axisZ = BABYLON.Vector3.Zero();
  49769. this._cam_axisY = BABYLON.Vector3.Zero();
  49770. this._cam_axisX = BABYLON.Vector3.Zero();
  49771. this._axisX = BABYLON.Axis.X;
  49772. this._axisY = BABYLON.Axis.Y;
  49773. this._axisZ = BABYLON.Axis.Z;
  49774. this._camDir = BABYLON.Vector3.Zero();
  49775. this._rotMatrix = new BABYLON.Matrix();
  49776. this._invertMatrix = new BABYLON.Matrix();
  49777. this._rotated = BABYLON.Vector3.Zero();
  49778. this._quaternion = new BABYLON.Quaternion();
  49779. this._vertex = BABYLON.Vector3.Zero();
  49780. this._normal = BABYLON.Vector3.Zero();
  49781. this._yaw = 0.0;
  49782. this._pitch = 0.0;
  49783. this._roll = 0.0;
  49784. this._halfroll = 0.0;
  49785. this._halfpitch = 0.0;
  49786. this._halfyaw = 0.0;
  49787. this._sinRoll = 0.0;
  49788. this._cosRoll = 0.0;
  49789. this._sinPitch = 0.0;
  49790. this._cosPitch = 0.0;
  49791. this._sinYaw = 0.0;
  49792. this._cosYaw = 0.0;
  49793. this._w = 0.0;
  49794. this._minimum = BABYLON.Tmp.Vector3[0];
  49795. this._maximum = BABYLON.Tmp.Vector3[1];
  49796. this._scale = BABYLON.Tmp.Vector3[2];
  49797. this._translation = BABYLON.Tmp.Vector3[3];
  49798. this._minBbox = BABYLON.Tmp.Vector3[4];
  49799. this._maxBbox = BABYLON.Tmp.Vector3[5];
  49800. this._particlesIntersect = false;
  49801. this._bSphereOnly = false;
  49802. this._bSphereRadiusFactor = 1.0;
  49803. this.name = name;
  49804. this._scene = scene;
  49805. this._camera = scene.activeCamera;
  49806. this._pickable = options ? options.isPickable : false;
  49807. this._particlesIntersect = options ? options.particleIntersection : false;
  49808. this._bSphereOnly = options ? options.boundingSphereOnly : false;
  49809. this._bSphereRadiusFactor = (options && options.bSphereRadiusFactor) ? options.bSphereRadiusFactor : 1.0;
  49810. if (options && options.updatable) {
  49811. this._updatable = options.updatable;
  49812. }
  49813. else {
  49814. this._updatable = true;
  49815. }
  49816. if (this._pickable) {
  49817. this.pickedParticles = [];
  49818. }
  49819. }
  49820. /**
  49821. * Builds the SPS underlying mesh. Returns a standard Mesh.
  49822. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  49823. */
  49824. SolidParticleSystem.prototype.buildMesh = function () {
  49825. if (this.nbParticles === 0) {
  49826. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  49827. this.addShape(triangle, 1);
  49828. triangle.dispose();
  49829. }
  49830. this._positions32 = new Float32Array(this._positions);
  49831. this._uvs32 = new Float32Array(this._uvs);
  49832. this._colors32 = new Float32Array(this._colors);
  49833. if (this.recomputeNormals) {
  49834. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices, this._normals);
  49835. }
  49836. this._normals32 = new Float32Array(this._normals);
  49837. this._fixedNormal32 = new Float32Array(this._normals);
  49838. var vertexData = new BABYLON.VertexData();
  49839. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  49840. vertexData.indices = this._indices;
  49841. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  49842. if (this._uvs32) {
  49843. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  49844. ;
  49845. }
  49846. if (this._colors32) {
  49847. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  49848. }
  49849. var mesh = new BABYLON.Mesh(this.name, this._scene);
  49850. vertexData.applyToMesh(mesh, this._updatable);
  49851. this.mesh = mesh;
  49852. this.mesh.isPickable = this._pickable;
  49853. // free memory
  49854. this._positions = null;
  49855. this._normals = null;
  49856. this._uvs = null;
  49857. this._colors = null;
  49858. if (!this._updatable) {
  49859. this.particles.length = 0;
  49860. }
  49861. return mesh;
  49862. };
  49863. /**
  49864. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  49865. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  49866. * Thus the particles generated from `digest()` have their property `position` set yet.
  49867. * `mesh` ( Mesh ) is the mesh to be digested
  49868. * `facetNb` (optional integer, default 1) is the number of mesh facets per particle, this parameter is overriden by the parameter `number` if any
  49869. * `delta` (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  49870. * `number` (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  49871. */
  49872. SolidParticleSystem.prototype.digest = function (mesh, options) {
  49873. var size = (options && options.facetNb) || 1;
  49874. var number = (options && options.number);
  49875. var delta = (options && options.delta) || 0;
  49876. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  49877. var meshInd = mesh.getIndices();
  49878. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  49879. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  49880. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  49881. var f = 0; // facet counter
  49882. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  49883. // compute size from number
  49884. if (number) {
  49885. number = (number > totalFacets) ? totalFacets : number;
  49886. size = Math.round(totalFacets / number);
  49887. delta = 0;
  49888. }
  49889. else {
  49890. size = (size > totalFacets) ? totalFacets : size;
  49891. }
  49892. var facetPos = []; // submesh positions
  49893. var facetInd = []; // submesh indices
  49894. var facetUV = []; // submesh UV
  49895. var facetCol = []; // submesh colors
  49896. var barycenter = BABYLON.Tmp.Vector3[0];
  49897. var rand;
  49898. var sizeO = size;
  49899. while (f < totalFacets) {
  49900. size = sizeO + Math.floor((1 + delta) * Math.random());
  49901. if (f > totalFacets - size) {
  49902. size = totalFacets - f;
  49903. }
  49904. // reset temp arrays
  49905. facetPos.length = 0;
  49906. facetInd.length = 0;
  49907. facetUV.length = 0;
  49908. facetCol.length = 0;
  49909. // iterate over "size" facets
  49910. var fi = 0;
  49911. for (var j = f * 3; j < (f + size) * 3; j++) {
  49912. facetInd.push(fi);
  49913. var i = meshInd[j];
  49914. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  49915. if (meshUV) {
  49916. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  49917. }
  49918. if (meshCol) {
  49919. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  49920. }
  49921. fi++;
  49922. }
  49923. // create a model shape for each single particle
  49924. var idx = this.nbParticles;
  49925. var shape = this._posToShape(facetPos);
  49926. var shapeUV = this._uvsToShapeUV(facetUV);
  49927. // compute the barycenter of the shape
  49928. var v;
  49929. for (v = 0; v < shape.length; v++) {
  49930. barycenter.addInPlace(shape[v]);
  49931. }
  49932. barycenter.scaleInPlace(1 / shape.length);
  49933. // shift the shape from its barycenter to the origin
  49934. for (v = 0; v < shape.length; v++) {
  49935. shape[v].subtractInPlace(barycenter);
  49936. }
  49937. var bInfo;
  49938. if (this._particlesIntersect) {
  49939. bInfo = new BABYLON.BoundingInfo(barycenter, barycenter);
  49940. }
  49941. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, shapeUV, null, null);
  49942. // add the particle in the SPS
  49943. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, meshNor, this._normals, idx, 0, null);
  49944. this._addParticle(idx, this._positions.length, modelShape, this._shapeCounter, 0, bInfo);
  49945. // initialize the particle position
  49946. this.particles[this.nbParticles].position.addInPlace(barycenter);
  49947. this._index += shape.length;
  49948. idx++;
  49949. this.nbParticles++;
  49950. this._shapeCounter++;
  49951. f += size;
  49952. }
  49953. return this;
  49954. };
  49955. //reset copy
  49956. SolidParticleSystem.prototype._resetCopy = function () {
  49957. this._copy.position.x = 0;
  49958. this._copy.position.y = 0;
  49959. this._copy.position.z = 0;
  49960. this._copy.rotation.x = 0;
  49961. this._copy.rotation.y = 0;
  49962. this._copy.rotation.z = 0;
  49963. this._copy.rotationQuaternion = null;
  49964. this._copy.scaling.x = 1;
  49965. this._copy.scaling.y = 1;
  49966. this._copy.scaling.z = 1;
  49967. this._copy.uvs.x = 0;
  49968. this._copy.uvs.y = 0;
  49969. this._copy.uvs.z = 1;
  49970. this._copy.uvs.w = 1;
  49971. this._copy.color = null;
  49972. };
  49973. // _meshBuilder : inserts the shape model in the global SPS mesh
  49974. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, meshNor, normals, idx, idxInShape, options) {
  49975. var i;
  49976. var u = 0;
  49977. var c = 0;
  49978. var n = 0;
  49979. this._resetCopy();
  49980. if (options && options.positionFunction) {
  49981. options.positionFunction(this._copy, idx, idxInShape);
  49982. }
  49983. if (this._copy.rotationQuaternion) {
  49984. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  49985. }
  49986. else {
  49987. this._yaw = this._copy.rotation.y;
  49988. this._pitch = this._copy.rotation.x;
  49989. this._roll = this._copy.rotation.z;
  49990. this._quaternionRotationYPR();
  49991. }
  49992. this._quaternionToRotationMatrix();
  49993. for (i = 0; i < shape.length; i++) {
  49994. this._vertex.x = shape[i].x;
  49995. this._vertex.y = shape[i].y;
  49996. this._vertex.z = shape[i].z;
  49997. if (options && options.vertexFunction) {
  49998. options.vertexFunction(this._copy, this._vertex, i);
  49999. }
  50000. this._vertex.x *= this._copy.scaling.x;
  50001. this._vertex.y *= this._copy.scaling.y;
  50002. this._vertex.z *= this._copy.scaling.z;
  50003. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  50004. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  50005. if (meshUV) {
  50006. 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);
  50007. u += 2;
  50008. }
  50009. if (this._copy.color) {
  50010. this._color = this._copy.color;
  50011. }
  50012. else if (meshCol && meshCol[c] !== undefined) {
  50013. this._color.r = meshCol[c];
  50014. this._color.g = meshCol[c + 1];
  50015. this._color.b = meshCol[c + 2];
  50016. this._color.a = meshCol[c + 3];
  50017. }
  50018. else {
  50019. this._color.r = 1;
  50020. this._color.g = 1;
  50021. this._color.b = 1;
  50022. this._color.a = 1;
  50023. }
  50024. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  50025. c += 4;
  50026. if (!this.recomputeNormals && meshNor) {
  50027. this._normal.x = meshNor[n];
  50028. this._normal.y = meshNor[n + 1];
  50029. this._normal.z = meshNor[n + 2];
  50030. BABYLON.Vector3.TransformCoordinatesToRef(this._normal, this._rotMatrix, this._normal);
  50031. normals.push(this._normal.x, this._normal.y, this._normal.z);
  50032. n += 3;
  50033. }
  50034. }
  50035. for (i = 0; i < meshInd.length; i++) {
  50036. indices.push(p + meshInd[i]);
  50037. }
  50038. if (this._pickable) {
  50039. var nbfaces = meshInd.length / 3;
  50040. for (i = 0; i < nbfaces; i++) {
  50041. this.pickedParticles.push({ idx: idx, faceId: i });
  50042. }
  50043. }
  50044. };
  50045. // returns a shape array from positions array
  50046. SolidParticleSystem.prototype._posToShape = function (positions) {
  50047. var shape = [];
  50048. for (var i = 0; i < positions.length; i += 3) {
  50049. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  50050. }
  50051. return shape;
  50052. };
  50053. // returns a shapeUV array from a Vector4 uvs
  50054. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  50055. var shapeUV = [];
  50056. if (uvs) {
  50057. for (var i = 0; i < uvs.length; i++)
  50058. shapeUV.push(uvs[i]);
  50059. }
  50060. return shapeUV;
  50061. };
  50062. // adds a new particle object in the particles array
  50063. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, model, shapeId, idxInShape, bInfo) {
  50064. this.particles.push(new BABYLON.SolidParticle(idx, idxpos, model, shapeId, idxInShape, this, bInfo));
  50065. };
  50066. /**
  50067. * Adds some particles to the SPS from the model shape. Returns the shape id.
  50068. * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps
  50069. * `mesh` is any Mesh object that will be used as a model for the solid particles.
  50070. * `nb` (positive integer) the number of particles to be created from this model
  50071. * `positionFunction` is an optional javascript function to called for each particle on SPS creation.
  50072. * `vertexFunction` is an optional javascript function to called for each vertex of each particle on SPS creation
  50073. */
  50074. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  50075. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  50076. var meshInd = mesh.getIndices();
  50077. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  50078. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  50079. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  50080. var bbInfo;
  50081. if (this._particlesIntersect) {
  50082. bbInfo = mesh.getBoundingInfo();
  50083. }
  50084. var shape = this._posToShape(meshPos);
  50085. var shapeUV = this._uvsToShapeUV(meshUV);
  50086. var posfunc = options ? options.positionFunction : null;
  50087. var vtxfunc = options ? options.vertexFunction : null;
  50088. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, shapeUV, posfunc, vtxfunc);
  50089. // particles
  50090. var idx = this.nbParticles;
  50091. for (var i = 0; i < nb; i++) {
  50092. this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, meshNor, this._normals, idx, i, options);
  50093. if (this._updatable) {
  50094. this._addParticle(idx, this._positions.length, modelShape, this._shapeCounter, i, bbInfo);
  50095. }
  50096. this._index += shape.length;
  50097. idx++;
  50098. }
  50099. this.nbParticles += nb;
  50100. this._shapeCounter++;
  50101. return this._shapeCounter - 1;
  50102. };
  50103. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  50104. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  50105. this._resetCopy();
  50106. if (particle._model._positionFunction) {
  50107. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  50108. }
  50109. if (this._copy.rotationQuaternion) {
  50110. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  50111. }
  50112. else {
  50113. this._yaw = this._copy.rotation.y;
  50114. this._pitch = this._copy.rotation.x;
  50115. this._roll = this._copy.rotation.z;
  50116. this._quaternionRotationYPR();
  50117. }
  50118. this._quaternionToRotationMatrix();
  50119. this._shape = particle._model._shape;
  50120. for (var pt = 0; pt < this._shape.length; pt++) {
  50121. this._vertex.x = this._shape[pt].x;
  50122. this._vertex.y = this._shape[pt].y;
  50123. this._vertex.z = this._shape[pt].z;
  50124. if (particle._model._vertexFunction) {
  50125. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  50126. }
  50127. this._vertex.x *= this._copy.scaling.x;
  50128. this._vertex.y *= this._copy.scaling.y;
  50129. this._vertex.z *= this._copy.scaling.z;
  50130. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  50131. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  50132. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  50133. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  50134. }
  50135. particle.position.x = 0.0;
  50136. particle.position.y = 0.0;
  50137. particle.position.z = 0.0;
  50138. particle.rotation.x = 0.0;
  50139. particle.rotation.y = 0.0;
  50140. particle.rotation.z = 0.0;
  50141. particle.rotationQuaternion = null;
  50142. particle.scaling.x = 1.0;
  50143. particle.scaling.y = 1.0;
  50144. particle.scaling.z = 1.0;
  50145. };
  50146. /**
  50147. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  50148. */
  50149. SolidParticleSystem.prototype.rebuildMesh = function () {
  50150. for (var p = 0; p < this.particles.length; p++) {
  50151. this._rebuildParticle(this.particles[p]);
  50152. }
  50153. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  50154. };
  50155. /**
  50156. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  50157. * This method calls `updateParticle()` for each particle of the SPS.
  50158. * For an animated SPS, it is usually called within the render loop.
  50159. * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_
  50160. * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_
  50161. * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_
  50162. */
  50163. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  50164. if (start === void 0) { start = 0; }
  50165. if (end === void 0) { end = this.nbParticles - 1; }
  50166. if (update === void 0) { update = true; }
  50167. if (!this._updatable) {
  50168. return;
  50169. }
  50170. // custom beforeUpdate
  50171. this.beforeUpdateParticles(start, end, update);
  50172. this._cam_axisX.x = 1.0;
  50173. this._cam_axisX.y = 0.0;
  50174. this._cam_axisX.z = 0.0;
  50175. this._cam_axisY.x = 0.0;
  50176. this._cam_axisY.y = 1.0;
  50177. this._cam_axisY.z = 0.0;
  50178. this._cam_axisZ.x = 0.0;
  50179. this._cam_axisZ.y = 0.0;
  50180. this._cam_axisZ.z = 1.0;
  50181. // if the particles will always face the camera
  50182. if (this.billboard) {
  50183. // compute the camera position and un-rotate it by the current mesh rotation
  50184. if (this.mesh._worldMatrix.decompose(this._scale, this._quaternion, this._translation)) {
  50185. this._quaternionToRotationMatrix();
  50186. this._rotMatrix.invertToRef(this._invertMatrix);
  50187. this._camera._currentTarget.subtractToRef(this._camera.globalPosition, this._camDir);
  50188. BABYLON.Vector3.TransformCoordinatesToRef(this._camDir, this._invertMatrix, this._cam_axisZ);
  50189. this._cam_axisZ.normalize();
  50190. // set two orthogonal vectors (_cam_axisX and and _cam_axisY) to the rotated camDir axis (_cam_axisZ)
  50191. BABYLON.Vector3.CrossToRef(this._cam_axisZ, this._axisX, this._cam_axisY);
  50192. BABYLON.Vector3.CrossToRef(this._cam_axisY, this._cam_axisZ, this._cam_axisX);
  50193. this._cam_axisY.normalize();
  50194. this._cam_axisX.normalize();
  50195. }
  50196. }
  50197. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  50198. var idx = 0; // current position index in the global array positions32
  50199. var index = 0; // position start index in the global array positions32 of the current particle
  50200. var colidx = 0; // current color index in the global array colors32
  50201. var colorIndex = 0; // color start index in the global array colors32 of the current particle
  50202. var uvidx = 0; // current uv index in the global array uvs32
  50203. var uvIndex = 0; // uv start index in the global array uvs32 of the current particle
  50204. var pt = 0; // current index in the particle model shape
  50205. if (this.mesh.isFacetDataEnabled) {
  50206. this._computeBoundingBox = true;
  50207. }
  50208. if (this._computeBoundingBox) {
  50209. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  50210. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  50211. }
  50212. // particle loop
  50213. end = (end > this.nbParticles - 1) ? this.nbParticles - 1 : end;
  50214. for (var p = start; p <= end; p++) {
  50215. this._particle = this.particles[p];
  50216. this._shape = this._particle._model._shape;
  50217. this._shapeUV = this._particle._model._shapeUV;
  50218. // call to custom user function to update the particle properties
  50219. this.updateParticle(this._particle);
  50220. if (this._particle.isVisible) {
  50221. // particle rotation matrix
  50222. if (this.billboard) {
  50223. this._particle.rotation.x = 0.0;
  50224. this._particle.rotation.y = 0.0;
  50225. }
  50226. if (this._computeParticleRotation || this.billboard) {
  50227. if (this._particle.rotationQuaternion) {
  50228. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  50229. }
  50230. else {
  50231. this._yaw = this._particle.rotation.y;
  50232. this._pitch = this._particle.rotation.x;
  50233. this._roll = this._particle.rotation.z;
  50234. this._quaternionRotationYPR();
  50235. }
  50236. this._quaternionToRotationMatrix();
  50237. }
  50238. // particle vertex loop
  50239. for (pt = 0; pt < this._shape.length; pt++) {
  50240. idx = index + pt * 3;
  50241. colidx = colorIndex + pt * 4;
  50242. uvidx = uvIndex + pt * 2;
  50243. this._vertex.x = this._shape[pt].x;
  50244. this._vertex.y = this._shape[pt].y;
  50245. this._vertex.z = this._shape[pt].z;
  50246. if (this._computeParticleVertex) {
  50247. this.updateParticleVertex(this._particle, this._vertex, pt);
  50248. }
  50249. // positions
  50250. this._vertex.x *= this._particle.scaling.x;
  50251. this._vertex.y *= this._particle.scaling.y;
  50252. this._vertex.z *= this._particle.scaling.z;
  50253. 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];
  50254. 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;
  50255. 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;
  50256. 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;
  50257. 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;
  50258. 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;
  50259. 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;
  50260. if (this._computeBoundingBox) {
  50261. if (this._positions32[idx] < this._minimum.x) {
  50262. this._minimum.x = this._positions32[idx];
  50263. }
  50264. if (this._positions32[idx] > this._maximum.x) {
  50265. this._maximum.x = this._positions32[idx];
  50266. }
  50267. if (this._positions32[idx + 1] < this._minimum.y) {
  50268. this._minimum.y = this._positions32[idx + 1];
  50269. }
  50270. if (this._positions32[idx + 1] > this._maximum.y) {
  50271. this._maximum.y = this._positions32[idx + 1];
  50272. }
  50273. if (this._positions32[idx + 2] < this._minimum.z) {
  50274. this._minimum.z = this._positions32[idx + 2];
  50275. }
  50276. if (this._positions32[idx + 2] > this._maximum.z) {
  50277. this._maximum.z = this._positions32[idx + 2];
  50278. }
  50279. }
  50280. // normals : if the particles can't be morphed then just rotate the normals, what is much more faster than ComputeNormals()
  50281. if (!this._computeParticleVertex) {
  50282. this._normal.x = this._fixedNormal32[idx];
  50283. this._normal.y = this._fixedNormal32[idx + 1];
  50284. this._normal.z = this._fixedNormal32[idx + 2];
  50285. 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]);
  50286. 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]);
  50287. 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]);
  50288. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  50289. 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;
  50290. 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;
  50291. }
  50292. if (this._computeParticleColor) {
  50293. this._colors32[colidx] = this._particle.color.r;
  50294. this._colors32[colidx + 1] = this._particle.color.g;
  50295. this._colors32[colidx + 2] = this._particle.color.b;
  50296. this._colors32[colidx + 3] = this._particle.color.a;
  50297. }
  50298. if (this._computeParticleTexture) {
  50299. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  50300. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  50301. }
  50302. }
  50303. }
  50304. else {
  50305. for (pt = 0; pt < this._shape.length; pt++) {
  50306. idx = index + pt * 3;
  50307. colidx = colorIndex + pt * 4;
  50308. uvidx = uvIndex + pt * 2;
  50309. this._positions32[idx] = this._camera.position.x;
  50310. this._positions32[idx + 1] = this._camera.position.y;
  50311. this._positions32[idx + 2] = this._camera.position.z;
  50312. this._normals32[idx] = 0.0;
  50313. this._normals32[idx + 1] = 0.0;
  50314. this._normals32[idx + 2] = 0.0;
  50315. if (this._computeParticleColor) {
  50316. this._colors32[colidx] = this._particle.color.r;
  50317. this._colors32[colidx + 1] = this._particle.color.g;
  50318. this._colors32[colidx + 2] = this._particle.color.b;
  50319. this._colors32[colidx + 3] = this._particle.color.a;
  50320. }
  50321. if (this._computeParticleTexture) {
  50322. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  50323. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  50324. }
  50325. }
  50326. }
  50327. // if the particle intersections must be computed : update the bbInfo
  50328. if (this._particlesIntersect) {
  50329. var bInfo = this._particle._boundingInfo;
  50330. var bBox = bInfo.boundingBox;
  50331. var bSphere = bInfo.boundingSphere;
  50332. if (!this._bSphereOnly) {
  50333. // place, scale and rotate the particle bbox within the SPS local system, then update it
  50334. for (var b = 0; b < bBox.vectors.length; b++) {
  50335. this._vertex.x = this._particle._modelBoundingInfo.boundingBox.vectors[b].x * this._particle.scaling.x;
  50336. this._vertex.y = this._particle._modelBoundingInfo.boundingBox.vectors[b].y * this._particle.scaling.y;
  50337. this._vertex.z = this._particle._modelBoundingInfo.boundingBox.vectors[b].z * this._particle.scaling.z;
  50338. 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];
  50339. 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;
  50340. 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;
  50341. 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;
  50342. 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;
  50343. 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;
  50344. 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;
  50345. }
  50346. bBox._update(this.mesh._worldMatrix);
  50347. }
  50348. // place and scale the particle bouding sphere in the SPS local system, then update it
  50349. this._minBbox.x = this._particle._modelBoundingInfo.minimum.x * this._particle.scaling.x;
  50350. this._minBbox.y = this._particle._modelBoundingInfo.minimum.y * this._particle.scaling.y;
  50351. this._minBbox.z = this._particle._modelBoundingInfo.minimum.z * this._particle.scaling.z;
  50352. this._maxBbox.x = this._particle._modelBoundingInfo.maximum.x * this._particle.scaling.x;
  50353. this._maxBbox.y = this._particle._modelBoundingInfo.maximum.y * this._particle.scaling.y;
  50354. this._maxBbox.z = this._particle._modelBoundingInfo.maximum.z * this._particle.scaling.z;
  50355. bSphere.center.x = this._particle.position.x + (this._minBbox.x + this._maxBbox.x) * 0.5;
  50356. bSphere.center.y = this._particle.position.y + (this._minBbox.y + this._maxBbox.y) * 0.5;
  50357. bSphere.center.z = this._particle.position.z + (this._minBbox.z + this._maxBbox.z) * 0.5;
  50358. 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));
  50359. bSphere._update(this.mesh._worldMatrix);
  50360. }
  50361. // increment indexes for the next particle
  50362. index = idx + 3;
  50363. colorIndex = colidx + 4;
  50364. uvIndex = uvidx + 2;
  50365. }
  50366. // if the VBO must be updated
  50367. if (update) {
  50368. if (this._computeParticleColor) {
  50369. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  50370. }
  50371. if (this._computeParticleTexture) {
  50372. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  50373. }
  50374. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  50375. if (!this.mesh.areNormalsFrozen || this.mesh.isFacetDataEnabled) {
  50376. if (this._computeParticleVertex || this.mesh.isFacetDataEnabled) {
  50377. // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]
  50378. var params = this.mesh.isFacetDataEnabled ? this.mesh.getFacetDataParameters() : null;
  50379. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices, this._normals32, params);
  50380. for (var i = 0; i < this._normals32.length; i++) {
  50381. this._fixedNormal32[i] = this._normals32[i];
  50382. }
  50383. }
  50384. if (!this.mesh.areNormalsFrozen) {
  50385. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  50386. }
  50387. }
  50388. }
  50389. if (this._computeBoundingBox) {
  50390. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  50391. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  50392. }
  50393. this.afterUpdateParticles(start, end, update);
  50394. };
  50395. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  50396. this._halfroll = this._roll * 0.5;
  50397. this._halfpitch = this._pitch * 0.5;
  50398. this._halfyaw = this._yaw * 0.5;
  50399. this._sinRoll = Math.sin(this._halfroll);
  50400. this._cosRoll = Math.cos(this._halfroll);
  50401. this._sinPitch = Math.sin(this._halfpitch);
  50402. this._cosPitch = Math.cos(this._halfpitch);
  50403. this._sinYaw = Math.sin(this._halfyaw);
  50404. this._cosYaw = Math.cos(this._halfyaw);
  50405. this._quaternion.x = (this._cosYaw * this._sinPitch * this._cosRoll) + (this._sinYaw * this._cosPitch * this._sinRoll);
  50406. this._quaternion.y = (this._sinYaw * this._cosPitch * this._cosRoll) - (this._cosYaw * this._sinPitch * this._sinRoll);
  50407. this._quaternion.z = (this._cosYaw * this._cosPitch * this._sinRoll) - (this._sinYaw * this._sinPitch * this._cosRoll);
  50408. this._quaternion.w = (this._cosYaw * this._cosPitch * this._cosRoll) + (this._sinYaw * this._sinPitch * this._sinRoll);
  50409. };
  50410. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  50411. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  50412. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  50413. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  50414. this._rotMatrix.m[3] = 0;
  50415. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  50416. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  50417. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  50418. this._rotMatrix.m[7] = 0;
  50419. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  50420. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  50421. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  50422. this._rotMatrix.m[11] = 0;
  50423. this._rotMatrix.m[12] = 0;
  50424. this._rotMatrix.m[13] = 0;
  50425. this._rotMatrix.m[14] = 0;
  50426. this._rotMatrix.m[15] = 1.0;
  50427. };
  50428. /**
  50429. * Disposes the SPS
  50430. */
  50431. SolidParticleSystem.prototype.dispose = function () {
  50432. this.mesh.dispose();
  50433. this.vars = null;
  50434. // drop references to internal big arrays for the GC
  50435. this._positions = null;
  50436. this._indices = null;
  50437. this._normals = null;
  50438. this._uvs = null;
  50439. this._colors = null;
  50440. this._positions32 = null;
  50441. this._normals32 = null;
  50442. this._fixedNormal32 = null;
  50443. this._uvs32 = null;
  50444. this._colors32 = null;
  50445. this.pickedParticles = null;
  50446. };
  50447. /**
  50448. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  50449. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  50450. */
  50451. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  50452. if (!this._isVisibilityBoxLocked) {
  50453. this.mesh.refreshBoundingInfo();
  50454. }
  50455. };
  50456. /**
  50457. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  50458. * @param size the size (float) of the visibility box
  50459. * note : this doesn't lock the SPS mesh bounding box.
  50460. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  50461. */
  50462. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  50463. var vis = size / 2;
  50464. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  50465. };
  50466. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  50467. // getter and setter
  50468. get: function () {
  50469. return this._alwaysVisible;
  50470. },
  50471. /**
  50472. * Sets the SPS as always visible or not
  50473. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  50474. */
  50475. set: function (val) {
  50476. this._alwaysVisible = val;
  50477. this.mesh.alwaysSelectAsActiveMesh = val;
  50478. },
  50479. enumerable: true,
  50480. configurable: true
  50481. });
  50482. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  50483. get: function () {
  50484. return this._isVisibilityBoxLocked;
  50485. },
  50486. /**
  50487. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  50488. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  50489. */
  50490. set: function (val) {
  50491. this._isVisibilityBoxLocked = val;
  50492. this.mesh.getBoundingInfo().isLocked = val;
  50493. },
  50494. enumerable: true,
  50495. configurable: true
  50496. });
  50497. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  50498. // getters
  50499. get: function () {
  50500. return this._computeParticleRotation;
  50501. },
  50502. // Optimizer setters
  50503. /**
  50504. * Tells to `setParticles()` to compute the particle rotations or not.
  50505. * Default value : true. The SPS is faster when it's set to false.
  50506. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  50507. */
  50508. set: function (val) {
  50509. this._computeParticleRotation = val;
  50510. },
  50511. enumerable: true,
  50512. configurable: true
  50513. });
  50514. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  50515. get: function () {
  50516. return this._computeParticleColor;
  50517. },
  50518. /**
  50519. * Tells to `setParticles()` to compute the particle colors or not.
  50520. * Default value : true. The SPS is faster when it's set to false.
  50521. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  50522. */
  50523. set: function (val) {
  50524. this._computeParticleColor = val;
  50525. },
  50526. enumerable: true,
  50527. configurable: true
  50528. });
  50529. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  50530. get: function () {
  50531. return this._computeParticleTexture;
  50532. },
  50533. /**
  50534. * Tells to `setParticles()` to compute the particle textures or not.
  50535. * Default value : true. The SPS is faster when it's set to false.
  50536. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  50537. */
  50538. set: function (val) {
  50539. this._computeParticleTexture = val;
  50540. },
  50541. enumerable: true,
  50542. configurable: true
  50543. });
  50544. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  50545. get: function () {
  50546. return this._computeParticleVertex;
  50547. },
  50548. /**
  50549. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  50550. * Default value : false. The SPS is faster when it's set to false.
  50551. * Note : the particle custom vertex positions aren't stored values.
  50552. */
  50553. set: function (val) {
  50554. this._computeParticleVertex = val;
  50555. },
  50556. enumerable: true,
  50557. configurable: true
  50558. });
  50559. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  50560. get: function () {
  50561. return this._computeBoundingBox;
  50562. },
  50563. /**
  50564. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  50565. */
  50566. set: function (val) {
  50567. this._computeBoundingBox = val;
  50568. },
  50569. enumerable: true,
  50570. configurable: true
  50571. });
  50572. // =======================================================================
  50573. // Particle behavior logic
  50574. // these following methods may be overwritten by the user to fit his needs
  50575. /**
  50576. * This function does nothing. It may be overwritten to set all the particle first values.
  50577. * The SPS doesn't call this function, you may have to call it by your own.
  50578. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  50579. */
  50580. SolidParticleSystem.prototype.initParticles = function () {
  50581. };
  50582. /**
  50583. * This function does nothing. It may be overwritten to recycle a particle.
  50584. * The SPS doesn't call this function, you may have to call it by your own.
  50585. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  50586. */
  50587. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  50588. return particle;
  50589. };
  50590. /**
  50591. * Updates a particle : this function should be overwritten by the user.
  50592. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  50593. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  50594. * ex : just set a particle position or velocity and recycle conditions
  50595. */
  50596. SolidParticleSystem.prototype.updateParticle = function (particle) {
  50597. return particle;
  50598. };
  50599. /**
  50600. * Updates a vertex of a particle : it can be overwritten by the user.
  50601. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  50602. * @param particle the current particle
  50603. * @param vertex the current index of the current particle
  50604. * @param pt the index of the current vertex in the particle shape
  50605. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape
  50606. * ex : just set a vertex particle position
  50607. */
  50608. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  50609. return vertex;
  50610. };
  50611. /**
  50612. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  50613. * This does nothing and may be overwritten by the user.
  50614. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  50615. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  50616. * @param update the boolean update value actually passed to setParticles()
  50617. */
  50618. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  50619. };
  50620. /**
  50621. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  50622. * This will be passed three parameters.
  50623. * This does nothing and may be overwritten by the user.
  50624. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  50625. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  50626. * @param update the boolean update value actually passed to setParticles()
  50627. */
  50628. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  50629. };
  50630. return SolidParticleSystem;
  50631. }());
  50632. BABYLON.SolidParticleSystem = SolidParticleSystem;
  50633. })(BABYLON || (BABYLON = {}));
  50634. //# sourceMappingURL=babylon.solidParticleSystem.js.map
  50635. var BABYLON;
  50636. (function (BABYLON) {
  50637. var Internals;
  50638. (function (Internals) {
  50639. var FileFaceOrientation = (function () {
  50640. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  50641. this.name = name;
  50642. this.worldAxisForNormal = worldAxisForNormal;
  50643. this.worldAxisForFileX = worldAxisForFileX;
  50644. this.worldAxisForFileY = worldAxisForFileY;
  50645. }
  50646. return FileFaceOrientation;
  50647. }());
  50648. ;
  50649. /**
  50650. * Helper class dealing with the extraction of spherical polynomial dataArray
  50651. * from a cube map.
  50652. */
  50653. var CubeMapToSphericalPolynomialTools = (function () {
  50654. function CubeMapToSphericalPolynomialTools() {
  50655. }
  50656. /**
  50657. * Converts a cubemap to the according Spherical Polynomial data.
  50658. * This extracts the first 3 orders only as they are the only one used in the lighting.
  50659. *
  50660. * @param cubeInfo The Cube map to extract the information from.
  50661. * @return The Spherical Polynomial data.
  50662. */
  50663. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  50664. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  50665. var totalSolidAngle = 0.0;
  50666. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  50667. var du = 2.0 / cubeInfo.size;
  50668. var dv = du;
  50669. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  50670. var minUV = du * 0.5 - 1.0;
  50671. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  50672. var fileFace = this.FileFaces[faceIndex];
  50673. var dataArray = cubeInfo[fileFace.name];
  50674. var v = minUV;
  50675. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  50676. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  50677. // Because SP is still linear, so summation is fine in that basis.
  50678. for (var y = 0; y < cubeInfo.size; y++) {
  50679. var u = minUV;
  50680. for (var x = 0; x < cubeInfo.size; x++) {
  50681. // World direction (not normalised)
  50682. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  50683. worldDirection.normalize();
  50684. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  50685. if (1) {
  50686. var r = dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0];
  50687. var g = dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1];
  50688. var b = dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2];
  50689. var color = new BABYLON.Color3(r, g, b);
  50690. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  50691. }
  50692. else {
  50693. if (faceIndex == 0) {
  50694. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 1;
  50695. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 0;
  50696. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 0;
  50697. }
  50698. else if (faceIndex == 1) {
  50699. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 0;
  50700. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 1;
  50701. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 0;
  50702. }
  50703. else if (faceIndex == 2) {
  50704. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 0;
  50705. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 0;
  50706. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 1;
  50707. }
  50708. else if (faceIndex == 3) {
  50709. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 1;
  50710. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 1;
  50711. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 0;
  50712. }
  50713. else if (faceIndex == 4) {
  50714. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 1;
  50715. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 0;
  50716. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 1;
  50717. }
  50718. else if (faceIndex == 5) {
  50719. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 0;
  50720. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 1;
  50721. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 1;
  50722. }
  50723. 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]);
  50724. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  50725. }
  50726. totalSolidAngle += deltaSolidAngle;
  50727. u += du;
  50728. }
  50729. v += dv;
  50730. }
  50731. }
  50732. var correctSolidAngle = 4.0 * Math.PI; // Solid angle for entire sphere is 4*pi
  50733. var correction = correctSolidAngle / totalSolidAngle;
  50734. sphericalHarmonics.scale(correction);
  50735. // Additionally scale by pi -- audit needed
  50736. sphericalHarmonics.scale(1.0 / Math.PI);
  50737. return BABYLON.SphericalPolynomial.getSphericalPolynomialFromHarmonics(sphericalHarmonics);
  50738. };
  50739. return CubeMapToSphericalPolynomialTools;
  50740. }());
  50741. CubeMapToSphericalPolynomialTools.FileFaces = [
  50742. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  50743. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  50744. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  50745. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  50746. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  50747. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  50748. ];
  50749. Internals.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  50750. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  50751. })(BABYLON || (BABYLON = {}));
  50752. //# sourceMappingURL=babylon.tools.cubemapToSphericalPolynomial.js.map
  50753. var BABYLON;
  50754. (function (BABYLON) {
  50755. var Internals;
  50756. (function (Internals) {
  50757. /**
  50758. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  50759. */
  50760. var PanoramaToCubeMapTools = (function () {
  50761. function PanoramaToCubeMapTools() {
  50762. }
  50763. /**
  50764. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  50765. *
  50766. * @param float32Array The source data.
  50767. * @param inputWidth The width of the input panorama.
  50768. * @param inputhHeight The height of the input panorama.
  50769. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  50770. * @return The cubemap data
  50771. */
  50772. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  50773. if (!float32Array) {
  50774. throw "ConvertPanoramaToCubemap: input cannot be null";
  50775. }
  50776. if (float32Array.length != inputWidth * inputHeight * 3) {
  50777. throw "ConvertPanoramaToCubemap: input size is wrong";
  50778. }
  50779. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  50780. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  50781. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  50782. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  50783. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  50784. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  50785. return {
  50786. front: textureFront,
  50787. back: textureBack,
  50788. left: textureLeft,
  50789. right: textureRight,
  50790. up: textureUp,
  50791. down: textureDown,
  50792. size: size
  50793. };
  50794. };
  50795. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  50796. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  50797. var textureArray = new Float32Array(buffer);
  50798. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  50799. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  50800. var dy = 1 / texSize;
  50801. var fy = 0;
  50802. for (var y = 0; y < texSize; y++) {
  50803. var xv1 = faceData[0];
  50804. var xv2 = faceData[2];
  50805. for (var x = 0; x < texSize; x++) {
  50806. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  50807. v.normalize();
  50808. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  50809. // 3 channels per pixels
  50810. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  50811. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  50812. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  50813. xv1 = xv1.add(rotDX1);
  50814. xv2 = xv2.add(rotDX2);
  50815. }
  50816. fy += dy;
  50817. }
  50818. return textureArray;
  50819. };
  50820. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  50821. var theta = Math.atan2(vDir.z, vDir.x);
  50822. var phi = Math.acos(vDir.y);
  50823. while (theta < -Math.PI)
  50824. theta += 2 * Math.PI;
  50825. while (theta > Math.PI)
  50826. theta -= 2 * Math.PI;
  50827. var dx = theta / Math.PI;
  50828. var dy = phi / Math.PI;
  50829. // recenter.
  50830. dx = dx * 0.5 + 0.5;
  50831. var px = Math.round(dx * inputWidth);
  50832. if (px < 0)
  50833. px = 0;
  50834. else if (px >= inputWidth)
  50835. px = inputWidth - 1;
  50836. var py = Math.round(dy * inputHeight);
  50837. if (py < 0)
  50838. py = 0;
  50839. else if (py >= inputHeight)
  50840. py = inputHeight - 1;
  50841. var inputY = (inputHeight - py - 1);
  50842. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  50843. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  50844. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  50845. return {
  50846. r: r,
  50847. g: g,
  50848. b: b
  50849. };
  50850. };
  50851. return PanoramaToCubeMapTools;
  50852. }());
  50853. PanoramaToCubeMapTools.FACE_FRONT = [
  50854. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  50855. new BABYLON.Vector3(1.0, -1.0, -1.0),
  50856. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  50857. new BABYLON.Vector3(1.0, 1.0, -1.0)
  50858. ];
  50859. PanoramaToCubeMapTools.FACE_BACK = [
  50860. new BABYLON.Vector3(1.0, -1.0, 1.0),
  50861. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  50862. new BABYLON.Vector3(1.0, 1.0, 1.0),
  50863. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  50864. ];
  50865. PanoramaToCubeMapTools.FACE_RIGHT = [
  50866. new BABYLON.Vector3(1.0, -1.0, -1.0),
  50867. new BABYLON.Vector3(1.0, -1.0, 1.0),
  50868. new BABYLON.Vector3(1.0, 1.0, -1.0),
  50869. new BABYLON.Vector3(1.0, 1.0, 1.0)
  50870. ];
  50871. PanoramaToCubeMapTools.FACE_LEFT = [
  50872. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  50873. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  50874. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  50875. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  50876. ];
  50877. PanoramaToCubeMapTools.FACE_DOWN = [
  50878. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  50879. new BABYLON.Vector3(1.0, 1.0, -1.0),
  50880. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  50881. new BABYLON.Vector3(1.0, 1.0, 1.0)
  50882. ];
  50883. PanoramaToCubeMapTools.FACE_UP = [
  50884. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  50885. new BABYLON.Vector3(1.0, -1.0, 1.0),
  50886. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  50887. new BABYLON.Vector3(1.0, -1.0, -1.0)
  50888. ];
  50889. Internals.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  50890. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  50891. })(BABYLON || (BABYLON = {}));
  50892. //# sourceMappingURL=babylon.tools.panoramaToCubemap.js.map
  50893. var BABYLON;
  50894. (function (BABYLON) {
  50895. var Internals;
  50896. (function (Internals) {
  50897. ;
  50898. /**
  50899. * This groups tools to convert HDR texture to native colors array.
  50900. */
  50901. var HDRTools = (function () {
  50902. function HDRTools() {
  50903. }
  50904. HDRTools.Ldexp = function (mantissa, exponent) {
  50905. if (exponent > 1023) {
  50906. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  50907. }
  50908. if (exponent < -1074) {
  50909. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  50910. }
  50911. return mantissa * Math.pow(2, exponent);
  50912. };
  50913. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  50914. if (exponent > 0) {
  50915. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  50916. float32array[index + 0] = red * exponent;
  50917. float32array[index + 1] = green * exponent;
  50918. float32array[index + 2] = blue * exponent;
  50919. }
  50920. else {
  50921. float32array[index + 0] = 0;
  50922. float32array[index + 1] = 0;
  50923. float32array[index + 2] = 0;
  50924. }
  50925. };
  50926. HDRTools.readStringLine = function (uint8array, startIndex) {
  50927. var line = "";
  50928. var character = "";
  50929. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  50930. character = String.fromCharCode(uint8array[i]);
  50931. if (character == "\n") {
  50932. break;
  50933. }
  50934. line += character;
  50935. }
  50936. return line;
  50937. };
  50938. /**
  50939. * Reads header information from an RGBE texture stored in a native array.
  50940. * More information on this format are available here:
  50941. * https://en.wikipedia.org/wiki/RGBE_image_format
  50942. *
  50943. * @param uint8array The binary file stored in native array.
  50944. * @return The header information.
  50945. */
  50946. HDRTools.RGBE_ReadHeader = function (uint8array) {
  50947. var height = 0;
  50948. var width = 0;
  50949. var line = this.readStringLine(uint8array, 0);
  50950. if (line[0] != '#' || line[1] != '?') {
  50951. throw "Bad HDR Format.";
  50952. }
  50953. var endOfHeader = false;
  50954. var findFormat = false;
  50955. var lineIndex = 0;
  50956. do {
  50957. lineIndex += (line.length + 1);
  50958. line = this.readStringLine(uint8array, lineIndex);
  50959. if (line == "FORMAT=32-bit_rle_rgbe") {
  50960. findFormat = true;
  50961. }
  50962. else if (line.length == 0) {
  50963. endOfHeader = true;
  50964. }
  50965. } while (!endOfHeader);
  50966. if (!findFormat) {
  50967. throw "HDR Bad header format, unsupported FORMAT";
  50968. }
  50969. lineIndex += (line.length + 1);
  50970. line = this.readStringLine(uint8array, lineIndex);
  50971. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  50972. var match = sizeRegexp.exec(line);
  50973. // TODO. Support +Y and -X if needed.
  50974. if (match.length < 3) {
  50975. throw "HDR Bad header format, no size";
  50976. }
  50977. width = parseInt(match[2]);
  50978. height = parseInt(match[1]);
  50979. if (width < 8 || width > 0x7fff) {
  50980. throw "HDR Bad header format, unsupported size";
  50981. }
  50982. lineIndex += (line.length + 1);
  50983. return {
  50984. height: height,
  50985. width: width,
  50986. dataPosition: lineIndex
  50987. };
  50988. };
  50989. /**
  50990. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  50991. * This RGBE texture needs to store the information as a panorama.
  50992. *
  50993. * More information on this format are available here:
  50994. * https://en.wikipedia.org/wiki/RGBE_image_format
  50995. *
  50996. * @param buffer The binary file stored in an array buffer.
  50997. * @param size The expected size of the extracted cubemap.
  50998. * @return The Cube Map information.
  50999. */
  51000. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  51001. var uint8array = new Uint8Array(buffer);
  51002. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  51003. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  51004. var cubeMapData = Internals.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  51005. return cubeMapData;
  51006. };
  51007. /**
  51008. * Returns the pixels data extracted from an RGBE texture.
  51009. * This pixels will be stored left to right up to down in the R G B order in one array.
  51010. *
  51011. * More information on this format are available here:
  51012. * https://en.wikipedia.org/wiki/RGBE_image_format
  51013. *
  51014. * @param uint8array The binary file stored in an array buffer.
  51015. * @param hdrInfo The header information of the file.
  51016. * @return The pixels data in RGB right to left up to down order.
  51017. */
  51018. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  51019. // Keep for multi format supports.
  51020. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  51021. };
  51022. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  51023. var num_scanlines = hdrInfo.height;
  51024. var scanline_width = hdrInfo.width;
  51025. var a, b, c, d, count;
  51026. var dataIndex = hdrInfo.dataPosition;
  51027. var index = 0, endIndex = 0, i = 0;
  51028. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  51029. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  51030. // 3 channels of 4 bytes per pixel in float.
  51031. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  51032. var resultArray = new Float32Array(resultBuffer);
  51033. // read in each successive scanline
  51034. while (num_scanlines > 0) {
  51035. a = uint8array[dataIndex++];
  51036. b = uint8array[dataIndex++];
  51037. c = uint8array[dataIndex++];
  51038. d = uint8array[dataIndex++];
  51039. if (a != 2 || b != 2 || (c & 0x80)) {
  51040. // this file is not run length encoded
  51041. throw "HDR Bad header format, not RLE";
  51042. }
  51043. if (((c << 8) | d) != scanline_width) {
  51044. throw "HDR Bad header format, wrong scan line width";
  51045. }
  51046. index = 0;
  51047. // read each of the four channels for the scanline into the buffer
  51048. for (i = 0; i < 4; i++) {
  51049. endIndex = (i + 1) * scanline_width;
  51050. while (index < endIndex) {
  51051. a = uint8array[dataIndex++];
  51052. b = uint8array[dataIndex++];
  51053. if (a > 128) {
  51054. // a run of the same value
  51055. count = a - 128;
  51056. if ((count == 0) || (count > endIndex - index)) {
  51057. throw "HDR Bad Format, bad scanline data (run)";
  51058. }
  51059. while (count-- > 0) {
  51060. scanLineArray[index++] = b;
  51061. }
  51062. }
  51063. else {
  51064. // a non-run
  51065. count = a;
  51066. if ((count == 0) || (count > endIndex - index)) {
  51067. throw "HDR Bad Format, bad scanline data (non-run)";
  51068. }
  51069. scanLineArray[index++] = b;
  51070. if (--count > 0) {
  51071. for (var j = 0; j < count; j++) {
  51072. scanLineArray[index++] = uint8array[dataIndex++];
  51073. }
  51074. }
  51075. }
  51076. }
  51077. }
  51078. // now convert data from buffer into floats
  51079. for (i = 0; i < scanline_width; i++) {
  51080. a = scanLineArray[i];
  51081. b = scanLineArray[i + scanline_width];
  51082. c = scanLineArray[i + 2 * scanline_width];
  51083. d = scanLineArray[i + 3 * scanline_width];
  51084. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  51085. }
  51086. num_scanlines--;
  51087. }
  51088. return resultArray;
  51089. };
  51090. return HDRTools;
  51091. }());
  51092. Internals.HDRTools = HDRTools;
  51093. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  51094. })(BABYLON || (BABYLON = {}));
  51095. //# sourceMappingURL=babylon.tools.hdr.js.map
  51096. //_______________________________________________________________
  51097. // Extracted from CubeMapGen:
  51098. // https://code.google.com/archive/p/cubemapgen/
  51099. //
  51100. // Following https://seblagarde.wordpress.com/2012/06/10/amd-cubemapgen-for-physically-based-rendering/
  51101. //_______________________________________________________________
  51102. var BABYLON;
  51103. (function (BABYLON) {
  51104. var Internals;
  51105. (function (Internals) {
  51106. /**
  51107. * The bounding box information used during the conversion process.
  51108. */
  51109. var CMGBoundinBox = (function () {
  51110. function CMGBoundinBox() {
  51111. this.min = new BABYLON.Vector3(0, 0, 0);
  51112. this.max = new BABYLON.Vector3(0, 0, 0);
  51113. this.clear();
  51114. }
  51115. CMGBoundinBox.prototype.clear = function () {
  51116. this.min.x = CMGBoundinBox.MAX;
  51117. this.min.y = CMGBoundinBox.MAX;
  51118. this.min.z = CMGBoundinBox.MAX;
  51119. this.max.x = CMGBoundinBox.MIN;
  51120. this.max.y = CMGBoundinBox.MIN;
  51121. this.max.z = CMGBoundinBox.MIN;
  51122. };
  51123. CMGBoundinBox.prototype.augment = function (x, y, z) {
  51124. this.min.x = Math.min(this.min.x, x);
  51125. this.min.y = Math.min(this.min.y, y);
  51126. this.min.z = Math.min(this.min.z, z);
  51127. this.max.x = Math.max(this.max.x, x);
  51128. this.max.y = Math.max(this.max.y, y);
  51129. this.max.z = Math.max(this.max.z, z);
  51130. };
  51131. CMGBoundinBox.prototype.clampMin = function (x, y, z) {
  51132. this.min.x = Math.max(this.min.x, x);
  51133. this.min.y = Math.max(this.min.y, y);
  51134. this.min.z = Math.max(this.min.z, z);
  51135. };
  51136. CMGBoundinBox.prototype.clampMax = function (x, y, z) {
  51137. this.max.x = Math.min(this.max.x, x);
  51138. this.max.y = Math.min(this.max.y, y);
  51139. this.max.z = Math.min(this.max.z, z);
  51140. };
  51141. CMGBoundinBox.prototype.empty = function () {
  51142. if ((this.min.x > this.max.y) ||
  51143. (this.min.y > this.max.y) ||
  51144. (this.min.z > this.max.y)) {
  51145. return true;
  51146. }
  51147. else {
  51148. return false;
  51149. }
  51150. };
  51151. return CMGBoundinBox;
  51152. }());
  51153. CMGBoundinBox.MAX = Number.MAX_VALUE;
  51154. CMGBoundinBox.MIN = Number.MIN_VALUE;
  51155. /**
  51156. * Helper class to PreProcess a cubemap in order to generate mipmap according to the level of blur
  51157. * required by the glossinees of a material.
  51158. *
  51159. * This only supports the cosine drop power as well as Warp fixup generation method.
  51160. *
  51161. * This is using the process from CubeMapGen described here:
  51162. * https://seblagarde.wordpress.com/2012/06/10/amd-cubemapgen-for-physically-based-rendering/
  51163. */
  51164. var PMREMGenerator = (function () {
  51165. /**
  51166. * Constructor of the generator.
  51167. *
  51168. * @param input The different faces data from the original cubemap in the order X+ X- Y+ Y- Z+ Z-
  51169. * @param inputSize The size of the cubemap faces
  51170. * @param outputSize The size of the output cubemap faces
  51171. * @param maxNumMipLevels The max number of mip map to generate (0 means all)
  51172. * @param numChannels The number of channels stored in the cubemap (3 for RBGE for instance)
  51173. * @param isFloat Specifies if the input texture is in float or int (hdr is usually in float)
  51174. * @param specularPower The max specular level of the desired cubemap
  51175. * @param cosinePowerDropPerMip The amount of drop the specular power will follow on each mip
  51176. * @param excludeBase Specifies wether to process the level 0 (original level) or not
  51177. * @param fixup Specifies wether to apply the edge fixup algorythm or not
  51178. */
  51179. function PMREMGenerator(input, inputSize, outputSize, maxNumMipLevels, numChannels, isFloat, specularPower, cosinePowerDropPerMip, excludeBase, fixup) {
  51180. this.input = input;
  51181. this.inputSize = inputSize;
  51182. this.outputSize = outputSize;
  51183. this.maxNumMipLevels = maxNumMipLevels;
  51184. this.numChannels = numChannels;
  51185. this.isFloat = isFloat;
  51186. this.specularPower = specularPower;
  51187. this.cosinePowerDropPerMip = cosinePowerDropPerMip;
  51188. this.excludeBase = excludeBase;
  51189. this.fixup = fixup;
  51190. this._outputSurface = [];
  51191. this._numMipLevels = 0;
  51192. }
  51193. /**
  51194. * Launches the filter process and return the result.
  51195. *
  51196. * @return the filter cubemap in the form mip0 [faces1..6] .. mipN [faces1..6]
  51197. */
  51198. PMREMGenerator.prototype.filterCubeMap = function () {
  51199. // Init cubemap processor
  51200. this.init();
  51201. // Filters the cubemap
  51202. this.filterCubeMapMipChain();
  51203. // Returns the filtered mips.
  51204. return this._outputSurface;
  51205. };
  51206. PMREMGenerator.prototype.init = function () {
  51207. var i;
  51208. var j;
  51209. var mipLevelSize;
  51210. //if nax num mip levels is set to 0, set it to generate the entire mip chain
  51211. if (this.maxNumMipLevels == 0) {
  51212. this.maxNumMipLevels = PMREMGenerator.CP_MAX_MIPLEVELS;
  51213. }
  51214. //first miplevel size
  51215. mipLevelSize = this.outputSize;
  51216. //Iterate over mip chain, and init ArrayBufferView for mip-chain
  51217. for (j = 0; j < this.maxNumMipLevels; j++) {
  51218. this._outputSurface.length++;
  51219. this._outputSurface[j] = [];
  51220. //Iterate over faces for output images
  51221. for (i = 0; i < 6; i++) {
  51222. this._outputSurface[j].length++;
  51223. // Initializes a new array for the output.
  51224. if (this.isFloat) {
  51225. this._outputSurface[j][i] = new Float32Array(mipLevelSize * mipLevelSize * this.numChannels);
  51226. }
  51227. else {
  51228. this._outputSurface[j][i] = new Uint32Array(mipLevelSize * mipLevelSize * this.numChannels);
  51229. }
  51230. }
  51231. //next mip level is half size
  51232. mipLevelSize >>= 1;
  51233. this._numMipLevels++;
  51234. //terminate if mip chain becomes too small
  51235. if (mipLevelSize == 0) {
  51236. this.maxNumMipLevels = j;
  51237. return;
  51238. }
  51239. }
  51240. };
  51241. //--------------------------------------------------------------------------------------
  51242. //Cube map filtering and mip chain generation.
  51243. // the cube map filtereing is specified using a number of parameters:
  51244. // Filtering per miplevel is specified using 2D cone angle (in degrees) that
  51245. // indicates the region of the hemisphere to filter over for each tap.
  51246. //
  51247. // Note that the top mip level is also a filtered version of the original input images
  51248. // as well in order to create mip chains for diffuse environment illumination.
  51249. // The cone angle for the top level is specified by a_BaseAngle. This can be used to
  51250. // generate mipchains used to store the resutls of preintegration across the hemisphere.
  51251. //
  51252. // Then the mip angle used to genreate the next level of the mip chain from the first level
  51253. // is a_InitialMipAngle
  51254. //
  51255. // The angle for the subsequent levels of the mip chain are specified by their parents
  51256. // filtering angle and a per-level scale and bias
  51257. // newAngle = oldAngle * a_MipAnglePerLevelScale;
  51258. //
  51259. //--------------------------------------------------------------------------------------
  51260. PMREMGenerator.prototype.filterCubeMapMipChain = function () {
  51261. // First, take count of the lighting model to modify SpecularPower
  51262. // 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;
  51263. // var refSpecularPower = this.specularPower; // Only Phong BRDF yet. This explains the line below using this.specularpower.
  51264. //Cone angle start (for generating subsequent mip levels)
  51265. var currentSpecularPower = this.specularPower;
  51266. //Build filter lookup tables based on the source miplevel size
  51267. this.precomputeFilterLookupTables(this.inputSize);
  51268. // Note that we need to filter the first level before generating mipmap
  51269. // So LevelIndex == 0 is base filtering hen LevelIndex > 0 is mipmap generation
  51270. for (var levelIndex = 0; levelIndex < this._numMipLevels; levelIndex++) {
  51271. // TODO : Write a function to copy and scale the base mipmap in output
  51272. // I am just lazy here and just put a high specular power value, and do some if.
  51273. if (this.excludeBase && (levelIndex == 0)) {
  51274. // 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).
  51275. currentSpecularPower = 100000.0;
  51276. }
  51277. // Special case for cosine power mipmap chain. For quality requirement, we always process the current mipmap from the top mipmap
  51278. var srcCubeImage = this.input;
  51279. var dstCubeImage = this._outputSurface[levelIndex];
  51280. var dstSize = this.outputSize >> levelIndex;
  51281. // Compute required angle.
  51282. var angle = this.getBaseFilterAngle(currentSpecularPower);
  51283. // filter cube surfaces
  51284. this.filterCubeSurfaces(srcCubeImage, this.inputSize, dstCubeImage, dstSize, angle, currentSpecularPower);
  51285. // fix seams
  51286. if (this.fixup) {
  51287. this.fixupCubeEdges(dstCubeImage, dstSize);
  51288. }
  51289. // Decrease the specular power to generate the mipmap chain
  51290. // TODO : Use another method for Exclude (see first comment at start of the function
  51291. if (this.excludeBase && (levelIndex == 0)) {
  51292. currentSpecularPower = this.specularPower;
  51293. }
  51294. currentSpecularPower *= this.cosinePowerDropPerMip;
  51295. }
  51296. };
  51297. //--------------------------------------------------------------------------------------
  51298. // This function return the BaseFilterAngle require by PMREMGenerator to its FilterExtends
  51299. // It allow to optimize the texel to access base on the specular power.
  51300. //--------------------------------------------------------------------------------------
  51301. PMREMGenerator.prototype.getBaseFilterAngle = function (cosinePower) {
  51302. // We want to find the alpha such that:
  51303. // cos(alpha)^cosinePower = epsilon
  51304. // That's: acos(epsilon^(1/cosinePower))
  51305. var threshold = 0.000001; // Empirical threshold (Work perfectly, didn't check for a more big number, may get some performance and still god approximation)
  51306. var angle = 180.0;
  51307. angle = Math.acos(Math.pow(threshold, 1.0 / cosinePower));
  51308. angle *= 180.0 / Math.PI; // Convert to degree
  51309. angle *= 2.0; // * 2.0f because PMREMGenerator divide by 2 later
  51310. return angle;
  51311. };
  51312. //--------------------------------------------------------------------------------------
  51313. //Builds the following lookup tables prior to filtering:
  51314. // -normalizer cube map
  51315. // -tap weight lookup table
  51316. //
  51317. //--------------------------------------------------------------------------------------
  51318. PMREMGenerator.prototype.precomputeFilterLookupTables = function (srcCubeMapWidth) {
  51319. var srcTexelAngle;
  51320. var iCubeFace;
  51321. //clear pre-existing normalizer cube map
  51322. this._normCubeMap = [];
  51323. //Normalized vectors per cubeface and per-texel solid angle
  51324. this.buildNormalizerSolidAngleCubemap(srcCubeMapWidth);
  51325. };
  51326. //--------------------------------------------------------------------------------------
  51327. //Builds a normalizer cubemap, with the texels solid angle stored in the fourth component
  51328. //
  51329. //Takes in a cube face size, and an array of 6 surfaces to write the cube faces into
  51330. //
  51331. //Note that this normalizer cube map stores the vectors in unbiased -1 to 1 range.
  51332. // if _bx2 style scaled and biased vectors are needed, uncomment the SCALE and BIAS
  51333. // below
  51334. //--------------------------------------------------------------------------------------
  51335. PMREMGenerator.prototype.buildNormalizerSolidAngleCubemap = function (size) {
  51336. var iCubeFace;
  51337. var u;
  51338. var v;
  51339. //iterate over cube faces
  51340. for (iCubeFace = 0; iCubeFace < 6; iCubeFace++) {
  51341. //First three channels for norm cube, and last channel for solid angle
  51342. this._normCubeMap.push(new Float32Array(size * size * 4));
  51343. //fast texture walk, build normalizer cube map
  51344. var facesData = this.input[iCubeFace];
  51345. for (v = 0; v < size; v++) {
  51346. for (u = 0; u < size; u++) {
  51347. var vect = this.texelCoordToVect(iCubeFace, u, v, size, this.fixup);
  51348. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 0] = vect.x;
  51349. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 1] = vect.y;
  51350. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 2] = vect.z;
  51351. var solidAngle = this.texelCoordSolidAngle(iCubeFace, u, v, size);
  51352. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 4] = solidAngle;
  51353. }
  51354. }
  51355. }
  51356. };
  51357. //--------------------------------------------------------------------------------------
  51358. // Convert cubemap face texel coordinates and face idx to 3D vector
  51359. // note the U and V coords are integer coords and range from 0 to size-1
  51360. // this routine can be used to generate a normalizer cube map
  51361. //--------------------------------------------------------------------------------------
  51362. // SL BEGIN
  51363. PMREMGenerator.prototype.texelCoordToVect = function (faceIdx, u, v, size, fixup) {
  51364. var nvcU;
  51365. var nvcV;
  51366. var tempVec;
  51367. // Change from original AMD code
  51368. // transform from [0..res - 1] to [- (1 - 1 / res) .. (1 - 1 / res)]
  51369. // + 0.5f is for texel center addressing
  51370. nvcU = (2.0 * (u + 0.5) / size) - 1.0;
  51371. nvcV = (2.0 * (v + 0.5) / size) - 1.0;
  51372. // warp fixup
  51373. if (fixup && size > 1) {
  51374. // Code from Nvtt : http://code.google.com/p/nvidia-texture-tools/source/browse/trunk/src/nvtt/CubeSurface.cpp
  51375. var a = Math.pow(size, 2.0) / Math.pow(size - 1, 3.0);
  51376. nvcU = a * Math.pow(nvcU, 3) + nvcU;
  51377. nvcV = a * Math.pow(nvcV, 3) + nvcV;
  51378. }
  51379. // Get current vector
  51380. // generate x,y,z vector (xform 2d NVC coord to 3D vector)
  51381. // U contribution
  51382. var UVec = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_UDIR];
  51383. PMREMGenerator._vectorTemp.x = UVec[0] * nvcU;
  51384. PMREMGenerator._vectorTemp.y = UVec[1] * nvcU;
  51385. PMREMGenerator._vectorTemp.z = UVec[2] * nvcU;
  51386. // V contribution and Sum
  51387. var VVec = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_VDIR];
  51388. PMREMGenerator._vectorTemp.x += VVec[0] * nvcV;
  51389. PMREMGenerator._vectorTemp.y += VVec[1] * nvcV;
  51390. PMREMGenerator._vectorTemp.z += VVec[2] * nvcV;
  51391. //add face axis
  51392. var faceAxis = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_FACEAXIS];
  51393. PMREMGenerator._vectorTemp.x += faceAxis[0];
  51394. PMREMGenerator._vectorTemp.y += faceAxis[1];
  51395. PMREMGenerator._vectorTemp.z += faceAxis[2];
  51396. //normalize vector
  51397. PMREMGenerator._vectorTemp.normalize();
  51398. return PMREMGenerator._vectorTemp;
  51399. };
  51400. //--------------------------------------------------------------------------------------
  51401. // Convert 3D vector to cubemap face texel coordinates and face idx
  51402. // note the U and V coords are integer coords and range from 0 to size-1
  51403. // this routine can be used to generate a normalizer cube map
  51404. //
  51405. // returns face IDX and texel coords
  51406. //--------------------------------------------------------------------------------------
  51407. // SL BEGIN
  51408. /*
  51409. Mapping Texture Coordinates to Cube Map Faces
  51410. Because there are multiple faces, the mapping of texture coordinates to positions on cube map faces
  51411. is more complicated than the other texturing targets. The EXT_texture_cube_map extension is purposefully
  51412. designed to be consistent with DirectX 7's cube map arrangement. This is also consistent with the cube
  51413. map arrangement in Pixar's RenderMan package.
  51414. For cube map texturing, the (s,t,r) texture coordinates are treated as a direction vector (rx,ry,rz)
  51415. emanating from the center of a cube. (The q coordinate can be ignored since it merely scales the vector
  51416. without affecting the direction.) At texture application time, the interpolated per-fragment (s,t,r)
  51417. selects one of the cube map face's 2D mipmap sets based on the largest magnitude coordinate direction
  51418. the major axis direction). The target column in the table below explains how the major axis direction
  51419. maps to the 2D image of a particular cube map target.
  51420. major axis
  51421. direction target sc tc ma
  51422. ---------- --------------------------------- --- --- ---
  51423. +rx GL_TEXTURE_CUBE_MAP_POSITIVE_X_EXT -rz -ry rx
  51424. -rx GL_TEXTURE_CUBE_MAP_NEGATIVE_X_EXT +rz -ry rx
  51425. +ry GL_TEXTURE_CUBE_MAP_POSITIVE_Y_EXT +rx +rz ry
  51426. -ry GL_TEXTURE_CUBE_MAP_NEGATIVE_Y_EXT +rx -rz ry
  51427. +rz GL_TEXTURE_CUBE_MAP_POSITIVE_Z_EXT +rx -ry rz
  51428. -rz GL_TEXTURE_CUBE_MAP_NEGATIVE_Z_EXT -rx -ry rz
  51429. Using the sc, tc, and ma determined by the major axis direction as specified in the table above,
  51430. an updated (s,t) is calculated as follows
  51431. s = ( sc/|ma| + 1 ) / 2
  51432. t = ( tc/|ma| + 1 ) / 2
  51433. If |ma| is zero or very nearly zero, the results of the above two equations need not be defined
  51434. (though the result may not lead to GL interruption or termination). Once the cube map face's 2D mipmap
  51435. set and (s,t) is determined, texture fetching and filtering proceeds like standard OpenGL 2D texturing.
  51436. */
  51437. // Note this method return U and V in range from 0 to size-1
  51438. // SL END
  51439. // Store the information in vector3 for convenience (faceindex, u, v)
  51440. PMREMGenerator.prototype.vectToTexelCoord = function (x, y, z, size) {
  51441. var maxCoord;
  51442. var faceIdx;
  51443. //absolute value 3
  51444. var absX = Math.abs(x);
  51445. var absY = Math.abs(y);
  51446. var absZ = Math.abs(z);
  51447. if (absX >= absY && absX >= absZ) {
  51448. maxCoord = absX;
  51449. if (x >= 0) {
  51450. faceIdx = PMREMGenerator.CP_FACE_X_POS;
  51451. }
  51452. else {
  51453. faceIdx = PMREMGenerator.CP_FACE_X_NEG;
  51454. }
  51455. }
  51456. else if (absY >= absX && absY >= absZ) {
  51457. maxCoord = absY;
  51458. if (y >= 0) {
  51459. faceIdx = PMREMGenerator.CP_FACE_Y_POS;
  51460. }
  51461. else {
  51462. faceIdx = PMREMGenerator.CP_FACE_Y_NEG;
  51463. }
  51464. }
  51465. else {
  51466. maxCoord = absZ;
  51467. if (z >= 0) {
  51468. faceIdx = PMREMGenerator.CP_FACE_Z_POS;
  51469. }
  51470. else {
  51471. faceIdx = PMREMGenerator.CP_FACE_Z_NEG;
  51472. }
  51473. }
  51474. //divide through by max coord so face vector lies on cube face
  51475. var scale = 1 / maxCoord;
  51476. x *= scale;
  51477. y *= scale;
  51478. z *= scale;
  51479. var temp = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_UDIR];
  51480. var nvcU = temp[0] * x + temp[1] * y + temp[2] * z;
  51481. temp = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_VDIR];
  51482. var nvcV = temp[0] * x + temp[1] * y + temp[2] * z;
  51483. // Modify original AMD code to return value from 0 to Size - 1
  51484. var u = Math.floor((size - 1) * 0.5 * (nvcU + 1.0));
  51485. var v = Math.floor((size - 1) * 0.5 * (nvcV + 1.0));
  51486. PMREMGenerator._vectorTemp.x = faceIdx;
  51487. PMREMGenerator._vectorTemp.y = u;
  51488. PMREMGenerator._vectorTemp.z = v;
  51489. return PMREMGenerator._vectorTemp;
  51490. };
  51491. //--------------------------------------------------------------------------------------
  51492. //Original code from Ignacio CastaÒo
  51493. // This formula is from Manne ÷hrstrˆm's thesis.
  51494. // Take two coordiantes in the range [-1, 1] that define a portion of a
  51495. // cube face and return the area of the projection of that portion on the
  51496. // surface of the sphere.
  51497. //--------------------------------------------------------------------------------------
  51498. PMREMGenerator.prototype.areaElement = function (x, y) {
  51499. return Math.atan2(x * y, Math.sqrt(x * x + y * y + 1));
  51500. };
  51501. PMREMGenerator.prototype.texelCoordSolidAngle = function (faceIdx, u, v, size) {
  51502. // transform from [0..res - 1] to [- (1 - 1 / res) .. (1 - 1 / res)]
  51503. // (+ 0.5f is for texel center addressing)
  51504. u = (2.0 * (u + 0.5) / size) - 1.0;
  51505. v = (2.0 * (v + 0.5) / size) - 1.0;
  51506. // Shift from a demi texel, mean 1.0f / a_Size with U and V in [-1..1]
  51507. var invResolution = 1.0 / size;
  51508. // U and V are the -1..1 texture coordinate on the current face.
  51509. // Get projected area for this texel
  51510. var x0 = u - invResolution;
  51511. var y0 = v - invResolution;
  51512. var x1 = u + invResolution;
  51513. var y1 = v + invResolution;
  51514. var solidAngle = this.areaElement(x0, y0) - this.areaElement(x0, y1) - this.areaElement(x1, y0) + this.areaElement(x1, y1);
  51515. return solidAngle;
  51516. };
  51517. //--------------------------------------------------------------------------------------
  51518. //The key to the speed of these filtering routines is to quickly define a per-face
  51519. // bounding box of pixels which enclose all the taps in the filter kernel efficiently.
  51520. // Later these pixels are selectively processed based on their dot products to see if
  51521. // they reside within the filtering cone.
  51522. //
  51523. //This is done by computing the smallest per-texel angle to get a conservative estimate
  51524. // of the number of texels needed to be covered in width and height order to filter the
  51525. // region. the bounding box for the center taps face is defined first, and if the
  51526. // filtereing region bleeds onto the other faces, bounding boxes for the other faces are
  51527. // defined next
  51528. //--------------------------------------------------------------------------------------
  51529. PMREMGenerator.prototype.filterCubeSurfaces = function (srcCubeMap, srcSize, dstCubeMap, dstSize, filterConeAngle, specularPower) {
  51530. // note that pixels within these regions may be rejected
  51531. // based on the anlge
  51532. var iCubeFace;
  51533. var u;
  51534. var v;
  51535. // bounding box per face to specify region to process
  51536. var filterExtents = [];
  51537. for (iCubeFace = 0; iCubeFace < 6; iCubeFace++) {
  51538. filterExtents.push(new CMGBoundinBox());
  51539. }
  51540. // min angle a src texel can cover (in degrees)
  51541. var srcTexelAngle = (180.0 / (Math.PI) * Math.atan2(1.0, srcSize));
  51542. // angle about center tap to define filter cone
  51543. // filter angle is 1/2 the cone angle
  51544. var filterAngle = filterConeAngle / 2.0;
  51545. //ensure filter angle is larger than a texel
  51546. if (filterAngle < srcTexelAngle) {
  51547. filterAngle = srcTexelAngle;
  51548. }
  51549. //ensure filter cone is always smaller than the hemisphere
  51550. if (filterAngle > 90.0) {
  51551. filterAngle = 90.0;
  51552. }
  51553. // the maximum number of texels in 1D the filter cone angle will cover
  51554. // used to determine bounding box size for filter extents
  51555. var filterSize = Math.ceil(filterAngle / srcTexelAngle);
  51556. // ensure conservative region always covers at least one texel
  51557. if (filterSize < 1) {
  51558. filterSize = 1;
  51559. }
  51560. // dotProdThresh threshold based on cone angle to determine whether or not taps
  51561. // reside within the cone angle
  51562. var dotProdThresh = Math.cos((Math.PI / 180.0) * filterAngle);
  51563. // process required faces
  51564. for (iCubeFace = 0; iCubeFace < 6; iCubeFace++) {
  51565. //iterate over dst cube map face texel
  51566. for (v = 0; v < dstSize; v++) {
  51567. for (u = 0; u < dstSize; u++) {
  51568. //get center tap direction
  51569. var centerTapDir = this.texelCoordToVect(iCubeFace, u, v, dstSize, this.fixup).clone();
  51570. //clear old per-face filter extents
  51571. this.clearFilterExtents(filterExtents);
  51572. //define per-face filter extents
  51573. this.determineFilterExtents(centerTapDir, srcSize, filterSize, filterExtents);
  51574. //perform filtering of src faces using filter extents
  51575. var vect = this.processFilterExtents(centerTapDir, dotProdThresh, filterExtents, srcCubeMap, srcSize, specularPower);
  51576. dstCubeMap[iCubeFace][(v * dstSize + u) * this.numChannels + 0] = vect.x;
  51577. dstCubeMap[iCubeFace][(v * dstSize + u) * this.numChannels + 1] = vect.y;
  51578. dstCubeMap[iCubeFace][(v * dstSize + u) * this.numChannels + 2] = vect.z;
  51579. }
  51580. }
  51581. }
  51582. };
  51583. //--------------------------------------------------------------------------------------
  51584. //Clear filter extents for the 6 cube map faces
  51585. //--------------------------------------------------------------------------------------
  51586. PMREMGenerator.prototype.clearFilterExtents = function (filterExtents) {
  51587. for (var iCubeFaces = 0; iCubeFaces < 6; iCubeFaces++) {
  51588. filterExtents[iCubeFaces].clear();
  51589. }
  51590. };
  51591. //--------------------------------------------------------------------------------------
  51592. //Define per-face bounding box filter extents
  51593. //
  51594. // These define conservative texel regions in each of the faces the filter can possibly
  51595. // process. When the pixels in the regions are actually processed, the dot product
  51596. // between the tap vector and the center tap vector is used to determine the weight of
  51597. // the tap and whether or not the tap is within the cone.
  51598. //
  51599. //--------------------------------------------------------------------------------------
  51600. PMREMGenerator.prototype.determineFilterExtents = function (centerTapDir, srcSize, bboxSize, filterExtents) {
  51601. //neighboring face and bleed over amount, and width of BBOX for
  51602. // left, right, top, and bottom edges of this face
  51603. var bleedOverAmount = [0, 0, 0, 0];
  51604. var bleedOverBBoxMin = [0, 0, 0, 0];
  51605. var bleedOverBBoxMax = [0, 0, 0, 0];
  51606. var neighborFace;
  51607. var neighborEdge;
  51608. var oppositeFaceIdx;
  51609. //get face idx, and u, v info from center tap dir
  51610. var result = this.vectToTexelCoord(centerTapDir.x, centerTapDir.y, centerTapDir.z, srcSize);
  51611. var faceIdx = result.x;
  51612. var u = result.y;
  51613. var v = result.z;
  51614. //define bbox size within face
  51615. filterExtents[faceIdx].augment(u - bboxSize, v - bboxSize, 0);
  51616. filterExtents[faceIdx].augment(u + bboxSize, v + bboxSize, 0);
  51617. filterExtents[faceIdx].clampMin(0, 0, 0);
  51618. filterExtents[faceIdx].clampMax(srcSize - 1, srcSize - 1, 0);
  51619. //u and v extent in face corresponding to center tap
  51620. var minU = filterExtents[faceIdx].min.x;
  51621. var minV = filterExtents[faceIdx].min.y;
  51622. var maxU = filterExtents[faceIdx].max.x;
  51623. var maxV = filterExtents[faceIdx].max.y;
  51624. //bleed over amounts for face across u=0 edge (left)
  51625. bleedOverAmount[0] = (bboxSize - u);
  51626. bleedOverBBoxMin[0] = minV;
  51627. bleedOverBBoxMax[0] = maxV;
  51628. //bleed over amounts for face across u=1 edge (right)
  51629. bleedOverAmount[1] = (u + bboxSize) - (srcSize - 1);
  51630. bleedOverBBoxMin[1] = minV;
  51631. bleedOverBBoxMax[1] = maxV;
  51632. //bleed over to face across v=0 edge (up)
  51633. bleedOverAmount[2] = (bboxSize - v);
  51634. bleedOverBBoxMin[2] = minU;
  51635. bleedOverBBoxMax[2] = maxU;
  51636. //bleed over to face across v=1 edge (down)
  51637. bleedOverAmount[3] = (v + bboxSize) - (srcSize - 1);
  51638. bleedOverBBoxMin[3] = minU;
  51639. bleedOverBBoxMax[3] = maxU;
  51640. //compute bleed over regions in neighboring faces
  51641. for (var i = 0; i < 4; i++) {
  51642. if (bleedOverAmount[i] > 0) {
  51643. neighborFace = PMREMGenerator._sgCubeNgh[faceIdx][i][0];
  51644. neighborEdge = PMREMGenerator._sgCubeNgh[faceIdx][i][1];
  51645. //For certain types of edge abutments, the bleedOverBBoxMin, and bleedOverBBoxMax need to
  51646. // be flipped: the cases are
  51647. // if a left edge mates with a left or bottom edge on the neighbor
  51648. // if a top edge mates with a top or right edge on the neighbor
  51649. // if a right edge mates with a right or top edge on the neighbor
  51650. // if a bottom edge mates with a bottom or left edge on the neighbor
  51651. //Seeing as the edges are enumerated as follows
  51652. // left =0
  51653. // right =1
  51654. // top =2
  51655. // bottom =3
  51656. //
  51657. // so if the edge enums are the same, or the sum of the enums == 3,
  51658. // the bbox needs to be flipped
  51659. if ((i == neighborEdge) || ((i + neighborEdge) == 3)) {
  51660. bleedOverBBoxMin[i] = (srcSize - 1) - bleedOverBBoxMin[i];
  51661. bleedOverBBoxMax[i] = (srcSize - 1) - bleedOverBBoxMax[i];
  51662. }
  51663. //The way the bounding box is extended onto the neighboring face
  51664. // depends on which edge of neighboring face abuts with this one
  51665. switch (PMREMGenerator._sgCubeNgh[faceIdx][i][1]) {
  51666. case PMREMGenerator.CP_EDGE_LEFT:
  51667. filterExtents[neighborFace].augment(0, bleedOverBBoxMin[i], 0);
  51668. filterExtents[neighborFace].augment(bleedOverAmount[i], bleedOverBBoxMax[i], 0);
  51669. break;
  51670. case PMREMGenerator.CP_EDGE_RIGHT:
  51671. filterExtents[neighborFace].augment((srcSize - 1), bleedOverBBoxMin[i], 0);
  51672. filterExtents[neighborFace].augment((srcSize - 1) - bleedOverAmount[i], bleedOverBBoxMax[i], 0);
  51673. break;
  51674. case PMREMGenerator.CP_EDGE_TOP:
  51675. filterExtents[neighborFace].augment(bleedOverBBoxMin[i], 0, 0);
  51676. filterExtents[neighborFace].augment(bleedOverBBoxMax[i], bleedOverAmount[i], 0);
  51677. break;
  51678. case PMREMGenerator.CP_EDGE_BOTTOM:
  51679. filterExtents[neighborFace].augment(bleedOverBBoxMin[i], (srcSize - 1), 0);
  51680. filterExtents[neighborFace].augment(bleedOverBBoxMax[i], (srcSize - 1) - bleedOverAmount[i], 0);
  51681. break;
  51682. }
  51683. //clamp filter extents in non-center tap faces to remain within surface
  51684. filterExtents[neighborFace].clampMin(0, 0, 0);
  51685. filterExtents[neighborFace].clampMax(srcSize - 1, srcSize - 1, 0);
  51686. }
  51687. //If the bleed over amount bleeds past the adjacent face onto the opposite face
  51688. // from the center tap face, then process the opposite face entirely for now.
  51689. //Note that the cases in which this happens, what usually happens is that
  51690. // more than one edge bleeds onto the opposite face, and the bounding box
  51691. // encompasses the entire cube map face.
  51692. if (bleedOverAmount[i] > srcSize) {
  51693. //determine opposite face
  51694. switch (faceIdx) {
  51695. case PMREMGenerator.CP_FACE_X_POS:
  51696. oppositeFaceIdx = PMREMGenerator.CP_FACE_X_NEG;
  51697. break;
  51698. case PMREMGenerator.CP_FACE_X_NEG:
  51699. oppositeFaceIdx = PMREMGenerator.CP_FACE_X_POS;
  51700. break;
  51701. case PMREMGenerator.CP_FACE_Y_POS:
  51702. oppositeFaceIdx = PMREMGenerator.CP_FACE_Y_NEG;
  51703. break;
  51704. case PMREMGenerator.CP_FACE_Y_NEG:
  51705. oppositeFaceIdx = PMREMGenerator.CP_FACE_Y_POS;
  51706. break;
  51707. case PMREMGenerator.CP_FACE_Z_POS:
  51708. oppositeFaceIdx = PMREMGenerator.CP_FACE_Z_NEG;
  51709. break;
  51710. case PMREMGenerator.CP_FACE_Z_NEG:
  51711. oppositeFaceIdx = PMREMGenerator.CP_FACE_Z_POS;
  51712. break;
  51713. default:
  51714. break;
  51715. }
  51716. //just encompass entire face for now
  51717. filterExtents[oppositeFaceIdx].augment(0, 0, 0);
  51718. filterExtents[oppositeFaceIdx].augment((srcSize - 1), (srcSize - 1), 0);
  51719. }
  51720. }
  51721. };
  51722. //--------------------------------------------------------------------------------------
  51723. //ProcessFilterExtents
  51724. // Process bounding box in each cube face
  51725. //
  51726. //--------------------------------------------------------------------------------------
  51727. PMREMGenerator.prototype.processFilterExtents = function (centerTapDir, dotProdThresh, filterExtents, srcCubeMap, srcSize, specularPower) {
  51728. //accumulators are 64-bit floats in order to have the precision needed
  51729. // over a summation of a large number of pixels
  51730. var dstAccum = [0, 0, 0, 0];
  51731. var weightAccum = 0;
  51732. var k = 0;
  51733. var nSrcChannels = this.numChannels;
  51734. // norm cube map and srcCubeMap have same face width
  51735. var faceWidth = srcSize;
  51736. //amount to add to pointer to move to next scanline in images
  51737. var normCubePitch = faceWidth * 4; // 4 channels in normCubeMap.
  51738. var srcCubePitch = faceWidth * this.numChannels; // numChannels correponds to the cubemap number of channel
  51739. var IsPhongBRDF = 1; // Only works in Phong BRDF yet.
  51740. //(a_LightingModel == CP_LIGHTINGMODEL_PHONG_BRDF || a_LightingModel == CP_LIGHTINGMODEL_BLINN_BRDF) ? 1 : 0; // This value will be added to the specular power
  51741. // iterate over cubefaces
  51742. for (var iFaceIdx = 0; iFaceIdx < 6; iFaceIdx++) {
  51743. //if bbox is non empty
  51744. if (!filterExtents[iFaceIdx].empty()) {
  51745. var uStart = filterExtents[iFaceIdx].min.x;
  51746. var vStart = filterExtents[iFaceIdx].min.y;
  51747. var uEnd = filterExtents[iFaceIdx].max.x;
  51748. var vEnd = filterExtents[iFaceIdx].max.y;
  51749. var startIndexNormCubeMap = (4 * ((vStart * faceWidth) + uStart));
  51750. var startIndexSrcCubeMap = (this.numChannels * ((vStart * faceWidth) + uStart));
  51751. //note that <= is used to ensure filter extents always encompass at least one pixel if bbox is non empty
  51752. for (var v = vStart; v <= vEnd; v++) {
  51753. var normCubeRowWalk = 0;
  51754. var srcCubeRowWalk = 0;
  51755. for (var u = uStart; u <= uEnd; u++) {
  51756. //pointer to direction in cube map associated with texel
  51757. var texelVectX = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 0];
  51758. var texelVectY = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 1];
  51759. var texelVectZ = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 2];
  51760. //check dot product to see if texel is within cone
  51761. var tapDotProd = texelVectX * centerTapDir.x +
  51762. texelVectY * centerTapDir.y +
  51763. texelVectZ * centerTapDir.z;
  51764. if (tapDotProd >= dotProdThresh && tapDotProd > 0.0) {
  51765. //solid angle stored in 4th channel of normalizer/solid angle cube map
  51766. var weight = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 3];
  51767. // Here we decide if we use a Phong/Blinn or a Phong/Blinn BRDF.
  51768. // Phong/Blinn BRDF is just the Phong/Blinn model multiply by the cosine of the lambert law
  51769. // so just adding one to specularpower do the trick.
  51770. weight *= Math.pow(tapDotProd, (specularPower + IsPhongBRDF));
  51771. //iterate over channels
  51772. for (k = 0; k < nSrcChannels; k++) {
  51773. dstAccum[k] += weight * srcCubeMap[iFaceIdx][startIndexSrcCubeMap + srcCubeRowWalk];
  51774. srcCubeRowWalk++;
  51775. }
  51776. weightAccum += weight; //accumulate weight
  51777. }
  51778. else {
  51779. //step across source pixel
  51780. srcCubeRowWalk += nSrcChannels;
  51781. }
  51782. normCubeRowWalk += 4; // 4 channels per norm cube map.
  51783. }
  51784. startIndexNormCubeMap += normCubePitch;
  51785. startIndexSrcCubeMap += srcCubePitch;
  51786. }
  51787. }
  51788. }
  51789. //divide through by weights if weight is non zero
  51790. if (weightAccum != 0.0) {
  51791. PMREMGenerator._vectorTemp.x = (dstAccum[0] / weightAccum);
  51792. PMREMGenerator._vectorTemp.y = (dstAccum[1] / weightAccum);
  51793. PMREMGenerator._vectorTemp.z = (dstAccum[2] / weightAccum);
  51794. if (this.numChannels > 3) {
  51795. PMREMGenerator._vectorTemp.w = (dstAccum[3] / weightAccum);
  51796. }
  51797. }
  51798. else {
  51799. // otherwise sample nearest
  51800. // get face idx and u, v texel coordinate in face
  51801. var coord = this.vectToTexelCoord(centerTapDir.x, centerTapDir.y, centerTapDir.z, srcSize).clone();
  51802. PMREMGenerator._vectorTemp.x = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 0];
  51803. PMREMGenerator._vectorTemp.y = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 1];
  51804. PMREMGenerator._vectorTemp.z = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 2];
  51805. if (this.numChannels > 3) {
  51806. PMREMGenerator._vectorTemp.z = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 3];
  51807. }
  51808. }
  51809. return PMREMGenerator._vectorTemp;
  51810. };
  51811. //--------------------------------------------------------------------------------------
  51812. // Fixup cube edges
  51813. //
  51814. // average texels on cube map faces across the edges
  51815. // WARP/BENT Method Only.
  51816. //--------------------------------------------------------------------------------------
  51817. PMREMGenerator.prototype.fixupCubeEdges = function (cubeMap, cubeMapSize) {
  51818. var k;
  51819. var j;
  51820. var i;
  51821. var iFace;
  51822. var iCorner = 0;
  51823. var cornerNumPtrs = [0, 0, 0, 0, 0, 0, 0, 0]; //indexed by corner and face idx
  51824. var faceCornerStartIndicies = [[], [], [], []]; //corner pointers for face keeping track of the face they belong to.
  51825. // note that if functionality to filter across the three texels for each corner, then
  51826. //indexed by corner and face idx. the array contains the face the start points belongs to.
  51827. var cornerPtr = [
  51828. [[], [], []],
  51829. [[], [], []],
  51830. [[], [], []],
  51831. [[], [], []],
  51832. [[], [], []],
  51833. [[], [], []],
  51834. [[], [], []],
  51835. [[], [], []]
  51836. ];
  51837. //if there is no fixup, or fixup width = 0, do nothing
  51838. if (cubeMapSize < 1) {
  51839. return;
  51840. }
  51841. //special case 1x1 cubemap, average face colors
  51842. if (cubeMapSize == 1) {
  51843. //iterate over channels
  51844. for (k = 0; k < this.numChannels; k++) {
  51845. var accum = 0.0;
  51846. //iterate over faces to accumulate face colors
  51847. for (iFace = 0; iFace < 6; iFace++) {
  51848. accum += cubeMap[iFace][k];
  51849. }
  51850. //compute average over 6 face colors
  51851. accum /= 6.0;
  51852. //iterate over faces to distribute face colors
  51853. for (iFace = 0; iFace < 6; iFace++) {
  51854. cubeMap[iFace][k] = accum;
  51855. }
  51856. }
  51857. return;
  51858. }
  51859. //iterate over faces to collect list of corner texel pointers
  51860. for (iFace = 0; iFace < 6; iFace++) {
  51861. //the 4 corner pointers for this face
  51862. faceCornerStartIndicies[0] = [iFace, 0];
  51863. faceCornerStartIndicies[1] = [iFace, ((cubeMapSize - 1) * this.numChannels)];
  51864. faceCornerStartIndicies[2] = [iFace, ((cubeMapSize) * (cubeMapSize - 1) * this.numChannels)];
  51865. faceCornerStartIndicies[3] = [iFace, ((((cubeMapSize) * (cubeMapSize - 1)) + (cubeMapSize - 1)) * this.numChannels)];
  51866. //iterate over face corners to collect cube corner pointers
  51867. for (iCorner = 0; iCorner < 4; iCorner++) {
  51868. var corner = PMREMGenerator._sgCubeCornerList[iFace][iCorner];
  51869. cornerPtr[corner][cornerNumPtrs[corner]] = faceCornerStartIndicies[iCorner];
  51870. cornerNumPtrs[corner]++;
  51871. }
  51872. }
  51873. //iterate over corners to average across corner tap values
  51874. for (iCorner = 0; iCorner < 8; iCorner++) {
  51875. for (k = 0; k < this.numChannels; k++) {
  51876. var cornerTapAccum = 0.0;
  51877. //iterate over corner texels and average results
  51878. for (i = 0; i < 3; i++) {
  51879. cornerTapAccum += cubeMap[cornerPtr[iCorner][i][0]][cornerPtr[iCorner][i][1] + k]; // Get in the cube map face the start point + channel.
  51880. }
  51881. //divide by 3 to compute average of corner tap values
  51882. cornerTapAccum *= (1.0 / 3.0);
  51883. //iterate over corner texels and average results
  51884. for (i = 0; i < 3; i++) {
  51885. cubeMap[cornerPtr[iCorner][i][0]][cornerPtr[iCorner][i][1] + k] = cornerTapAccum;
  51886. }
  51887. }
  51888. }
  51889. //iterate over the twelve edges of the cube to average across edges
  51890. for (i = 0; i < 12; i++) {
  51891. var face = PMREMGenerator._sgCubeEdgeList[i][0];
  51892. var edge = PMREMGenerator._sgCubeEdgeList[i][1];
  51893. var neighborFace = PMREMGenerator._sgCubeNgh[face][edge][0];
  51894. var neighborEdge = PMREMGenerator._sgCubeNgh[face][edge][1];
  51895. var edgeStartIndex = 0; // a_CubeMap[face].m_ImgData;
  51896. var neighborEdgeStartIndex = 0; // a_CubeMap[neighborFace].m_ImgData;
  51897. var edgeWalk = 0;
  51898. var neighborEdgeWalk = 0;
  51899. //Determine walking pointers based on edge type
  51900. // e.g. CP_EDGE_LEFT, CP_EDGE_RIGHT, CP_EDGE_TOP, CP_EDGE_BOTTOM
  51901. switch (edge) {
  51902. case PMREMGenerator.CP_EDGE_LEFT:
  51903. // no change to faceEdgeStartPtr
  51904. edgeWalk = this.numChannels * cubeMapSize;
  51905. break;
  51906. case PMREMGenerator.CP_EDGE_RIGHT:
  51907. edgeStartIndex += (cubeMapSize - 1) * this.numChannels;
  51908. edgeWalk = this.numChannels * cubeMapSize;
  51909. break;
  51910. case PMREMGenerator.CP_EDGE_TOP:
  51911. // no change to faceEdgeStartPtr
  51912. edgeWalk = this.numChannels;
  51913. break;
  51914. case PMREMGenerator.CP_EDGE_BOTTOM:
  51915. edgeStartIndex += (cubeMapSize) * (cubeMapSize - 1) * this.numChannels;
  51916. edgeWalk = this.numChannels;
  51917. break;
  51918. }
  51919. //For certain types of edge abutments, the neighbor edge walk needs to
  51920. // be flipped: the cases are
  51921. // if a left edge mates with a left or bottom edge on the neighbor
  51922. // if a top edge mates with a top or right edge on the neighbor
  51923. // if a right edge mates with a right or top edge on the neighbor
  51924. // if a bottom edge mates with a bottom or left edge on the neighbor
  51925. //Seeing as the edges are enumerated as follows
  51926. // left =0
  51927. // right =1
  51928. // top =2
  51929. // bottom =3
  51930. //
  51931. //If the edge enums are the same, or the sum of the enums == 3,
  51932. // the neighbor edge walk needs to be flipped
  51933. if ((edge == neighborEdge) || ((edge + neighborEdge) == 3)) {
  51934. switch (neighborEdge) {
  51935. case PMREMGenerator.CP_EDGE_LEFT:
  51936. neighborEdgeStartIndex += (cubeMapSize - 1) * (cubeMapSize) * this.numChannels;
  51937. neighborEdgeWalk = -(this.numChannels * cubeMapSize);
  51938. break;
  51939. case PMREMGenerator.CP_EDGE_RIGHT:
  51940. neighborEdgeStartIndex += ((cubeMapSize - 1) * (cubeMapSize) + (cubeMapSize - 1)) * this.numChannels;
  51941. neighborEdgeWalk = -(this.numChannels * cubeMapSize);
  51942. break;
  51943. case PMREMGenerator.CP_EDGE_TOP:
  51944. neighborEdgeStartIndex += (cubeMapSize - 1) * this.numChannels;
  51945. neighborEdgeWalk = -this.numChannels;
  51946. break;
  51947. case PMREMGenerator.CP_EDGE_BOTTOM:
  51948. neighborEdgeStartIndex += ((cubeMapSize - 1) * (cubeMapSize) + (cubeMapSize - 1)) * this.numChannels;
  51949. neighborEdgeWalk = -this.numChannels;
  51950. break;
  51951. }
  51952. }
  51953. else {
  51954. //swapped direction neighbor edge walk
  51955. switch (neighborEdge) {
  51956. case PMREMGenerator.CP_EDGE_LEFT:
  51957. //no change to neighborEdgeStartPtr for this case since it points
  51958. // to the upper left corner already
  51959. neighborEdgeWalk = this.numChannels * cubeMapSize;
  51960. break;
  51961. case PMREMGenerator.CP_EDGE_RIGHT:
  51962. neighborEdgeStartIndex += (cubeMapSize - 1) * this.numChannels;
  51963. neighborEdgeWalk = this.numChannels * cubeMapSize;
  51964. break;
  51965. case PMREMGenerator.CP_EDGE_TOP:
  51966. //no change to neighborEdgeStartPtr for this case since it points
  51967. // to the upper left corner already
  51968. neighborEdgeWalk = this.numChannels;
  51969. break;
  51970. case PMREMGenerator.CP_EDGE_BOTTOM:
  51971. neighborEdgeStartIndex += (cubeMapSize) * (cubeMapSize - 1) * this.numChannels;
  51972. neighborEdgeWalk = this.numChannels;
  51973. break;
  51974. }
  51975. }
  51976. //Perform edge walk, to average across the 12 edges and smoothly propagate change to
  51977. //nearby neighborhood
  51978. //step ahead one texel on edge
  51979. edgeStartIndex += edgeWalk;
  51980. neighborEdgeStartIndex += neighborEdgeWalk;
  51981. // note that this loop does not process the corner texels, since they have already been
  51982. // averaged across faces across earlier
  51983. for (j = 1; j < (cubeMapSize - 1); j++) {
  51984. //for each set of taps along edge, average them
  51985. // and rewrite the results into the edges
  51986. for (k = 0; k < this.numChannels; k++) {
  51987. var edgeTap = cubeMap[face][edgeStartIndex + k];
  51988. var neighborEdgeTap = cubeMap[neighborFace][neighborEdgeStartIndex + k];
  51989. //compute average of tap intensity values
  51990. var avgTap = 0.5 * (edgeTap + neighborEdgeTap);
  51991. //propagate average of taps to edge taps
  51992. cubeMap[face][edgeStartIndex + k] = avgTap;
  51993. cubeMap[neighborFace][neighborEdgeStartIndex + k] = avgTap;
  51994. }
  51995. edgeStartIndex += edgeWalk;
  51996. neighborEdgeStartIndex += neighborEdgeWalk;
  51997. }
  51998. }
  51999. };
  52000. return PMREMGenerator;
  52001. }());
  52002. PMREMGenerator.CP_MAX_MIPLEVELS = 16;
  52003. PMREMGenerator.CP_UDIR = 0;
  52004. PMREMGenerator.CP_VDIR = 1;
  52005. PMREMGenerator.CP_FACEAXIS = 2;
  52006. //used to index cube faces
  52007. PMREMGenerator.CP_FACE_X_POS = 0;
  52008. PMREMGenerator.CP_FACE_X_NEG = 1;
  52009. PMREMGenerator.CP_FACE_Y_POS = 2;
  52010. PMREMGenerator.CP_FACE_Y_NEG = 3;
  52011. PMREMGenerator.CP_FACE_Z_POS = 4;
  52012. PMREMGenerator.CP_FACE_Z_NEG = 5;
  52013. //used to index image edges
  52014. // NOTE.. the actual number corresponding to the edge is important
  52015. // do not change these, or the code will break
  52016. //
  52017. // CP_EDGE_LEFT is u = 0
  52018. // CP_EDGE_RIGHT is u = width-1
  52019. // CP_EDGE_TOP is v = 0
  52020. // CP_EDGE_BOTTOM is v = height-1
  52021. PMREMGenerator.CP_EDGE_LEFT = 0;
  52022. PMREMGenerator.CP_EDGE_RIGHT = 1;
  52023. PMREMGenerator.CP_EDGE_TOP = 2;
  52024. PMREMGenerator.CP_EDGE_BOTTOM = 3;
  52025. //corners of CUBE map (P or N specifys if it corresponds to the
  52026. // positive or negative direction each of X, Y, and Z
  52027. PMREMGenerator.CP_CORNER_NNN = 0;
  52028. PMREMGenerator.CP_CORNER_NNP = 1;
  52029. PMREMGenerator.CP_CORNER_NPN = 2;
  52030. PMREMGenerator.CP_CORNER_NPP = 3;
  52031. PMREMGenerator.CP_CORNER_PNN = 4;
  52032. PMREMGenerator.CP_CORNER_PNP = 5;
  52033. PMREMGenerator.CP_CORNER_PPN = 6;
  52034. PMREMGenerator.CP_CORNER_PPP = 7;
  52035. PMREMGenerator._vectorTemp = new BABYLON.Vector4(0, 0, 0, 0);
  52036. //3x2 matrices that map cube map indexing vectors in 3d
  52037. // (after face selection and divide through by the
  52038. // _ABSOLUTE VALUE_ of the max coord)
  52039. // into NVC space
  52040. //Note this currently assumes the D3D cube face ordering and orientation
  52041. PMREMGenerator._sgFace2DMapping = [
  52042. //XPOS face
  52043. [[0, 0, -1],
  52044. [0, -1, 0],
  52045. [1, 0, 0]],
  52046. //XNEG face
  52047. [[0, 0, 1],
  52048. [0, -1, 0],
  52049. [-1, 0, 0]],
  52050. //YPOS face
  52051. [[1, 0, 0],
  52052. [0, 0, 1],
  52053. [0, 1, 0]],
  52054. //YNEG face
  52055. [[1, 0, 0],
  52056. [0, 0, -1],
  52057. [0, -1, 0]],
  52058. //ZPOS face
  52059. [[1, 0, 0],
  52060. [0, -1, 0],
  52061. [0, 0, 1]],
  52062. //ZNEG face
  52063. [[-1, 0, 0],
  52064. [0, -1, 0],
  52065. [0, 0, -1]],
  52066. ];
  52067. //------------------------------------------------------------------------------
  52068. // D3D cube map face specification
  52069. // mapping from 3D x,y,z cube map lookup coordinates
  52070. // to 2D within face u,v coordinates
  52071. //
  52072. // --------------------> U direction
  52073. // | (within-face texture space)
  52074. // | _____
  52075. // | | |
  52076. // | | +Y |
  52077. // | _____|_____|_____ _____
  52078. // | | | | | |
  52079. // | | -X | +Z | +X | -Z |
  52080. // | |_____|_____|_____|_____|
  52081. // | | |
  52082. // | | -Y |
  52083. // | |_____|
  52084. // |
  52085. // v V direction
  52086. // (within-face texture space)
  52087. //------------------------------------------------------------------------------
  52088. //Information about neighbors and how texture coorrdinates change across faces
  52089. // in ORDER of left, right, top, bottom (e.g. edges corresponding to u=0,
  52090. // u=1, v=0, v=1 in the 2D coordinate system of the particular face.
  52091. //Note this currently assumes the D3D cube face ordering and orientation
  52092. PMREMGenerator._sgCubeNgh = [
  52093. //XPOS face
  52094. [[PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_RIGHT],
  52095. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_LEFT],
  52096. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_RIGHT],
  52097. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_RIGHT]],
  52098. //XNEG face
  52099. [[PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_RIGHT],
  52100. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_LEFT],
  52101. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_LEFT],
  52102. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_LEFT]],
  52103. //YPOS face
  52104. [[PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_TOP],
  52105. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_TOP],
  52106. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_TOP],
  52107. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_TOP]],
  52108. //YNEG face
  52109. [[PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_BOTTOM],
  52110. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  52111. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  52112. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_BOTTOM]],
  52113. //ZPOS face
  52114. [[PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_RIGHT],
  52115. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_LEFT],
  52116. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  52117. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_TOP]],
  52118. //ZNEG face
  52119. [[PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_RIGHT],
  52120. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_LEFT],
  52121. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_TOP],
  52122. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_BOTTOM]]
  52123. ];
  52124. //The 12 edges of the cubemap, (entries are used to index into the neighbor table)
  52125. // this table is used to average over the edges.
  52126. PMREMGenerator._sgCubeEdgeList = [
  52127. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_LEFT],
  52128. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_RIGHT],
  52129. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_TOP],
  52130. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  52131. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_LEFT],
  52132. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_RIGHT],
  52133. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_TOP],
  52134. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_BOTTOM],
  52135. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_TOP],
  52136. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  52137. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_TOP],
  52138. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_BOTTOM]
  52139. ];
  52140. //Information about which of the 8 cube corners are correspond to the
  52141. // the 4 corners in each cube face
  52142. // the order is upper left, upper right, lower left, lower right
  52143. PMREMGenerator._sgCubeCornerList = [
  52144. [PMREMGenerator.CP_CORNER_PPP, PMREMGenerator.CP_CORNER_PPN, PMREMGenerator.CP_CORNER_PNP, PMREMGenerator.CP_CORNER_PNN],
  52145. [PMREMGenerator.CP_CORNER_NPN, PMREMGenerator.CP_CORNER_NPP, PMREMGenerator.CP_CORNER_NNN, PMREMGenerator.CP_CORNER_NNP],
  52146. [PMREMGenerator.CP_CORNER_NPN, PMREMGenerator.CP_CORNER_PPN, PMREMGenerator.CP_CORNER_NPP, PMREMGenerator.CP_CORNER_PPP],
  52147. [PMREMGenerator.CP_CORNER_NNP, PMREMGenerator.CP_CORNER_PNP, PMREMGenerator.CP_CORNER_NNN, PMREMGenerator.CP_CORNER_PNN],
  52148. [PMREMGenerator.CP_CORNER_NPP, PMREMGenerator.CP_CORNER_PPP, PMREMGenerator.CP_CORNER_NNP, PMREMGenerator.CP_CORNER_PNP],
  52149. [PMREMGenerator.CP_CORNER_PPN, PMREMGenerator.CP_CORNER_NPN, PMREMGenerator.CP_CORNER_PNN, PMREMGenerator.CP_CORNER_NNN] // ZNEG face
  52150. ];
  52151. Internals.PMREMGenerator = PMREMGenerator;
  52152. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  52153. })(BABYLON || (BABYLON = {}));
  52154. //# sourceMappingURL=babylon.tools.pmremgenerator.js.map
  52155. var BABYLON;
  52156. (function (BABYLON) {
  52157. /**
  52158. * This represents a texture coming from an HDR input.
  52159. *
  52160. * The only supported format is currently panorama picture stored in RGBE format.
  52161. * Example of such files can be found on HDRLib: http://hdrlib.com/
  52162. */
  52163. var HDRCubeTexture = (function (_super) {
  52164. __extends(HDRCubeTexture, _super);
  52165. /**
  52166. * Instantiates an HDRTexture from the following parameters.
  52167. *
  52168. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  52169. * @param scene The scene the texture will be used in
  52170. * @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.
  52171. * @param noMipmap Forces to not generate the mipmap if true
  52172. * @param generateHarmonics Specifies wether you want to extract the polynomial harmonics during the generation process
  52173. * @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)
  52174. * @param usePMREMGenerator Specifies wether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time.
  52175. */
  52176. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator) {
  52177. if (noMipmap === void 0) { noMipmap = false; }
  52178. if (generateHarmonics === void 0) { generateHarmonics = true; }
  52179. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  52180. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  52181. var _this = _super.call(this, scene) || this;
  52182. _this._useInGammaSpace = false;
  52183. _this._generateHarmonics = true;
  52184. _this._isBABYLONPreprocessed = false;
  52185. /**
  52186. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  52187. */
  52188. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  52189. /**
  52190. * The spherical polynomial data extracted from the texture.
  52191. */
  52192. _this.sphericalPolynomial = null;
  52193. /**
  52194. * Specifies wether the texture has been generated through the PMREMGenerator tool.
  52195. * This is usefull at run time to apply the good shader.
  52196. */
  52197. _this.isPMREM = false;
  52198. if (!url) {
  52199. return _this;
  52200. }
  52201. _this.name = url;
  52202. _this.url = url;
  52203. _this.hasAlpha = false;
  52204. _this.isCube = true;
  52205. _this._textureMatrix = BABYLON.Matrix.Identity();
  52206. if (size) {
  52207. _this._isBABYLONPreprocessed = false;
  52208. _this._noMipmap = noMipmap;
  52209. _this._size = size;
  52210. _this._useInGammaSpace = useInGammaSpace;
  52211. _this._usePMREMGenerator = usePMREMGenerator &&
  52212. scene.getEngine().getCaps().textureLOD &&
  52213. _this.getScene().getEngine().getCaps().textureFloat &&
  52214. !_this._useInGammaSpace;
  52215. }
  52216. else {
  52217. _this._isBABYLONPreprocessed = true;
  52218. _this._noMipmap = false;
  52219. _this._useInGammaSpace = false;
  52220. _this._usePMREMGenerator = scene.getEngine().getCaps().textureLOD &&
  52221. _this.getScene().getEngine().getCaps().textureFloat &&
  52222. !_this._useInGammaSpace;
  52223. }
  52224. _this.isPMREM = _this._usePMREMGenerator;
  52225. _this._texture = _this._getFromCache(url, _this._noMipmap);
  52226. if (!_this._texture) {
  52227. if (!scene.useDelayedTextureLoading) {
  52228. _this.loadTexture();
  52229. }
  52230. else {
  52231. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  52232. }
  52233. }
  52234. return _this;
  52235. }
  52236. /**
  52237. * Occurs when the file is a preprocessed .babylon.hdr file.
  52238. */
  52239. HDRCubeTexture.prototype.loadBabylonTexture = function () {
  52240. var _this = this;
  52241. var mipLevels = 0;
  52242. var floatArrayView = null;
  52243. var mipmapGenerator = (!this._useInGammaSpace && this.getScene().getEngine().getCaps().textureFloat) ? function (data) {
  52244. var mips = [];
  52245. var startIndex = 30;
  52246. for (var level = 0; level < mipLevels; level++) {
  52247. mips.push([]);
  52248. // Fill each pixel of the mip level.
  52249. var faceSize = Math.pow(_this._size >> level, 2) * 3;
  52250. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  52251. var faceData = floatArrayView.subarray(startIndex, startIndex + faceSize);
  52252. mips[level].push(faceData);
  52253. startIndex += faceSize;
  52254. }
  52255. }
  52256. return mips;
  52257. } : null;
  52258. var callback = function (buffer) {
  52259. // Create Native Array Views
  52260. var intArrayView = new Int32Array(buffer);
  52261. floatArrayView = new Float32Array(buffer);
  52262. // Fill header.
  52263. var version = intArrayView[0]; // Version 1. (MAy be use in case of format changes for backward compaibility)
  52264. _this._size = intArrayView[1]; // CubeMap max mip face size.
  52265. // Update Texture Information.
  52266. _this.getScene().getEngine().updateTextureSize(_this._texture, _this._size, _this._size);
  52267. // Fill polynomial information.
  52268. _this.sphericalPolynomial = new BABYLON.SphericalPolynomial();
  52269. _this.sphericalPolynomial.x.copyFromFloats(floatArrayView[2], floatArrayView[3], floatArrayView[4]);
  52270. _this.sphericalPolynomial.y.copyFromFloats(floatArrayView[5], floatArrayView[6], floatArrayView[7]);
  52271. _this.sphericalPolynomial.z.copyFromFloats(floatArrayView[8], floatArrayView[9], floatArrayView[10]);
  52272. _this.sphericalPolynomial.xx.copyFromFloats(floatArrayView[11], floatArrayView[12], floatArrayView[13]);
  52273. _this.sphericalPolynomial.yy.copyFromFloats(floatArrayView[14], floatArrayView[15], floatArrayView[16]);
  52274. _this.sphericalPolynomial.zz.copyFromFloats(floatArrayView[17], floatArrayView[18], floatArrayView[19]);
  52275. _this.sphericalPolynomial.xy.copyFromFloats(floatArrayView[20], floatArrayView[21], floatArrayView[22]);
  52276. _this.sphericalPolynomial.yz.copyFromFloats(floatArrayView[23], floatArrayView[24], floatArrayView[25]);
  52277. _this.sphericalPolynomial.zx.copyFromFloats(floatArrayView[26], floatArrayView[27], floatArrayView[28]);
  52278. // Fill pixel data.
  52279. mipLevels = intArrayView[29]; // Number of mip levels.
  52280. var startIndex = 30;
  52281. var data = [];
  52282. var faceSize = Math.pow(_this._size, 2) * 3;
  52283. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  52284. data.push(floatArrayView.subarray(startIndex, startIndex + faceSize));
  52285. startIndex += faceSize;
  52286. }
  52287. var results = [];
  52288. var byteArray = null;
  52289. // Push each faces.
  52290. for (var k = 0; k < 6; k++) {
  52291. var dataFace = null;
  52292. // If special cases.
  52293. if (!mipmapGenerator) {
  52294. var j = ([0, 2, 4, 1, 3, 5])[k]; // Transforms +X+Y+Z... to +X-X+Y-Y... if no mipmapgenerator...
  52295. dataFace = data[j];
  52296. if (!_this.getScene().getEngine().getCaps().textureFloat) {
  52297. // 3 channels of 1 bytes per pixel in bytes.
  52298. var byteBuffer = new ArrayBuffer(faceSize);
  52299. byteArray = new Uint8Array(byteBuffer);
  52300. }
  52301. for (var i = 0; i < _this._size * _this._size; i++) {
  52302. // Put in gamma space if requested.
  52303. if (_this._useInGammaSpace) {
  52304. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  52305. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  52306. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  52307. }
  52308. // Convert to int texture for fallback.
  52309. if (byteArray) {
  52310. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  52311. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  52312. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  52313. // May use luminance instead if the result is not accurate.
  52314. var max = Math.max(Math.max(r, g), b);
  52315. if (max > 255) {
  52316. var scale = 255 / max;
  52317. r *= scale;
  52318. g *= scale;
  52319. b *= scale;
  52320. }
  52321. byteArray[(i * 3) + 0] = r;
  52322. byteArray[(i * 3) + 1] = g;
  52323. byteArray[(i * 3) + 2] = b;
  52324. }
  52325. }
  52326. }
  52327. else {
  52328. dataFace = data[k];
  52329. }
  52330. // Fill the array accordingly.
  52331. if (byteArray) {
  52332. results.push(byteArray);
  52333. }
  52334. else {
  52335. results.push(dataFace);
  52336. }
  52337. }
  52338. return results;
  52339. };
  52340. this._texture = this.getScene().getEngine().createRawCubeTexture(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);
  52341. };
  52342. /**
  52343. * Occurs when the file is raw .hdr file.
  52344. */
  52345. HDRCubeTexture.prototype.loadHDRTexture = function () {
  52346. var _this = this;
  52347. var callback = function (buffer) {
  52348. // Extract the raw linear data.
  52349. var data = BABYLON.Internals.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  52350. // Generate harmonics if needed.
  52351. if (_this._generateHarmonics) {
  52352. _this.sphericalPolynomial = BABYLON.Internals.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  52353. }
  52354. var results = [];
  52355. var byteArray = null;
  52356. // Push each faces.
  52357. for (var j = 0; j < 6; j++) {
  52358. // Create uintarray fallback.
  52359. if (!_this.getScene().getEngine().getCaps().textureFloat) {
  52360. // 3 channels of 1 bytes per pixel in bytes.
  52361. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  52362. byteArray = new Uint8Array(byteBuffer);
  52363. }
  52364. var dataFace = data[HDRCubeTexture._facesMapping[j]];
  52365. // If special cases.
  52366. if (_this._useInGammaSpace || byteArray) {
  52367. for (var i = 0; i < _this._size * _this._size; i++) {
  52368. // Put in gamma space if requested.
  52369. if (_this._useInGammaSpace) {
  52370. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  52371. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  52372. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  52373. }
  52374. // Convert to int texture for fallback.
  52375. if (byteArray) {
  52376. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  52377. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  52378. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  52379. // May use luminance instead if the result is not accurate.
  52380. var max = Math.max(Math.max(r, g), b);
  52381. if (max > 255) {
  52382. var scale = 255 / max;
  52383. r *= scale;
  52384. g *= scale;
  52385. b *= scale;
  52386. }
  52387. byteArray[(i * 3) + 0] = r;
  52388. byteArray[(i * 3) + 1] = g;
  52389. byteArray[(i * 3) + 2] = b;
  52390. }
  52391. }
  52392. }
  52393. if (byteArray) {
  52394. results.push(byteArray);
  52395. }
  52396. else {
  52397. results.push(dataFace);
  52398. }
  52399. }
  52400. return results;
  52401. };
  52402. var mipmapGenerator = null;
  52403. if (!this._noMipmap &&
  52404. this._usePMREMGenerator) {
  52405. mipmapGenerator = function (data) {
  52406. // Custom setup of the generator matching with the PBR shader values.
  52407. var generator = new BABYLON.Internals.PMREMGenerator(data, _this._size, _this._size, 0, 3, _this.getScene().getEngine().getCaps().textureFloat, 2048, 0.25, false, true);
  52408. return generator.filterCubeMap();
  52409. };
  52410. }
  52411. this._texture = this.getScene().getEngine().createRawCubeTexture(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);
  52412. };
  52413. /**
  52414. * Starts the loading process of the texture.
  52415. */
  52416. HDRCubeTexture.prototype.loadTexture = function () {
  52417. if (this._isBABYLONPreprocessed) {
  52418. this.loadBabylonTexture();
  52419. }
  52420. else {
  52421. this.loadHDRTexture();
  52422. }
  52423. };
  52424. HDRCubeTexture.prototype.clone = function () {
  52425. var size = this._isBABYLONPreprocessed ? null : this._size;
  52426. var newTexture = new HDRCubeTexture(this.url, this.getScene(), size, this._noMipmap, this._generateHarmonics, this._useInGammaSpace, this._usePMREMGenerator);
  52427. // Base texture
  52428. newTexture.level = this.level;
  52429. newTexture.wrapU = this.wrapU;
  52430. newTexture.wrapV = this.wrapV;
  52431. newTexture.coordinatesIndex = this.coordinatesIndex;
  52432. newTexture.coordinatesMode = this.coordinatesMode;
  52433. return newTexture;
  52434. };
  52435. // Methods
  52436. HDRCubeTexture.prototype.delayLoad = function () {
  52437. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  52438. return;
  52439. }
  52440. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  52441. this._texture = this._getFromCache(this.url, this._noMipmap);
  52442. if (!this._texture) {
  52443. this.loadTexture();
  52444. }
  52445. };
  52446. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  52447. return this._textureMatrix;
  52448. };
  52449. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  52450. var texture = null;
  52451. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  52452. var size = parsedTexture.isBABYLONPreprocessed ? null : parsedTexture.size;
  52453. texture = new BABYLON.HDRCubeTexture(rootUrl + parsedTexture.name, scene, size, parsedTexture.noMipmap, parsedTexture.generateHarmonics, parsedTexture.useInGammaSpace, parsedTexture.usePMREMGenerator);
  52454. texture.name = parsedTexture.name;
  52455. texture.hasAlpha = parsedTexture.hasAlpha;
  52456. texture.level = parsedTexture.level;
  52457. texture.coordinatesMode = parsedTexture.coordinatesMode;
  52458. }
  52459. return texture;
  52460. };
  52461. HDRCubeTexture.prototype.serialize = function () {
  52462. if (!this.name) {
  52463. return null;
  52464. }
  52465. var serializationObject = {};
  52466. serializationObject.name = this.name;
  52467. serializationObject.hasAlpha = this.hasAlpha;
  52468. serializationObject.isCube = true;
  52469. serializationObject.level = this.level;
  52470. serializationObject.size = this._size;
  52471. serializationObject.coordinatesMode = this.coordinatesMode;
  52472. serializationObject.useInGammaSpace = this._useInGammaSpace;
  52473. serializationObject.generateHarmonics = this._generateHarmonics;
  52474. serializationObject.usePMREMGenerator = this._usePMREMGenerator;
  52475. serializationObject.isBABYLONPreprocessed = this._isBABYLONPreprocessed;
  52476. serializationObject.customType = "BABYLON.HDRCubeTexture";
  52477. serializationObject.noMipmap = this._noMipmap;
  52478. return serializationObject;
  52479. };
  52480. /**
  52481. * Saves as a file the data contained in the texture in a binary format.
  52482. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  52483. * as the spherical used in the lighting.
  52484. * @param url The HDR file url.
  52485. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  52486. * @param onError Method called if any error happens during download.
  52487. * @return The packed binary data.
  52488. */
  52489. HDRCubeTexture.generateBabylonHDROnDisk = function (url, size, onError) {
  52490. if (onError === void 0) { onError = null; }
  52491. var callback = function (buffer) {
  52492. var data = new Blob([buffer], { type: 'application/octet-stream' });
  52493. // Returns a URL you can use as a href.
  52494. var objUrl = window.URL.createObjectURL(data);
  52495. // Simulates a link to it and click to dowload.
  52496. var a = document.createElement("a");
  52497. document.body.appendChild(a);
  52498. a.style.display = "none";
  52499. a.href = objUrl;
  52500. a.download = "envmap.babylon.hdr";
  52501. a.click();
  52502. };
  52503. HDRCubeTexture.generateBabylonHDR(url, size, callback, onError);
  52504. };
  52505. /**
  52506. * Serializes the data contained in the texture in a binary format.
  52507. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  52508. * as the spherical used in the lighting.
  52509. * @param url The HDR file url.
  52510. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  52511. * @param onError Method called if any error happens during download.
  52512. * @return The packed binary data.
  52513. */
  52514. HDRCubeTexture.generateBabylonHDR = function (url, size, callback, onError) {
  52515. if (onError === void 0) { onError = null; }
  52516. // Needs the url tho create the texture.
  52517. if (!url) {
  52518. return null;
  52519. }
  52520. // Check Power of two size.
  52521. if (!BABYLON.Tools.IsExponentOfTwo(size)) {
  52522. return null;
  52523. }
  52524. var getDataCallback = function (dataBuffer) {
  52525. // Extract the raw linear data.
  52526. var cubeData = BABYLON.Internals.HDRTools.GetCubeMapTextureData(dataBuffer, size);
  52527. // Generate harmonics if needed.
  52528. var sphericalPolynomial = BABYLON.Internals.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(cubeData);
  52529. // Generate seamless faces
  52530. var mipGeneratorArray = [];
  52531. // Data are known to be in +X +Y +Z -X -Y -Z
  52532. // mipmmapGenerator data is expected to be order in +X -X +Y -Y +Z -Z
  52533. mipGeneratorArray.push(cubeData.right); // +X
  52534. mipGeneratorArray.push(cubeData.left); // -X
  52535. mipGeneratorArray.push(cubeData.up); // +Y
  52536. mipGeneratorArray.push(cubeData.down); // -Y
  52537. mipGeneratorArray.push(cubeData.front); // +Z
  52538. mipGeneratorArray.push(cubeData.back); // -Z
  52539. // Custom setup of the generator matching with the PBR shader values.
  52540. var generator = new BABYLON.Internals.PMREMGenerator(mipGeneratorArray, size, size, 0, 3, true, 2048, 0.25, false, true);
  52541. var mippedData = generator.filterCubeMap();
  52542. // Compute required byte length.
  52543. var byteLength = 1 * 4; // Raw Data Version int32.
  52544. byteLength += 4; // CubeMap max mip face size int32.
  52545. byteLength += (9 * 3 * 4); // Spherical polynomial byte length 9 Vector 3 of floats.
  52546. // Add data size.
  52547. byteLength += 4; // Number of mip levels int32.
  52548. for (var level = 0; level < mippedData.length; level++) {
  52549. var mipSize = size >> level;
  52550. byteLength += (6 * mipSize * mipSize * 3 * 4); // 6 faces of size squared rgb float pixels.
  52551. }
  52552. // Prepare binary structure.
  52553. var buffer = new ArrayBuffer(byteLength);
  52554. var intArrayView = new Int32Array(buffer);
  52555. var floatArrayView = new Float32Array(buffer);
  52556. // Fill header.
  52557. intArrayView[0] = 1; // Version 1.
  52558. intArrayView[1] = size; // CubeMap max mip face size.
  52559. // Fill polynomial information.
  52560. sphericalPolynomial.x.toArray(floatArrayView, 2);
  52561. sphericalPolynomial.y.toArray(floatArrayView, 5);
  52562. sphericalPolynomial.z.toArray(floatArrayView, 8);
  52563. sphericalPolynomial.xx.toArray(floatArrayView, 11);
  52564. sphericalPolynomial.yy.toArray(floatArrayView, 14);
  52565. sphericalPolynomial.zz.toArray(floatArrayView, 17);
  52566. sphericalPolynomial.xy.toArray(floatArrayView, 20);
  52567. sphericalPolynomial.yz.toArray(floatArrayView, 23);
  52568. sphericalPolynomial.zx.toArray(floatArrayView, 26);
  52569. // Fill pixel data.
  52570. intArrayView[29] = mippedData.length; // Number of mip levels.
  52571. var startIndex = 30;
  52572. for (var level = 0; level < mippedData.length; level++) {
  52573. // Fill each pixel of the mip level.
  52574. var faceSize = Math.pow(size >> level, 2) * 3;
  52575. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  52576. floatArrayView.set(mippedData[level][faceIndex], startIndex);
  52577. startIndex += faceSize;
  52578. }
  52579. }
  52580. // Callback.
  52581. callback(buffer);
  52582. };
  52583. // Download and process.
  52584. BABYLON.Tools.LoadFile(url, function (data) {
  52585. getDataCallback(data);
  52586. }, null, null, true, onError);
  52587. };
  52588. return HDRCubeTexture;
  52589. }(BABYLON.BaseTexture));
  52590. HDRCubeTexture._facesMapping = [
  52591. "right",
  52592. "up",
  52593. "front",
  52594. "left",
  52595. "down",
  52596. "back"
  52597. ];
  52598. BABYLON.HDRCubeTexture = HDRCubeTexture;
  52599. })(BABYLON || (BABYLON = {}));
  52600. //# sourceMappingURL=babylon.hdrCubeTexture.js.map
  52601. var BABYLON;
  52602. (function (BABYLON) {
  52603. var Debug;
  52604. (function (Debug) {
  52605. /**
  52606. * Demo available here: http://www.babylonjs-playground.com/#1BZJVJ#8
  52607. */
  52608. var SkeletonViewer = (function () {
  52609. function SkeletonViewer(skeleton, mesh, scene, autoUpdateBonesMatrices, renderingGroupId) {
  52610. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  52611. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  52612. this.skeleton = skeleton;
  52613. this.mesh = mesh;
  52614. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  52615. this.renderingGroupId = renderingGroupId;
  52616. this.color = BABYLON.Color3.White();
  52617. this._debugLines = [];
  52618. this._isEnabled = false;
  52619. this._scene = scene;
  52620. this.update();
  52621. this._renderFunction = this.update.bind(this);
  52622. }
  52623. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  52624. get: function () {
  52625. return this._isEnabled;
  52626. },
  52627. set: function (value) {
  52628. if (this._isEnabled === value) {
  52629. return;
  52630. }
  52631. this._isEnabled = value;
  52632. if (value) {
  52633. this._scene.registerBeforeRender(this._renderFunction);
  52634. }
  52635. else {
  52636. this._scene.unregisterBeforeRender(this._renderFunction);
  52637. }
  52638. },
  52639. enumerable: true,
  52640. configurable: true
  52641. });
  52642. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  52643. if (x === void 0) { x = 0; }
  52644. if (y === void 0) { y = 0; }
  52645. if (z === void 0) { z = 0; }
  52646. var tmat = BABYLON.Tmp.Matrix[0];
  52647. var parentBone = bone.getParent();
  52648. tmat.copyFrom(bone.getLocalMatrix());
  52649. if (x !== 0 || y !== 0 || z !== 0) {
  52650. var tmat2 = BABYLON.Tmp.Matrix[1];
  52651. BABYLON.Matrix.IdentityToRef(tmat2);
  52652. tmat2.m[12] = x;
  52653. tmat2.m[13] = y;
  52654. tmat2.m[14] = z;
  52655. tmat2.multiplyToRef(tmat, tmat);
  52656. }
  52657. if (parentBone) {
  52658. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  52659. }
  52660. tmat.multiplyToRef(meshMat, tmat);
  52661. position.x = tmat.m[12];
  52662. position.y = tmat.m[13];
  52663. position.z = tmat.m[14];
  52664. };
  52665. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  52666. var len = bones.length;
  52667. for (var i = 0; i < len; i++) {
  52668. var bone = bones[i];
  52669. var points = this._debugLines[i];
  52670. if (!points) {
  52671. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  52672. this._debugLines[i] = points;
  52673. }
  52674. this._getBonePosition(points[0], bone, meshMat);
  52675. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  52676. }
  52677. };
  52678. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  52679. var len = bones.length;
  52680. var boneNum = 0;
  52681. for (var i = len - 1; i >= 0; i--) {
  52682. var childBone = bones[i];
  52683. var parentBone = childBone.getParent();
  52684. if (!parentBone) {
  52685. continue;
  52686. }
  52687. var points = this._debugLines[boneNum];
  52688. if (!points) {
  52689. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  52690. this._debugLines[boneNum] = points;
  52691. }
  52692. childBone.getAbsolutePositionToRef(this.mesh, points[0]);
  52693. parentBone.getAbsolutePositionToRef(this.mesh, points[1]);
  52694. boneNum++;
  52695. }
  52696. };
  52697. SkeletonViewer.prototype.update = function () {
  52698. if (this.autoUpdateBonesMatrices) {
  52699. this.skeleton.computeAbsoluteTransforms();
  52700. }
  52701. if (this.skeleton.bones[0].length === undefined) {
  52702. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  52703. }
  52704. else {
  52705. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  52706. }
  52707. if (!this._debugMesh) {
  52708. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem(null, { lines: this._debugLines, updatable: true }, this._scene);
  52709. this._debugMesh.renderingGroupId = this.renderingGroupId;
  52710. }
  52711. else {
  52712. BABYLON.MeshBuilder.CreateLineSystem(null, { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  52713. }
  52714. this._debugMesh.color = this.color;
  52715. };
  52716. SkeletonViewer.prototype.dispose = function () {
  52717. if (this._debugMesh) {
  52718. this.isEnabled = false;
  52719. this._debugMesh.dispose();
  52720. this._debugMesh = null;
  52721. }
  52722. };
  52723. return SkeletonViewer;
  52724. }());
  52725. Debug.SkeletonViewer = SkeletonViewer;
  52726. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  52727. })(BABYLON || (BABYLON = {}));
  52728. //# sourceMappingURL=babylon.skeletonViewer.js.map
  52729. var BABYLON;
  52730. (function (BABYLON) {
  52731. var Debug;
  52732. (function (Debug) {
  52733. var AxesViewer = (function () {
  52734. function AxesViewer(scene, scaleLines) {
  52735. if (scaleLines === void 0) { scaleLines = 1; }
  52736. this._xline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  52737. this._yline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  52738. this._zline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  52739. this.scaleLines = 1;
  52740. this.scaleLines = scaleLines;
  52741. this._xmesh = BABYLON.Mesh.CreateLines("xline", this._xline, scene, true);
  52742. this._ymesh = BABYLON.Mesh.CreateLines("yline", this._yline, scene, true);
  52743. this._zmesh = BABYLON.Mesh.CreateLines("zline", this._zline, scene, true);
  52744. this._xmesh.renderingGroupId = 2;
  52745. this._ymesh.renderingGroupId = 2;
  52746. this._zmesh.renderingGroupId = 2;
  52747. this._xmesh.material.checkReadyOnlyOnce = true;
  52748. this._xmesh.color = new BABYLON.Color3(1, 0, 0);
  52749. this._ymesh.material.checkReadyOnlyOnce = true;
  52750. this._ymesh.color = new BABYLON.Color3(0, 1, 0);
  52751. this._zmesh.material.checkReadyOnlyOnce = true;
  52752. this._zmesh.color = new BABYLON.Color3(0, 0, 1);
  52753. this.scene = scene;
  52754. }
  52755. AxesViewer.prototype.update = function (position, xaxis, yaxis, zaxis) {
  52756. var scaleLines = this.scaleLines;
  52757. var point1 = this._xline[0];
  52758. var point2 = this._xline[1];
  52759. point1.x = position.x;
  52760. point1.y = position.y;
  52761. point1.z = position.z;
  52762. point2.x = point1.x + xaxis.x * scaleLines;
  52763. point2.y = point1.y + xaxis.y * scaleLines;
  52764. point2.z = point1.z + xaxis.z * scaleLines;
  52765. BABYLON.Mesh.CreateLines(null, this._xline, null, null, this._xmesh);
  52766. point1 = this._yline[0];
  52767. point2 = this._yline[1];
  52768. point1.x = position.x;
  52769. point1.y = position.y;
  52770. point1.z = position.z;
  52771. point2.x = point1.x + yaxis.x * scaleLines;
  52772. point2.y = point1.y + yaxis.y * scaleLines;
  52773. point2.z = point1.z + yaxis.z * scaleLines;
  52774. BABYLON.Mesh.CreateLines(null, this._yline, null, null, this._ymesh);
  52775. point1 = this._zline[0];
  52776. point2 = this._zline[1];
  52777. point1.x = position.x;
  52778. point1.y = position.y;
  52779. point1.z = position.z;
  52780. point2.x = point1.x + zaxis.x * scaleLines;
  52781. point2.y = point1.y + zaxis.y * scaleLines;
  52782. point2.z = point1.z + zaxis.z * scaleLines;
  52783. BABYLON.Mesh.CreateLines(null, this._zline, null, null, this._zmesh);
  52784. };
  52785. AxesViewer.prototype.dispose = function () {
  52786. if (this._xmesh) {
  52787. this._xmesh.dispose();
  52788. this._ymesh.dispose();
  52789. this._zmesh.dispose();
  52790. this._xmesh = null;
  52791. this._ymesh = null;
  52792. this._zmesh = null;
  52793. this._xline = null;
  52794. this._yline = null;
  52795. this._zline = null;
  52796. this.scene = null;
  52797. }
  52798. };
  52799. return AxesViewer;
  52800. }());
  52801. Debug.AxesViewer = AxesViewer;
  52802. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  52803. })(BABYLON || (BABYLON = {}));
  52804. //# sourceMappingURL=babylon.axesViewer.js.map
  52805. var BABYLON;
  52806. (function (BABYLON) {
  52807. var Debug;
  52808. (function (Debug) {
  52809. var BoneAxesViewer = (function (_super) {
  52810. __extends(BoneAxesViewer, _super);
  52811. function BoneAxesViewer(scene, bone, mesh, scaleLines) {
  52812. if (scaleLines === void 0) { scaleLines = 1; }
  52813. var _this = _super.call(this, scene, scaleLines) || this;
  52814. _this.pos = BABYLON.Vector3.Zero();
  52815. _this.xaxis = BABYLON.Vector3.Zero();
  52816. _this.yaxis = BABYLON.Vector3.Zero();
  52817. _this.zaxis = BABYLON.Vector3.Zero();
  52818. _this.mesh = mesh;
  52819. _this.bone = bone;
  52820. return _this;
  52821. }
  52822. BoneAxesViewer.prototype.update = function () {
  52823. var bone = this.bone;
  52824. bone.getAbsolutePositionToRef(this.mesh, this.pos);
  52825. bone.getDirectionToRef(BABYLON.Axis.X, this.mesh, this.xaxis);
  52826. bone.getDirectionToRef(BABYLON.Axis.Y, this.mesh, this.yaxis);
  52827. bone.getDirectionToRef(BABYLON.Axis.Z, this.mesh, this.zaxis);
  52828. _super.prototype.update.call(this, this.pos, this.xaxis, this.yaxis, this.zaxis);
  52829. };
  52830. BoneAxesViewer.prototype.dispose = function () {
  52831. if (this.pos) {
  52832. this.pos = null;
  52833. this.xaxis = null;
  52834. this.yaxis = null;
  52835. this.zaxis = null;
  52836. this.mesh = null;
  52837. this.bone = null;
  52838. _super.prototype.dispose.call(this);
  52839. }
  52840. };
  52841. return BoneAxesViewer;
  52842. }(Debug.AxesViewer));
  52843. Debug.BoneAxesViewer = BoneAxesViewer;
  52844. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  52845. })(BABYLON || (BABYLON = {}));
  52846. //# sourceMappingURL=babylon.boneAxesViewer.js.map
  52847. var BABYLON;
  52848. (function (BABYLON) {
  52849. /**
  52850. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  52851. * It can help converting any input color in a desired output one. This can then be used to create effects
  52852. * from sepia, black and white to sixties or futuristic rendering...
  52853. *
  52854. * The only supported format is currently 3dl.
  52855. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
  52856. */
  52857. var ColorGradingTexture = (function (_super) {
  52858. __extends(ColorGradingTexture, _super);
  52859. /**
  52860. * Instantiates a ColorGradingTexture from the following parameters.
  52861. *
  52862. * @param url The location of the color gradind data (currently only supporting 3dl)
  52863. * @param scene The scene the texture will be used in
  52864. */
  52865. function ColorGradingTexture(url, scene) {
  52866. var _this = _super.call(this, scene) || this;
  52867. if (!url) {
  52868. return _this;
  52869. }
  52870. _this._textureMatrix = BABYLON.Matrix.Identity();
  52871. _this.name = url;
  52872. _this.url = url;
  52873. _this.hasAlpha = false;
  52874. _this.isCube = false;
  52875. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  52876. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  52877. _this.anisotropicFilteringLevel = 1;
  52878. _this._texture = _this._getFromCache(url, true);
  52879. if (!_this._texture) {
  52880. if (!scene.useDelayedTextureLoading) {
  52881. _this.loadTexture();
  52882. }
  52883. else {
  52884. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  52885. }
  52886. }
  52887. return _this;
  52888. }
  52889. /**
  52890. * Returns the texture matrix used in most of the material.
  52891. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  52892. */
  52893. ColorGradingTexture.prototype.getTextureMatrix = function () {
  52894. return this._textureMatrix;
  52895. };
  52896. /**
  52897. * Occurs when the file being loaded is a .3dl LUT file.
  52898. */
  52899. ColorGradingTexture.prototype.load3dlTexture = function () {
  52900. var _this = this;
  52901. var mipLevels = 0;
  52902. var floatArrayView = null;
  52903. var texture = this.getScene().getEngine().createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  52904. this._texture = texture;
  52905. var callback = function (text) {
  52906. var data;
  52907. var tempData;
  52908. var line;
  52909. var lines = text.split('\n');
  52910. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  52911. var maxColor = 0;
  52912. for (var i = 0; i < lines.length; i++) {
  52913. line = lines[i];
  52914. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  52915. continue;
  52916. if (line.indexOf('#') === 0)
  52917. continue;
  52918. var words = line.split(" ");
  52919. if (size === 0) {
  52920. // Number of space + one
  52921. size = words.length;
  52922. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  52923. tempData = new Float32Array(size * size * size * 4);
  52924. continue;
  52925. }
  52926. if (size != 0) {
  52927. var r = Math.max(parseInt(words[0]), 0);
  52928. var g = Math.max(parseInt(words[1]), 0);
  52929. var b = Math.max(parseInt(words[2]), 0);
  52930. maxColor = Math.max(r, maxColor);
  52931. maxColor = Math.max(g, maxColor);
  52932. maxColor = Math.max(b, maxColor);
  52933. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  52934. tempData[pixelStorageIndex + 0] = r;
  52935. tempData[pixelStorageIndex + 1] = g;
  52936. tempData[pixelStorageIndex + 2] = b;
  52937. tempData[pixelStorageIndex + 3] = 0;
  52938. pixelIndexSlice++;
  52939. if (pixelIndexSlice % size == 0) {
  52940. pixelIndexH++;
  52941. pixelIndexSlice = 0;
  52942. if (pixelIndexH % size == 0) {
  52943. pixelIndexW++;
  52944. pixelIndexH = 0;
  52945. }
  52946. }
  52947. }
  52948. }
  52949. for (var i = 0; i < tempData.length; i++) {
  52950. var value = tempData[i];
  52951. data[i] = (value / maxColor * 255);
  52952. }
  52953. _this.getScene().getEngine().updateTextureSize(texture, size * size, size);
  52954. _this.getScene().getEngine().updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  52955. };
  52956. BABYLON.Tools.LoadFile(this.url, callback);
  52957. return this._texture;
  52958. };
  52959. /**
  52960. * Starts the loading process of the texture.
  52961. */
  52962. ColorGradingTexture.prototype.loadTexture = function () {
  52963. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  52964. this.load3dlTexture();
  52965. }
  52966. };
  52967. /**
  52968. * Clones the color gradind texture.
  52969. */
  52970. ColorGradingTexture.prototype.clone = function () {
  52971. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  52972. // Base texture
  52973. newTexture.level = this.level;
  52974. return newTexture;
  52975. };
  52976. /**
  52977. * Called during delayed load for textures.
  52978. */
  52979. ColorGradingTexture.prototype.delayLoad = function () {
  52980. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  52981. return;
  52982. }
  52983. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  52984. this._texture = this._getFromCache(this.url, true);
  52985. if (!this._texture) {
  52986. this.loadTexture();
  52987. }
  52988. };
  52989. /**
  52990. * Binds the color grading to the shader.
  52991. * @param colorGrading The texture to bind
  52992. * @param effect The effect to bind to
  52993. */
  52994. ColorGradingTexture.Bind = function (colorGrading, effect) {
  52995. effect.setTexture("cameraColorGrading2DSampler", colorGrading);
  52996. var x = colorGrading.level; // Texture Level
  52997. var y = colorGrading.getSize().height; // Texture Size example with 8
  52998. var z = y - 1.0; // SizeMinusOne 8 - 1
  52999. var w = 1 / y; // Space of 1 slice 1 / 8
  53000. effect.setFloat4("vCameraColorGradingInfos", x, y, z, w);
  53001. var slicePixelSizeU = w / y; // Space of 1 pixel in U direction, e.g. 1/64
  53002. 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
  53003. 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
  53004. 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
  53005. var z2 = 0.5 * slicePixelSizeU; // Offset of lookup range in U to align sample position with texel centre, for example 0.5/64
  53006. var w2 = 0.5 * slicePixelSizeV; // Offset of lookup range in V to align sample position with texel centre, for example 0.5/8
  53007. effect.setFloat4("vCameraColorGradingScaleOffset", x2, y2, z2, w2);
  53008. };
  53009. /**
  53010. * Prepare the list of uniforms associated with the ColorGrading effects.
  53011. * @param uniformsList The list of uniforms used in the effect
  53012. * @param samplersList The list of samplers used in the effect
  53013. */
  53014. ColorGradingTexture.PrepareUniformsAndSamplers = function (uniformsList, samplersList) {
  53015. uniformsList.push("vCameraColorGradingInfos", "vCameraColorGradingScaleOffset");
  53016. samplersList.push("cameraColorGrading2DSampler");
  53017. };
  53018. /**
  53019. * Parses a color grading texture serialized by Babylon.
  53020. * @param parsedTexture The texture information being parsedTexture
  53021. * @param scene The scene to load the texture in
  53022. * @param rootUrl The root url of the data assets to load
  53023. * @return A color gradind texture
  53024. */
  53025. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  53026. var texture = null;
  53027. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  53028. texture = new BABYLON.ColorGradingTexture(parsedTexture.name, scene);
  53029. texture.name = parsedTexture.name;
  53030. texture.level = parsedTexture.level;
  53031. }
  53032. return texture;
  53033. };
  53034. /**
  53035. * Serializes the LUT texture to json format.
  53036. */
  53037. ColorGradingTexture.prototype.serialize = function () {
  53038. if (!this.name) {
  53039. return null;
  53040. }
  53041. var serializationObject = {};
  53042. serializationObject.name = this.name;
  53043. serializationObject.level = this.level;
  53044. serializationObject.customType = "BABYLON.ColorGradingTexture";
  53045. return serializationObject;
  53046. };
  53047. return ColorGradingTexture;
  53048. }(BABYLON.BaseTexture));
  53049. /**
  53050. * Empty line regex stored for GC.
  53051. */
  53052. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  53053. BABYLON.ColorGradingTexture = ColorGradingTexture;
  53054. })(BABYLON || (BABYLON = {}));
  53055. //# sourceMappingURL=babylon.colorGradingTexture.js.map
  53056. var BABYLON;
  53057. (function (BABYLON) {
  53058. /**
  53059. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  53060. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  53061. * 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;
  53062. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  53063. */
  53064. var ColorCurves = (function () {
  53065. function ColorCurves() {
  53066. this._dirty = true;
  53067. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  53068. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  53069. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  53070. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  53071. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  53072. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  53073. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  53074. this._globalHue = 30;
  53075. this._globalDensity = 0;
  53076. this._globalSaturation = 0;
  53077. this._globalExposure = 0;
  53078. this._highlightsHue = 30;
  53079. this._highlightsDensity = 0;
  53080. this._highlightsSaturation = 0;
  53081. this._highlightsExposure = 0;
  53082. this._midtonesHue = 30;
  53083. this._midtonesDensity = 0;
  53084. this._midtonesSaturation = 0;
  53085. this._midtonesExposure = 0;
  53086. this._shadowsHue = 30;
  53087. this._shadowsDensity = 0;
  53088. this._shadowsSaturation = 0;
  53089. this._shadowsExposure = 0;
  53090. }
  53091. Object.defineProperty(ColorCurves.prototype, "GlobalHue", {
  53092. /**
  53093. * Gets the global Hue value.
  53094. * 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).
  53095. */
  53096. get: function () {
  53097. return this._globalHue;
  53098. },
  53099. /**
  53100. * Sets the global Hue value.
  53101. * 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).
  53102. */
  53103. set: function (value) {
  53104. this._globalHue = value;
  53105. this._dirty = true;
  53106. },
  53107. enumerable: true,
  53108. configurable: true
  53109. });
  53110. Object.defineProperty(ColorCurves.prototype, "GlobalDensity", {
  53111. /**
  53112. * Gets the global Density value.
  53113. * 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.
  53114. * Values less than zero provide a filter of opposite hue.
  53115. */
  53116. get: function () {
  53117. return this._globalDensity;
  53118. },
  53119. /**
  53120. * Sets the global Density value.
  53121. * 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.
  53122. * Values less than zero provide a filter of opposite hue.
  53123. */
  53124. set: function (value) {
  53125. this._globalDensity = value;
  53126. this._dirty = true;
  53127. },
  53128. enumerable: true,
  53129. configurable: true
  53130. });
  53131. Object.defineProperty(ColorCurves.prototype, "GlobalSaturation", {
  53132. /**
  53133. * Gets the global Saturation value.
  53134. * 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.
  53135. */
  53136. get: function () {
  53137. return this._globalSaturation;
  53138. },
  53139. /**
  53140. * Sets the global Saturation value.
  53141. * 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.
  53142. */
  53143. set: function (value) {
  53144. this._globalSaturation = value;
  53145. this._dirty = true;
  53146. },
  53147. enumerable: true,
  53148. configurable: true
  53149. });
  53150. Object.defineProperty(ColorCurves.prototype, "HighlightsHue", {
  53151. /**
  53152. * Gets the highlights Hue value.
  53153. * 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).
  53154. */
  53155. get: function () {
  53156. return this._highlightsHue;
  53157. },
  53158. /**
  53159. * Sets the highlights Hue value.
  53160. * 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).
  53161. */
  53162. set: function (value) {
  53163. this._highlightsHue = value;
  53164. this._dirty = true;
  53165. },
  53166. enumerable: true,
  53167. configurable: true
  53168. });
  53169. Object.defineProperty(ColorCurves.prototype, "HighlightsDensity", {
  53170. /**
  53171. * Gets the highlights Density value.
  53172. * 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.
  53173. * Values less than zero provide a filter of opposite hue.
  53174. */
  53175. get: function () {
  53176. return this._highlightsDensity;
  53177. },
  53178. /**
  53179. * Sets the highlights Density value.
  53180. * 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.
  53181. * Values less than zero provide a filter of opposite hue.
  53182. */
  53183. set: function (value) {
  53184. this._highlightsDensity = value;
  53185. this._dirty = true;
  53186. },
  53187. enumerable: true,
  53188. configurable: true
  53189. });
  53190. Object.defineProperty(ColorCurves.prototype, "HighlightsSaturation", {
  53191. /**
  53192. * Gets the highlights Saturation value.
  53193. * 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.
  53194. */
  53195. get: function () {
  53196. return this._highlightsSaturation;
  53197. },
  53198. /**
  53199. * Sets the highlights Saturation value.
  53200. * 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.
  53201. */
  53202. set: function (value) {
  53203. this._highlightsSaturation = value;
  53204. this._dirty = true;
  53205. },
  53206. enumerable: true,
  53207. configurable: true
  53208. });
  53209. Object.defineProperty(ColorCurves.prototype, "HighlightsExposure", {
  53210. /**
  53211. * Gets the highlights Exposure value.
  53212. * 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.
  53213. */
  53214. get: function () {
  53215. return this._highlightsExposure;
  53216. },
  53217. /**
  53218. * Sets the highlights Exposure value.
  53219. * 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.
  53220. */
  53221. set: function (value) {
  53222. this._highlightsExposure = value;
  53223. this._dirty = true;
  53224. },
  53225. enumerable: true,
  53226. configurable: true
  53227. });
  53228. Object.defineProperty(ColorCurves.prototype, "MidtonesHue", {
  53229. /**
  53230. * Gets the midtones Hue value.
  53231. * 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).
  53232. */
  53233. get: function () {
  53234. return this._midtonesHue;
  53235. },
  53236. /**
  53237. * Sets the midtones Hue value.
  53238. * 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).
  53239. */
  53240. set: function (value) {
  53241. this._midtonesHue = value;
  53242. this._dirty = true;
  53243. },
  53244. enumerable: true,
  53245. configurable: true
  53246. });
  53247. Object.defineProperty(ColorCurves.prototype, "MidtonesDensity", {
  53248. /**
  53249. * Gets the midtones Density value.
  53250. * 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.
  53251. * Values less than zero provide a filter of opposite hue.
  53252. */
  53253. get: function () {
  53254. return this._midtonesDensity;
  53255. },
  53256. /**
  53257. * Sets the midtones Density value.
  53258. * 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.
  53259. * Values less than zero provide a filter of opposite hue.
  53260. */
  53261. set: function (value) {
  53262. this._midtonesDensity = value;
  53263. this._dirty = true;
  53264. },
  53265. enumerable: true,
  53266. configurable: true
  53267. });
  53268. Object.defineProperty(ColorCurves.prototype, "MidtonesSaturation", {
  53269. /**
  53270. * Gets the midtones Saturation value.
  53271. * 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.
  53272. */
  53273. get: function () {
  53274. return this._midtonesSaturation;
  53275. },
  53276. /**
  53277. * Sets the midtones Saturation value.
  53278. * 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.
  53279. */
  53280. set: function (value) {
  53281. this._midtonesSaturation = value;
  53282. this._dirty = true;
  53283. },
  53284. enumerable: true,
  53285. configurable: true
  53286. });
  53287. Object.defineProperty(ColorCurves.prototype, "MidtonesExposure", {
  53288. /**
  53289. * Gets the midtones Exposure value.
  53290. * 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.
  53291. */
  53292. get: function () {
  53293. return this._midtonesExposure;
  53294. },
  53295. /**
  53296. * Sets the midtones Exposure value.
  53297. * 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.
  53298. */
  53299. set: function (value) {
  53300. this._midtonesExposure = value;
  53301. this._dirty = true;
  53302. },
  53303. enumerable: true,
  53304. configurable: true
  53305. });
  53306. Object.defineProperty(ColorCurves.prototype, "ShadowsHue", {
  53307. /**
  53308. * Gets the shadows Hue value.
  53309. * 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).
  53310. */
  53311. get: function () {
  53312. return this._shadowsHue;
  53313. },
  53314. /**
  53315. * Sets the shadows Hue value.
  53316. * 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).
  53317. */
  53318. set: function (value) {
  53319. this._shadowsHue = value;
  53320. this._dirty = true;
  53321. },
  53322. enumerable: true,
  53323. configurable: true
  53324. });
  53325. Object.defineProperty(ColorCurves.prototype, "ShadowsDensity", {
  53326. /**
  53327. * Gets the shadows Density value.
  53328. * 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.
  53329. * Values less than zero provide a filter of opposite hue.
  53330. */
  53331. get: function () {
  53332. return this._shadowsDensity;
  53333. },
  53334. /**
  53335. * Sets the shadows Density value.
  53336. * 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.
  53337. * Values less than zero provide a filter of opposite hue.
  53338. */
  53339. set: function (value) {
  53340. this._shadowsDensity = value;
  53341. this._dirty = true;
  53342. },
  53343. enumerable: true,
  53344. configurable: true
  53345. });
  53346. Object.defineProperty(ColorCurves.prototype, "ShadowsSaturation", {
  53347. /**
  53348. * Gets the shadows Saturation value.
  53349. * 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.
  53350. */
  53351. get: function () {
  53352. return this._shadowsSaturation;
  53353. },
  53354. /**
  53355. * Sets the shadows Saturation value.
  53356. * 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.
  53357. */
  53358. set: function (value) {
  53359. this._shadowsSaturation = value;
  53360. this._dirty = true;
  53361. },
  53362. enumerable: true,
  53363. configurable: true
  53364. });
  53365. Object.defineProperty(ColorCurves.prototype, "ShadowsExposure", {
  53366. /**
  53367. * Gets the shadows Exposure value.
  53368. * 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.
  53369. */
  53370. get: function () {
  53371. return this._shadowsExposure;
  53372. },
  53373. /**
  53374. * Sets the shadows Exposure value.
  53375. * 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.
  53376. */
  53377. set: function (value) {
  53378. this._shadowsExposure = value;
  53379. this._dirty = true;
  53380. },
  53381. enumerable: true,
  53382. configurable: true
  53383. });
  53384. /**
  53385. * Binds the color curves to the shader.
  53386. * @param colorCurves The color curve to bind
  53387. * @param effect The effect to bind to
  53388. */
  53389. ColorCurves.Bind = function (colorCurves, effect) {
  53390. if (colorCurves._dirty) {
  53391. colorCurves._dirty = false;
  53392. // Fill in global info.
  53393. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  53394. // Compute highlights info.
  53395. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  53396. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  53397. // Compute midtones info.
  53398. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  53399. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  53400. // Compute shadows info.
  53401. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  53402. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  53403. // Compute deltas (neutral is midtones).
  53404. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  53405. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  53406. }
  53407. effect.setFloat4("vCameraColorCurvePositive", colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  53408. effect.setFloat4("vCameraColorCurveNeutral", colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  53409. effect.setFloat4("vCameraColorCurveNegative", colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  53410. };
  53411. /**
  53412. * Prepare the list of uniforms associated with the ColorCurves effects.
  53413. * @param uniformsList The list of uniforms used in the effect
  53414. */
  53415. ColorCurves.PrepareUniforms = function (uniformsList) {
  53416. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  53417. };
  53418. /**
  53419. * Returns color grading data based on a hue, density, saturation and exposure value.
  53420. * @param filterHue The hue of the color filter.
  53421. * @param filterDensity The density of the color filter.
  53422. * @param saturation The saturation.
  53423. * @param exposure The exposure.
  53424. * @param result The result data container.
  53425. */
  53426. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  53427. if (hue == null) {
  53428. return;
  53429. }
  53430. hue = ColorCurves.clamp(hue, 0, 360);
  53431. density = ColorCurves.clamp(density, -100, 100);
  53432. saturation = ColorCurves.clamp(saturation, -100, 100);
  53433. exposure = ColorCurves.clamp(exposure, -100, 100);
  53434. // Remap the slider/config filter density with non-linear mapping and also scale by half
  53435. // so that the maximum filter density is only 50% control. This provides fine control
  53436. // for small values and reasonable range.
  53437. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  53438. density *= 0.5;
  53439. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  53440. if (density < 0) {
  53441. density *= -1;
  53442. hue = (hue + 180) % 360;
  53443. }
  53444. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  53445. result.scaleToRef(2, result);
  53446. result.a = 1 + 0.01 * saturation;
  53447. };
  53448. /**
  53449. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  53450. * @param value The input slider value in range [-100,100].
  53451. * @returns Adjusted value.
  53452. */
  53453. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  53454. value /= 100;
  53455. var x = Math.abs(value);
  53456. x = Math.pow(x, 2);
  53457. if (value < 0) {
  53458. x *= -1;
  53459. }
  53460. x *= 100;
  53461. return x;
  53462. };
  53463. /**
  53464. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  53465. * @param hue The hue (H) input.
  53466. * @param saturation The saturation (S) input.
  53467. * @param brightness The brightness (B) input.
  53468. * @result An RGBA color represented as Vector4.
  53469. */
  53470. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  53471. var h = ColorCurves.clamp(hue, 0, 360);
  53472. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  53473. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  53474. if (s === 0) {
  53475. result.r = v;
  53476. result.g = v;
  53477. result.b = v;
  53478. }
  53479. else {
  53480. // sector 0 to 5
  53481. h /= 60;
  53482. var i = Math.floor(h);
  53483. // fractional part of h
  53484. var f = h - i;
  53485. var p = v * (1 - s);
  53486. var q = v * (1 - s * f);
  53487. var t = v * (1 - s * (1 - f));
  53488. switch (i) {
  53489. case 0:
  53490. result.r = v;
  53491. result.g = t;
  53492. result.b = p;
  53493. break;
  53494. case 1:
  53495. result.r = q;
  53496. result.g = v;
  53497. result.b = p;
  53498. break;
  53499. case 2:
  53500. result.r = p;
  53501. result.g = v;
  53502. result.b = t;
  53503. break;
  53504. case 3:
  53505. result.r = p;
  53506. result.g = q;
  53507. result.b = v;
  53508. break;
  53509. case 4:
  53510. result.r = t;
  53511. result.g = p;
  53512. result.b = v;
  53513. break;
  53514. default:
  53515. result.r = v;
  53516. result.g = p;
  53517. result.b = q;
  53518. break;
  53519. }
  53520. }
  53521. result.a = 1;
  53522. };
  53523. /**
  53524. * Returns a value clamped between min and max
  53525. * @param value The value to clamp
  53526. * @param min The minimum of value
  53527. * @param max The maximum of value
  53528. * @returns The clamped value.
  53529. */
  53530. ColorCurves.clamp = function (value, min, max) {
  53531. return Math.min(Math.max(value, min), max);
  53532. };
  53533. /**
  53534. * Clones the current color curve instance.
  53535. * @return The cloned curves
  53536. */
  53537. ColorCurves.prototype.clone = function () {
  53538. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  53539. };
  53540. /**
  53541. * Serializes the current color curve instance to a json representation.
  53542. * @return a JSON representation
  53543. */
  53544. ColorCurves.prototype.serialize = function () {
  53545. return BABYLON.SerializationHelper.Serialize(this);
  53546. };
  53547. /**
  53548. * Parses the color curve from a json representation.
  53549. * @param source the JSON source to parse
  53550. * @return The parsed curves
  53551. */
  53552. ColorCurves.Parse = function (source) {
  53553. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  53554. };
  53555. return ColorCurves;
  53556. }());
  53557. __decorate([
  53558. BABYLON.serialize()
  53559. ], ColorCurves.prototype, "_globalHue", void 0);
  53560. __decorate([
  53561. BABYLON.serialize()
  53562. ], ColorCurves.prototype, "_globalDensity", void 0);
  53563. __decorate([
  53564. BABYLON.serialize()
  53565. ], ColorCurves.prototype, "_globalSaturation", void 0);
  53566. __decorate([
  53567. BABYLON.serialize()
  53568. ], ColorCurves.prototype, "_globalExposure", void 0);
  53569. __decorate([
  53570. BABYLON.serialize()
  53571. ], ColorCurves.prototype, "_highlightsHue", void 0);
  53572. __decorate([
  53573. BABYLON.serialize()
  53574. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  53575. __decorate([
  53576. BABYLON.serialize()
  53577. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  53578. __decorate([
  53579. BABYLON.serialize()
  53580. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  53581. __decorate([
  53582. BABYLON.serialize()
  53583. ], ColorCurves.prototype, "_midtonesHue", void 0);
  53584. __decorate([
  53585. BABYLON.serialize()
  53586. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  53587. __decorate([
  53588. BABYLON.serialize()
  53589. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  53590. __decorate([
  53591. BABYLON.serialize()
  53592. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  53593. BABYLON.ColorCurves = ColorCurves;
  53594. })(BABYLON || (BABYLON = {}));
  53595. //# sourceMappingURL=babylon.colorCurves.js.map
  53596. var BABYLON;
  53597. (function (BABYLON) {
  53598. var PBRMaterialDefines = (function (_super) {
  53599. __extends(PBRMaterialDefines, _super);
  53600. function PBRMaterialDefines() {
  53601. var _this = _super.call(this) || this;
  53602. _this.ALBEDO = false;
  53603. _this.AMBIENT = false;
  53604. _this.OPACITY = false;
  53605. _this.OPACITYRGB = false;
  53606. _this.REFLECTION = false;
  53607. _this.EMISSIVE = false;
  53608. _this.REFLECTIVITY = false;
  53609. _this.BUMP = false;
  53610. _this.PARALLAX = false;
  53611. _this.PARALLAXOCCLUSION = false;
  53612. _this.SPECULAROVERALPHA = false;
  53613. _this.CLIPPLANE = false;
  53614. _this.ALPHATEST = false;
  53615. _this.ALPHAFROMALBEDO = false;
  53616. _this.POINTSIZE = false;
  53617. _this.FOG = false;
  53618. _this.SPECULARTERM = false;
  53619. _this.OPACITYFRESNEL = false;
  53620. _this.EMISSIVEFRESNEL = false;
  53621. _this.FRESNEL = false;
  53622. _this.NORMAL = false;
  53623. _this.UV1 = false;
  53624. _this.UV2 = false;
  53625. _this.VERTEXCOLOR = false;
  53626. _this.VERTEXALPHA = false;
  53627. _this.NUM_BONE_INFLUENCERS = 0;
  53628. _this.BonesPerMesh = 0;
  53629. _this.INSTANCES = false;
  53630. _this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  53631. _this.MICROSURFACEAUTOMATIC = false;
  53632. _this.EMISSIVEASILLUMINATION = false;
  53633. _this.LINKEMISSIVEWITHALBEDO = false;
  53634. _this.LIGHTMAP = false;
  53635. _this.USELIGHTMAPASSHADOWMAP = false;
  53636. _this.REFLECTIONMAP_3D = false;
  53637. _this.REFLECTIONMAP_SPHERICAL = false;
  53638. _this.REFLECTIONMAP_PLANAR = false;
  53639. _this.REFLECTIONMAP_CUBIC = false;
  53640. _this.REFLECTIONMAP_PROJECTION = false;
  53641. _this.REFLECTIONMAP_SKYBOX = false;
  53642. _this.REFLECTIONMAP_EXPLICIT = false;
  53643. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  53644. _this.INVERTCUBICMAP = false;
  53645. _this.LOGARITHMICDEPTH = false;
  53646. _this.CAMERATONEMAP = false;
  53647. _this.CAMERACONTRAST = false;
  53648. _this.CAMERACOLORGRADING = false;
  53649. _this.CAMERACOLORCURVES = false;
  53650. _this.OVERLOADEDVALUES = false;
  53651. _this.OVERLOADEDSHADOWVALUES = false;
  53652. _this.USESPHERICALFROMREFLECTIONMAP = false;
  53653. _this.REFRACTION = false;
  53654. _this.REFRACTIONMAP_3D = false;
  53655. _this.LINKREFRACTIONTOTRANSPARENCY = false;
  53656. _this.REFRACTIONMAPINLINEARSPACE = false;
  53657. _this.LODBASEDMICROSFURACE = false;
  53658. _this.USEPHYSICALLIGHTFALLOFF = false;
  53659. _this.RADIANCEOVERALPHA = false;
  53660. _this.USEPMREMREFLECTION = false;
  53661. _this.USEPMREMREFRACTION = false;
  53662. _this.OPENGLNORMALMAP = false;
  53663. _this.INVERTNORMALMAPX = false;
  53664. _this.INVERTNORMALMAPY = false;
  53665. _this.SHADOWFULLFLOAT = false;
  53666. _this.METALLICWORKFLOW = false;
  53667. _this.METALLICROUGHNESSMAP = false;
  53668. _this.METALLICROUGHNESSGSTOREINALPHA = false;
  53669. _this.METALLICROUGHNESSGSTOREINGREEN = false;
  53670. _this.rebuild();
  53671. return _this;
  53672. }
  53673. return PBRMaterialDefines;
  53674. }(BABYLON.MaterialDefines));
  53675. /**
  53676. * The Physically based material of BJS.
  53677. *
  53678. * This offers the main features of a standard PBR material.
  53679. * For more information, please refer to the documentation :
  53680. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  53681. */
  53682. var PBRMaterial = (function (_super) {
  53683. __extends(PBRMaterial, _super);
  53684. /**
  53685. * Instantiates a new PBRMaterial instance.
  53686. *
  53687. * @param name The material name
  53688. * @param scene The scene the material will be use in.
  53689. */
  53690. function PBRMaterial(name, scene) {
  53691. var _this = _super.call(this, name, scene) || this;
  53692. /**
  53693. * Intensity of the direct lights e.g. the four lights available in your scene.
  53694. * This impacts both the direct diffuse and specular highlights.
  53695. */
  53696. _this.directIntensity = 1.0;
  53697. /**
  53698. * Intensity of the emissive part of the material.
  53699. * This helps controlling the emissive effect without modifying the emissive color.
  53700. */
  53701. _this.emissiveIntensity = 1.0;
  53702. /**
  53703. * Intensity of the environment e.g. how much the environment will light the object
  53704. * either through harmonics for rough material or through the refelction for shiny ones.
  53705. */
  53706. _this.environmentIntensity = 1.0;
  53707. /**
  53708. * This is a special control allowing the reduction of the specular highlights coming from the
  53709. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  53710. */
  53711. _this.specularIntensity = 1.0;
  53712. _this._lightingInfos = new BABYLON.Vector4(_this.directIntensity, _this.emissiveIntensity, _this.environmentIntensity, _this.specularIntensity);
  53713. /**
  53714. * Debug Control allowing disabling the bump map on this material.
  53715. */
  53716. _this.disableBumpMap = false;
  53717. /**
  53718. * Debug Control helping enforcing or dropping the darkness of shadows.
  53719. * 1.0 means the shadows have their normal darkness, 0.0 means the shadows are not visible.
  53720. */
  53721. _this.overloadedShadowIntensity = 1.0;
  53722. /**
  53723. * Debug Control helping dropping the shading effect coming from the diffuse lighting.
  53724. * 1.0 means the shade have their normal impact, 0.0 means no shading at all.
  53725. */
  53726. _this.overloadedShadeIntensity = 1.0;
  53727. _this._overloadedShadowInfos = new BABYLON.Vector4(_this.overloadedShadowIntensity, _this.overloadedShadeIntensity, 0.0, 0.0);
  53728. /**
  53729. * The camera exposure used on this material.
  53730. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  53731. * This corresponds to a photographic exposure.
  53732. */
  53733. _this.cameraExposure = 1.0;
  53734. /**
  53735. * The camera contrast used on this material.
  53736. * This property is here and not in the camera to allow controlling contrast without full screen post process.
  53737. */
  53738. _this.cameraContrast = 1.0;
  53739. /**
  53740. * Color Grading 2D Lookup Texture.
  53741. * This allows special effects like sepia, black and white to sixties rendering style.
  53742. */
  53743. _this.cameraColorGradingTexture = null;
  53744. /**
  53745. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  53746. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  53747. * 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;
  53748. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  53749. */
  53750. _this.cameraColorCurves = null;
  53751. _this._cameraInfos = new BABYLON.Vector4(1.0, 1.0, 0.0, 0.0);
  53752. _this._microsurfaceTextureLods = new BABYLON.Vector2(0.0, 0.0);
  53753. /**
  53754. * Debug Control allowing to overload the ambient color.
  53755. * This as to be use with the overloadedAmbientIntensity parameter.
  53756. */
  53757. _this.overloadedAmbient = BABYLON.Color3.White();
  53758. /**
  53759. * Debug Control indicating how much the overloaded ambient color is used against the default one.
  53760. */
  53761. _this.overloadedAmbientIntensity = 0.0;
  53762. /**
  53763. * Debug Control allowing to overload the albedo color.
  53764. * This as to be use with the overloadedAlbedoIntensity parameter.
  53765. */
  53766. _this.overloadedAlbedo = BABYLON.Color3.White();
  53767. /**
  53768. * Debug Control indicating how much the overloaded albedo color is used against the default one.
  53769. */
  53770. _this.overloadedAlbedoIntensity = 0.0;
  53771. /**
  53772. * Debug Control allowing to overload the reflectivity color.
  53773. * This as to be use with the overloadedReflectivityIntensity parameter.
  53774. */
  53775. _this.overloadedReflectivity = new BABYLON.Color3(0.3, 0.3, 0.3);
  53776. /**
  53777. * Debug Control indicating how much the overloaded reflectivity color is used against the default one.
  53778. */
  53779. _this.overloadedReflectivityIntensity = 0.0;
  53780. /**
  53781. * Debug Control allowing to overload the emissive color.
  53782. * This as to be use with the overloadedEmissiveIntensity parameter.
  53783. */
  53784. _this.overloadedEmissive = BABYLON.Color3.White();
  53785. /**
  53786. * Debug Control indicating how much the overloaded emissive color is used against the default one.
  53787. */
  53788. _this.overloadedEmissiveIntensity = 0.0;
  53789. _this._overloadedIntensity = new BABYLON.Vector4(_this.overloadedAmbientIntensity, _this.overloadedAlbedoIntensity, _this.overloadedReflectivityIntensity, _this.overloadedEmissiveIntensity);
  53790. /**
  53791. * Debug Control allowing to overload the reflection color.
  53792. * This as to be use with the overloadedReflectionIntensity parameter.
  53793. */
  53794. _this.overloadedReflection = BABYLON.Color3.White();
  53795. /**
  53796. * Debug Control indicating how much the overloaded reflection color is used against the default one.
  53797. */
  53798. _this.overloadedReflectionIntensity = 0.0;
  53799. /**
  53800. * Debug Control allowing to overload the microsurface.
  53801. * This as to be use with the overloadedMicroSurfaceIntensity parameter.
  53802. */
  53803. _this.overloadedMicroSurface = 0.0;
  53804. /**
  53805. * Debug Control indicating how much the overloaded microsurface is used against the default one.
  53806. */
  53807. _this.overloadedMicroSurfaceIntensity = 0.0;
  53808. _this._overloadedMicroSurface = new BABYLON.Vector3(_this.overloadedMicroSurface, _this.overloadedMicroSurfaceIntensity, _this.overloadedReflectionIntensity);
  53809. /**
  53810. * AKA Occlusion Texture Intensity in other nomenclature.
  53811. */
  53812. _this.ambientTextureStrength = 1.0;
  53813. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  53814. /**
  53815. * AKA Diffuse Color in other nomenclature.
  53816. */
  53817. _this.albedoColor = new BABYLON.Color3(1, 1, 1);
  53818. /**
  53819. * AKA Specular Color in other nomenclature.
  53820. */
  53821. _this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  53822. _this.reflectionColor = new BABYLON.Color3(0.5, 0.5, 0.5);
  53823. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  53824. /**
  53825. * AKA Glossiness in other nomenclature.
  53826. */
  53827. _this.microSurface = 0.9;
  53828. /**
  53829. * source material index of refraction (IOR)' / 'destination material IOR.
  53830. */
  53831. _this.indexOfRefraction = 0.66;
  53832. /**
  53833. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  53834. */
  53835. _this.invertRefractionY = false;
  53836. /**
  53837. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  53838. * Materials half opaque for instance using refraction could benefit from this control.
  53839. */
  53840. _this.linkRefractionWithTransparency = false;
  53841. /**
  53842. * The emissive and albedo are linked to never be more than one (Energy conservation).
  53843. */
  53844. _this.linkEmissiveWithAlbedo = false;
  53845. _this.useLightmapAsShadowmap = false;
  53846. /**
  53847. * In this mode, the emissive informtaion will always be added to the lighting once.
  53848. * A light for instance can be thought as emissive.
  53849. */
  53850. _this.useEmissiveAsIllumination = false;
  53851. /**
  53852. * Secifies that the alpha is coming form the albedo channel alpha channel.
  53853. */
  53854. _this.useAlphaFromAlbedoTexture = false;
  53855. /**
  53856. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  53857. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  53858. */
  53859. _this.useSpecularOverAlpha = true;
  53860. /**
  53861. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  53862. */
  53863. _this.useMicroSurfaceFromReflectivityMapAlpha = false;
  53864. /**
  53865. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  53866. */
  53867. _this.useRoughnessFromMetallicTextureAlpha = true;
  53868. /**
  53869. * Specifies if the metallic texture contains the roughness information in its green channel.
  53870. */
  53871. _this.useRoughnessFromMetallicTextureGreen = false;
  53872. /**
  53873. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  53874. * The material will try to infer what glossiness each pixel should be.
  53875. */
  53876. _this.useAutoMicroSurfaceFromReflectivityMap = false;
  53877. /**
  53878. * Allows to work with scalar in linear mode. This is definitely a matter of preferences and tools used during
  53879. * the creation of the material.
  53880. */
  53881. _this.useScalarInLinearSpace = false;
  53882. /**
  53883. * BJS is using an harcoded light falloff based on a manually sets up range.
  53884. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  53885. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  53886. */
  53887. _this.usePhysicalLightFalloff = true;
  53888. /**
  53889. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  53890. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  53891. */
  53892. _this.useRadianceOverAlpha = true;
  53893. /**
  53894. * Allows using the bump map in parallax mode.
  53895. */
  53896. _this.useParallax = false;
  53897. /**
  53898. * Allows using the bump map in parallax occlusion mode.
  53899. */
  53900. _this.useParallaxOcclusion = false;
  53901. /**
  53902. * Controls the scale bias of the parallax mode.
  53903. */
  53904. _this.parallaxScaleBias = 0.05;
  53905. /**
  53906. * If sets to true, disables all the lights affecting the material.
  53907. */
  53908. _this.disableLighting = false;
  53909. /**
  53910. * Number of Simultaneous lights allowed on the material.
  53911. */
  53912. _this.maxSimultaneousLights = 4;
  53913. /**
  53914. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  53915. */
  53916. _this.invertNormalMapX = false;
  53917. /**
  53918. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  53919. */
  53920. _this.invertNormalMapY = false;
  53921. _this._renderTargets = new BABYLON.SmartArray(16);
  53922. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  53923. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  53924. _this._tempColor = new BABYLON.Color3();
  53925. _this._defines = new PBRMaterialDefines();
  53926. _this._cachedDefines = new PBRMaterialDefines();
  53927. _this._myScene = null;
  53928. _this._myShadowGenerator = null;
  53929. _this._cachedDefines.BonesPerMesh = -1;
  53930. _this.getRenderTargetTextures = function () {
  53931. _this._renderTargets.reset();
  53932. if (_this.reflectionTexture && _this.reflectionTexture.isRenderTarget) {
  53933. _this._renderTargets.push(_this.reflectionTexture);
  53934. }
  53935. if (_this.refractionTexture && _this.refractionTexture.isRenderTarget) {
  53936. _this._renderTargets.push(_this.refractionTexture);
  53937. }
  53938. return _this._renderTargets;
  53939. };
  53940. return _this;
  53941. }
  53942. PBRMaterial.prototype.getClassName = function () {
  53943. return "PBRMaterial";
  53944. };
  53945. Object.defineProperty(PBRMaterial.prototype, "useLogarithmicDepth", {
  53946. get: function () {
  53947. return this._useLogarithmicDepth;
  53948. },
  53949. set: function (value) {
  53950. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  53951. },
  53952. enumerable: true,
  53953. configurable: true
  53954. });
  53955. PBRMaterial.prototype.needAlphaBlending = function () {
  53956. if (this.linkRefractionWithTransparency) {
  53957. return false;
  53958. }
  53959. return (this.alpha < 1.0) || (this.opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture() || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled;
  53960. };
  53961. PBRMaterial.prototype.needAlphaTesting = function () {
  53962. if (this.linkRefractionWithTransparency) {
  53963. return false;
  53964. }
  53965. return this.albedoTexture != null && this.albedoTexture.hasAlpha;
  53966. };
  53967. PBRMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  53968. return this.albedoTexture != null && this.albedoTexture.hasAlpha && this.useAlphaFromAlbedoTexture;
  53969. };
  53970. PBRMaterial.prototype.getAlphaTestTexture = function () {
  53971. return this.albedoTexture;
  53972. };
  53973. PBRMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  53974. if (!mesh) {
  53975. return true;
  53976. }
  53977. if (this._defines.INSTANCES !== useInstances) {
  53978. return false;
  53979. }
  53980. if (mesh._materialDefines && mesh._materialDefines.isEqual(this._defines)) {
  53981. return true;
  53982. }
  53983. return false;
  53984. };
  53985. PBRMaterial.prototype.convertColorToLinearSpaceToRef = function (color, ref) {
  53986. PBRMaterial.convertColorToLinearSpaceToRef(color, ref, this.useScalarInLinearSpace);
  53987. };
  53988. PBRMaterial.convertColorToLinearSpaceToRef = function (color, ref, useScalarInLinear) {
  53989. if (!useScalarInLinear) {
  53990. color.toLinearSpaceToRef(ref);
  53991. }
  53992. else {
  53993. ref.r = color.r;
  53994. ref.g = color.g;
  53995. ref.b = color.b;
  53996. }
  53997. };
  53998. PBRMaterial.BindLights = function (scene, mesh, effect, defines, useScalarInLinearSpace, maxSimultaneousLights, usePhysicalLightFalloff) {
  53999. var lightIndex = 0;
  54000. var depthValuesAlreadySet = false;
  54001. for (var index = 0; index < scene.lights.length; index++) {
  54002. var light = scene.lights[index];
  54003. if (!light.isEnabled()) {
  54004. continue;
  54005. }
  54006. if (!light.canAffectMesh(mesh)) {
  54007. continue;
  54008. }
  54009. BABYLON.MaterialHelper.BindLightProperties(light, effect, lightIndex);
  54010. // GAMMA CORRECTION.
  54011. this.convertColorToLinearSpaceToRef(light.diffuse, PBRMaterial._scaledAlbedo, useScalarInLinearSpace);
  54012. PBRMaterial._scaledAlbedo.scaleToRef(light.intensity, PBRMaterial._scaledAlbedo);
  54013. effect.setColor4("vLightDiffuse" + lightIndex, PBRMaterial._scaledAlbedo, usePhysicalLightFalloff ? light.radius : light.range);
  54014. if (defines["SPECULARTERM"]) {
  54015. this.convertColorToLinearSpaceToRef(light.specular, PBRMaterial._scaledReflectivity, useScalarInLinearSpace);
  54016. PBRMaterial._scaledReflectivity.scaleToRef(light.intensity, PBRMaterial._scaledReflectivity);
  54017. effect.setColor3("vLightSpecular" + lightIndex, PBRMaterial._scaledReflectivity);
  54018. }
  54019. // Shadows
  54020. if (scene.shadowsEnabled) {
  54021. depthValuesAlreadySet = BABYLON.MaterialHelper.BindLightShadow(light, scene, mesh, lightIndex, effect, depthValuesAlreadySet);
  54022. }
  54023. lightIndex++;
  54024. if (lightIndex === maxSimultaneousLights)
  54025. break;
  54026. }
  54027. };
  54028. PBRMaterial.prototype.isReady = function (mesh, useInstances) {
  54029. if (this.isFrozen) {
  54030. if (this._wasPreviouslyReady) {
  54031. return true;
  54032. }
  54033. }
  54034. var scene = this.getScene();
  54035. var engine = scene.getEngine();
  54036. var needNormals = false;
  54037. var needUVs = false;
  54038. this._defines.reset();
  54039. if (scene.lightsEnabled && !this.disableLighting) {
  54040. needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, this._defines, this.maxSimultaneousLights) || needNormals;
  54041. }
  54042. if (!this.checkReadyOnEveryCall) {
  54043. if (this._renderId === scene.getRenderId()) {
  54044. if (this._checkCache(scene, mesh, useInstances)) {
  54045. return true;
  54046. }
  54047. }
  54048. }
  54049. if (scene.texturesEnabled) {
  54050. if (scene.getEngine().getCaps().textureLOD) {
  54051. this._defines.LODBASEDMICROSFURACE = true;
  54052. }
  54053. if (this.albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  54054. if (!this.albedoTexture.isReady()) {
  54055. return false;
  54056. }
  54057. else {
  54058. needUVs = true;
  54059. this._defines.ALBEDO = true;
  54060. }
  54061. }
  54062. if (this.ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  54063. if (!this.ambientTexture.isReady()) {
  54064. return false;
  54065. }
  54066. else {
  54067. needUVs = true;
  54068. this._defines.AMBIENT = true;
  54069. }
  54070. }
  54071. if (this.opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  54072. if (!this.opacityTexture.isReady()) {
  54073. return false;
  54074. }
  54075. else {
  54076. needUVs = true;
  54077. this._defines.OPACITY = true;
  54078. if (this.opacityTexture.getAlphaFromRGB) {
  54079. this._defines.OPACITYRGB = true;
  54080. }
  54081. }
  54082. }
  54083. if (this.reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  54084. if (!this.reflectionTexture.isReady()) {
  54085. return false;
  54086. }
  54087. else {
  54088. needNormals = true;
  54089. this._defines.REFLECTION = true;
  54090. if (this.reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  54091. this._defines.INVERTCUBICMAP = true;
  54092. }
  54093. this._defines.REFLECTIONMAP_3D = this.reflectionTexture.isCube;
  54094. switch (this.reflectionTexture.coordinatesMode) {
  54095. case BABYLON.Texture.CUBIC_MODE:
  54096. case BABYLON.Texture.INVCUBIC_MODE:
  54097. this._defines.REFLECTIONMAP_CUBIC = true;
  54098. break;
  54099. case BABYLON.Texture.EXPLICIT_MODE:
  54100. this._defines.REFLECTIONMAP_EXPLICIT = true;
  54101. break;
  54102. case BABYLON.Texture.PLANAR_MODE:
  54103. this._defines.REFLECTIONMAP_PLANAR = true;
  54104. break;
  54105. case BABYLON.Texture.PROJECTION_MODE:
  54106. this._defines.REFLECTIONMAP_PROJECTION = true;
  54107. break;
  54108. case BABYLON.Texture.SKYBOX_MODE:
  54109. this._defines.REFLECTIONMAP_SKYBOX = true;
  54110. break;
  54111. case BABYLON.Texture.SPHERICAL_MODE:
  54112. this._defines.REFLECTIONMAP_SPHERICAL = true;
  54113. break;
  54114. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  54115. this._defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  54116. break;
  54117. }
  54118. if (this.reflectionTexture instanceof BABYLON.HDRCubeTexture && this.reflectionTexture) {
  54119. this._defines.USESPHERICALFROMREFLECTIONMAP = true;
  54120. needNormals = true;
  54121. if (this.reflectionTexture.isPMREM) {
  54122. this._defines.USEPMREMREFLECTION = true;
  54123. }
  54124. }
  54125. }
  54126. }
  54127. if (this.lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  54128. if (!this.lightmapTexture.isReady()) {
  54129. return false;
  54130. }
  54131. else {
  54132. needUVs = true;
  54133. this._defines.LIGHTMAP = true;
  54134. this._defines.USELIGHTMAPASSHADOWMAP = this.useLightmapAsShadowmap;
  54135. }
  54136. }
  54137. if (this.emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  54138. if (!this.emissiveTexture.isReady()) {
  54139. return false;
  54140. }
  54141. else {
  54142. needUVs = true;
  54143. this._defines.EMISSIVE = true;
  54144. }
  54145. }
  54146. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  54147. if (this.metallicTexture) {
  54148. if (!this.metallicTexture.isReady()) {
  54149. return false;
  54150. }
  54151. else {
  54152. needUVs = true;
  54153. this._defines.METALLICWORKFLOW = true;
  54154. this._defines.METALLICROUGHNESSMAP = true;
  54155. this._defines.METALLICROUGHNESSGSTOREINALPHA = this.useRoughnessFromMetallicTextureAlpha;
  54156. this._defines.METALLICROUGHNESSGSTOREINGREEN = !this.useRoughnessFromMetallicTextureAlpha && this.useRoughnessFromMetallicTextureGreen;
  54157. }
  54158. }
  54159. else if (this.reflectivityTexture) {
  54160. if (!this.reflectivityTexture.isReady()) {
  54161. return false;
  54162. }
  54163. else {
  54164. needUVs = true;
  54165. this._defines.REFLECTIVITY = true;
  54166. this._defines.MICROSURFACEFROMREFLECTIVITYMAP = this.useMicroSurfaceFromReflectivityMapAlpha;
  54167. this._defines.MICROSURFACEAUTOMATIC = this.useAutoMicroSurfaceFromReflectivityMap;
  54168. }
  54169. }
  54170. }
  54171. if (scene.getEngine().getCaps().standardDerivatives && this.bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this.disableBumpMap) {
  54172. if (!this.bumpTexture.isReady()) {
  54173. return false;
  54174. }
  54175. else {
  54176. needUVs = true;
  54177. this._defines.BUMP = true;
  54178. if (this.useParallax && this.albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  54179. this._defines.PARALLAX = true;
  54180. if (this.useParallaxOcclusion) {
  54181. this._defines.PARALLAXOCCLUSION = true;
  54182. }
  54183. }
  54184. if (this.invertNormalMapX) {
  54185. this._defines.INVERTNORMALMAPX = true;
  54186. }
  54187. if (this.invertNormalMapY) {
  54188. this._defines.INVERTNORMALMAPY = true;
  54189. }
  54190. if (scene._mirroredCameraPosition) {
  54191. this._defines.INVERTNORMALMAPX = !this._defines.INVERTNORMALMAPX;
  54192. this._defines.INVERTNORMALMAPY = !this._defines.INVERTNORMALMAPY;
  54193. }
  54194. }
  54195. }
  54196. if (this.refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  54197. if (!this.refractionTexture.isReady()) {
  54198. return false;
  54199. }
  54200. else {
  54201. needUVs = true;
  54202. this._defines.REFRACTION = true;
  54203. this._defines.REFRACTIONMAP_3D = this.refractionTexture.isCube;
  54204. if (this.linkRefractionWithTransparency) {
  54205. this._defines.LINKREFRACTIONTOTRANSPARENCY = true;
  54206. }
  54207. if (this.refractionTexture instanceof BABYLON.HDRCubeTexture) {
  54208. this._defines.REFRACTIONMAPINLINEARSPACE = true;
  54209. if (this.refractionTexture.isPMREM) {
  54210. this._defines.USEPMREMREFRACTION = true;
  54211. }
  54212. }
  54213. }
  54214. }
  54215. if (this.cameraColorGradingTexture && BABYLON.StandardMaterial.ColorGradingTextureEnabled) {
  54216. if (!this.cameraColorGradingTexture.isReady()) {
  54217. return false;
  54218. }
  54219. else {
  54220. this._defines.CAMERACOLORGRADING = true;
  54221. }
  54222. }
  54223. }
  54224. // Effect
  54225. if (scene.clipPlane) {
  54226. this._defines.CLIPPLANE = true;
  54227. }
  54228. if (engine.getAlphaTesting()) {
  54229. this._defines.ALPHATEST = true;
  54230. }
  54231. if (this._shouldUseAlphaFromAlbedoTexture()) {
  54232. this._defines.ALPHAFROMALBEDO = true;
  54233. }
  54234. if (this.useEmissiveAsIllumination) {
  54235. this._defines.EMISSIVEASILLUMINATION = true;
  54236. }
  54237. if (this.linkEmissiveWithAlbedo) {
  54238. this._defines.LINKEMISSIVEWITHALBEDO = true;
  54239. }
  54240. if (this.useLogarithmicDepth) {
  54241. this._defines.LOGARITHMICDEPTH = true;
  54242. }
  54243. if (this.cameraContrast != 1) {
  54244. this._defines.CAMERACONTRAST = true;
  54245. }
  54246. if (this.cameraExposure != 1) {
  54247. this._defines.CAMERATONEMAP = true;
  54248. }
  54249. if (this.cameraColorCurves) {
  54250. this._defines.CAMERACOLORCURVES = true;
  54251. }
  54252. if (this.overloadedShadeIntensity != 1 ||
  54253. this.overloadedShadowIntensity != 1) {
  54254. this._defines.OVERLOADEDSHADOWVALUES = true;
  54255. }
  54256. if (this.overloadedMicroSurfaceIntensity > 0 ||
  54257. this.overloadedEmissiveIntensity > 0 ||
  54258. this.overloadedReflectivityIntensity > 0 ||
  54259. this.overloadedAlbedoIntensity > 0 ||
  54260. this.overloadedAmbientIntensity > 0 ||
  54261. this.overloadedReflectionIntensity > 0) {
  54262. this._defines.OVERLOADEDVALUES = true;
  54263. }
  54264. // Point size
  54265. if (this.pointsCloud || scene.forcePointsCloud) {
  54266. this._defines.POINTSIZE = true;
  54267. }
  54268. // Fog
  54269. if (scene.fogEnabled && mesh && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  54270. this._defines.FOG = true;
  54271. }
  54272. if (BABYLON.StandardMaterial.FresnelEnabled) {
  54273. // Fresnel
  54274. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled ||
  54275. this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  54276. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  54277. this._defines.OPACITYFRESNEL = true;
  54278. }
  54279. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  54280. this._defines.EMISSIVEFRESNEL = true;
  54281. }
  54282. needNormals = true;
  54283. this._defines.FRESNEL = true;
  54284. }
  54285. }
  54286. if (this._defines.SPECULARTERM && this.useSpecularOverAlpha) {
  54287. this._defines.SPECULAROVERALPHA = true;
  54288. }
  54289. if (this.usePhysicalLightFalloff) {
  54290. this._defines.USEPHYSICALLIGHTFALLOFF = true;
  54291. }
  54292. if (this.useRadianceOverAlpha) {
  54293. this._defines.RADIANCEOVERALPHA = true;
  54294. }
  54295. if ((this.metallic !== undefined && this.metallic !== null) || (this.roughness !== undefined && this.roughness !== null)) {
  54296. this._defines.METALLICWORKFLOW = true;
  54297. }
  54298. // Attribs
  54299. if (mesh) {
  54300. if (needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  54301. this._defines.NORMAL = true;
  54302. }
  54303. if (needUVs) {
  54304. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  54305. this._defines.UV1 = true;
  54306. }
  54307. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  54308. this._defines.UV2 = true;
  54309. }
  54310. }
  54311. if (mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  54312. this._defines.VERTEXCOLOR = true;
  54313. if (mesh.hasVertexAlpha) {
  54314. this._defines.VERTEXALPHA = true;
  54315. }
  54316. }
  54317. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  54318. this._defines.NUM_BONE_INFLUENCERS = mesh.numBoneInfluencers;
  54319. this._defines.BonesPerMesh = (mesh.skeleton.bones.length + 1);
  54320. }
  54321. // Instances
  54322. if (useInstances) {
  54323. this._defines.INSTANCES = true;
  54324. }
  54325. }
  54326. // Get correct effect
  54327. if (!this._defines.isEqual(this._cachedDefines)) {
  54328. this._defines.cloneTo(this._cachedDefines);
  54329. scene.resetCachedMaterial();
  54330. // Fallbacks
  54331. var fallbacks = new BABYLON.EffectFallbacks();
  54332. if (this._defines.REFLECTION) {
  54333. fallbacks.addFallback(0, "REFLECTION");
  54334. }
  54335. if (this._defines.REFRACTION) {
  54336. fallbacks.addFallback(0, "REFRACTION");
  54337. }
  54338. if (this._defines.REFLECTIVITY) {
  54339. fallbacks.addFallback(0, "REFLECTIVITY");
  54340. }
  54341. if (this._defines.BUMP) {
  54342. fallbacks.addFallback(0, "BUMP");
  54343. }
  54344. if (this._defines.PARALLAX) {
  54345. fallbacks.addFallback(1, "PARALLAX");
  54346. }
  54347. if (this._defines.PARALLAXOCCLUSION) {
  54348. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  54349. }
  54350. if (this._defines.SPECULAROVERALPHA) {
  54351. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  54352. }
  54353. if (this._defines.FOG) {
  54354. fallbacks.addFallback(1, "FOG");
  54355. }
  54356. if (this._defines.POINTSIZE) {
  54357. fallbacks.addFallback(0, "POINTSIZE");
  54358. }
  54359. if (this._defines.LOGARITHMICDEPTH) {
  54360. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  54361. }
  54362. BABYLON.MaterialHelper.HandleFallbacksForShadows(this._defines, fallbacks, this.maxSimultaneousLights);
  54363. if (this._defines.SPECULARTERM) {
  54364. fallbacks.addFallback(0, "SPECULARTERM");
  54365. }
  54366. if (this._defines.OPACITYFRESNEL) {
  54367. fallbacks.addFallback(1, "OPACITYFRESNEL");
  54368. }
  54369. if (this._defines.EMISSIVEFRESNEL) {
  54370. fallbacks.addFallback(2, "EMISSIVEFRESNEL");
  54371. }
  54372. if (this._defines.FRESNEL) {
  54373. fallbacks.addFallback(3, "FRESNEL");
  54374. }
  54375. if (this._defines.NUM_BONE_INFLUENCERS > 0) {
  54376. fallbacks.addCPUSkinningFallback(0, mesh);
  54377. }
  54378. //Attributes
  54379. var attribs = [BABYLON.VertexBuffer.PositionKind];
  54380. if (this._defines.NORMAL) {
  54381. attribs.push(BABYLON.VertexBuffer.NormalKind);
  54382. }
  54383. if (this._defines.UV1) {
  54384. attribs.push(BABYLON.VertexBuffer.UVKind);
  54385. }
  54386. if (this._defines.UV2) {
  54387. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  54388. }
  54389. if (this._defines.VERTEXCOLOR) {
  54390. attribs.push(BABYLON.VertexBuffer.ColorKind);
  54391. }
  54392. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, this._defines, fallbacks);
  54393. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, this._defines);
  54394. // Legacy browser patch
  54395. var join = this._defines.toString();
  54396. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  54397. "vFogInfos", "vFogColor", "pointSize",
  54398. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vReflectivityInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  54399. "mBones",
  54400. "vClipPlane", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  54401. "depthValues",
  54402. "opacityParts", "emissiveLeftColor", "emissiveRightColor",
  54403. "vLightingIntensity", "vOverloadedShadowIntensity", "vOverloadedIntensity", "vOverloadedAlbedo", "vOverloadedReflection", "vOverloadedReflectivity", "vOverloadedEmissive", "vOverloadedMicroSurface",
  54404. "logarithmicDepthConstant",
  54405. "vSphericalX", "vSphericalY", "vSphericalZ",
  54406. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  54407. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  54408. "vMicrosurfaceTextureLods",
  54409. "vCameraInfos"
  54410. ];
  54411. var samplers = ["albedoSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "reflectivitySampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  54412. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  54413. BABYLON.ColorGradingTexture.PrepareUniformsAndSamplers(uniforms, samplers);
  54414. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList(uniforms, samplers, this._defines, this.maxSimultaneousLights);
  54415. this._effect = scene.getEngine().createEffect("pbr", attribs, uniforms, samplers, join, fallbacks, this.onCompiled, this.onError, { maxSimultaneousLights: this.maxSimultaneousLights });
  54416. }
  54417. if (!this._effect.isReady()) {
  54418. return false;
  54419. }
  54420. this._renderId = scene.getRenderId();
  54421. this._wasPreviouslyReady = true;
  54422. if (mesh) {
  54423. if (!mesh._materialDefines) {
  54424. mesh._materialDefines = new PBRMaterialDefines();
  54425. }
  54426. this._defines.cloneTo(mesh._materialDefines);
  54427. }
  54428. return true;
  54429. };
  54430. PBRMaterial.prototype.unbind = function () {
  54431. if (this.reflectionTexture && this.reflectionTexture.isRenderTarget) {
  54432. this._effect.setTexture("reflection2DSampler", null);
  54433. }
  54434. if (this.refractionTexture && this.refractionTexture.isRenderTarget) {
  54435. this._effect.setTexture("refraction2DSampler", null);
  54436. }
  54437. _super.prototype.unbind.call(this);
  54438. };
  54439. PBRMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  54440. this._effect.setMatrix("world", world);
  54441. };
  54442. PBRMaterial.prototype.bind = function (world, mesh) {
  54443. this._myScene = this.getScene();
  54444. // Matrices
  54445. this.bindOnlyWorldMatrix(world);
  54446. // Bones
  54447. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  54448. if (this._myScene.getCachedMaterial() !== this) {
  54449. this._effect.setMatrix("viewProjection", this._myScene.getTransformMatrix());
  54450. if (BABYLON.StandardMaterial.FresnelEnabled) {
  54451. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  54452. this._effect.setColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  54453. }
  54454. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  54455. this._effect.setColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  54456. this._effect.setColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  54457. }
  54458. }
  54459. // Textures
  54460. if (this._myScene.texturesEnabled) {
  54461. if (this.albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  54462. this._effect.setTexture("albedoSampler", this.albedoTexture);
  54463. this._effect.setFloat2("vAlbedoInfos", this.albedoTexture.coordinatesIndex, this.albedoTexture.level);
  54464. this._effect.setMatrix("albedoMatrix", this.albedoTexture.getTextureMatrix());
  54465. }
  54466. if (this.ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  54467. this._effect.setTexture("ambientSampler", this.ambientTexture);
  54468. this._effect.setFloat3("vAmbientInfos", this.ambientTexture.coordinatesIndex, this.ambientTexture.level, this.ambientTextureStrength);
  54469. this._effect.setMatrix("ambientMatrix", this.ambientTexture.getTextureMatrix());
  54470. }
  54471. if (this.opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  54472. this._effect.setTexture("opacitySampler", this.opacityTexture);
  54473. this._effect.setFloat2("vOpacityInfos", this.opacityTexture.coordinatesIndex, this.opacityTexture.level);
  54474. this._effect.setMatrix("opacityMatrix", this.opacityTexture.getTextureMatrix());
  54475. }
  54476. if (this.reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  54477. this._microsurfaceTextureLods.x = Math.round(Math.log(this.reflectionTexture.getSize().width) * Math.LOG2E);
  54478. if (this.reflectionTexture.isCube) {
  54479. this._effect.setTexture("reflectionCubeSampler", this.reflectionTexture);
  54480. }
  54481. else {
  54482. this._effect.setTexture("reflection2DSampler", this.reflectionTexture);
  54483. }
  54484. this._effect.setMatrix("reflectionMatrix", this.reflectionTexture.getReflectionTextureMatrix());
  54485. this._effect.setFloat2("vReflectionInfos", this.reflectionTexture.level, 0);
  54486. if (this._defines.USESPHERICALFROMREFLECTIONMAP) {
  54487. this._effect.setFloat3("vSphericalX", this.reflectionTexture.sphericalPolynomial.x.x, this.reflectionTexture.sphericalPolynomial.x.y, this.reflectionTexture.sphericalPolynomial.x.z);
  54488. this._effect.setFloat3("vSphericalY", this.reflectionTexture.sphericalPolynomial.y.x, this.reflectionTexture.sphericalPolynomial.y.y, this.reflectionTexture.sphericalPolynomial.y.z);
  54489. this._effect.setFloat3("vSphericalZ", this.reflectionTexture.sphericalPolynomial.z.x, this.reflectionTexture.sphericalPolynomial.z.y, this.reflectionTexture.sphericalPolynomial.z.z);
  54490. this._effect.setFloat3("vSphericalXX", this.reflectionTexture.sphericalPolynomial.xx.x, this.reflectionTexture.sphericalPolynomial.xx.y, this.reflectionTexture.sphericalPolynomial.xx.z);
  54491. this._effect.setFloat3("vSphericalYY", this.reflectionTexture.sphericalPolynomial.yy.x, this.reflectionTexture.sphericalPolynomial.yy.y, this.reflectionTexture.sphericalPolynomial.yy.z);
  54492. this._effect.setFloat3("vSphericalZZ", this.reflectionTexture.sphericalPolynomial.zz.x, this.reflectionTexture.sphericalPolynomial.zz.y, this.reflectionTexture.sphericalPolynomial.zz.z);
  54493. this._effect.setFloat3("vSphericalXY", this.reflectionTexture.sphericalPolynomial.xy.x, this.reflectionTexture.sphericalPolynomial.xy.y, this.reflectionTexture.sphericalPolynomial.xy.z);
  54494. this._effect.setFloat3("vSphericalYZ", this.reflectionTexture.sphericalPolynomial.yz.x, this.reflectionTexture.sphericalPolynomial.yz.y, this.reflectionTexture.sphericalPolynomial.yz.z);
  54495. this._effect.setFloat3("vSphericalZX", this.reflectionTexture.sphericalPolynomial.zx.x, this.reflectionTexture.sphericalPolynomial.zx.y, this.reflectionTexture.sphericalPolynomial.zx.z);
  54496. }
  54497. }
  54498. if (this.emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  54499. this._effect.setTexture("emissiveSampler", this.emissiveTexture);
  54500. this._effect.setFloat2("vEmissiveInfos", this.emissiveTexture.coordinatesIndex, this.emissiveTexture.level);
  54501. this._effect.setMatrix("emissiveMatrix", this.emissiveTexture.getTextureMatrix());
  54502. }
  54503. if (this.lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  54504. this._effect.setTexture("lightmapSampler", this.lightmapTexture);
  54505. this._effect.setFloat2("vLightmapInfos", this.lightmapTexture.coordinatesIndex, this.lightmapTexture.level);
  54506. this._effect.setMatrix("lightmapMatrix", this.lightmapTexture.getTextureMatrix());
  54507. }
  54508. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  54509. if (this.metallicTexture) {
  54510. this._effect.setTexture("reflectivitySampler", this.metallicTexture);
  54511. this._effect.setFloat2("vReflectivityInfos", this.metallicTexture.coordinatesIndex, this.metallicTexture.level);
  54512. this._effect.setMatrix("reflectivityMatrix", this.metallicTexture.getTextureMatrix());
  54513. }
  54514. else if (this.reflectivityTexture) {
  54515. this._effect.setTexture("reflectivitySampler", this.reflectivityTexture);
  54516. this._effect.setFloat2("vReflectivityInfos", this.reflectivityTexture.coordinatesIndex, this.reflectivityTexture.level);
  54517. this._effect.setMatrix("reflectivityMatrix", this.reflectivityTexture.getTextureMatrix());
  54518. }
  54519. }
  54520. if (this.bumpTexture && this._myScene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this.disableBumpMap) {
  54521. this._effect.setTexture("bumpSampler", this.bumpTexture);
  54522. this._effect.setFloat3("vBumpInfos", this.bumpTexture.coordinatesIndex, 1.0 / this.bumpTexture.level, this.parallaxScaleBias);
  54523. this._effect.setMatrix("bumpMatrix", this.bumpTexture.getTextureMatrix());
  54524. }
  54525. if (this.refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  54526. this._microsurfaceTextureLods.y = Math.round(Math.log(this.refractionTexture.getSize().width) * Math.LOG2E);
  54527. var depth = 1.0;
  54528. if (this.refractionTexture.isCube) {
  54529. this._effect.setTexture("refractionCubeSampler", this.refractionTexture);
  54530. }
  54531. else {
  54532. this._effect.setTexture("refraction2DSampler", this.refractionTexture);
  54533. this._effect.setMatrix("refractionMatrix", this.refractionTexture.getReflectionTextureMatrix());
  54534. if (this.refractionTexture.depth) {
  54535. depth = this.refractionTexture.depth;
  54536. }
  54537. }
  54538. this._effect.setFloat4("vRefractionInfos", this.refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  54539. }
  54540. if ((this.reflectionTexture || this.refractionTexture)) {
  54541. this._effect.setFloat2("vMicrosurfaceTextureLods", this._microsurfaceTextureLods.x, this._microsurfaceTextureLods.y);
  54542. }
  54543. if (this.cameraColorGradingTexture && BABYLON.StandardMaterial.ColorGradingTextureEnabled) {
  54544. BABYLON.ColorGradingTexture.Bind(this.cameraColorGradingTexture, this._effect);
  54545. }
  54546. }
  54547. // Clip plane
  54548. BABYLON.MaterialHelper.BindClipPlane(this._effect, this._myScene);
  54549. // Point size
  54550. if (this.pointsCloud) {
  54551. this._effect.setFloat("pointSize", this.pointSize);
  54552. }
  54553. // Colors
  54554. this._myScene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  54555. if (this._defines.METALLICWORKFLOW) {
  54556. PBRMaterial._scaledReflectivity.r = this.metallic === undefined ? 1 : this.metallic;
  54557. PBRMaterial._scaledReflectivity.g = this.roughness === undefined ? 1 : this.roughness;
  54558. this._effect.setColor4("vReflectivityColor", PBRMaterial._scaledReflectivity, 0);
  54559. }
  54560. else {
  54561. // GAMMA CORRECTION.
  54562. this.convertColorToLinearSpaceToRef(this.reflectivityColor, PBRMaterial._scaledReflectivity);
  54563. this._effect.setColor4("vReflectivityColor", PBRMaterial._scaledReflectivity, this.microSurface);
  54564. }
  54565. this._effect.setVector3("vEyePosition", this._myScene._mirroredCameraPosition ? this._myScene._mirroredCameraPosition : this._myScene.activeCamera.position);
  54566. this._effect.setColor3("vAmbientColor", this._globalAmbientColor);
  54567. // GAMMA CORRECTION.
  54568. this.convertColorToLinearSpaceToRef(this.emissiveColor, PBRMaterial._scaledEmissive);
  54569. this._effect.setColor3("vEmissiveColor", PBRMaterial._scaledEmissive);
  54570. // GAMMA CORRECTION.
  54571. this.convertColorToLinearSpaceToRef(this.reflectionColor, PBRMaterial._scaledReflection);
  54572. this._effect.setColor3("vReflectionColor", PBRMaterial._scaledReflection);
  54573. }
  54574. if (this._myScene.getCachedMaterial() !== this || !this.isFrozen) {
  54575. // GAMMA CORRECTION.
  54576. this.convertColorToLinearSpaceToRef(this.albedoColor, PBRMaterial._scaledAlbedo);
  54577. this._effect.setColor4("vAlbedoColor", PBRMaterial._scaledAlbedo, this.alpha * mesh.visibility);
  54578. // Lights
  54579. if (this._myScene.lightsEnabled && !this.disableLighting) {
  54580. PBRMaterial.BindLights(this._myScene, mesh, this._effect, this._defines, this.useScalarInLinearSpace, this.maxSimultaneousLights, this.usePhysicalLightFalloff);
  54581. }
  54582. // View
  54583. if (this._myScene.fogEnabled && mesh.applyFog && this._myScene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this.reflectionTexture) {
  54584. this._effect.setMatrix("view", this._myScene.getViewMatrix());
  54585. }
  54586. // Fog
  54587. BABYLON.MaterialHelper.BindFogParameters(this._myScene, mesh, this._effect);
  54588. this._lightingInfos.x = this.directIntensity;
  54589. this._lightingInfos.y = this.emissiveIntensity;
  54590. this._lightingInfos.z = this.environmentIntensity;
  54591. this._lightingInfos.w = this.specularIntensity;
  54592. this._effect.setVector4("vLightingIntensity", this._lightingInfos);
  54593. this._overloadedShadowInfos.x = this.overloadedShadowIntensity;
  54594. this._overloadedShadowInfos.y = this.overloadedShadeIntensity;
  54595. this._effect.setVector4("vOverloadedShadowIntensity", this._overloadedShadowInfos);
  54596. this._cameraInfos.x = this.cameraExposure;
  54597. this._cameraInfos.y = this.cameraContrast;
  54598. this._effect.setVector4("vCameraInfos", this._cameraInfos);
  54599. if (this.cameraColorCurves) {
  54600. BABYLON.ColorCurves.Bind(this.cameraColorCurves, this._effect);
  54601. }
  54602. this._overloadedIntensity.x = this.overloadedAmbientIntensity;
  54603. this._overloadedIntensity.y = this.overloadedAlbedoIntensity;
  54604. this._overloadedIntensity.z = this.overloadedReflectivityIntensity;
  54605. this._overloadedIntensity.w = this.overloadedEmissiveIntensity;
  54606. this._effect.setVector4("vOverloadedIntensity", this._overloadedIntensity);
  54607. this._effect.setColor3("vOverloadedAmbient", this.overloadedAmbient);
  54608. this.convertColorToLinearSpaceToRef(this.overloadedAlbedo, this._tempColor);
  54609. this._effect.setColor3("vOverloadedAlbedo", this._tempColor);
  54610. this.convertColorToLinearSpaceToRef(this.overloadedReflectivity, this._tempColor);
  54611. this._effect.setColor3("vOverloadedReflectivity", this._tempColor);
  54612. this.convertColorToLinearSpaceToRef(this.overloadedEmissive, this._tempColor);
  54613. this._effect.setColor3("vOverloadedEmissive", this._tempColor);
  54614. this.convertColorToLinearSpaceToRef(this.overloadedReflection, this._tempColor);
  54615. this._effect.setColor3("vOverloadedReflection", this._tempColor);
  54616. this._overloadedMicroSurface.x = this.overloadedMicroSurface;
  54617. this._overloadedMicroSurface.y = this.overloadedMicroSurfaceIntensity;
  54618. this._overloadedMicroSurface.z = this.overloadedReflectionIntensity;
  54619. this._effect.setVector3("vOverloadedMicroSurface", this._overloadedMicroSurface);
  54620. // Log. depth
  54621. BABYLON.MaterialHelper.BindLogDepth(this._defines, this._effect, this._myScene);
  54622. }
  54623. _super.prototype.bind.call(this, world, mesh);
  54624. this._myScene = null;
  54625. };
  54626. PBRMaterial.prototype.getAnimatables = function () {
  54627. var results = [];
  54628. if (this.albedoTexture && this.albedoTexture.animations && this.albedoTexture.animations.length > 0) {
  54629. results.push(this.albedoTexture);
  54630. }
  54631. if (this.ambientTexture && this.ambientTexture.animations && this.ambientTexture.animations.length > 0) {
  54632. results.push(this.ambientTexture);
  54633. }
  54634. if (this.opacityTexture && this.opacityTexture.animations && this.opacityTexture.animations.length > 0) {
  54635. results.push(this.opacityTexture);
  54636. }
  54637. if (this.reflectionTexture && this.reflectionTexture.animations && this.reflectionTexture.animations.length > 0) {
  54638. results.push(this.reflectionTexture);
  54639. }
  54640. if (this.emissiveTexture && this.emissiveTexture.animations && this.emissiveTexture.animations.length > 0) {
  54641. results.push(this.emissiveTexture);
  54642. }
  54643. if (this.metallicTexture && this.metallicTexture.animations && this.metallicTexture.animations.length > 0) {
  54644. results.push(this.metallicTexture);
  54645. }
  54646. else if (this.reflectivityTexture && this.reflectivityTexture.animations && this.reflectivityTexture.animations.length > 0) {
  54647. results.push(this.reflectivityTexture);
  54648. }
  54649. if (this.bumpTexture && this.bumpTexture.animations && this.bumpTexture.animations.length > 0) {
  54650. results.push(this.bumpTexture);
  54651. }
  54652. if (this.lightmapTexture && this.lightmapTexture.animations && this.lightmapTexture.animations.length > 0) {
  54653. results.push(this.lightmapTexture);
  54654. }
  54655. if (this.refractionTexture && this.refractionTexture.animations && this.refractionTexture.animations.length > 0) {
  54656. results.push(this.refractionTexture);
  54657. }
  54658. if (this.cameraColorGradingTexture && this.cameraColorGradingTexture.animations && this.cameraColorGradingTexture.animations.length > 0) {
  54659. results.push(this.cameraColorGradingTexture);
  54660. }
  54661. return results;
  54662. };
  54663. PBRMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  54664. if (forceDisposeTextures) {
  54665. if (this.albedoTexture) {
  54666. this.albedoTexture.dispose();
  54667. }
  54668. if (this.ambientTexture) {
  54669. this.ambientTexture.dispose();
  54670. }
  54671. if (this.opacityTexture) {
  54672. this.opacityTexture.dispose();
  54673. }
  54674. if (this.reflectionTexture) {
  54675. this.reflectionTexture.dispose();
  54676. }
  54677. if (this.emissiveTexture) {
  54678. this.emissiveTexture.dispose();
  54679. }
  54680. if (this.metallicTexture) {
  54681. this.metallicTexture.dispose();
  54682. }
  54683. if (this.reflectivityTexture) {
  54684. this.reflectivityTexture.dispose();
  54685. }
  54686. if (this.bumpTexture) {
  54687. this.bumpTexture.dispose();
  54688. }
  54689. if (this.lightmapTexture) {
  54690. this.lightmapTexture.dispose();
  54691. }
  54692. if (this.refractionTexture) {
  54693. this.refractionTexture.dispose();
  54694. }
  54695. if (this.cameraColorGradingTexture) {
  54696. this.cameraColorGradingTexture.dispose();
  54697. }
  54698. }
  54699. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  54700. };
  54701. PBRMaterial.prototype.clone = function (name) {
  54702. var _this = this;
  54703. return BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  54704. };
  54705. PBRMaterial.prototype.serialize = function () {
  54706. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  54707. serializationObject.customType = "BABYLON.PBRMaterial";
  54708. return serializationObject;
  54709. };
  54710. // Statics
  54711. PBRMaterial.Parse = function (source, scene, rootUrl) {
  54712. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  54713. };
  54714. return PBRMaterial;
  54715. }(BABYLON.Material));
  54716. PBRMaterial._scaledAlbedo = new BABYLON.Color3();
  54717. PBRMaterial._scaledReflectivity = new BABYLON.Color3();
  54718. PBRMaterial._scaledEmissive = new BABYLON.Color3();
  54719. PBRMaterial._scaledReflection = new BABYLON.Color3();
  54720. __decorate([
  54721. BABYLON.serialize()
  54722. ], PBRMaterial.prototype, "directIntensity", void 0);
  54723. __decorate([
  54724. BABYLON.serialize()
  54725. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  54726. __decorate([
  54727. BABYLON.serialize()
  54728. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  54729. __decorate([
  54730. BABYLON.serialize()
  54731. ], PBRMaterial.prototype, "specularIntensity", void 0);
  54732. __decorate([
  54733. BABYLON.serialize()
  54734. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  54735. __decorate([
  54736. BABYLON.serialize()
  54737. ], PBRMaterial.prototype, "overloadedShadowIntensity", void 0);
  54738. __decorate([
  54739. BABYLON.serialize()
  54740. ], PBRMaterial.prototype, "overloadedShadeIntensity", void 0);
  54741. __decorate([
  54742. BABYLON.serialize()
  54743. ], PBRMaterial.prototype, "cameraExposure", void 0);
  54744. __decorate([
  54745. BABYLON.serialize()
  54746. ], PBRMaterial.prototype, "cameraContrast", void 0);
  54747. __decorate([
  54748. BABYLON.serializeAsTexture()
  54749. ], PBRMaterial.prototype, "cameraColorGradingTexture", void 0);
  54750. __decorate([
  54751. BABYLON.serializeAsColorCurves()
  54752. ], PBRMaterial.prototype, "cameraColorCurves", void 0);
  54753. __decorate([
  54754. BABYLON.serializeAsColor3()
  54755. ], PBRMaterial.prototype, "overloadedAmbient", void 0);
  54756. __decorate([
  54757. BABYLON.serialize()
  54758. ], PBRMaterial.prototype, "overloadedAmbientIntensity", void 0);
  54759. __decorate([
  54760. BABYLON.serializeAsColor3()
  54761. ], PBRMaterial.prototype, "overloadedAlbedo", void 0);
  54762. __decorate([
  54763. BABYLON.serialize()
  54764. ], PBRMaterial.prototype, "overloadedAlbedoIntensity", void 0);
  54765. __decorate([
  54766. BABYLON.serializeAsColor3()
  54767. ], PBRMaterial.prototype, "overloadedReflectivity", void 0);
  54768. __decorate([
  54769. BABYLON.serialize()
  54770. ], PBRMaterial.prototype, "overloadedReflectivityIntensity", void 0);
  54771. __decorate([
  54772. BABYLON.serializeAsColor3()
  54773. ], PBRMaterial.prototype, "overloadedEmissive", void 0);
  54774. __decorate([
  54775. BABYLON.serialize()
  54776. ], PBRMaterial.prototype, "overloadedEmissiveIntensity", void 0);
  54777. __decorate([
  54778. BABYLON.serializeAsColor3()
  54779. ], PBRMaterial.prototype, "overloadedReflection", void 0);
  54780. __decorate([
  54781. BABYLON.serialize()
  54782. ], PBRMaterial.prototype, "overloadedReflectionIntensity", void 0);
  54783. __decorate([
  54784. BABYLON.serialize()
  54785. ], PBRMaterial.prototype, "overloadedMicroSurface", void 0);
  54786. __decorate([
  54787. BABYLON.serialize()
  54788. ], PBRMaterial.prototype, "overloadedMicroSurfaceIntensity", void 0);
  54789. __decorate([
  54790. BABYLON.serializeAsTexture()
  54791. ], PBRMaterial.prototype, "albedoTexture", void 0);
  54792. __decorate([
  54793. BABYLON.serializeAsTexture()
  54794. ], PBRMaterial.prototype, "ambientTexture", void 0);
  54795. __decorate([
  54796. BABYLON.serialize()
  54797. ], PBRMaterial.prototype, "ambientTextureStrength", void 0);
  54798. __decorate([
  54799. BABYLON.serializeAsTexture()
  54800. ], PBRMaterial.prototype, "opacityTexture", void 0);
  54801. __decorate([
  54802. BABYLON.serializeAsTexture()
  54803. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  54804. __decorate([
  54805. BABYLON.serializeAsTexture()
  54806. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  54807. __decorate([
  54808. BABYLON.serializeAsTexture()
  54809. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  54810. __decorate([
  54811. BABYLON.serializeAsTexture()
  54812. ], PBRMaterial.prototype, "metallicTexture", void 0);
  54813. __decorate([
  54814. BABYLON.serialize()
  54815. ], PBRMaterial.prototype, "metallic", void 0);
  54816. __decorate([
  54817. BABYLON.serialize()
  54818. ], PBRMaterial.prototype, "roughness", void 0);
  54819. __decorate([
  54820. BABYLON.serializeAsTexture()
  54821. ], PBRMaterial.prototype, "bumpTexture", void 0);
  54822. __decorate([
  54823. BABYLON.serializeAsTexture()
  54824. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  54825. __decorate([
  54826. BABYLON.serializeAsTexture()
  54827. ], PBRMaterial.prototype, "refractionTexture", void 0);
  54828. __decorate([
  54829. BABYLON.serializeAsColor3("ambient")
  54830. ], PBRMaterial.prototype, "ambientColor", void 0);
  54831. __decorate([
  54832. BABYLON.serializeAsColor3("albedo")
  54833. ], PBRMaterial.prototype, "albedoColor", void 0);
  54834. __decorate([
  54835. BABYLON.serializeAsColor3("reflectivity")
  54836. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  54837. __decorate([
  54838. BABYLON.serializeAsColor3("reflection")
  54839. ], PBRMaterial.prototype, "reflectionColor", void 0);
  54840. __decorate([
  54841. BABYLON.serializeAsColor3("emissive")
  54842. ], PBRMaterial.prototype, "emissiveColor", void 0);
  54843. __decorate([
  54844. BABYLON.serialize()
  54845. ], PBRMaterial.prototype, "microSurface", void 0);
  54846. __decorate([
  54847. BABYLON.serialize()
  54848. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  54849. __decorate([
  54850. BABYLON.serialize()
  54851. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  54852. __decorate([
  54853. BABYLON.serializeAsFresnelParameters()
  54854. ], PBRMaterial.prototype, "opacityFresnelParameters", void 0);
  54855. __decorate([
  54856. BABYLON.serializeAsFresnelParameters()
  54857. ], PBRMaterial.prototype, "emissiveFresnelParameters", void 0);
  54858. __decorate([
  54859. BABYLON.serialize()
  54860. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  54861. __decorate([
  54862. BABYLON.serialize()
  54863. ], PBRMaterial.prototype, "linkEmissiveWithAlbedo", void 0);
  54864. __decorate([
  54865. BABYLON.serialize()
  54866. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  54867. __decorate([
  54868. BABYLON.serialize()
  54869. ], PBRMaterial.prototype, "useEmissiveAsIllumination", void 0);
  54870. __decorate([
  54871. BABYLON.serialize()
  54872. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  54873. __decorate([
  54874. BABYLON.serialize()
  54875. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  54876. __decorate([
  54877. BABYLON.serialize()
  54878. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  54879. __decorate([
  54880. BABYLON.serialize()
  54881. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureAlpha", void 0);
  54882. __decorate([
  54883. BABYLON.serialize()
  54884. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureGreen", void 0);
  54885. __decorate([
  54886. BABYLON.serialize()
  54887. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  54888. __decorate([
  54889. BABYLON.serialize()
  54890. ], PBRMaterial.prototype, "useScalarInLinearSpace", void 0);
  54891. __decorate([
  54892. BABYLON.serialize()
  54893. ], PBRMaterial.prototype, "usePhysicalLightFalloff", void 0);
  54894. __decorate([
  54895. BABYLON.serialize()
  54896. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  54897. __decorate([
  54898. BABYLON.serialize()
  54899. ], PBRMaterial.prototype, "useParallax", void 0);
  54900. __decorate([
  54901. BABYLON.serialize()
  54902. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  54903. __decorate([
  54904. BABYLON.serialize()
  54905. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  54906. __decorate([
  54907. BABYLON.serialize()
  54908. ], PBRMaterial.prototype, "disableLighting", void 0);
  54909. __decorate([
  54910. BABYLON.serialize()
  54911. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  54912. __decorate([
  54913. BABYLON.serialize()
  54914. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  54915. __decorate([
  54916. BABYLON.serialize()
  54917. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  54918. __decorate([
  54919. BABYLON.serialize()
  54920. ], PBRMaterial.prototype, "useLogarithmicDepth", null);
  54921. BABYLON.PBRMaterial = PBRMaterial;
  54922. })(BABYLON || (BABYLON = {}));
  54923. //# sourceMappingURL=babylon.pbrMaterial.js.map
  54924. var BABYLON;
  54925. (function (BABYLON) {
  54926. var DebugLayer = (function () {
  54927. function DebugLayer(scene) {
  54928. this._scene = scene;
  54929. }
  54930. /** Creates the inspector window. */
  54931. DebugLayer.prototype._createInspector = function (popup) {
  54932. if (!this._inspector) {
  54933. this._inspector = new INSPECTOR.Inspector(this._scene, popup);
  54934. } // else nothing to do,; instance is already existing
  54935. };
  54936. DebugLayer.prototype.isVisible = function () {
  54937. return false;
  54938. };
  54939. DebugLayer.prototype.hide = function () {
  54940. if (this._inspector) {
  54941. this._inspector.dispose();
  54942. this._inspector = null;
  54943. }
  54944. };
  54945. DebugLayer.prototype.show = function (popup) {
  54946. if (typeof INSPECTOR == 'undefined') {
  54947. // Load inspector and add it to the DOM
  54948. BABYLON.Tools.LoadScript(DebugLayer.InspectorURL, this._createInspector.bind(this, popup));
  54949. }
  54950. else {
  54951. // Otherwise creates the inspector
  54952. this._createInspector(popup);
  54953. }
  54954. };
  54955. return DebugLayer;
  54956. }());
  54957. DebugLayer.InspectorURL = 'http://www.babylonjs.com/babylon.inspector.bundle.js';
  54958. BABYLON.DebugLayer = DebugLayer;
  54959. })(BABYLON || (BABYLON = {}));
  54960. //# sourceMappingURL=babylon.debugLayer.js.map
  54961. var BABYLON;
  54962. (function (BABYLON) {
  54963. var StandardRenderingPipeline = (function (_super) {
  54964. __extends(StandardRenderingPipeline, _super);
  54965. /**
  54966. * @constructor
  54967. * @param {string} name - The rendering pipeline name
  54968. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  54969. * @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)
  54970. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  54971. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  54972. */
  54973. function StandardRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  54974. if (originalPostProcess === void 0) { originalPostProcess = null; }
  54975. var _this = _super.call(this, scene.getEngine(), name) || this;
  54976. _this.downSampleX4PostProcess = null;
  54977. _this.brightPassPostProcess = null;
  54978. _this.gaussianBlurHPostProcesses = [];
  54979. _this.gaussianBlurVPostProcesses = [];
  54980. _this.textureAdderPostProcess = null;
  54981. _this.textureAdderFinalPostProcess = null;
  54982. _this.lensFlarePostProcess = null;
  54983. _this.lensFlareComposePostProcess = null;
  54984. _this.depthOfFieldPostProcess = null;
  54985. // Values
  54986. _this.brightThreshold = 1.0;
  54987. _this.blurWidth = 2.0;
  54988. _this.gaussianCoefficient = 0.25;
  54989. _this.gaussianMean = 1.0;
  54990. _this.gaussianStandardDeviation = 1.0;
  54991. _this.exposure = 1.0;
  54992. _this.lensTexture = null;
  54993. _this.lensColorTexture = null;
  54994. _this.lensFlareStrength = 20.0;
  54995. _this.lensFlareGhostDispersal = 1.4;
  54996. _this.lensFlareHaloWidth = 0.7;
  54997. _this.lensFlareDistortionStrength = 16.0;
  54998. _this.lensStarTexture = null;
  54999. _this.lensFlareDirtTexture = null;
  55000. _this.depthOfFieldDistance = 10.0;
  55001. // IAnimatable
  55002. _this.animations = [];
  55003. _this._depthRenderer = null;
  55004. // Getters and setters
  55005. _this._depthOfFieldEnabled = true;
  55006. _this._lensFlareEnabled = true;
  55007. // Initialize
  55008. _this._scene = scene;
  55009. // Create pass post-processe
  55010. if (!originalPostProcess) {
  55011. _this.originalPostProcess = new BABYLON.PostProcess("HDRPass", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), true, "#define PASS_POST_PROCESS", BABYLON.Engine.TEXTURETYPE_FLOAT);
  55012. }
  55013. else {
  55014. _this.originalPostProcess = originalPostProcess;
  55015. }
  55016. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this.originalPostProcess; }, true));
  55017. // Create down sample X4 post-process
  55018. _this._createDownSampleX4PostProcess(scene, ratio / 2);
  55019. // Create bright pass post-process
  55020. _this._createBrightPassPostProcess(scene, ratio / 2);
  55021. // Create gaussian blur post-processes (down sampling blurs)
  55022. _this._createGaussianBlurPostProcesses(scene, ratio / 2, 0);
  55023. _this._createGaussianBlurPostProcesses(scene, ratio / 4, 1);
  55024. _this._createGaussianBlurPostProcesses(scene, ratio / 8, 2);
  55025. _this._createGaussianBlurPostProcesses(scene, ratio / 16, 3);
  55026. // Create texture adder post-process
  55027. _this._createTextureAdderPostProcess(scene, ratio);
  55028. // Create depth-of-field source post-process
  55029. _this.textureAdderFinalPostProcess = new BABYLON.PostProcess("HDRDepthOfFieldSource", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), true, "#define PASS_POST_PROCESS", BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  55030. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfFieldSource", function () { return _this.textureAdderFinalPostProcess; }, true));
  55031. // Create lens flare post-process
  55032. _this._createLensFlarePostProcess(scene, ratio);
  55033. // Create gaussian blur used by depth-of-field
  55034. _this._createGaussianBlurPostProcesses(scene, ratio / 2, 5);
  55035. // Create depth-of-field post-process
  55036. _this._createDepthOfFieldPostProcess(scene, ratio);
  55037. // Finish
  55038. scene.postProcessRenderPipelineManager.addPipeline(_this);
  55039. if (cameras !== null) {
  55040. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  55041. }
  55042. // Deactivate
  55043. _this.LensFlareEnabled = false;
  55044. _this.DepthOfFieldEnabled = false;
  55045. return _this;
  55046. }
  55047. Object.defineProperty(StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", {
  55048. get: function () {
  55049. return this._depthOfFieldEnabled;
  55050. },
  55051. set: function (enabled) {
  55052. var blurIndex = this.gaussianBlurHPostProcesses.length - 1;
  55053. if (enabled && !this._depthOfFieldEnabled) {
  55054. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRGaussianBlurH" + blurIndex, this._scene.cameras);
  55055. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRGaussianBlurV" + blurIndex, this._scene.cameras);
  55056. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRDepthOfField", this._scene.cameras);
  55057. this._depthRenderer = this._scene.enableDepthRenderer();
  55058. }
  55059. else if (!enabled && this._depthOfFieldEnabled) {
  55060. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRGaussianBlurH" + blurIndex, this._scene.cameras);
  55061. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRGaussianBlurV" + blurIndex, this._scene.cameras);
  55062. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRDepthOfField", this._scene.cameras);
  55063. }
  55064. this._depthOfFieldEnabled = enabled;
  55065. },
  55066. enumerable: true,
  55067. configurable: true
  55068. });
  55069. Object.defineProperty(StandardRenderingPipeline.prototype, "LensFlareEnabled", {
  55070. get: function () {
  55071. return this._lensFlareEnabled;
  55072. },
  55073. set: function (enabled) {
  55074. var blurIndex = this.gaussianBlurHPostProcesses.length - 2;
  55075. if (enabled && !this._lensFlareEnabled) {
  55076. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRLensFlare", this._scene.cameras);
  55077. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRLensFlareShift", this._scene.cameras);
  55078. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRGaussianBlurH" + blurIndex, this._scene.cameras);
  55079. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRGaussianBlurV" + blurIndex, this._scene.cameras);
  55080. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRLensFlareCompose", this._scene.cameras);
  55081. }
  55082. else if (!enabled && this._lensFlareEnabled) {
  55083. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRLensFlare", this._scene.cameras);
  55084. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRLensFlareShift", this._scene.cameras);
  55085. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRGaussianBlurH" + blurIndex, this._scene.cameras);
  55086. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRGaussianBlurV" + blurIndex, this._scene.cameras);
  55087. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRLensFlareCompose", this._scene.cameras);
  55088. }
  55089. this._lensFlareEnabled = enabled;
  55090. },
  55091. enumerable: true,
  55092. configurable: true
  55093. });
  55094. // Down Sample X4 Post-Processs
  55095. StandardRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  55096. var _this = this;
  55097. var downSampleX4Offsets = new Array(32);
  55098. 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);
  55099. this.downSampleX4PostProcess.onApply = function (effect) {
  55100. var id = 0;
  55101. for (var i = -2; i < 2; i++) {
  55102. for (var j = -2; j < 2; j++) {
  55103. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / _this.downSampleX4PostProcess.width);
  55104. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / _this.downSampleX4PostProcess.height);
  55105. id += 2;
  55106. }
  55107. }
  55108. effect.setArray2("dsOffsets", downSampleX4Offsets);
  55109. };
  55110. // Add to pipeline
  55111. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this.downSampleX4PostProcess; }, true));
  55112. };
  55113. // Brightpass Post-Process
  55114. StandardRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  55115. var _this = this;
  55116. var brightOffsets = new Array(8);
  55117. 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);
  55118. this.brightPassPostProcess.onApply = function (effect) {
  55119. var sU = (1.0 / _this.brightPassPostProcess.width);
  55120. var sV = (1.0 / _this.brightPassPostProcess.height);
  55121. brightOffsets[0] = -0.5 * sU;
  55122. brightOffsets[1] = 0.5 * sV;
  55123. brightOffsets[2] = 0.5 * sU;
  55124. brightOffsets[3] = 0.5 * sV;
  55125. brightOffsets[4] = -0.5 * sU;
  55126. brightOffsets[5] = -0.5 * sV;
  55127. brightOffsets[6] = 0.5 * sU;
  55128. brightOffsets[7] = -0.5 * sV;
  55129. effect.setArray2("dsOffsets", brightOffsets);
  55130. effect.setFloat("brightThreshold", _this.brightThreshold);
  55131. };
  55132. // Add to pipeline
  55133. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this.brightPassPostProcess; }, true));
  55134. };
  55135. // Create gaussian blur H&V post-processes
  55136. StandardRenderingPipeline.prototype._createGaussianBlurPostProcesses = function (scene, ratio, indice) {
  55137. var _this = this;
  55138. var blurOffsets = new Array(9);
  55139. var blurWeights = new Array(9);
  55140. var uniforms = ["blurOffsets", "blurWeights", "blurWidth"];
  55141. var callback = function (height) {
  55142. return function (effect) {
  55143. // Weights
  55144. var x = 0.0;
  55145. for (var i = 0; i < 9; i++) {
  55146. x = (i - 4.0) / 4.0;
  55147. blurWeights[i] =
  55148. _this.gaussianCoefficient
  55149. * (1.0 / Math.sqrt(2.0 * Math.PI * _this.gaussianStandardDeviation))
  55150. * Math.exp((-((x - _this.gaussianMean) * (x - _this.gaussianMean))) / (2.0 * _this.gaussianStandardDeviation * _this.gaussianStandardDeviation));
  55151. }
  55152. var lastOutputDimensions = {
  55153. width: scene.getEngine().getRenderWidth(),
  55154. height: scene.getEngine().getRenderHeight()
  55155. };
  55156. for (var i = 0; i < 9; i++) {
  55157. var value = (i - 4.0) * (1.0 / (height === true ? lastOutputDimensions.height : lastOutputDimensions.width));
  55158. blurOffsets[i] = value;
  55159. }
  55160. effect.setArray("blurOffsets", blurOffsets);
  55161. effect.setArray("blurWeights", blurWeights);
  55162. effect.setFloat("blurWidth", _this.blurWidth);
  55163. };
  55164. };
  55165. // Create horizontal gaussian blur post-processes
  55166. var gaussianBlurHPostProcess = new BABYLON.PostProcess("HDRGaussianBlurH" + ratio, "standard", uniforms, [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define GAUSSIAN_BLUR_H", BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  55167. gaussianBlurHPostProcess.onApply = callback(false);
  55168. // Create vertical gaussian blur post-process
  55169. var gaussianBlurVPostProcess = new BABYLON.PostProcess("HDRGaussianBlurV" + ratio, "standard", uniforms, [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define GAUSSIAN_BLUR_V", BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  55170. gaussianBlurVPostProcess.onApply = callback(true);
  55171. // Add to pipeline
  55172. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurH" + indice, function () { return gaussianBlurHPostProcess; }, true));
  55173. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurV" + indice, function () { return gaussianBlurVPostProcess; }, true));
  55174. // Finish
  55175. this.gaussianBlurHPostProcesses.push(gaussianBlurHPostProcess);
  55176. this.gaussianBlurVPostProcesses.push(gaussianBlurVPostProcess);
  55177. };
  55178. // Create texture adder post-process
  55179. StandardRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  55180. var _this = this;
  55181. var lastGaussianBlurPostProcess = this.gaussianBlurVPostProcesses[3];
  55182. 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);
  55183. this.textureAdderPostProcess.onApply = function (effect) {
  55184. effect.setTextureFromPostProcess("otherSampler", _this.originalPostProcess);
  55185. effect.setTexture("lensSampler", _this.lensTexture);
  55186. effect.setFloat("exposure", _this.exposure);
  55187. };
  55188. // Add to pipeline
  55189. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this.textureAdderPostProcess; }, true));
  55190. };
  55191. // Create lens flare post-process
  55192. StandardRenderingPipeline.prototype._createLensFlarePostProcess = function (scene, ratio) {
  55193. var _this = this;
  55194. this.lensFlarePostProcess = new BABYLON.PostProcess("HDRLensFlare", "standard", ["strength", "ghostDispersal", "haloWidth", "resolution", "distortionStrength"], ["lensColorSampler"], ratio / 2, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), true, "#define LENS_FLARE", BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  55195. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlare", function () { return _this.lensFlarePostProcess; }, false));
  55196. this._createGaussianBlurPostProcesses(scene, ratio / 4, 4);
  55197. 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);
  55198. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlareCompose", function () { return _this.lensFlareComposePostProcess; }, false));
  55199. var resolution = new BABYLON.Vector2(0, 0);
  55200. // Lens flare
  55201. this.lensFlarePostProcess.onApply = function (effect) {
  55202. effect.setTextureFromPostProcess("textureSampler", _this.gaussianBlurHPostProcesses[0]);
  55203. effect.setTexture("lensColorSampler", _this.lensColorTexture);
  55204. effect.setFloat("strength", _this.lensFlareStrength);
  55205. effect.setFloat("ghostDispersal", _this.lensFlareGhostDispersal);
  55206. effect.setFloat("haloWidth", _this.lensFlareHaloWidth);
  55207. // Shift
  55208. resolution.x = _this.lensFlarePostProcess.width;
  55209. resolution.y = _this.lensFlarePostProcess.height;
  55210. effect.setVector2("resolution", resolution);
  55211. effect.setFloat("distortionStrength", _this.lensFlareDistortionStrength);
  55212. };
  55213. // Compose
  55214. 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);
  55215. 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);
  55216. this.lensFlareComposePostProcess.onApply = function (effect) {
  55217. effect.setTextureFromPostProcess("otherSampler", _this.textureAdderFinalPostProcess);
  55218. effect.setTexture("lensDirtSampler", _this.lensFlareDirtTexture);
  55219. effect.setTexture("lensStarSampler", _this.lensStarTexture);
  55220. // Lens start rotation matrix
  55221. var camerax = _this._scene.activeCamera.getViewMatrix().getRow(0);
  55222. var cameraz = _this._scene.activeCamera.getViewMatrix().getRow(2);
  55223. 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));
  55224. camRot *= 4.0;
  55225. 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);
  55226. var lensStarMatrix = scaleBias2.multiply(starRotation).multiply(scaleBias1);
  55227. effect.setMatrix("lensStarMatrix", lensStarMatrix);
  55228. };
  55229. };
  55230. // Create depth-of-field post-process
  55231. StandardRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (scene, ratio) {
  55232. var _this = this;
  55233. 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);
  55234. this.depthOfFieldPostProcess.onApply = function (effect) {
  55235. effect.setTextureFromPostProcess("otherSampler", _this.textureAdderFinalPostProcess);
  55236. effect.setTexture("depthSampler", _this._depthRenderer.getDepthMap());
  55237. effect.setFloat("distance", _this.depthOfFieldDistance);
  55238. };
  55239. // Add to pipeline
  55240. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfField", function () { return _this.depthOfFieldPostProcess; }, true));
  55241. };
  55242. // Dispose
  55243. StandardRenderingPipeline.prototype.dispose = function () {
  55244. for (var i = 0; i < this._scene.cameras.length; i++) {
  55245. var camera = this._scene.cameras[i];
  55246. this.originalPostProcess.dispose(camera);
  55247. this.downSampleX4PostProcess.dispose(camera);
  55248. this.brightPassPostProcess.dispose(camera);
  55249. this.textureAdderPostProcess.dispose(camera);
  55250. for (var j = 0; j < this.gaussianBlurHPostProcesses.length; j++) {
  55251. this.gaussianBlurHPostProcesses[j].dispose(camera);
  55252. }
  55253. for (var j = 0; j < this.gaussianBlurVPostProcesses.length; j++) {
  55254. this.gaussianBlurVPostProcesses[j].dispose(camera);
  55255. }
  55256. this.textureAdderFinalPostProcess.dispose(camera);
  55257. this.lensFlarePostProcess.dispose(camera);
  55258. this.lensFlareComposePostProcess.dispose(camera);
  55259. this.depthOfFieldPostProcess.dispose(camera);
  55260. }
  55261. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  55262. _super.prototype.dispose.call(this);
  55263. };
  55264. return StandardRenderingPipeline;
  55265. }(BABYLON.PostProcessRenderPipeline));
  55266. BABYLON.StandardRenderingPipeline = StandardRenderingPipeline;
  55267. })(BABYLON || (BABYLON = {}));
  55268. //# sourceMappingURL=babylon.standardRenderingPipeline.js.map
  55269. BABYLON.Effect.ShadersStore={"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}","blackAndWhitePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nvoid main(void) \n{\nfloat luminance=dot(texture2D(textureSampler,vUV).rgb,vec3(0.3,0.59,0.11));\ngl_FragColor=vec4(luminance,luminance,luminance,1.0);\n}","blurPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nuniform vec2 direction;\nuniform float blurWidth;\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{\nbaseColor+=texture2D(textureSampler,start+texelOffset)*weights[i];\ntexelOffset+=texelStep;\n}\ngl_FragColor=baseColor;\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}","colorPixelShader":"uniform vec4 color;\nvoid main(void) {\ngl_FragColor=color;\n}","colorVertexShader":"\nattribute vec3 position;\n\nuniform mat4 worldViewProjection;\nvoid main(void) {\ngl_Position=worldViewProjection*vec4(position,1.0);\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}","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}","defaultPixelShader":"#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;\nuniform vec4 vDiffuseColor;\n#ifdef SPECULARTERM\nuniform vec4 vSpecularColor;\n#endif\nuniform vec3 vEmissiveColor;\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<lightFragmentDeclaration>[0..maxSimultaneousLights]\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;\nuniform sampler2D diffuseSampler;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform sampler2D ambientSampler;\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY \nvarying vec2 vOpacityUV;\nuniform sampler2D opacitySampler;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform vec2 vEmissiveInfos;\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\nvarying vec2 vLightmapUV;\nuniform vec2 vLightmapInfos;\nuniform sampler2D lightmapSampler;\n#endif\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\n#ifdef REFRACTIONMAP_3D\nuniform samplerCube refractionCubeSampler;\n#else\nuniform sampler2D refraction2DSampler;\nuniform mat4 refractionMatrix;\n#endif\n#ifdef REFRACTIONFRESNEL\nuniform vec4 refractionLeftColor;\nuniform vec4 refractionRightColor;\n#endif\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nvarying vec2 vSpecularUV;\nuniform vec2 vSpecularInfos;\nuniform sampler2D specularSampler;\n#endif\n\n#include<fresnelFunction>\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_3D\nuniform samplerCube reflectionCubeSampler;\n#else\nuniform sampler2D reflection2DSampler;\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR_FIXED\nvarying vec3 vDirectionW;\n#endif\n#if defined(REFLECTIONMAP_PLANAR) || defined(REFLECTIONMAP_CUBIC) || defined(REFLECTIONMAP_PROJECTION)\nuniform mat4 reflectionMatrix;\n#endif\n#endif\n#include<reflectionFunction>\n#ifdef REFLECTIONFRESNEL\nuniform vec4 reflectionLeftColor;\nuniform vec4 reflectionRightColor;\n#endif\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 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#else\nvec3 finalSpecular=vec3(0.0);\n#endif\n#ifdef SPECULAROVERALPHA\nalpha=clamp(alpha+dot(finalSpecular,vec3(0.3,0.59,0.11)),0.,1.);\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}","defaultVertexShader":"\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\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>\nuniform mat4 view;\nuniform mat4 viewProjection;\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform mat4 ambientMatrix;\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY\nvarying vec2 vOpacityUV;\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#ifdef LIGHTMAP\nvarying vec2 vLightmapUV;\nuniform vec2 vLightmapInfos;\nuniform mat4 lightmapMatrix;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nvarying vec2 vSpecularUV;\nuniform vec2 vSpecularInfos;\nuniform mat4 specularMatrix;\n#endif\n#ifdef BUMP\nvarying vec2 vBumpUV;\nuniform vec3 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n#include<pointCloudVertexDeclaration>\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<shadowsVertexDeclaration>[0..maxSimultaneousLights]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR_FIXED\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=position;\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvec4 worldPos=finalWorld*vec4(position,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nvNormalW=normalize(vec3(finalWorld*vec4(normal,0.0)));\n#endif\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR_FIXED\nvDirectionW=normalize(vec3(finalWorld*vec4(position,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<clipPlaneVertex>\n#include<fogVertex>\n#include<shadowsVertex>[0..maxSimultaneousLights]\n#ifdef VERTEXCOLOR\n\nvColor=color;\n#endif\n#include<pointCloudVertex>\n#include<logDepthVertex>\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}","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}","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}","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","displayPassPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D passSampler;\nvoid main(void)\n{\ngl_FragColor=texture2D(passSampler,vUV);\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":"#define FXAA_REDUCE_MIN (1.0/128.0)\n#define FXAA_REDUCE_MUL (1.0/8.0)\n#define FXAA_SPAN_MAX 8.0\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 texelSize;\nvoid main(){\nvec2 localTexelSize=texelSize;\nvec4 rgbNW=texture2D(textureSampler,(vUV+vec2(-1.0,-1.0)*localTexelSize));\nvec4 rgbNE=texture2D(textureSampler,(vUV+vec2(1.0,-1.0)*localTexelSize));\nvec4 rgbSW=texture2D(textureSampler,(vUV+vec2(-1.0,1.0)*localTexelSize));\nvec4 rgbSE=texture2D(textureSampler,(vUV+vec2(1.0,1.0)*localTexelSize));\nvec4 rgbM=texture2D(textureSampler,vUV);\nvec4 luma=vec4(0.299,0.587,0.114,1.0);\nfloat lumaNW=dot(rgbNW,luma);\nfloat lumaNE=dot(rgbNE,luma);\nfloat lumaSW=dot(rgbSW,luma);\nfloat lumaSE=dot(rgbSE,luma);\nfloat lumaM=dot(rgbM,luma);\nfloat lumaMin=min(lumaM,min(min(lumaNW,lumaNE),min(lumaSW,lumaSE)));\nfloat lumaMax=max(lumaM,max(max(lumaNW,lumaNE),max(lumaSW,lumaSE)));\nvec2 dir=vec2(-((lumaNW+lumaNE)-(lumaSW+lumaSE)),((lumaNW+lumaSW)-(lumaNE+lumaSE)));\nfloat dirReduce=max(\n(lumaNW+lumaNE+lumaSW+lumaSE)*(0.25*FXAA_REDUCE_MUL),\nFXAA_REDUCE_MIN);\nfloat rcpDirMin=1.0/(min(abs(dir.x),abs(dir.y))+dirReduce);\ndir=min(vec2(FXAA_SPAN_MAX,FXAA_SPAN_MAX),\nmax(vec2(-FXAA_SPAN_MAX,-FXAA_SPAN_MAX),\ndir*rcpDirMin))*localTexelSize;\nvec4 rgbA=0.5*(\ntexture2D(textureSampler,vUV+dir*(1.0/3.0-0.5)) +\ntexture2D(textureSampler,vUV+dir*(2.0/3.0-0.5)));\nvec4 rgbB=rgbA*0.5+0.25*(\ntexture2D(textureSampler,vUV+dir*-0.5) +\ntexture2D(textureSampler,vUV+dir*0.5));\nfloat lumaB=dot(rgbB,luma);\nif ((lumaB<lumaMin) || (lumaB>lumaMax)) {\ngl_FragColor=rgbA;\n}\nelse {\ngl_FragColor=rgbB;\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}","hdrPixelShader":"uniform sampler2D textureSampler;\nvarying vec2 vUV;\n#if defined(GAUSSIAN_BLUR_H) || defined(GAUSSIAN_BLUR_V)\nuniform float blurOffsets[9];\nuniform float blurWeights[9];\nuniform float multiplier;\nvoid main(void) {\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]*multiplier,0.0))*blurWeights[i]);\n#else\ncolor+=(texture2D(textureSampler,vUV+vec2(0.0,blurOffsets[i]*multiplier))*blurWeights[i]);\n#endif\n}\ncolor.a=1.0;\ngl_FragColor=color;\n}\n#endif\n#if defined(TEXTURE_ADDER)\nuniform sampler2D otherSampler;\nvoid main() {\nvec4 sum=texture2D(textureSampler,vUV)+texture2D(otherSampler,vUV);\nsum.a=clamp(sum.a,0.0,1.0);\ngl_FragColor=sum;\n}\n#endif\n#if defined(LUMINANCE_GENERATOR)\nuniform vec2 lumOffsets[4];\nvoid main() {\nfloat average=0.0;\nvec4 color=vec4(0.0,0.0,0.0,0.0);\nfloat maximum=-1e20;\nfor (int i=0; i<4; i++) {\ncolor=texture2D(textureSampler,vUV+lumOffsets[i]);\nfloat GreyValue=length(color.rgb);\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(DOWN_SAMPLE)\nuniform vec2 dsOffsets[9];\nuniform float halfDestPixelSize;\n#ifdef FINAL_DOWN_SAMPLE\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() {\nvec4 color=vec4(0.0,0.0,0.0,0.0);\nfloat average=0.0;\nfor (int i=0; i<9; i++) {\ncolor=texture2D(textureSampler,vUV+vec2(halfDestPixelSize,halfDestPixelSize)+dsOffsets[i]);\naverage+=color.r;\n}\naverage/=9.0;\n#ifndef FINAL_DOWN_SAMPLE\ngl_FragColor=vec4(average,average,0.0,1.0);\n#else\ngl_FragColor=pack(average);\n#endif\n}\n#endif\n#if defined(BRIGHT_PASS)\nuniform vec2 dsOffsets[4];\nuniform float brightThreshold;\nvoid main() {\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(DOWN_SAMPLE_X4)\nuniform vec2 dsOffsets[16];\nvoid main() {\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(HDR)\nuniform sampler2D otherSampler;\nuniform float exposure;\nuniform float avgLuminance;\nvoid main() {\nvec4 color=texture2D(textureSampler,vUV)+texture2D(otherSampler,vUV);\nvec4 adjustedColor=color/avgLuminance*exposure;\ncolor=adjustedColor;\ncolor.a=1.0;\ngl_FragColor=color;\n}\n#endif\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}","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}","lensFlarePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\ngl_FragColor=baseColor*color;\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}","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}","linePixelShader":"uniform vec4 color;\nvoid main(void) {\ngl_FragColor=color;\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}","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}","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","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}","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}","passPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nvoid main(void) \n{\ngl_FragColor=texture2D(textureSampler,vUV);\n}","pbrPixelShader":"#ifdef BUMP\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;\nuniform vec3 vEyePosition;\nuniform vec3 vAmbientColor;\nuniform vec3 vReflectionColor;\nuniform vec4 vAlbedoColor;\n\nuniform vec4 vLightingIntensity;\nuniform vec4 vCameraInfos;\n#ifdef OVERLOADEDVALUES\nuniform vec4 vOverloadedIntensity;\nuniform vec3 vOverloadedAmbient;\nuniform vec3 vOverloadedAlbedo;\nuniform vec3 vOverloadedReflectivity;\nuniform vec3 vOverloadedEmissive;\nuniform vec3 vOverloadedReflection;\nuniform vec3 vOverloadedMicroSurface;\n#endif\n#ifdef OVERLOADEDSHADOWVALUES\nuniform vec4 vOverloadedShadowIntensity;\n#endif\n#if defined(REFLECTION) || defined(REFRACTION)\nuniform vec2 vMicrosurfaceTextureLods;\n#endif\nuniform vec4 vReflectivityColor;\nuniform vec3 vEmissiveColor;\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n#include<lightFragmentDeclaration>[0..maxSimultaneousLights]\n\n#ifdef ALBEDO\nvarying vec2 vAlbedoUV;\nuniform sampler2D albedoSampler;\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform sampler2D ambientSampler;\nuniform vec3 vAmbientInfos;\n#endif\n#ifdef OPACITY \nvarying vec2 vOpacityUV;\nuniform sampler2D opacitySampler;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform vec2 vEmissiveInfos;\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\nvarying vec2 vLightmapUV;\nuniform vec2 vLightmapInfos;\nuniform sampler2D lightmapSampler;\n#endif\n#if defined(REFLECTIVITY) || defined(METALLICWORKFLOW) \nvarying vec2 vReflectivityUV;\nuniform vec2 vReflectivityInfos;\nuniform sampler2D reflectivitySampler;\n#endif\n\n#include<fresnelFunction>\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\nuniform samplerCube refractionCubeSampler;\n#else\nuniform sampler2D refraction2DSampler;\nuniform mat4 refractionMatrix;\n#endif\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\n#ifdef REFLECTIONMAP_3D\nuniform samplerCube reflectionCubeSampler;\n#else\nuniform sampler2D reflection2DSampler;\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR_FIXED\nvarying vec3 vDirectionW;\n#endif\n#if defined(REFLECTIONMAP_PLANAR) || defined(REFLECTIONMAP_CUBIC) || defined(REFLECTIONMAP_PROJECTION)\nuniform mat4 reflectionMatrix;\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<pbrShadowFunctions>\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=vec3(1.0,1.0,1.0);\n#endif\n#include<bumpFragment>\n\nvec4 surfaceAlbedo=vec4(1.,1.,1.,1.);\nvec3 surfaceAlbedoContribution=vAlbedoColor.rgb;\n\nfloat alpha=vAlbedoColor.a;\n#ifdef ALBEDO\nsurfaceAlbedo=texture2D(albedoSampler,vAlbedoUV+uvOffset);\nsurfaceAlbedo=vec4(toLinearSpace(surfaceAlbedo.rgb),surfaceAlbedo.a);\n#ifndef LINKREFRACTIONTOTRANSPARENCY\n#ifdef ALPHATEST\nif (surfaceAlbedo.a<0.4)\ndiscard;\n#endif\n#endif\n#ifdef ALPHAFROMALBEDO\nalpha*=surfaceAlbedo.a;\n#endif\nsurfaceAlbedo.rgb*=vAlbedoInfos.y;\n#else\n\nsurfaceAlbedo.rgb=surfaceAlbedoContribution;\nsurfaceAlbedoContribution=vec3(1.,1.,1.);\n#endif\n#ifdef VERTEXCOLOR\nsurfaceAlbedo.rgb*=vColor.rgb;\n#endif\n#ifdef OVERLOADEDVALUES\nsurfaceAlbedo.rgb=mix(surfaceAlbedo.rgb,vOverloadedAlbedo,vOverloadedIntensity.y);\n#endif\n\nvec3 ambientColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nambientColor=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y;\nambientColor=vec3(1.,1.,1.)-((vec3(1.,1.,1.)-ambientColor)*vAmbientInfos.z);\n#ifdef OVERLOADEDVALUES\nambientColor.rgb=mix(ambientColor.rgb,vOverloadedAmbient,vOverloadedIntensity.x);\n#endif\n#endif\n\nfloat microSurface=vReflectivityColor.a;\nvec3 surfaceReflectivityColor=vReflectivityColor.rgb;\n#ifdef OVERLOADEDVALUES\nsurfaceReflectivityColor.rgb=mix(surfaceReflectivityColor.rgb,vOverloadedReflectivity,vOverloadedIntensity.z);\n#endif\n#ifdef REFLECTIVITY\nvec4 surfaceReflectivityColorMap=texture2D(reflectivitySampler,vReflectivityUV+uvOffset);\nsurfaceReflectivityColor=surfaceReflectivityColorMap.rgb;\nsurfaceReflectivityColor=toLinearSpace(surfaceReflectivityColor);\n#ifdef OVERLOADEDVALUES\nsurfaceReflectivityColor=mix(surfaceReflectivityColor,vOverloadedReflectivity,vOverloadedIntensity.z);\n#endif\n#ifdef MICROSURFACEFROMREFLECTIVITYMAP\nmicroSurface=surfaceReflectivityColorMap.a;\n#else\n#ifdef MICROSURFACEAUTOMATIC\nmicroSurface=computeDefaultMicroSurface(microSurface,surfaceReflectivityColor);\n#endif\n#endif\n#endif\n#ifdef METALLICWORKFLOW\nvec2 metallicRoughness=surfaceReflectivityColor.rg;\n#ifdef METALLICROUGHNESSMAP\nvec4 surfaceMetallicColorMap=texture2D(reflectivitySampler,vReflectivityUV+uvOffset);\n\nmetallicRoughness.r*=surfaceMetallicColorMap.r;\n#ifdef METALLICROUGHNESSGSTOREINALPHA\nmetallicRoughness.g*=surfaceMetallicColorMap.a;\n#else\n#ifdef METALLICROUGHNESSGSTOREINGREEN\nmetallicRoughness.g*=surfaceMetallicColorMap.g;\n#endif\n#endif\n#endif\n\nvec3 baseColor=surfaceAlbedo.rgb;\n\nsurfaceAlbedo.rgb*=(1.0-metallicRoughness.r);\n\n\nconst vec3 DefaultSpecularReflectanceDielectric=vec3(0.04,0.04,0.04);\n\nsurfaceReflectivityColor=mix(DefaultSpecularReflectanceDielectric,baseColor,metallicRoughness.r);\n#ifdef OVERLOADEDVALUES\nsurfaceReflectivityColor=mix(surfaceReflectivityColor,vOverloadedReflectivity,vOverloadedIntensity.z);\n#endif\nmicroSurface=1.0-metallicRoughness.g;\n#endif\n#ifdef OVERLOADEDVALUES\nmicroSurface=mix(microSurface,vOverloadedMicroSurface.x,vOverloadedMicroSurface.y);\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\nvec3 lightDiffuseContribution=vec3(0.,0.,0.);\n#ifdef OVERLOADEDSHADOWVALUES\nvec3 shadowedOnlyLightDiffuseContribution=vec3(1.,1.,1.);\n#endif\n#ifdef SPECULARTERM\nvec3 lightSpecularContribution=vec3(0.,0.,0.);\n#endif\nfloat notShadowLevel=1.; \n#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset).rgb*vLightmapInfos.y;\n#endif\nfloat NdotL=-1.;\nlightingInfo info;\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#include<pbrLightFunctionsCall>[0..maxSimultaneousLights]\n#ifdef SPECULARTERM\nlightSpecularContribution*=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\n#ifdef OVERLOADEDVALUES\nenvironmentIrradiance=mix(environmentIrradiance,vOverloadedReflection,vOverloadedMicroSurface.z);\nenvironmentRadiance=mix(environmentRadiance,vOverloadedReflection,vOverloadedMicroSurface.z);\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=surfaceAlbedoContribution.rgb*surfaceAlbedo.rgb;\nfloat maxChannel=max(max(mixedAlbedo.r,mixedAlbedo.g),mixedAlbedo.b);\nvec3 tint=clamp(maxChannel*mixedAlbedo,0.0,1.0);\n\nsurfaceAlbedoContribution*=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 OVERLOADEDVALUES\nsurfaceEmissiveColor=mix(surfaceEmissiveColor,vOverloadedEmissive,vOverloadedIntensity.w);\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\n#ifdef EMISSIVEASILLUMINATION\nvec3 finalDiffuse=max(lightDiffuseContribution*surfaceAlbedoContribution+vAmbientColor,0.0)*surfaceAlbedo.rgb;\n#ifdef OVERLOADEDSHADOWVALUES\nshadowedOnlyLightDiffuseContribution=max(shadowedOnlyLightDiffuseContribution*surfaceAlbedoContribution+vAmbientColor,0.0)*surfaceAlbedo.rgb;\n#endif\n#else\n#ifdef LINKEMISSIVEWITHALBEDO\nvec3 finalDiffuse=max((lightDiffuseContribution+surfaceEmissiveColor)*surfaceAlbedoContribution+vAmbientColor,0.0)*surfaceAlbedo.rgb;\n#ifdef OVERLOADEDSHADOWVALUES\nshadowedOnlyLightDiffuseContribution=max((shadowedOnlyLightDiffuseContribution+surfaceEmissiveColor)*surfaceAlbedoContribution+vAmbientColor,0.0)*surfaceAlbedo.rgb;\n#endif\n#else\nvec3 finalDiffuse=max(lightDiffuseContribution*surfaceAlbedoContribution+surfaceEmissiveColor+vAmbientColor,0.0)*surfaceAlbedo.rgb;\n#ifdef OVERLOADEDSHADOWVALUES\nshadowedOnlyLightDiffuseContribution=max(shadowedOnlyLightDiffuseContribution*surfaceAlbedoContribution+surfaceEmissiveColor+vAmbientColor,0.0)*surfaceAlbedo.rgb;\n#endif\n#endif\n#endif\n#ifdef OVERLOADEDSHADOWVALUES\nfinalDiffuse=mix(finalDiffuse,shadowedOnlyLightDiffuseContribution,(1.0-vOverloadedShadowIntensity.y));\n#endif\n#ifdef SPECULARTERM\nvec3 finalSpecular=lightSpecularContribution*surfaceReflectivityColor;\n#else\nvec3 finalSpecular=vec3(0.0);\n#endif\n#ifdef SPECULAROVERALPHA\nalpha=clamp(alpha+getLuminance(finalSpecular),0.,1.);\n#endif\n#ifdef RADIANCEOVERALPHA\nalpha=clamp(alpha+getLuminance(environmentRadiance),0.,1.);\n#endif\n\n\n#ifdef EMISSIVEASILLUMINATION\nvec4 finalColor=vec4(finalDiffuse*ambientColor*vLightingIntensity.x+surfaceAlbedo.rgb*environmentIrradiance+finalSpecular*vLightingIntensity.x+environmentRadiance+surfaceEmissiveColor*vLightingIntensity.y+refractance,alpha);\n#else\nvec4 finalColor=vec4(finalDiffuse*ambientColor*vLightingIntensity.x+surfaceAlbedo.rgb*environmentIrradiance+finalSpecular*vLightingIntensity.x+environmentRadiance+refractance,alpha);\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\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\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\ngl_FragColor=finalColor;\n}","pbrVertexShader":"precision highp float;\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\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>\nuniform mat4 view;\nuniform mat4 viewProjection;\n#ifdef ALBEDO\nvarying vec2 vAlbedoUV;\nuniform mat4 albedoMatrix;\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform mat4 ambientMatrix;\nuniform vec3 vAmbientInfos;\n#endif\n#ifdef OPACITY\nvarying vec2 vOpacityUV;\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#ifdef LIGHTMAP\nvarying vec2 vLightmapUV;\nuniform vec2 vLightmapInfos;\nuniform mat4 lightmapMatrix;\n#endif\n#if defined(REFLECTIVITY) || defined(METALLICWORKFLOW) \nvarying vec2 vReflectivityUV;\nuniform vec2 vReflectivityInfos;\nuniform mat4 reflectivityMatrix;\n#endif\n#ifdef BUMP\nvarying vec2 vBumpUV;\nuniform vec3 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<shadowsVertexDeclaration>[0..maxSimultaneousLights]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR_FIXED\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=position;\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvec4 worldPos=finalWorld*vec4(position,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nvNormalW=normalize(vec3(finalWorld*vec4(normal,0.0)));\n#endif\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR_FIXED\nvDirectionW=normalize(vec3(finalWorld*vec4(position,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 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<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}","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}","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}","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}","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\nvec2 packHalf(float depth) \n{ \nconst vec2 bitOffset=vec2(1.0/255.,0.);\nvec2 color=vec2(depth,fract(depth*255.));\nreturn color-(color.yy*bitOffset);\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\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\n#ifdef VSM\nfloat moment1=depth;\nfloat moment2=moment1*moment1;\n#ifndef FULLFLOAT\ngl_FragColor=vec4(packHalf(moment1),packHalf(moment2));\n#else\ngl_FragColor=vec4(moment1,moment2,1.0,1.0);\n#endif\n#else\n#ifndef FULLFLOAT\ngl_FragColor=pack(depth);\n#else\ngl_FragColor=vec4(depth,1.0,1.0,1.0);\n#endif\n#endif\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}","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}","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\nfFogDistance=abs(viewPos.z);\n#endif\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","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","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(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","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}","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}","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","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}"};
  55270. 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","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","bumpFragment":"vec2 uvOffset=vec2(0.0,0.0);\n#if defined(BUMP) || defined(PARALLAX)\nmat3 TBN=cotangent_frame(normalW*vBumpInfos.y,-viewDirectionW,vBumpUV);\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(viewDirectionW,TBN,vBumpUV+uvOffset);\n#endif","bumpFragmentFunctions":"#ifdef BUMP\nvarying vec2 vBumpUV;\nuniform vec3 vBumpInfos;\nuniform sampler2D bumpSampler;\n\nmat3 cotangent_frame(vec3 normal,vec3 p,vec2 uv)\n{\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\nfloat invmax=inversesqrt(max(dot(tangent,tangent),dot(binormal,binormal)));\nreturn mat3(tangent*invmax,binormal*invmax,normal);\n}\nvec3 perturbNormal(vec3 viewDir,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","clipPlaneFragment":"#ifdef CLIPPLANE\nif (fClipDistance>0.0)\n{\ndiscard;\n}\n#endif","clipPlaneFragmentDeclaration":"#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif","clipPlaneVertex":"#ifdef CLIPPLANE\nfClipDistance=dot(worldPos,vClipPlane);\n#endif","clipPlaneVertexDeclaration":"#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nvarying float fClipDistance;\n#endif","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}","colorCurvesDefinition":"uniform vec4 vCameraColorCurveNeutral;\nuniform vec4 vCameraColorCurvePositive;\nuniform vec4 vCameraColorCurveNegative;","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}","colorGradingDefinition":"uniform sampler2D cameraColorGrading2DSampler;\nuniform vec4 vCameraColorGradingInfos;\nuniform vec4 vCameraColorGradingScaleOffset;","fogFragment":"#ifdef FOG\nfloat fog=CalcFogFactor();\ncolor.rgb=fog*color.rgb+(1.0-fog)*vFogColor;\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 float fFogDistance;\nfloat CalcFogFactor()\n{\nfloat fogCoeff=1.0;\nfloat fogStart=vFogInfos.y;\nfloat fogEnd=vFogInfos.z;\nfloat fogDensity=vFogInfos.w;\nif (FOGMODE_LINEAR == vFogInfos.x)\n{\nfogCoeff=(fogEnd-fFogDistance)/(fogEnd-fogStart);\n}\nelse if (FOGMODE_EXP == vFogInfos.x)\n{\nfogCoeff=1.0/pow(E,fFogDistance*fogDensity);\n}\nelse if (FOGMODE_EXP2 == vFogInfos.x)\n{\nfogCoeff=1.0/pow(E,fFogDistance*fFogDistance*fogDensity*fogDensity);\n}\nreturn clamp(fogCoeff,0.0,1.0);\n}\n#endif","fogVertex":"#ifdef FOG\nfFogDistance=abs((view*worldPos).z);\n#endif","fogVertexDeclaration":"#ifdef FOG\nvarying float fFogDistance;\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","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","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}","instancesDeclaration":"#ifdef INSTANCES\nattribute vec4 world0;\nattribute vec4 world1;\nattribute vec4 world2;\nattribute vec4 world3;\n#else\nuniform mat4 world;\n#endif","instancesVertex":"#ifdef INSTANCES\nmat4 finalWorld=mat4(world0,world1,world2,world3);\n#else\nmat4 finalWorld=world;\n#endif","lightFragment":"#ifdef LIGHT{X}\n#if defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X}) && defined(LIGHTMAPNOSPECULAR{X})\n\n#else\n#ifndef SPECULARTERM\nvec3 vLightSpecular{X}=vec3(0.);\n#endif\n#ifdef SPOTLIGHT{X}\ninfo=computeSpotLighting(viewDirectionW,normalW,vLightData{X},vLightDirection{X},vLightDiffuse{X}.rgb,vLightSpecular{X},vLightDiffuse{X}.a,glossiness);\n#endif\n#ifdef HEMILIGHT{X}\ninfo=computeHemisphericLighting(viewDirectionW,normalW,vLightData{X},vLightDiffuse{X}.rgb,vLightSpecular{X},vLightGround{X},glossiness);\n#endif\n#if defined(POINTLIGHT{X}) || defined(DIRLIGHT{X})\ninfo=computeLighting(viewDirectionW,normalW,vLightData{X},vLightDiffuse{X}.rgb,vLightSpecular{X},vLightDiffuse{X}.a,glossiness);\n#endif\n#endif\n#ifdef SHADOW{X}\n#ifdef SHADOWVSM{X}\nshadow=computeShadowWithVSM(vPositionFromLight{X},shadowSampler{X},shadowsInfo{X}.z,shadowsInfo{X}.x);\n#else\n#ifdef SHADOWPCF{X}\n#if defined(POINTLIGHT{X})\nshadow=computeShadowWithPCFCube(vLightData{X}.xyz,shadowSampler{X},shadowsInfo{X}.y,shadowsInfo{X}.z,shadowsInfo{X}.x);\n#else\nshadow=computeShadowWithPCF(vPositionFromLight{X},shadowSampler{X},shadowsInfo{X}.y,shadowsInfo{X}.z,shadowsInfo{X}.x);\n#endif\n#else\n#if defined(POINTLIGHT{X})\nshadow=computeShadowCube(vLightData{X}.xyz,shadowSampler{X},shadowsInfo{X}.x,shadowsInfo{X}.z);\n#else\nshadow=computeShadow(vPositionFromLight{X},shadowSampler{X},shadowsInfo{X}.x,shadowsInfo{X}.z);\n#endif\n#endif\n#endif\n#else\nshadow=1.;\n#endif\n#if 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","lightFragmentDeclaration":"#ifdef LIGHT{X}\nuniform vec4 vLightData{X};\nuniform vec4 vLightDiffuse{X};\n#ifdef SPECULARTERM\nuniform vec3 vLightSpecular{X};\n#endif\n#ifdef SHADOW{X}\n#if defined(SPOTLIGHT{X}) || defined(DIRLIGHT{X})\nvarying vec4 vPositionFromLight{X};\nuniform sampler2D shadowSampler{X};\n#else\nuniform samplerCube 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};\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));\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,-lightDirection.xyz));\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW-lightDirection.xyz);\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\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;\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","logDepthDeclaration":"#ifdef LOGARITHMICDEPTH\nuniform float logarithmicDepthConstant;\nvarying float vFragmentDepth;\n#endif","logDepthFragment":"#ifdef LOGARITHMICDEPTH\ngl_FragDepthEXT=log2(vFragmentDepth)*logarithmicDepthConstant*0.5;\n#endif","logDepthVertex":"#ifdef LOGARITHMICDEPTH\nvFragmentDepth=1.0+gl_Position.w;\ngl_Position.z=log2(max(0.000001,vFragmentDepth))*logarithmicDepthConstant;\n#endif","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","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-lightDirection.xyz);\nNdotL=max(0.00000000001,dot(vNormal,-lightDirection.xyz));\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}","pbrLightFunctionsCall":"#ifdef LIGHT{X}\n#if defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X}) && defined(LIGHTMAPNOSPECULAR{X})\n\n#else\n#ifndef SPECULARTERM\nvec3 vLightSpecular{X}=vec3(0.0);\n#endif\n#ifdef SPOTLIGHT{X}\ninfo=computeSpotLighting(viewDirectionW,normalW,vLightData{X},vLightDirection{X},vLightDiffuse{X}.rgb,vLightSpecular{X},vLightDiffuse{X}.a,roughness,NdotV,specularEnvironmentR90,NdotL);\n#endif\n#ifdef HEMILIGHT{X}\ninfo=computeHemisphericLighting(viewDirectionW,normalW,vLightData{X},vLightDiffuse{X}.rgb,vLightSpecular{X},vLightGround{X},roughness,NdotV,specularEnvironmentR90,NdotL);\n#endif\n#if defined(POINTLIGHT{X}) || defined(DIRLIGHT{X})\ninfo=computeLighting(viewDirectionW,normalW,vLightData{X},vLightDiffuse{X}.rgb,vLightSpecular{X},vLightDiffuse{X}.a,roughness,NdotV,specularEnvironmentR90,NdotL);\n#endif\n#endif\n#ifdef SHADOW{X}\n#ifdef SHADOWVSM{X}\nnotShadowLevel=computeShadowWithVSM(vPositionFromLight{X},shadowSampler{X},shadowsInfo{X}.z,shadowsInfo{X}.x);\n#else\n#ifdef SHADOWPCF{X}\n#if defined(POINTLIGHT{X})\nnotShadowLevel=computeShadowWithPCFCube(vLightData{X}.xyz,shadowSampler{X},shadowsInfo{X}.y,shadowsInfo{X}.z,shadowsInfo{X}.x);\n#else\nnotShadowLevel=computeShadowWithPCF(vPositionFromLight{X},shadowSampler{X},shadowsInfo{X}.y,shadowsInfo{X}.z,shadowsInfo{X}.x);\n#endif\n#else\n#if defined(POINTLIGHT{X})\nnotShadowLevel=computeShadowCube(vLightData{X}.xyz,shadowSampler{X},shadowsInfo{X}.x,shadowsInfo{X}.z);\n#else\nnotShadowLevel=computeShadow(vPositionFromLight{X},shadowSampler{X},shadowsInfo{X}.x,shadowsInfo{X}.z);\n#endif\n#endif\n#endif\n#else\nnotShadowLevel=1.;\n#endif\n#if defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X})\nlightDiffuseContribution+=lightmapColor*notShadowLevel;\n#ifdef SPECULARTERM\n#ifndef LIGHTMAPNOSPECULAR{X}\nlightSpecularContribution+=info.specular*notShadowLevel*lightmapColor;\n#endif\n#endif\n#else\nlightDiffuseContribution+=info.diffuse*notShadowLevel;\n#ifdef OVERLOADEDSHADOWVALUES\nif (NdotL<0.000000000011)\n{\nnotShadowLevel=1.;\n}\nshadowedOnlyLightDiffuseContribution*=notShadowLevel;\n#endif\n#ifdef SPECULARTERM\nlightSpecularContribution+=info.specular*notShadowLevel;\n#endif\n#endif\n#endif","pbrShadowFunctions":"\n#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,float bias)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y =-directionToLight.y;\n#ifndef SHADOWFULLFLOAT\nfloat shadow=unpack(textureCube(shadowSampler,directionToLight))+bias;\n#else\nfloat shadow=textureCube(shadowSampler,directionToLight).x+bias;\n#endif\nif (depth>shadow)\n{\n#ifdef OVERLOADEDSHADOWVALUES\nreturn mix(1.0,darkness,vOverloadedShadowIntensity.x);\n#else\nreturn darkness;\n#endif\n}\nreturn 1.0;\n}\nfloat computeShadowWithPCFCube(vec3 lightPosition,samplerCube shadowSampler,float mapSize,float bias,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\nfloat biasedDepth=depth-bias;\n#ifndef SHADOWFULLFLOAT\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize))<biasedDepth) visibility-=0.25;\n#else\nif (textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize).x<biasedDepth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize).x<biasedDepth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize).x<biasedDepth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize).x<biasedDepth) visibility-=0.25;\n#endif\n#ifdef OVERLOADEDSHADOWVALUES\nreturn min(1.0,mix(1.0,visibility+darkness,vOverloadedShadowIntensity.x));\n#else\nreturn min(1.0,visibility+darkness);\n#endif\n}\nfloat computeShadow(vec4 vPositionFromLight,sampler2D shadowSampler,float darkness,float bias)\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))+bias;\n#else\nfloat shadow=texture2D(shadowSampler,uv).x+bias;\n#endif\nif (depth.z>shadow)\n{\n#ifdef OVERLOADEDSHADOWVALUES\nreturn mix(1.0,darkness,vOverloadedShadowIntensity.x);\n#else\nreturn darkness;\n#endif\n}\nreturn 1.;\n}\nfloat computeShadowWithPCF(vec4 vPositionFromLight,sampler2D shadowSampler,float mapSize,float bias,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\nfloat biasedDepth=depth.z-bias;\n#ifndef SHADOWFULLFLOAT\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[0]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[1]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[2]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[3]*mapSize))<biasedDepth) visibility-=0.25;\n#else\nif (texture2D(shadowSampler,uv+poissonDisk[0]*mapSize).x<biasedDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[1]*mapSize).x<biasedDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[2]*mapSize).x<biasedDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[3]*mapSize).x<biasedDepth) visibility-=0.25;\n#endif\n#ifdef OVERLOADEDSHADOWVALUES\nreturn min(1.0,mix(1.0,visibility+darkness,vOverloadedShadowIntensity.x));\n#else\nreturn min(1.0,visibility+darkness);\n#endif\n}\n#ifndef SHADOWFULLFLOAT\n\nfloat unpackHalf(vec2 color)\n{\nreturn color.x+(color.y/255.0);\n}\n#endif\nfloat linstep(float low,float high,float v) {\nreturn clamp((v-low)/(high-low),0.0,1.0);\n}\nfloat ChebychevInequality(vec2 moments,float compare,float bias)\n{\nfloat p=smoothstep(compare-bias,compare,moments.x);\nfloat variance=max(moments.y-moments.x*moments.x,0.02);\nfloat d=compare-moments.x;\nfloat p_max=linstep(0.2,1.0,variance/(variance+d*d));\nreturn clamp(max(p,p_max),0.0,1.0);\n}\nfloat computeShadowWithVSM(vec4 vPositionFromLight,sampler2D shadowSampler,float bias,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 || depth.z>=1.0)\n{\nreturn 1.0;\n}\nvec4 texel=texture2D(shadowSampler,uv);\n#ifndef SHADOWFULLFLOAT\nvec2 moments=vec2(unpackHalf(texel.xy),unpackHalf(texel.zw));\n#else\nvec2 moments=texel.xy;\n#endif\n#ifdef OVERLOADEDSHADOWVALUES\nreturn min(1.0,mix(1.0,1.0-ChebychevInequality(moments,depth.z,bias)+darkness,vOverloadedShadowIntensity.x));\n#else\nreturn min(1.0,1.0-ChebychevInequality(moments,depth.z,bias)+darkness);\n#endif\n}\n#endif","pointCloudVertex":"#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif","pointCloudVertexDeclaration":"#ifdef POINTSIZE\nuniform float pointSize;\n#endif","reflectionFunction":"vec3 computeReflectionCoords(vec4 worldPos,vec3 worldNormal)\n{\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR_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;\nreturn vec3(s,t,0);\n#endif\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR\nvec3 cameraToVertex=normalize(worldPos.xyz-vEyePosition);\nvec3 r=reflect(cameraToVertex,worldNormal);\nfloat t=clamp(r.y*-0.5+0.5,0.,1.0);\nfloat s=atan(r.z,r.x)*RECIPROCAL_PI2+0.5;\nreturn vec3(s,t,0);\n#endif\n#ifdef REFLECTIONMAP_SPHERICAL\nvec3 viewDir=normalize(vec3(view*worldPos));\nvec3 viewNormal=normalize(vec3(view*vec4(worldNormal,0.0)));\nvec3 r=reflect(viewDir,viewNormal);\nr.z=r.z-1.0;\nfloat m=2.0*length(r);\nreturn vec3(r.x/m+0.5,1.0-r.y/m-0.5,0);\n#endif\n#ifdef REFLECTIONMAP_PLANAR\nvec3 viewDir=worldPos.xyz-vEyePosition;\nvec3 coords=normalize(reflect(viewDir,worldNormal));\nreturn vec3(reflectionMatrix*vec4(coords,1));\n#endif\n#ifdef REFLECTIONMAP_CUBIC\nvec3 viewDir=worldPos.xyz-vEyePosition;\nvec3 coords=reflect(viewDir,worldNormal);\n#ifdef INVERTCUBICMAP\ncoords.y=1.0-coords.y;\n#endif\nreturn vec3(reflectionMatrix*vec4(coords,0));\n#endif\n#ifdef REFLECTIONMAP_PROJECTION\nreturn vec3(reflectionMatrix*(view*worldPos));\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nreturn vPositionUVW;\n#endif\n#ifdef REFLECTIONMAP_EXPLICIT\nreturn vec3(0,0,0);\n#endif\n}","shadowsFragmentFunctions":"#ifdef SHADOWS\n#ifndef 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,float bias)\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))+bias;\n#else\nfloat shadow=textureCube(shadowSampler,directionToLight).x+bias;\n#endif\nif (depth>shadow)\n{\nreturn darkness;\n}\nreturn 1.0;\n}\nfloat computeShadowWithPCFCube(vec3 lightPosition,samplerCube shadowSampler,float mapSize,float bias,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\nfloat biasedDepth=depth-bias;\n#ifndef SHADOWFULLFLOAT\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize))<biasedDepth) visibility-=0.25;\n#else\nif (textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize).x<biasedDepth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize).x<biasedDepth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize).x<biasedDepth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize).x<biasedDepth) visibility-=0.25;\n#endif\nreturn min(1.0,visibility+darkness);\n}\nfloat computeShadow(vec4 vPositionFromLight,sampler2D shadowSampler,float darkness,float bias)\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))+bias;\n#else\nfloat shadow=texture2D(shadowSampler,uv).x+bias;\n#endif\nif (depth.z>shadow)\n{\nreturn darkness;\n}\nreturn 1.;\n}\nfloat computeShadowWithPCF(vec4 vPositionFromLight,sampler2D shadowSampler,float mapSize,float bias,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\nfloat biasedDepth=depth.z-bias;\n#ifndef SHADOWFULLFLOAT\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[0]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[1]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[2]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[3]*mapSize))<biasedDepth) visibility-=0.25;\n#else\nif (texture2D(shadowSampler,uv+poissonDisk[0]*mapSize).x<biasedDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[1]*mapSize).x<biasedDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[2]*mapSize).x<biasedDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[3]*mapSize).x<biasedDepth) visibility-=0.25;\n#endif\nreturn min(1.0,visibility+darkness);\n}\n#ifndef SHADOWFULLFLOAT\n\nfloat unpackHalf(vec2 color)\n{\nreturn color.x+(color.y/255.0);\n}\n#endif\nfloat linstep(float low,float high,float v) {\nreturn clamp((v-low)/(high-low),0.0,1.0);\n}\nfloat ChebychevInequality(vec2 moments,float compare,float bias)\n{\nfloat p=smoothstep(compare-bias,compare,moments.x);\nfloat variance=max(moments.y-moments.x*moments.x,0.02);\nfloat d=compare-moments.x;\nfloat p_max=linstep(0.2,1.0,variance/(variance+d*d));\nreturn clamp(max(p,p_max),0.0,1.0);\n}\nfloat computeShadowWithVSM(vec4 vPositionFromLight,sampler2D shadowSampler,float bias,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 || depth.z>=1.0)\n{\nreturn 1.0;\n}\nvec4 texel=texture2D(shadowSampler,uv);\n#ifndef SHADOWFULLFLOAT\nvec2 moments=vec2(unpackHalf(texel.xy),unpackHalf(texel.zw));\n#else\nvec2 moments=texel.xy;\n#endif\nreturn min(1.0,1.0-ChebychevInequality(moments,depth.z,bias)+darkness);\n}\n#endif","shadowsVertex":"#ifdef SHADOWS\n#if defined(SPOTLIGHT{X}) || defined(DIRLIGHT{X})\nvPositionFromLight{X}=lightMatrix{X}*worldPos;\n#endif\n#endif","shadowsVertexDeclaration":"#ifdef SHADOWS\n#if defined(SPOTLIGHT{X}) || defined(DIRLIGHT{X})\nuniform mat4 lightMatrix{X};\nvarying vec4 vPositionFromLight{X};\n#endif\n#endif\n"};
  55271. BABYLON.CollisionWorker="var BABYLON;!function(t){var e=function(t,e,o,i){return!(t.x>o.x+i)&&(!(o.x-i>e.x)&&(!(t.y>o.y+i)&&(!(o.y-i>e.y)&&(!(t.z>o.z+i)&&!(o.z-i>e.z)))))},o=function(){var t={root:0,found:!1};return function(e,o,i,s){t.root=0,t.found=!1;var r=o*o-4*e*i;if(r<0)return t;var n=Math.sqrt(r),c=(-o-n)/(2*e),h=(-o+n)/(2*e);if(c>h){var a=h;h=c,c=a}return c>0&&c<s?(t.root=c,t.found=!0,t):h>0&&h<s?(t.root=h,t.found=!0,t):t}}(),i=function(){function i(){this.radius=new t.Vector3(1,1,1),this.retry=0,this.basePointWorld=t.Vector3.Zero(),this.velocityWorld=t.Vector3.Zero(),this.normalizedVelocity=t.Vector3.Zero(),this._collisionPoint=t.Vector3.Zero(),this._planeIntersectionPoint=t.Vector3.Zero(),this._tempVector=t.Vector3.Zero(),this._tempVector2=t.Vector3.Zero(),this._tempVector3=t.Vector3.Zero(),this._tempVector4=t.Vector3.Zero(),this._edge=t.Vector3.Zero(),this._baseToVertex=t.Vector3.Zero(),this._destinationPoint=t.Vector3.Zero(),this._slidePlaneNormal=t.Vector3.Zero(),this._displacementVector=t.Vector3.Zero()}return i.prototype._initialize=function(e,o,i){this.velocity=o,t.Vector3.NormalizeToRef(o,this.normalizedVelocity),this.basePoint=e,e.multiplyToRef(this.radius,this.basePointWorld),o.multiplyToRef(this.radius,this.velocityWorld),this.velocityWorldLength=this.velocityWorld.length(),this.epsilon=i,this.collisionFound=!1},i.prototype._checkPointInTriangle=function(e,o,i,s,r){o.subtractToRef(e,this._tempVector),i.subtractToRef(e,this._tempVector2),t.Vector3.CrossToRef(this._tempVector,this._tempVector2,this._tempVector4);var n=t.Vector3.Dot(this._tempVector4,r);return!(n<0)&&(s.subtractToRef(e,this._tempVector3),t.Vector3.CrossToRef(this._tempVector2,this._tempVector3,this._tempVector4),n=t.Vector3.Dot(this._tempVector4,r),!(n<0)&&(t.Vector3.CrossToRef(this._tempVector3,this._tempVector,this._tempVector4),n=t.Vector3.Dot(this._tempVector4,r),n>=0))},i.prototype._canDoCollision=function(o,i,s,r){var n=t.Vector3.Distance(this.basePointWorld,o),c=Math.max(this.radius.x,this.radius.y,this.radius.z);return!(n>this.velocityWorldLength+c+i)&&!!e(s,r,this.basePointWorld,this.velocityWorldLength+c)},i.prototype._testTriangle=function(e,i,s,r,n,c){var h,a=!1;i||(i=[]),i[e]||(i[e]=new t.Plane(0,0,0,0),i[e].copyFromPoints(s,r,n));var l=i[e];if(c||l.isFrontFacingTo(this.normalizedVelocity,0)){var _=l.signedDistanceTo(this.basePoint),d=t.Vector3.Dot(l.normal,this.velocity);if(0==d){if(Math.abs(_)>=1)return;a=!0,h=0}else{h=(-1-_)/d;var V=(1-_)/d;if(h>V){var u=V;V=h,h=u}if(h>1||V<0)return;h<0&&(h=0),h>1&&(h=1)}this._collisionPoint.copyFromFloats(0,0,0);var P=!1,p=1;if(a||(this.basePoint.subtractToRef(l.normal,this._planeIntersectionPoint),this.velocity.scaleToRef(h,this._tempVector),this._planeIntersectionPoint.addInPlace(this._tempVector),this._checkPointInTriangle(this._planeIntersectionPoint,s,r,n,l.normal)&&(P=!0,p=h,this._collisionPoint.copyFrom(this._planeIntersectionPoint))),!P){var f=this.velocity.lengthSquared(),m=f;this.basePoint.subtractToRef(s,this._tempVector);var T=2*t.Vector3.Dot(this.velocity,this._tempVector),b=this._tempVector.lengthSquared()-1,y=o(m,T,b,p);y.found&&(p=y.root,P=!0,this._collisionPoint.copyFrom(s)),this.basePoint.subtractToRef(r,this._tempVector),T=2*t.Vector3.Dot(this.velocity,this._tempVector),b=this._tempVector.lengthSquared()-1,y=o(m,T,b,p),y.found&&(p=y.root,P=!0,this._collisionPoint.copyFrom(r)),this.basePoint.subtractToRef(n,this._tempVector),T=2*t.Vector3.Dot(this.velocity,this._tempVector),b=this._tempVector.lengthSquared()-1,y=o(m,T,b,p),y.found&&(p=y.root,P=!0,this._collisionPoint.copyFrom(n)),r.subtractToRef(s,this._edge),s.subtractToRef(this.basePoint,this._baseToVertex);var g=this._edge.lengthSquared(),v=t.Vector3.Dot(this._edge,this.velocity),R=t.Vector3.Dot(this._edge,this._baseToVertex);if(m=g*-f+v*v,T=g*(2*t.Vector3.Dot(this.velocity,this._baseToVertex))-2*v*R,b=g*(1-this._baseToVertex.lengthSquared())+R*R,y=o(m,T,b,p),y.found){var D=(v*y.root-R)/g;D>=0&&D<=1&&(p=y.root,P=!0,this._edge.scaleInPlace(D),s.addToRef(this._edge,this._collisionPoint))}n.subtractToRef(r,this._edge),r.subtractToRef(this.basePoint,this._baseToVertex),g=this._edge.lengthSquared(),v=t.Vector3.Dot(this._edge,this.velocity),R=t.Vector3.Dot(this._edge,this._baseToVertex),m=g*-f+v*v,T=g*(2*t.Vector3.Dot(this.velocity,this._baseToVertex))-2*v*R,b=g*(1-this._baseToVertex.lengthSquared())+R*R,y=o(m,T,b,p),y.found&&(D=(v*y.root-R)/g,D>=0&&D<=1&&(p=y.root,P=!0,this._edge.scaleInPlace(D),r.addToRef(this._edge,this._collisionPoint))),s.subtractToRef(n,this._edge),n.subtractToRef(this.basePoint,this._baseToVertex),g=this._edge.lengthSquared(),v=t.Vector3.Dot(this._edge,this.velocity),R=t.Vector3.Dot(this._edge,this._baseToVertex),m=g*-f+v*v,T=g*(2*t.Vector3.Dot(this.velocity,this._baseToVertex))-2*v*R,b=g*(1-this._baseToVertex.lengthSquared())+R*R,y=o(m,T,b,p),y.found&&(D=(v*y.root-R)/g,D>=0&&D<=1&&(p=y.root,P=!0,this._edge.scaleInPlace(D),n.addToRef(this._edge,this._collisionPoint)))}if(P){var x=p*this.velocity.length();(!this.collisionFound||x<this.nearestDistance)&&(this.intersectionPoint?this.intersectionPoint.copyFrom(this._collisionPoint):this.intersectionPoint=this._collisionPoint.clone(),this.nearestDistance=x,this.collisionFound=!0)}}},i.prototype._collide=function(t,e,o,i,s,r,n){for(var c=i;c<s;c+=3){var h=e[o[c]-r],a=e[o[c+1]-r],l=e[o[c+2]-r];this._testTriangle(c,t,l,a,h,n)}},i.prototype._getResponse=function(e,o){e.addToRef(o,this._destinationPoint),o.scaleInPlace(this.nearestDistance/o.length()),this.basePoint.addToRef(o,e),e.subtractToRef(this.intersectionPoint,this._slidePlaneNormal),this._slidePlaneNormal.normalize(),this._slidePlaneNormal.scaleToRef(this.epsilon,this._displacementVector),e.addInPlace(this._displacementVector),this.intersectionPoint.addInPlace(this._displacementVector),this._slidePlaneNormal.scaleInPlace(t.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint,this._slidePlaneNormal,this._destinationPoint)),this._destinationPoint.subtractInPlace(this._slidePlaneNormal),this._destinationPoint.subtractToRef(this.intersectionPoint,o)},i}();t.Collider=i}(BABYLON||(BABYLON={}));var BABYLON;!function(o){o.WorkerIncluded=!0;var e=function(){function o(){this._meshes={},this._geometries={}}return o.prototype.getMeshes=function(){return this._meshes},o.prototype.getGeometries=function(){return this._geometries},o.prototype.getMesh=function(o){return this._meshes[o]},o.prototype.addMesh=function(o){this._meshes[o.uniqueId]=o},o.prototype.removeMesh=function(o){delete this._meshes[o]},o.prototype.getGeometry=function(o){return this._geometries[o]},o.prototype.addGeometry=function(o){this._geometries[o.id]=o},o.prototype.removeGeometry=function(o){delete this._geometries[o]},o}();o.CollisionCache=e;var i=function(){function e(e,i,r){this.collider=e,this._collisionCache=i,this.finalPosition=r,this.collisionsScalingMatrix=o.Matrix.Zero(),this.collisionTranformationMatrix=o.Matrix.Zero()}return e.prototype.collideWithWorld=function(o,e,i,r){var t=.01;if(this.collider.retry>=i)return void this.finalPosition.copyFrom(o);this.collider._initialize(o,e,t);for(var s,l=this._collisionCache.getMeshes(),n=Object.keys(l),a=n.length,c=0;c<a;++c)if(s=n[c],parseInt(s)!=r){var d=l[s];d.checkCollisions&&this.checkCollision(d)}return this.collider.collisionFound?(0===e.x&&0===e.y&&0===e.z||this.collider._getResponse(o,e),e.length()<=t?void this.finalPosition.copyFrom(o):(this.collider.retry++,void this.collideWithWorld(o,e,i,r))):void o.addToRef(e,this.finalPosition)},e.prototype.checkCollision=function(e){if(this.collider._canDoCollision(o.Vector3.FromArray(e.sphereCenter),e.sphereRadius,o.Vector3.FromArray(e.boxMinimum),o.Vector3.FromArray(e.boxMaximum))){o.Matrix.ScalingToRef(1/this.collider.radius.x,1/this.collider.radius.y,1/this.collider.radius.z,this.collisionsScalingMatrix);var i=o.Matrix.FromArray(e.worldMatrixFromCache);i.multiplyToRef(this.collisionsScalingMatrix,this.collisionTranformationMatrix),this.processCollisionsForSubMeshes(this.collisionTranformationMatrix,e)}},e.prototype.processCollisionsForSubMeshes=function(o,e){var i=e.subMeshes,r=i.length;if(!e.geometryId)return void console.log(\"no mesh geometry id\");var t=this._collisionCache.getGeometry(e.geometryId);if(!t)return void console.log(\"couldn't find geometry\",e.geometryId);for(var s=0;s<r;s++){var l=i[s];r>1&&!this.checkSubmeshCollision(l)||(this.collideForSubMesh(l,o,t),this.collider.collisionFound&&(this.collider.collidedMesh=e.uniqueId))}},e.prototype.collideForSubMesh=function(e,i,r){if(!r.positionsArray){r.positionsArray=[];for(var t=0,s=r.positions.length;t<s;t+=3){var l=o.Vector3.FromArray([r.positions[t],r.positions[t+1],r.positions[t+2]]);r.positionsArray.push(l)}}if(!e._lastColliderWorldVertices||!e._lastColliderTransformMatrix.equals(i)){e._lastColliderTransformMatrix=i.clone(),e._lastColliderWorldVertices=[],e._trianglePlanes=[];for(var n=e.verticesStart,a=e.verticesStart+e.verticesCount,t=n;t<a;t++)e._lastColliderWorldVertices.push(o.Vector3.TransformCoordinates(r.positionsArray[t],i))}this.collider._collide(e._trianglePlanes,e._lastColliderWorldVertices,r.indices,e.indexStart,e.indexStart+e.indexCount,e.verticesStart,e.hasMaterial)},e.prototype.checkSubmeshCollision=function(e){return this.collider._canDoCollision(o.Vector3.FromArray(e.sphereCenter),e.sphereRadius,o.Vector3.FromArray(e.boxMinimum),o.Vector3.FromArray(e.boxMaximum))},e}();o.CollideWorker=i;var r=function(){function r(){}return r.prototype.onInit=function(i){this._collisionCache=new e;var r={error:o.WorkerReplyType.SUCCESS,taskType:o.WorkerTaskType.INIT};postMessage(r,void 0)},r.prototype.onUpdate=function(e){var i=this,r={error:o.WorkerReplyType.SUCCESS,taskType:o.WorkerTaskType.UPDATE};try{for(var t in e.updatedGeometries)e.updatedGeometries.hasOwnProperty(t)&&this._collisionCache.addGeometry(e.updatedGeometries[t]);for(var s in e.updatedMeshes)e.updatedMeshes.hasOwnProperty(s)&&this._collisionCache.addMesh(e.updatedMeshes[s]);e.removedGeometries.forEach(function(o){i._collisionCache.removeGeometry(o)}),e.removedMeshes.forEach(function(o){i._collisionCache.removeMesh(o)})}catch(l){r.error=o.WorkerReplyType.UNKNOWN_ERROR}postMessage(r,void 0)},r.prototype.onCollision=function(e){var r=o.Vector3.Zero(),t=new o.Collider;t.radius=o.Vector3.FromArray(e.collider.radius);var s=new i(t,this._collisionCache,r);s.collideWithWorld(o.Vector3.FromArray(e.collider.position),o.Vector3.FromArray(e.collider.velocity),e.maximumRetry,e.excludedMeshUniqueId);var l={collidedMeshUniqueId:t.collidedMesh,collisionId:e.collisionId,newPosition:r.asArray()},n={error:o.WorkerReplyType.SUCCESS,taskType:o.WorkerTaskType.COLLIDE,payload:l};postMessage(n,void 0)},r}();o.CollisionDetectorTransferable=r;try{if(self&&self instanceof WorkerGlobalScope){window={},o.Collider||(importScripts(\"./babylon.collisionCoordinator.js\"),importScripts(\"./babylon.collider.js\"),importScripts(\"../Math/babylon.math.js\"));var t=new r,s=function(e){var i=e.data;switch(i.taskType){case o.WorkerTaskType.INIT:t.onInit(i.payload);break;case o.WorkerTaskType.COLLIDE:t.onCollision(i.payload);break;case o.WorkerTaskType.UPDATE:t.onUpdate(i.payload)}};self.onmessage=s}}catch(l){console.log(\"single worker init\")}}(BABYLON||(BABYLON={}));var BABYLON;!function(e){e.CollisionWorker=\"\";var o;!function(e){e[e.INIT=0]=\"INIT\",e[e.UPDATE=1]=\"UPDATE\",e[e.COLLIDE=2]=\"COLLIDE\"}(o=e.WorkerTaskType||(e.WorkerTaskType={}));var i;!function(e){e[e.SUCCESS=0]=\"SUCCESS\",e[e.UNKNOWN_ERROR=1]=\"UNKNOWN_ERROR\"}(i=e.WorkerReplyType||(e.WorkerReplyType={}));var t=function(){function t(){var r=this;this._scaledPosition=e.Vector3.Zero(),this._scaledVelocity=e.Vector3.Zero(),this.onMeshUpdated=function(e){r._addUpdateMeshesList[e.uniqueId]=t.SerializeMesh(e)},this.onGeometryUpdated=function(e){r._addUpdateGeometriesList[e.id]=t.SerializeGeometry(e)},this._afterRender=function(){if(r._init&&!(0==r._toRemoveGeometryArray.length&&0==r._toRemoveMeshesArray.length&&0==Object.keys(r._addUpdateGeometriesList).length&&0==Object.keys(r._addUpdateMeshesList).length||r._runningUpdated>4)){++r._runningUpdated;var e={updatedMeshes:r._addUpdateMeshesList,updatedGeometries:r._addUpdateGeometriesList,removedGeometries:r._toRemoveGeometryArray,removedMeshes:r._toRemoveMeshesArray},i={payload:e,taskType:o.UPDATE},t=[];for(var s in e.updatedGeometries)e.updatedGeometries.hasOwnProperty(s)&&(t.push(i.payload.updatedGeometries[s].indices.buffer),t.push(i.payload.updatedGeometries[s].normals.buffer),t.push(i.payload.updatedGeometries[s].positions.buffer));r._worker.postMessage(i,t),r._addUpdateMeshesList={},r._addUpdateGeometriesList={},r._toRemoveGeometryArray=[],r._toRemoveMeshesArray=[]}},this._onMessageFromWorker=function(t){var s=t.data;if(s.error!=i.SUCCESS)return void e.Tools.Warn(\"error returned from worker!\");switch(s.taskType){case o.INIT:r._init=!0,r._scene.meshes.forEach(function(e){r.onMeshAdded(e)}),r._scene.getGeometries().forEach(function(e){r.onGeometryAdded(e)});break;case o.UPDATE:r._runningUpdated--;break;case o.COLLIDE:r._runningCollisionTask=!1;var n=s.payload;if(!r._collisionsCallbackArray[n.collisionId])return;r._collisionsCallbackArray[n.collisionId](n.collisionId,e.Vector3.FromArray(n.newPosition),r._scene.getMeshByUniqueID(n.collidedMeshUniqueId)),r._collisionsCallbackArray[n.collisionId]=void 0}},this._collisionsCallbackArray=[],this._init=!1,this._runningUpdated=0,this._runningCollisionTask=!1,this._addUpdateMeshesList={},this._addUpdateGeometriesList={},this._toRemoveGeometryArray=[],this._toRemoveMeshesArray=[]}return t.prototype.getNewPosition=function(e,i,t,r,s,n,a){if(this._init&&!this._collisionsCallbackArray[a]&&!this._collisionsCallbackArray[a+1e5]){e.divideToRef(t.radius,this._scaledPosition),i.divideToRef(t.radius,this._scaledVelocity),this._collisionsCallbackArray[a]=n;var d={collider:{position:this._scaledPosition.asArray(),velocity:this._scaledVelocity.asArray(),radius:t.radius.asArray()},collisionId:a,excludedMeshUniqueId:s?s.uniqueId:null,maximumRetry:r},l={payload:d,taskType:o.COLLIDE};this._worker.postMessage(l)}},t.prototype.init=function(i){this._scene=i,this._scene.registerAfterRender(this._afterRender);var t=e.WorkerIncluded?e.Engine.CodeRepository+\"Collisions/babylon.collisionWorker.js\":URL.createObjectURL(new Blob([e.CollisionWorker],{type:\"application/javascript\"}));this._worker=new Worker(t),this._worker.onmessage=this._onMessageFromWorker;var r={payload:{},taskType:o.INIT};this._worker.postMessage(r)},t.prototype.destroy=function(){this._scene.unregisterAfterRender(this._afterRender),this._worker.terminate()},t.prototype.onMeshAdded=function(e){e.registerAfterWorldMatrixUpdate(this.onMeshUpdated),this.onMeshUpdated(e)},t.prototype.onMeshRemoved=function(e){this._toRemoveMeshesArray.push(e.uniqueId)},t.prototype.onGeometryAdded=function(e){e.onGeometryUpdated=this.onGeometryUpdated,this.onGeometryUpdated(e)},t.prototype.onGeometryDeleted=function(e){this._toRemoveGeometryArray.push(e.id)},t}();t.SerializeMesh=function(o){var i=[];o.subMeshes&&(i=o.subMeshes.map(function(e,o){return{position:o,verticesStart:e.verticesStart,verticesCount:e.verticesCount,indexStart:e.indexStart,indexCount:e.indexCount,hasMaterial:!!e.getMaterial(),sphereCenter:e.getBoundingInfo().boundingSphere.centerWorld.asArray(),sphereRadius:e.getBoundingInfo().boundingSphere.radiusWorld,boxMinimum:e.getBoundingInfo().boundingBox.minimumWorld.asArray(),boxMaximum:e.getBoundingInfo().boundingBox.maximumWorld.asArray()}}));var t=null;return o instanceof e.Mesh?t=o.geometry?o.geometry.id:null:o instanceof e.InstancedMesh&&(t=o.sourceMesh&&o.sourceMesh.geometry?o.sourceMesh.geometry.id:null),{uniqueId:o.uniqueId,id:o.id,name:o.name,geometryId:t,sphereCenter:o.getBoundingInfo().boundingSphere.centerWorld.asArray(),sphereRadius:o.getBoundingInfo().boundingSphere.radiusWorld,boxMinimum:o.getBoundingInfo().boundingBox.minimumWorld.asArray(),boxMaximum:o.getBoundingInfo().boundingBox.maximumWorld.asArray(),worldMatrixFromCache:o.worldMatrixFromCache.asArray(),subMeshes:i,checkCollisions:o.checkCollisions}},t.SerializeGeometry=function(o){return{id:o.id,positions:new Float32Array(o.getVerticesData(e.VertexBuffer.PositionKind)||[]),normals:new Float32Array(o.getVerticesData(e.VertexBuffer.NormalKind)||[]),indices:new Uint32Array(o.getIndices()||[])}},e.CollisionCoordinatorWorker=t;var r=function(){function o(){this._scaledPosition=e.Vector3.Zero(),this._scaledVelocity=e.Vector3.Zero(),this._finalPosition=e.Vector3.Zero()}return o.prototype.getNewPosition=function(e,o,i,t,r,s,n){e.divideToRef(i.radius,this._scaledPosition),o.divideToRef(i.radius,this._scaledVelocity),i.collidedMesh=null,i.retry=0,i.initialVelocity=this._scaledVelocity,i.initialPosition=this._scaledPosition,this._collideWithWorld(this._scaledPosition,this._scaledVelocity,i,t,this._finalPosition,r),this._finalPosition.multiplyInPlace(i.radius),s(n,this._finalPosition,i.collidedMesh)},o.prototype.init=function(e){this._scene=e},o.prototype.destroy=function(){},o.prototype.onMeshAdded=function(e){},o.prototype.onMeshUpdated=function(e){},o.prototype.onMeshRemoved=function(e){},o.prototype.onGeometryAdded=function(e){},o.prototype.onGeometryUpdated=function(e){},o.prototype.onGeometryDeleted=function(e){},o.prototype._collideWithWorld=function(o,i,t,r,s,n){void 0===n&&(n=null);var a=10*e.Engine.CollisionsEpsilon;if(t.retry>=r)return void s.copyFrom(o);t._initialize(o,i,a);for(var d=0;d<this._scene.meshes.length;d++){var l=this._scene.meshes[d];l.isEnabled()&&l.checkCollisions&&l.subMeshes&&l!==n&&l._checkCollision(t)}return t.collisionFound?(0===i.x&&0===i.y&&0===i.z||t._getResponse(o,i),i.length()<=a?void s.copyFrom(o):(t.retry++,void this._collideWithWorld(o,i,t,r,s,n))):void o.addToRef(i,s)},o}();e.CollisionCoordinatorLegacy=r}(BABYLON||(BABYLON={}));var BABYLON;!function(t){t.ToGammaSpace=1/2.2,t.ToLinearSpace=2.2,t.Epsilon=.001;var i=function(){function t(){}return t.WithinEpsilon=function(t,i,r){void 0===r&&(r=1.401298e-45);var n=t-i;return-r<=n&&n<=r},t.ToHex=function(t){var i=t.toString(16);return t<=15?(\"0\"+i).toUpperCase():i.toUpperCase()},t.Sign=function(t){return t=+t,0===t||isNaN(t)?t:t>0?1:-1},t.Clamp=function(t,i,r){return void 0===i&&(i=0),void 0===r&&(r=1),Math.min(r,Math.max(i,t))},t}();t.MathTools=i;var r=function(){function r(t,i,r){void 0===t&&(t=0),void 0===i&&(i=0),void 0===r&&(r=0),this.r=t,this.g=i,this.b=r}return r.prototype.toString=function(){return\"{R: \"+this.r+\" G:\"+this.g+\" B:\"+this.b+\"}\"},r.prototype.getClassName=function(){return\"Color3\"},r.prototype.getHashCode=function(){var t=this.r||0;return t=397*t^(this.g||0),t=397*t^(this.b||0)},r.prototype.toArray=function(t,i){return void 0===i&&(i=0),t[i]=this.r,t[i+1]=this.g,t[i+2]=this.b,this},r.prototype.toColor4=function(t){return void 0===t&&(t=1),new n(this.r,this.g,this.b,t)},r.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},r.prototype.toLuminance=function(){return.3*this.r+.59*this.g+.11*this.b},r.prototype.multiply=function(t){return new r(this.r*t.r,this.g*t.g,this.b*t.b)},r.prototype.multiplyToRef=function(t,i){return i.r=this.r*t.r,i.g=this.g*t.g,i.b=this.b*t.b,this},r.prototype.equals=function(t){return t&&this.r===t.r&&this.g===t.g&&this.b===t.b},r.prototype.equalsFloats=function(t,i,r){return this.r===t&&this.g===i&&this.b===r},r.prototype.scale=function(t){return new r(this.r*t,this.g*t,this.b*t)},r.prototype.scaleToRef=function(t,i){return i.r=this.r*t,i.g=this.g*t,i.b=this.b*t,this},r.prototype.add=function(t){return new r(this.r+t.r,this.g+t.g,this.b+t.b)},r.prototype.addToRef=function(t,i){return i.r=this.r+t.r,i.g=this.g+t.g,i.b=this.b+t.b,this},r.prototype.subtract=function(t){return new r(this.r-t.r,this.g-t.g,this.b-t.b)},r.prototype.subtractToRef=function(t,i){return i.r=this.r-t.r,i.g=this.g-t.g,i.b=this.b-t.b,this},r.prototype.clone=function(){return new r(this.r,this.g,this.b)},r.prototype.copyFrom=function(t){return this.r=t.r,this.g=t.g,this.b=t.b,this},r.prototype.copyFromFloats=function(t,i,r){return this.r=t,this.g=i,this.b=r,this},r.prototype.toHexString=function(){var t=255*this.r|0,r=255*this.g|0,n=255*this.b|0;return\"#\"+i.ToHex(t)+i.ToHex(r)+i.ToHex(n)},r.prototype.toLinearSpace=function(){var t=new r;return this.toLinearSpaceToRef(t),t},r.prototype.toLinearSpaceToRef=function(i){return i.r=Math.pow(this.r,t.ToLinearSpace),i.g=Math.pow(this.g,t.ToLinearSpace),i.b=Math.pow(this.b,t.ToLinearSpace),this},r.prototype.toGammaSpace=function(){var t=new r;return this.toGammaSpaceToRef(t),t},r.prototype.toGammaSpaceToRef=function(i){return i.r=Math.pow(this.r,t.ToGammaSpace),i.g=Math.pow(this.g,t.ToGammaSpace),i.b=Math.pow(this.b,t.ToGammaSpace),this},r.FromHexString=function(t){if(\"#\"!==t.substring(0,1)||7!==t.length)return new r(0,0,0);var i=parseInt(t.substring(1,3),16),n=parseInt(t.substring(3,5),16),o=parseInt(t.substring(5,7),16);return r.FromInts(i,n,o)},r.FromArray=function(t,i){return void 0===i&&(i=0),new r(t[i],t[i+1],t[i+2])},r.FromInts=function(t,i,n){return new r(t/255,i/255,n/255)},r.Lerp=function(t,i,n){var o=t.r+(i.r-t.r)*n,e=t.g+(i.g-t.g)*n,s=t.b+(i.b-t.b)*n;return new r(o,e,s)},r.Red=function(){return new r(1,0,0)},r.Green=function(){return new r(0,1,0)},r.Blue=function(){return new r(0,0,1)},r.Black=function(){return new r(0,0,0)},r.White=function(){return new r(1,1,1)},r.Purple=function(){return new r(.5,0,.5)},r.Magenta=function(){return new r(1,0,1)},r.Yellow=function(){return new r(1,1,0)},r.Gray=function(){return new r(.5,.5,.5)},r.Random=function(){return new r(Math.random(),Math.random(),Math.random())},r}();t.Color3=r;var n=function(){function t(t,i,r,n){this.r=t,this.g=i,this.b=r,this.a=n}return t.prototype.addInPlace=function(t){return this.r+=t.r,this.g+=t.g,this.b+=t.b,this.a+=t.a,this},t.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},t.prototype.toArray=function(t,i){return void 0===i&&(i=0),t[i]=this.r,t[i+1]=this.g,t[i+2]=this.b,t[i+3]=this.a,this},t.prototype.add=function(i){return new t(this.r+i.r,this.g+i.g,this.b+i.b,this.a+i.a)},t.prototype.subtract=function(i){return new t(this.r-i.r,this.g-i.g,this.b-i.b,this.a-i.a)},t.prototype.subtractToRef=function(t,i){return i.r=this.r-t.r,i.g=this.g-t.g,i.b=this.b-t.b,i.a=this.a-t.a,this},t.prototype.scale=function(i){return new t(this.r*i,this.g*i,this.b*i,this.a*i)},t.prototype.scaleToRef=function(t,i){return i.r=this.r*t,i.g=this.g*t,i.b=this.b*t,i.a=this.a*t,this},t.prototype.multiply=function(i){return new t(this.r*i.r,this.g*i.g,this.b*i.b,this.a*i.a)},t.prototype.multiplyToRef=function(t,i){return i.r=this.r*t.r,i.g=this.g*t.g,i.b=this.b*t.b,i.a=this.a*t.a,i},t.prototype.toString=function(){return\"{R: \"+this.r+\" G:\"+this.g+\" B:\"+this.b+\" A:\"+this.a+\"}\"},t.prototype.getClassName=function(){return\"Color4\"},t.prototype.getHashCode=function(){var t=this.r||0;return t=397*t^(this.g||0),t=397*t^(this.b||0),t=397*t^(this.a||0)},t.prototype.clone=function(){return new t(this.r,this.g,this.b,this.a)},t.prototype.copyFrom=function(t){return this.r=t.r,this.g=t.g,this.b=t.b,this.a=t.a,this},t.prototype.toHexString=function(){var t=255*this.r|0,r=255*this.g|0,n=255*this.b|0,o=255*this.a|0;return\"#\"+i.ToHex(t)+i.ToHex(r)+i.ToHex(n)+i.ToHex(o)},t.FromHexString=function(i){if(\"#\"!==i.substring(0,1)||9!==i.length)return new t(0,0,0,0);var r=parseInt(i.substring(1,3),16),n=parseInt(i.substring(3,5),16),o=parseInt(i.substring(5,7),16),e=parseInt(i.substring(7,9),16);return t.FromInts(r,n,o,e)},t.Lerp=function(i,r,n){var o=new t(0,0,0,0);return t.LerpToRef(i,r,n,o),o},t.LerpToRef=function(t,i,r,n){n.r=t.r+(i.r-t.r)*r,n.g=t.g+(i.g-t.g)*r,n.b=t.b+(i.b-t.b)*r,n.a=t.a+(i.a-t.a)*r},t.FromArray=function(i,r){return void 0===r&&(r=0),new t(i[r],i[r+1],i[r+2],i[r+3])},t.FromInts=function(i,r,n,o){return new t(i/255,r/255,n/255,o/255)},t.CheckColors4=function(t,i){if(t.length===3*i){for(var r=[],n=0;n<t.length;n+=3){var o=n/3*4;r[o]=t[n],r[o+1]=t[n+1],r[o+2]=t[n+2],r[o+3]=1}return r}return t},t}();t.Color4=n;var o=function(){function r(t,i){this.x=t,this.y=i}return r.prototype.toString=function(){return\"{X: \"+this.x+\" Y:\"+this.y+\"}\"},r.prototype.getClassName=function(){return\"Vector2\"},r.prototype.getHashCode=function(){var t=this.x||0;return t=397*t^(this.y||0)},r.prototype.toArray=function(t,i){return void 0===i&&(i=0),t[i]=this.x,t[i+1]=this.y,this},r.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},r.prototype.copyFrom=function(t){return this.x=t.x,this.y=t.y,this},r.prototype.copyFromFloats=function(t,i){return this.x=t,this.y=i,this},r.prototype.add=function(t){return new r(this.x+t.x,this.y+t.y)},r.prototype.addToRef=function(t,i){return i.x=this.x+t.x,i.y=this.y+t.y,this},r.prototype.addInPlace=function(t){return this.x+=t.x,this.y+=t.y,this},r.prototype.addVector3=function(t){return new r(this.x+t.x,this.y+t.y)},r.prototype.subtract=function(t){return new r(this.x-t.x,this.y-t.y)},r.prototype.subtractToRef=function(t,i){return i.x=this.x-t.x,i.y=this.y-t.y,this},r.prototype.subtractInPlace=function(t){return this.x-=t.x,this.y-=t.y,this},r.prototype.multiplyInPlace=function(t){return this.x*=t.x,this.y*=t.y,this},r.prototype.multiply=function(t){return new r(this.x*t.x,this.y*t.y)},r.prototype.multiplyToRef=function(t,i){return i.x=this.x*t.x,i.y=this.y*t.y,this},r.prototype.multiplyByFloats=function(t,i){return new r(this.x*t,this.y*i)},r.prototype.divide=function(t){return new r(this.x/t.x,this.y/t.y)},r.prototype.divideToRef=function(t,i){return i.x=this.x/t.x,i.y=this.y/t.y,this},r.prototype.negate=function(){return new r((-this.x),(-this.y))},r.prototype.scaleInPlace=function(t){return this.x*=t,this.y*=t,this},r.prototype.scale=function(t){return new r(this.x*t,this.y*t)},r.prototype.equals=function(t){return t&&this.x===t.x&&this.y===t.y},r.prototype.equalsWithEpsilon=function(r,n){return void 0===n&&(n=t.Epsilon),r&&i.WithinEpsilon(this.x,r.x,n)&&i.WithinEpsilon(this.y,r.y,n)},r.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y)},r.prototype.lengthSquared=function(){return this.x*this.x+this.y*this.y},r.prototype.normalize=function(){var t=this.length();if(0===t)return this;var i=1/t;return this.x*=i,this.y*=i,this},r.prototype.clone=function(){return new r(this.x,this.y)},r.Zero=function(){return new r(0,0)},r.FromArray=function(t,i){return void 0===i&&(i=0),new r(t[i],t[i+1])},r.FromArrayToRef=function(t,i,r){r.x=t[i],r.y=t[i+1]},r.CatmullRom=function(t,i,n,o,e){var s=e*e,h=e*s,a=.5*(2*i.x+(-t.x+n.x)*e+(2*t.x-5*i.x+4*n.x-o.x)*s+(-t.x+3*i.x-3*n.x+o.x)*h),u=.5*(2*i.y+(-t.y+n.y)*e+(2*t.y-5*i.y+4*n.y-o.y)*s+(-t.y+3*i.y-3*n.y+o.y)*h);return new r(a,u)},r.Clamp=function(t,i,n){var o=t.x;o=o>n.x?n.x:o,o=o<i.x?i.x:o;var e=t.y;return e=e>n.y?n.y:e,e=e<i.y?i.y:e,new r(o,e)},r.Hermite=function(t,i,n,o,e){var s=e*e,h=e*s,a=2*h-3*s+1,u=-2*h+3*s,m=h-2*s+e,y=h-s,c=t.x*a+n.x*u+i.x*m+o.x*y,p=t.y*a+n.y*u+i.y*m+o.y*y;return new r(c,p)},r.Lerp=function(t,i,n){var o=t.x+(i.x-t.x)*n,e=t.y+(i.y-t.y)*n;return new r(o,e)},r.Dot=function(t,i){return t.x*i.x+t.y*i.y},r.Normalize=function(t){var i=t.clone();return i.normalize(),i},r.Minimize=function(t,i){var n=t.x<i.x?t.x:i.x,o=t.y<i.y?t.y:i.y;return new r(n,o)},r.Maximize=function(t,i){var n=t.x>i.x?t.x:i.x,o=t.y>i.y?t.y:i.y;return new r(n,o)},r.Transform=function(t,i){var n=r.Zero();return r.TransformToRef(t,i,n),n},r.TransformToRef=function(t,i,r){var n=t.x*i.m[0]+t.y*i.m[4]+i.m[12],o=t.x*i.m[1]+t.y*i.m[5]+i.m[13];r.x=n,r.y=o},r.PointInTriangle=function(t,i,r,n){var o=.5*(-r.y*n.x+i.y*(-r.x+n.x)+i.x*(r.y-n.y)+r.x*n.y),e=o<0?-1:1,s=(i.y*n.x-i.x*n.y+(n.y-i.y)*t.x+(i.x-n.x)*t.y)*e,h=(i.x*r.y-i.y*r.x+(i.y-r.y)*t.x+(r.x-i.x)*t.y)*e;return s>0&&h>0&&s+h<2*o*e},r.Distance=function(t,i){return Math.sqrt(r.DistanceSquared(t,i))},r.DistanceSquared=function(t,i){var r=t.x-i.x,n=t.y-i.y;return r*r+n*n},r.Center=function(t,i){var r=t.add(i);return r.scaleInPlace(.5),r},r.DistanceOfPointFromSegment=function(t,i,n){var o=r.DistanceSquared(i,n);if(0===o)return r.Distance(t,i);var e=n.subtract(i),s=Math.max(0,Math.min(1,r.Dot(t.subtract(i),e)/o)),h=i.add(e.multiplyByFloats(s,s));return r.Distance(t,h)},r}();t.Vector2=o;var e=function(){function r(t,i,r){this.x=t,this.y=i,this.z=r}return r.prototype.toString=function(){return\"{X: \"+this.x+\" Y:\"+this.y+\" Z:\"+this.z+\"}\"},r.prototype.getClassName=function(){return\"Vector3\"},r.prototype.getHashCode=function(){var t=this.x||0;return t=397*t^(this.y||0),t=397*t^(this.z||0)},r.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},r.prototype.toArray=function(t,i){return void 0===i&&(i=0),t[i]=this.x,t[i+1]=this.y,t[i+2]=this.z,this},r.prototype.toQuaternion=function(){var t=new a(0,0,0,1),i=Math.cos(.5*(this.x+this.z)),r=Math.sin(.5*(this.x+this.z)),n=Math.cos(.5*(this.z-this.x)),o=Math.sin(.5*(this.z-this.x)),e=Math.cos(.5*this.y),s=Math.sin(.5*this.y);return t.x=n*s,t.y=-o*s,t.z=r*e,t.w=i*e,t},r.prototype.addInPlace=function(t){return this.x+=t.x,this.y+=t.y,this.z+=t.z,this},r.prototype.add=function(t){return new r(this.x+t.x,this.y+t.y,this.z+t.z)},r.prototype.addToRef=function(t,i){return i.x=this.x+t.x,i.y=this.y+t.y,i.z=this.z+t.z,this},r.prototype.subtractInPlace=function(t){return this.x-=t.x,this.y-=t.y,this.z-=t.z,this},r.prototype.subtract=function(t){return new r(this.x-t.x,this.y-t.y,this.z-t.z)},r.prototype.subtractToRef=function(t,i){return i.x=this.x-t.x,i.y=this.y-t.y,i.z=this.z-t.z,this},r.prototype.subtractFromFloats=function(t,i,n){return new r(this.x-t,this.y-i,this.z-n)},r.prototype.subtractFromFloatsToRef=function(t,i,r,n){return n.x=this.x-t,n.y=this.y-i,n.z=this.z-r,this},r.prototype.negate=function(){return new r((-this.x),(-this.y),(-this.z))},r.prototype.scaleInPlace=function(t){return this.x*=t,this.y*=t,this.z*=t,this},r.prototype.scale=function(t){return new r(this.x*t,this.y*t,this.z*t)},r.prototype.scaleToRef=function(t,i){i.x=this.x*t,i.y=this.y*t,i.z=this.z*t},r.prototype.equals=function(t){return t&&this.x===t.x&&this.y===t.y&&this.z===t.z},r.prototype.equalsWithEpsilon=function(r,n){return void 0===n&&(n=t.Epsilon),r&&i.WithinEpsilon(this.x,r.x,n)&&i.WithinEpsilon(this.y,r.y,n)&&i.WithinEpsilon(this.z,r.z,n)},r.prototype.equalsToFloats=function(t,i,r){return this.x===t&&this.y===i&&this.z===r},r.prototype.multiplyInPlace=function(t){return this.x*=t.x,this.y*=t.y,this.z*=t.z,this},r.prototype.multiply=function(t){return new r(this.x*t.x,this.y*t.y,this.z*t.z)},r.prototype.multiplyToRef=function(t,i){return i.x=this.x*t.x,i.y=this.y*t.y,i.z=this.z*t.z,this},r.prototype.multiplyByFloats=function(t,i,n){return new r(this.x*t,this.y*i,this.z*n)},r.prototype.divide=function(t){return new r(this.x/t.x,this.y/t.y,this.z/t.z)},r.prototype.divideToRef=function(t,i){return i.x=this.x/t.x,i.y=this.y/t.y,i.z=this.z/t.z,this},r.prototype.MinimizeInPlace=function(t){return t.x<this.x&&(this.x=t.x),t.y<this.y&&(this.y=t.y),t.z<this.z&&(this.z=t.z),this},r.prototype.MaximizeInPlace=function(t){return t.x>this.x&&(this.x=t.x),t.y>this.y&&(this.y=t.y),t.z>this.z&&(this.z=t.z),this},r.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z)},r.prototype.lengthSquared=function(){return this.x*this.x+this.y*this.y+this.z*this.z},r.prototype.normalize=function(){var t=this.length();if(0===t||1===t)return this;var i=1/t;return this.x*=i,this.y*=i,this.z*=i,this},r.prototype.clone=function(){return new r(this.x,this.y,this.z)},r.prototype.copyFrom=function(t){return this.x=t.x,this.y=t.y,this.z=t.z,this},r.prototype.copyFromFloats=function(t,i,r){return this.x=t,this.y=i,this.z=r,this},r.GetClipFactor=function(t,i,n,o){var e=r.Dot(t,n)-o,s=r.Dot(i,n)-o,h=e/(e-s);return h},r.FromArray=function(t,i){return i||(i=0),new r(t[i],t[i+1],t[i+2])},r.FromFloatArray=function(t,i){return i||(i=0),new r(t[i],t[i+1],t[i+2])},r.FromArrayToRef=function(t,i,r){r.x=t[i],r.y=t[i+1],r.z=t[i+2]},r.FromFloatArrayToRef=function(t,i,r){r.x=t[i],r.y=t[i+1],r.z=t[i+2]},r.FromFloatsToRef=function(t,i,r,n){n.x=t,n.y=i,n.z=r},r.Zero=function(){return new r(0,0,0)},r.Up=function(){return new r(0,1,0)},r.Forward=function(){return new r(0,0,1)},r.Right=function(){return new r(1,0,0)},r.Left=function(){return new r((-1),0,0)},r.TransformCoordinates=function(t,i){var n=r.Zero();return r.TransformCoordinatesToRef(t,i,n),n},r.TransformCoordinatesToRef=function(t,i,r){var n=t.x*i.m[0]+t.y*i.m[4]+t.z*i.m[8]+i.m[12],o=t.x*i.m[1]+t.y*i.m[5]+t.z*i.m[9]+i.m[13],e=t.x*i.m[2]+t.y*i.m[6]+t.z*i.m[10]+i.m[14],s=t.x*i.m[3]+t.y*i.m[7]+t.z*i.m[11]+i.m[15];r.x=n/s,r.y=o/s,r.z=e/s},r.TransformCoordinatesFromFloatsToRef=function(t,i,r,n,o){var e=t*n.m[0]+i*n.m[4]+r*n.m[8]+n.m[12],s=t*n.m[1]+i*n.m[5]+r*n.m[9]+n.m[13],h=t*n.m[2]+i*n.m[6]+r*n.m[10]+n.m[14],a=t*n.m[3]+i*n.m[7]+r*n.m[11]+n.m[15];o.x=e/a,o.y=s/a,o.z=h/a},r.TransformNormal=function(t,i){var n=r.Zero();return r.TransformNormalToRef(t,i,n),n},r.TransformNormalToRef=function(t,i,r){var n=t.x*i.m[0]+t.y*i.m[4]+t.z*i.m[8],o=t.x*i.m[1]+t.y*i.m[5]+t.z*i.m[9],e=t.x*i.m[2]+t.y*i.m[6]+t.z*i.m[10];r.x=n,r.y=o,r.z=e},r.TransformNormalFromFloatsToRef=function(t,i,r,n,o){o.x=t*n.m[0]+i*n.m[4]+r*n.m[8],o.y=t*n.m[1]+i*n.m[5]+r*n.m[9],o.z=t*n.m[2]+i*n.m[6]+r*n.m[10]},r.CatmullRom=function(t,i,n,o,e){var s=e*e,h=e*s,a=.5*(2*i.x+(-t.x+n.x)*e+(2*t.x-5*i.x+4*n.x-o.x)*s+(-t.x+3*i.x-3*n.x+o.x)*h),u=.5*(2*i.y+(-t.y+n.y)*e+(2*t.y-5*i.y+4*n.y-o.y)*s+(-t.y+3*i.y-3*n.y+o.y)*h),m=.5*(2*i.z+(-t.z+n.z)*e+(2*t.z-5*i.z+4*n.z-o.z)*s+(-t.z+3*i.z-3*n.z+o.z)*h);return new r(a,u,m)},r.Clamp=function(t,i,n){var o=t.x;o=o>n.x?n.x:o,o=o<i.x?i.x:o;var e=t.y;e=e>n.y?n.y:e,e=e<i.y?i.y:e;var s=t.z;return s=s>n.z?n.z:s,s=s<i.z?i.z:s,new r(o,e,s)},r.Hermite=function(t,i,n,o,e){var s=e*e,h=e*s,a=2*h-3*s+1,u=-2*h+3*s,m=h-2*s+e,y=h-s,c=t.x*a+n.x*u+i.x*m+o.x*y,p=t.y*a+n.y*u+i.y*m+o.y*y,f=t.z*a+n.z*u+i.z*m+o.z*y;return new r(c,p,f)},r.Lerp=function(t,i,n){var o=new r(0,0,0);return r.LerpToRef(t,i,n,o),o},r.LerpToRef=function(t,i,r,n){n.x=t.x+(i.x-t.x)*r,n.y=t.y+(i.y-t.y)*r,n.z=t.z+(i.z-t.z)*r},r.Dot=function(t,i){return t.x*i.x+t.y*i.y+t.z*i.z},r.Cross=function(t,i){var n=r.Zero();return r.CrossToRef(t,i,n),n},r.CrossToRef=function(t,i,r){A.Vector3[0].x=t.y*i.z-t.z*i.y,A.Vector3[0].y=t.z*i.x-t.x*i.z,A.Vector3[0].z=t.x*i.y-t.y*i.x,r.copyFrom(A.Vector3[0])},r.Normalize=function(t){var i=r.Zero();return r.NormalizeToRef(t,i),i},r.NormalizeToRef=function(t,i){i.copyFrom(t),i.normalize()},r.Project=function(t,i,n,o){var e=o.width,s=o.height,h=o.x,a=o.y,m=r._viewportMatrixCache?r._viewportMatrixCache:r._viewportMatrixCache=new u;u.FromValuesToRef(e/2,0,0,0,0,-s/2,0,0,0,0,.5,0,h+e/2,s/2+a,.5,1,m);var y=r._matrixCache?r._matrixCache:r._matrixCache=new u;return i.multiplyToRef(n,y),y.multiplyToRef(m,y),r.TransformCoordinates(t,y)},r.UnprojectFromTransform=function(t,n,o,e,s){var h=r._matrixCache?r._matrixCache:r._matrixCache=new u;e.multiplyToRef(s,h),h.invert(),t.x=t.x/n*2-1,t.y=-(t.y/o*2-1);var a=r.TransformCoordinates(t,h),m=t.x*h.m[3]+t.y*h.m[7]+t.z*h.m[11]+h.m[15];return i.WithinEpsilon(m,1)&&(a=a.scale(1/m)),a},r.Unproject=function(t,n,o,e,s,h){var a=r._matrixCache?r._matrixCache:r._matrixCache=new u;e.multiplyToRef(s,a),a.multiplyToRef(h,a),a.invert();var m=new r(t.x/n*2-1,(-(t.y/o*2-1)),2*t.z-1),y=r.TransformCoordinates(m,a),c=m.x*a.m[3]+m.y*a.m[7]+m.z*a.m[11]+a.m[15];return i.WithinEpsilon(c,1)&&(y=y.scale(1/c)),y},r.Minimize=function(t,i){var r=t.clone();return r.MinimizeInPlace(i),r},r.Maximize=function(t,i){var r=t.clone();return r.MaximizeInPlace(i),r},r.Distance=function(t,i){return Math.sqrt(r.DistanceSquared(t,i))},r.DistanceSquared=function(t,i){var r=t.x-i.x,n=t.y-i.y,o=t.z-i.z;return r*r+n*n+o*o},r.Center=function(t,i){var r=t.add(i);return r.scaleInPlace(.5),r},r.RotationFromAxis=function(t,i,n){var o=r.Zero();return r.RotationFromAxisToRef(t,i,n,o),o},r.RotationFromAxisToRef=function(n,o,e,s){var h=n.normalize(),a=e.normalize(),u=f.X,m=f.Y,y=0,c=0,p=0,x=0,l=0,z=0,w=0,v=-1,d=0,g=A.Vector3[0],R=0,T=A.Vector3[1];i.WithinEpsilon(a.z,0,t.Epsilon)?z=1:i.WithinEpsilon(a.x,0,t.Epsilon)?x=1:(w=a.z/a.x,x=-w*Math.sqrt(1/(1+w*w)),z=Math.sqrt(1/(1+w*w))),T.x=x,T.y=l,T.z=z,T.normalize(),r.CrossToRef(h,T,g),g.normalize(),r.Dot(a,g)<0&&(v=1),R=r.Dot(h,T),R=Math.min(1,Math.max(-1,R)),p=Math.acos(R)*v,r.Dot(T,u)<0&&(p=Math.PI+p,T=T.scaleInPlace(-1),d++);var _=A.Vector3[2],M=A.Vector3[3];x=0,l=0,z=0,v=-1,i.WithinEpsilon(a.z,0,t.Epsilon)?x=1:(w=T.z/T.x,x=-w*Math.sqrt(1/(1+w*w)),z=Math.sqrt(1/(1+w*w))),_.x=x,_.y=l,_.z=z,_.normalize(),r.CrossToRef(_,T,M),M.normalize(),r.CrossToRef(a,_,g),g.normalize(),r.Dot(T,g)<0&&(v=1),R=r.Dot(a,_),R=Math.min(1,Math.max(-1,R)),c=Math.acos(R)*v,r.Dot(M,m)<0&&(c=Math.PI+c,d++),v=-1,r.CrossToRef(u,T,g),g.normalize(),r.Dot(g,m)<0&&(v=1),R=r.Dot(T,u),R=Math.min(1,Math.max(-1,R)),y=-Math.acos(R)*v,R<0&&d<2&&(y=Math.PI+y),s.x=c,s.y=y,s.z=p},r}();t.Vector3=e;var s=function(){function r(t,i,r,n){this.x=t,this.y=i,this.z=r,this.w=n}return r.prototype.toString=function(){return\"{X: \"+this.x+\" Y:\"+this.y+\" Z:\"+this.z+\" W:\"+this.w+\"}\"},r.prototype.getClassName=function(){return\"Vector4\"},r.prototype.getHashCode=function(){var t=this.x||0;return t=397*t^(this.y||0),t=397*t^(this.z||0),t=397*t^(this.w||0)},r.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},r.prototype.toArray=function(t,i){return void 0===i&&(i=0),t[i]=this.x,t[i+1]=this.y,t[i+2]=this.z,t[i+3]=this.w,this},r.prototype.addInPlace=function(t){return this.x+=t.x,this.y+=t.y,this.z+=t.z,this.w+=t.w,this},r.prototype.add=function(t){return new r(this.x+t.x,this.y+t.y,this.z+t.z,this.w+t.w)},r.prototype.addToRef=function(t,i){return i.x=this.x+t.x,i.y=this.y+t.y,i.z=this.z+t.z,i.w=this.w+t.w,this},r.prototype.subtractInPlace=function(t){return this.x-=t.x,this.y-=t.y,this.z-=t.z,this.w-=t.w,this},r.prototype.subtract=function(t){return new r(this.x-t.x,this.y-t.y,this.z-t.z,this.w-t.w)},r.prototype.subtractToRef=function(t,i){return i.x=this.x-t.x,i.y=this.y-t.y,i.z=this.z-t.z,i.w=this.w-t.w,this},r.prototype.subtractFromFloats=function(t,i,n,o){return new r(this.x-t,this.y-i,this.z-n,this.w-o)},r.prototype.subtractFromFloatsToRef=function(t,i,r,n,o){return o.x=this.x-t,o.y=this.y-i,o.z=this.z-r,o.w=this.w-n,this},r.prototype.negate=function(){return new r((-this.x),(-this.y),(-this.z),(-this.w))},r.prototype.scaleInPlace=function(t){return this.x*=t,this.y*=t,this.z*=t,this.w*=t,this},r.prototype.scale=function(t){return new r(this.x*t,this.y*t,this.z*t,this.w*t)},r.prototype.scaleToRef=function(t,i){i.x=this.x*t,i.y=this.y*t,i.z=this.z*t,i.w=this.w*t},r.prototype.equals=function(t){return t&&this.x===t.x&&this.y===t.y&&this.z===t.z&&this.w===t.w},r.prototype.equalsWithEpsilon=function(r,n){return void 0===n&&(n=t.Epsilon),r&&i.WithinEpsilon(this.x,r.x,n)&&i.WithinEpsilon(this.y,r.y,n)&&i.WithinEpsilon(this.z,r.z,n)&&i.WithinEpsilon(this.w,r.w,n)},r.prototype.equalsToFloats=function(t,i,r,n){return this.x===t&&this.y===i&&this.z===r&&this.w===n},r.prototype.multiplyInPlace=function(t){return this.x*=t.x,this.y*=t.y,this.z*=t.z,this.w*=t.w,this},r.prototype.multiply=function(t){return new r(this.x*t.x,this.y*t.y,this.z*t.z,this.w*t.w)},r.prototype.multiplyToRef=function(t,i){return i.x=this.x*t.x,i.y=this.y*t.y,i.z=this.z*t.z,i.w=this.w*t.w,this},r.prototype.multiplyByFloats=function(t,i,n,o){return new r(this.x*t,this.y*i,this.z*n,this.w*o)},r.prototype.divide=function(t){return new r(this.x/t.x,this.y/t.y,this.z/t.z,this.w/t.w)},r.prototype.divideToRef=function(t,i){return i.x=this.x/t.x,i.y=this.y/t.y,i.z=this.z/t.z,i.w=this.w/t.w,this},r.prototype.MinimizeInPlace=function(t){return t.x<this.x&&(this.x=t.x),t.y<this.y&&(this.y=t.y),t.z<this.z&&(this.z=t.z),t.w<this.w&&(this.w=t.w),this},r.prototype.MaximizeInPlace=function(t){return t.x>this.x&&(this.x=t.x),t.y>this.y&&(this.y=t.y),t.z>this.z&&(this.z=t.z),t.w>this.w&&(this.w=t.w),this},r.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w)},r.prototype.lengthSquared=function(){return this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w},r.prototype.normalize=function(){var t=this.length();if(0===t)return this;var i=1/t;return this.x*=i,this.y*=i,this.z*=i,this.w*=i,this},r.prototype.toVector3=function(){return new e(this.x,this.y,this.z)},r.prototype.clone=function(){return new r(this.x,this.y,this.z,this.w)},r.prototype.copyFrom=function(t){return this.x=t.x,this.y=t.y,this.z=t.z,this.w=t.w,this},r.prototype.copyFromFloats=function(t,i,r,n){return this.x=t,this.y=i,this.z=r,this.w=n,this},r.FromArray=function(t,i){return i||(i=0),new r(t[i],t[i+1],t[i+2],t[i+3])},r.FromArrayToRef=function(t,i,r){r.x=t[i],r.y=t[i+1],r.z=t[i+2],r.w=t[i+3]},r.FromFloatArrayToRef=function(t,i,r){r.x=t[i],r.y=t[i+1],r.z=t[i+2],r.w=t[i+3]},r.FromFloatsToRef=function(t,i,r,n,o){o.x=t,o.y=i,o.z=r,o.w=n},r.Zero=function(){return new r(0,0,0,0)},r.Normalize=function(t){var i=r.Zero();return r.NormalizeToRef(t,i),i},r.NormalizeToRef=function(t,i){i.copyFrom(t),i.normalize()},r.Minimize=function(t,i){var r=t.clone();return r.MinimizeInPlace(i),r},r.Maximize=function(t,i){var r=t.clone();return r.MaximizeInPlace(i),r},r.Distance=function(t,i){return Math.sqrt(r.DistanceSquared(t,i))},r.DistanceSquared=function(t,i){var r=t.x-i.x,n=t.y-i.y,o=t.z-i.z,e=t.w-i.w;return r*r+n*n+o*o+e*e},r.Center=function(t,i){var r=t.add(i);return r.scaleInPlace(.5),r},r}();t.Vector4=s;var h=function(){function t(t,i){this.width=t,this.height=i}return t.prototype.toString=function(){return\"{W: \"+this.width+\", H: \"+this.height+\"}\"},t.prototype.getClassName=function(){return\"Size\"},t.prototype.getHashCode=function(){var t=this.width||0;return t=397*t^(this.height||0)},t.prototype.copyFrom=function(t){this.width=t.width,this.height=t.height},t.prototype.copyFromFloats=function(t,i){this.width=t,this.height=i},t.prototype.multiplyByFloats=function(i,r){return new t(this.width*i,this.height*r)},t.prototype.clone=function(){return new t(this.width,this.height)},t.prototype.equals=function(t){return!!t&&(this.width===t.width&&this.height===t.height)},Object.defineProperty(t.prototype,\"surface\",{get:function(){return this.width*this.height},enumerable:!0,configurable:!0}),t.Zero=function(){return new t(0,0)},t.prototype.add=function(i){var r=new t(this.width+i.width,this.height+i.height);return r},t.prototype.subtract=function(i){var r=new t(this.width-i.width,this.height-i.height);return r},t.Lerp=function(i,r,n){var o=i.width+(r.width-i.width)*n,e=i.height+(r.height-i.height)*n;return new t(o,e)},t}();t.Size=h;var a=function(){function t(t,i,r,n){void 0===t&&(t=0),void 0===i&&(i=0),void 0===r&&(r=0),void 0===n&&(n=1),this.x=t,this.y=i,this.z=r,this.w=n}return t.prototype.toString=function(){return\"{X: \"+this.x+\" Y:\"+this.y+\" Z:\"+this.z+\" W:\"+this.w+\"}\"},t.prototype.getClassName=function(){return\"Quaternion\"},t.prototype.getHashCode=function(){var t=this.x||0;return t=397*t^(this.y||0),t=397*t^(this.z||0),t=397*t^(this.w||0)},t.prototype.asArray=function(){return[this.x,this.y,this.z,this.w]},t.prototype.equals=function(t){return t&&this.x===t.x&&this.y===t.y&&this.z===t.z&&this.w===t.w},t.prototype.clone=function(){return new t(this.x,this.y,this.z,this.w)},t.prototype.copyFrom=function(t){return this.x=t.x,this.y=t.y,this.z=t.z,this.w=t.w,this},t.prototype.copyFromFloats=function(t,i,r,n){return this.x=t,this.y=i,this.z=r,this.w=n,this},t.prototype.add=function(i){return new t(this.x+i.x,this.y+i.y,this.z+i.z,this.w+i.w)},t.prototype.subtract=function(i){return new t(this.x-i.x,this.y-i.y,this.z-i.z,this.w-i.w)},t.prototype.scale=function(i){return new t(this.x*i,this.y*i,this.z*i,this.w*i)},t.prototype.multiply=function(i){var r=new t(0,0,0,1);return this.multiplyToRef(i,r),r},t.prototype.multiplyToRef=function(t,i){var r=this.x*t.w+this.y*t.z-this.z*t.y+this.w*t.x,n=-this.x*t.z+this.y*t.w+this.z*t.x+this.w*t.y,o=this.x*t.y-this.y*t.x+this.z*t.w+this.w*t.z,e=-this.x*t.x-this.y*t.y-this.z*t.z+this.w*t.w;return i.copyFromFloats(r,n,o,e),this},t.prototype.multiplyInPlace=function(t){return this.multiplyToRef(t,this),this},t.prototype.conjugateToRef=function(t){return t.copyFromFloats(-this.x,-this.y,-this.z,this.w),this},t.prototype.conjugateInPlace=function(){return this.x*=-1,this.y*=-1,this.z*=-1,this},t.prototype.conjugate=function(){var i=new t((-this.x),(-this.y),(-this.z),this.w);return i},t.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w)},t.prototype.normalize=function(){var t=1/this.length();return this.x*=t,this.y*=t,this.z*=t,this.w*=t,this},t.prototype.toEulerAngles=function(t){void 0===t&&(t=\"YZX\");var i=e.Zero();return this.toEulerAnglesToRef(i,t),i},t.prototype.toEulerAnglesToRef=function(t,i){void 0===i&&(i=\"YZX\");var r=this.z,n=this.x,o=this.y,e=this.w,s=e*e,h=r*r,a=n*n,u=o*o,m=o*r-n*e,y=.4999999;return m<-y?(t.y=2*Math.atan2(o,e),t.x=Math.PI/2,t.z=0):m>y?(t.y=2*Math.atan2(o,e),t.x=-Math.PI/2,t.z=0):(t.z=Math.atan2(2*(n*o+r*e),-h-a+u+s),t.x=Math.asin(-2*(r*o-n*e)),t.y=Math.atan2(2*(r*n+o*e),h-a-u+s)),this},t.prototype.toRotationMatrix=function(t){var i=this.x*this.x,r=this.y*this.y,n=this.z*this.z,o=this.x*this.y,e=this.z*this.w,s=this.z*this.x,h=this.y*this.w,a=this.y*this.z,u=this.x*this.w;return t.m[0]=1-2*(r+n),t.m[1]=2*(o+e),t.m[2]=2*(s-h),t.m[3]=0,t.m[4]=2*(o-e),t.m[5]=1-2*(n+i),t.m[6]=2*(a+u),t.m[7]=0,t.m[8]=2*(s+h),t.m[9]=2*(a-u),t.m[10]=1-2*(r+i),t.m[11]=0,t.m[12]=0,t.m[13]=0,t.m[14]=0,t.m[15]=1,this},t.prototype.fromRotationMatrix=function(i){return t.FromRotationMatrixToRef(i,this),this},t.FromRotationMatrix=function(i){var r=new t;return t.FromRotationMatrixToRef(i,r),r},t.FromRotationMatrixToRef=function(t,i){var r,n=t.m,o=n[0],e=n[4],s=n[8],h=n[1],a=n[5],u=n[9],m=n[2],y=n[6],c=n[10],p=o+a+c;p>0?(r=.5/Math.sqrt(p+1),i.w=.25/r,i.x=(y-u)*r,i.y=(s-m)*r,i.z=(h-e)*r):o>a&&o>c?(r=2*Math.sqrt(1+o-a-c),i.w=(y-u)/r,i.x=.25*r,i.y=(e+h)/r,i.z=(s+m)/r):a>c?(r=2*Math.sqrt(1+a-o-c),i.w=(s-m)/r,i.x=(e+h)/r,i.y=.25*r,i.z=(u+y)/r):(r=2*Math.sqrt(1+c-o-a),i.w=(h-e)/r,i.x=(s+m)/r,i.y=(u+y)/r,i.z=.25*r)},t.Inverse=function(i){return new t((-i.x),(-i.y),(-i.z),i.w)},t.Identity=function(){return new t(0,0,0,1)},t.RotationAxis=function(i,r){return t.RotationAxisToRef(i,r,new t)},t.RotationAxisToRef=function(t,i,r){var n=Math.sin(i/2);return t.normalize(),r.w=Math.cos(i/2),r.x=t.x*n,r.y=t.y*n,r.z=t.z*n,r},t.FromArray=function(i,r){return r||(r=0),new t(i[r],i[r+1],i[r+2],i[r+3])},t.RotationYawPitchRoll=function(i,r,n){var o=new t;return t.RotationYawPitchRollToRef(i,r,n,o),o},t.RotationYawPitchRollToRef=function(t,i,r,n){var o=.5*r,e=.5*i,s=.5*t,h=Math.sin(o),a=Math.cos(o),u=Math.sin(e),m=Math.cos(e),y=Math.sin(s),c=Math.cos(s);n.x=c*u*a+y*m*h,n.y=y*m*a-c*u*h,n.z=c*m*h-y*u*a,n.w=c*m*a+y*u*h},t.RotationAlphaBetaGamma=function(i,r,n){var o=new t;return t.RotationAlphaBetaGammaToRef(i,r,n,o),o},t.RotationAlphaBetaGammaToRef=function(t,i,r,n){var o=.5*(r+t),e=.5*(r-t),s=.5*i;n.x=Math.cos(e)*Math.sin(s),n.y=Math.sin(e)*Math.sin(s),n.z=Math.sin(o)*Math.cos(s),n.w=Math.cos(o)*Math.cos(s)},t.Slerp=function(i,r,n){var o=t.Identity();return t.SlerpToRef(i,r,n,o),o},t.SlerpToRef=function(t,i,r,n){var o,e,s=r,h=t.x*i.x+t.y*i.y+t.z*i.z+t.w*i.w,a=!1;if(h<0&&(a=!0,h=-h),h>.999999)e=1-s,o=a?-s:s;else{var u=Math.acos(h),m=1/Math.sin(u);e=Math.sin((1-s)*u)*m,o=a?-Math.sin(s*u)*m:Math.sin(s*u)*m}n.x=e*t.x+o*i.x,n.y=e*t.y+o*i.y,n.z=e*t.z+o*i.z,n.w=e*t.w+o*i.w},t}();t.Quaternion=a;var u=function(){function r(){this.m=new Float32Array(16)}return r.prototype.isIdentity=function(){return 1===this.m[0]&&1===this.m[5]&&1===this.m[10]&&1===this.m[15]&&(0===this.m[1]&&0===this.m[2]&&0===this.m[3]&&0===this.m[4]&&0===this.m[6]&&0===this.m[7]&&0===this.m[8]&&0===this.m[9]&&0===this.m[11]&&0===this.m[12]&&0===this.m[13]&&0===this.m[14])},r.prototype.determinant=function(){var t=this.m[10]*this.m[15]-this.m[11]*this.m[14],i=this.m[9]*this.m[15]-this.m[11]*this.m[13],r=this.m[9]*this.m[14]-this.m[10]*this.m[13],n=this.m[8]*this.m[15]-this.m[11]*this.m[12],o=this.m[8]*this.m[14]-this.m[10]*this.m[12],e=this.m[8]*this.m[13]-this.m[9]*this.m[12];return this.m[0]*(this.m[5]*t-this.m[6]*i+this.m[7]*r)-this.m[1]*(this.m[4]*t-this.m[6]*n+this.m[7]*o)+this.m[2]*(this.m[4]*i-this.m[5]*n+this.m[7]*e)-this.m[3]*(this.m[4]*r-this.m[5]*o+this.m[6]*e)},r.prototype.toArray=function(){return this.m},r.prototype.asArray=function(){return this.toArray()},r.prototype.invert=function(){return this.invertToRef(this),this},r.prototype.reset=function(){for(var t=0;t<16;t++)this.m[t]=0;return this},r.prototype.add=function(t){var i=new r;return this.addToRef(t,i),i},r.prototype.addToRef=function(t,i){for(var r=0;r<16;r++)i.m[r]=this.m[r]+t.m[r];return this},r.prototype.addToSelf=function(t){for(var i=0;i<16;i++)this.m[i]+=t.m[i];return this},r.prototype.invertToRef=function(t){var i=this.m[0],r=this.m[1],n=this.m[2],o=this.m[3],e=this.m[4],s=this.m[5],h=this.m[6],a=this.m[7],u=this.m[8],m=this.m[9],y=this.m[10],c=this.m[11],p=this.m[12],f=this.m[13],x=this.m[14],l=this.m[15],z=y*l-c*x,w=m*l-c*f,v=m*x-y*f,d=u*l-c*p,g=u*x-y*p,R=u*f-m*p,T=s*z-h*w+a*v,_=-(e*z-h*d+a*g),M=e*w-s*d+a*R,A=-(e*v-s*g+h*R),F=1/(i*T+r*_+n*M+o*A),b=h*l-a*x,L=s*l-a*f,C=s*x-h*f,P=e*l-a*p,Z=e*x-h*p,S=e*f-s*p,I=h*c-a*y,H=s*c-a*m,V=s*y-h*m,q=e*c-a*u,D=e*y-h*u,N=e*m-s*u;return t.m[0]=T*F,t.m[4]=_*F,t.m[8]=M*F,t.m[12]=A*F,t.m[1]=-(r*z-n*w+o*v)*F,t.m[5]=(i*z-n*d+o*g)*F,t.m[9]=-(i*w-r*d+o*R)*F,t.m[13]=(i*v-r*g+n*R)*F,t.m[2]=(r*b-n*L+o*C)*F,t.m[6]=-(i*b-n*P+o*Z)*F,t.m[10]=(i*L-r*P+o*S)*F,t.m[14]=-(i*C-r*Z+n*S)*F,t.m[3]=-(r*I-n*H+o*V)*F,t.m[7]=(i*I-n*q+o*D)*F,t.m[11]=-(i*H-r*q+o*N)*F,t.m[15]=(i*V-r*D+n*N)*F,this},r.prototype.setTranslation=function(t){return this.m[12]=t.x,this.m[13]=t.y,this.m[14]=t.z,this},r.prototype.getTranslation=function(){return new e(this.m[12],this.m[13],this.m[14])},r.prototype.multiply=function(t){\nvar i=new r;return this.multiplyToRef(t,i),i},r.prototype.copyFrom=function(t){for(var i=0;i<16;i++)this.m[i]=t.m[i];return this},r.prototype.copyToArray=function(t,i){void 0===i&&(i=0);for(var r=0;r<16;r++)t[i+r]=this.m[r];return this},r.prototype.multiplyToRef=function(t,i){return this.multiplyToArray(t,i.m,0),this},r.prototype.multiplyToArray=function(t,i,r){var n=this.m[0],o=this.m[1],e=this.m[2],s=this.m[3],h=this.m[4],a=this.m[5],u=this.m[6],m=this.m[7],y=this.m[8],c=this.m[9],p=this.m[10],f=this.m[11],x=this.m[12],l=this.m[13],z=this.m[14],w=this.m[15],v=t.m[0],d=t.m[1],g=t.m[2],R=t.m[3],T=t.m[4],_=t.m[5],M=t.m[6],A=t.m[7],F=t.m[8],b=t.m[9],L=t.m[10],C=t.m[11],P=t.m[12],Z=t.m[13],S=t.m[14],I=t.m[15];return i[r]=n*v+o*T+e*F+s*P,i[r+1]=n*d+o*_+e*b+s*Z,i[r+2]=n*g+o*M+e*L+s*S,i[r+3]=n*R+o*A+e*C+s*I,i[r+4]=h*v+a*T+u*F+m*P,i[r+5]=h*d+a*_+u*b+m*Z,i[r+6]=h*g+a*M+u*L+m*S,i[r+7]=h*R+a*A+u*C+m*I,i[r+8]=y*v+c*T+p*F+f*P,i[r+9]=y*d+c*_+p*b+f*Z,i[r+10]=y*g+c*M+p*L+f*S,i[r+11]=y*R+c*A+p*C+f*I,i[r+12]=x*v+l*T+z*F+w*P,i[r+13]=x*d+l*_+z*b+w*Z,i[r+14]=x*g+l*M+z*L+w*S,i[r+15]=x*R+l*A+z*C+w*I,this},r.prototype.equals=function(t){return t&&this.m[0]===t.m[0]&&this.m[1]===t.m[1]&&this.m[2]===t.m[2]&&this.m[3]===t.m[3]&&this.m[4]===t.m[4]&&this.m[5]===t.m[5]&&this.m[6]===t.m[6]&&this.m[7]===t.m[7]&&this.m[8]===t.m[8]&&this.m[9]===t.m[9]&&this.m[10]===t.m[10]&&this.m[11]===t.m[11]&&this.m[12]===t.m[12]&&this.m[13]===t.m[13]&&this.m[14]===t.m[14]&&this.m[15]===t.m[15]},r.prototype.clone=function(){return r.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])},r.prototype.getClassName=function(){return\"Matrix\"},r.prototype.getHashCode=function(){for(var t=this.m[0]||0,i=1;i<16;i++)t=397*t^(this.m[i]||0);return t},r.prototype.decompose=function(t,n,o){o.x=this.m[12],o.y=this.m[13],o.z=this.m[14];var e=i.Sign(this.m[0]*this.m[1]*this.m[2]*this.m[3])<0?-1:1,s=i.Sign(this.m[4]*this.m[5]*this.m[6]*this.m[7])<0?-1:1,h=i.Sign(this.m[8]*this.m[9]*this.m[10]*this.m[11])<0?-1:1;return t.x=e*Math.sqrt(this.m[0]*this.m[0]+this.m[1]*this.m[1]+this.m[2]*this.m[2]),t.y=s*Math.sqrt(this.m[4]*this.m[4]+this.m[5]*this.m[5]+this.m[6]*this.m[6]),t.z=h*Math.sqrt(this.m[8]*this.m[8]+this.m[9]*this.m[9]+this.m[10]*this.m[10]),0===t.x||0===t.y||0===t.z?(n.x=0,n.y=0,n.z=0,n.w=1,!1):(r.FromValuesToRef(this.m[0]/t.x,this.m[1]/t.x,this.m[2]/t.x,0,this.m[4]/t.y,this.m[5]/t.y,this.m[6]/t.y,0,this.m[8]/t.z,this.m[9]/t.z,this.m[10]/t.z,0,0,0,0,1,A.Matrix[0]),a.FromRotationMatrixToRef(A.Matrix[0],n),!0)},r.prototype.getRotationMatrix=function(){var t=r.Identity();return this.getRotationMatrixToRef(t),t},r.prototype.getRotationMatrixToRef=function(t){var i=this.m,n=i[0]*i[1]*i[2]*i[3]<0?-1:1,o=i[4]*i[5]*i[6]*i[7]<0?-1:1,e=i[8]*i[9]*i[10]*i[11]<0?-1:1,s=n*Math.sqrt(i[0]*i[0]+i[1]*i[1]+i[2]*i[2]),h=o*Math.sqrt(i[4]*i[4]+i[5]*i[5]+i[6]*i[6]),a=e*Math.sqrt(i[8]*i[8]+i[9]*i[9]+i[10]*i[10]);r.FromValuesToRef(i[0]/s,i[1]/s,i[2]/s,0,i[4]/h,i[5]/h,i[6]/h,0,i[8]/a,i[9]/a,i[10]/a,0,0,0,0,1,t)},r.FromArray=function(t,i){var n=new r;return i||(i=0),r.FromArrayToRef(t,i,n),n},r.FromArrayToRef=function(t,i,r){for(var n=0;n<16;n++)r.m[n]=t[n+i]},r.FromFloat32ArrayToRefScaled=function(t,i,r,n){for(var o=0;o<16;o++)n.m[o]=t[o+i]*r},r.FromValuesToRef=function(t,i,r,n,o,e,s,h,a,u,m,y,c,p,f,x,l){l.m[0]=t,l.m[1]=i,l.m[2]=r,l.m[3]=n,l.m[4]=o,l.m[5]=e,l.m[6]=s,l.m[7]=h,l.m[8]=a,l.m[9]=u,l.m[10]=m,l.m[11]=y,l.m[12]=c,l.m[13]=p,l.m[14]=f,l.m[15]=x},r.prototype.getRow=function(t){if(t<0||t>3)return null;var i=4*t;return new s(this.m[i+0],this.m[i+1],this.m[i+2],this.m[i+3])},r.prototype.setRow=function(t,i){if(t<0||t>3)return this;var r=4*t;return this.m[r+0]=i.x,this.m[r+1]=i.y,this.m[r+2]=i.z,this.m[r+3]=i.w,this},r.FromValues=function(t,i,n,o,e,s,h,a,u,m,y,c,p,f,x,l){var z=new r;return z.m[0]=t,z.m[1]=i,z.m[2]=n,z.m[3]=o,z.m[4]=e,z.m[5]=s,z.m[6]=h,z.m[7]=a,z.m[8]=u,z.m[9]=m,z.m[10]=y,z.m[11]=c,z.m[12]=p,z.m[13]=f,z.m[14]=x,z.m[15]=l,z},r.Compose=function(t,i,n){var o=r.FromValues(t.x,0,0,0,0,t.y,0,0,0,0,t.z,0,0,0,0,1),e=r.Identity();return i.toRotationMatrix(e),o=o.multiply(e),o.setTranslation(n),o},r.Identity=function(){return r.FromValues(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1)},r.IdentityToRef=function(t){r.FromValuesToRef(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1,t)},r.Zero=function(){return r.FromValues(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)},r.RotationX=function(t){var i=new r;return r.RotationXToRef(t,i),i},r.Invert=function(t){var i=new r;return t.invertToRef(i),i},r.RotationXToRef=function(t,i){var r=Math.sin(t),n=Math.cos(t);i.m[0]=1,i.m[15]=1,i.m[5]=n,i.m[10]=n,i.m[9]=-r,i.m[6]=r,i.m[1]=0,i.m[2]=0,i.m[3]=0,i.m[4]=0,i.m[7]=0,i.m[8]=0,i.m[11]=0,i.m[12]=0,i.m[13]=0,i.m[14]=0},r.RotationY=function(t){var i=new r;return r.RotationYToRef(t,i),i},r.RotationYToRef=function(t,i){var r=Math.sin(t),n=Math.cos(t);i.m[5]=1,i.m[15]=1,i.m[0]=n,i.m[2]=-r,i.m[8]=r,i.m[10]=n,i.m[1]=0,i.m[3]=0,i.m[4]=0,i.m[6]=0,i.m[7]=0,i.m[9]=0,i.m[11]=0,i.m[12]=0,i.m[13]=0,i.m[14]=0},r.RotationZ=function(t){var i=new r;return r.RotationZToRef(t,i),i},r.RotationZToRef=function(t,i){var r=Math.sin(t),n=Math.cos(t);i.m[10]=1,i.m[15]=1,i.m[0]=n,i.m[1]=r,i.m[4]=-r,i.m[5]=n,i.m[2]=0,i.m[3]=0,i.m[6]=0,i.m[7]=0,i.m[8]=0,i.m[9]=0,i.m[11]=0,i.m[12]=0,i.m[13]=0,i.m[14]=0},r.RotationAxis=function(t,i){var n=r.Zero();return r.RotationAxisToRef(t,i,n),n},r.RotationAxisToRef=function(t,i,r){var n=Math.sin(-i),o=Math.cos(-i),e=1-o;t.normalize(),r.m[0]=t.x*t.x*e+o,r.m[1]=t.x*t.y*e-t.z*n,r.m[2]=t.x*t.z*e+t.y*n,r.m[3]=0,r.m[4]=t.y*t.x*e+t.z*n,r.m[5]=t.y*t.y*e+o,r.m[6]=t.y*t.z*e-t.x*n,r.m[7]=0,r.m[8]=t.z*t.x*e-t.y*n,r.m[9]=t.z*t.y*e+t.x*n,r.m[10]=t.z*t.z*e+o,r.m[11]=0,r.m[15]=1},r.RotationYawPitchRoll=function(t,i,n){var o=new r;return r.RotationYawPitchRollToRef(t,i,n,o),o},r.RotationYawPitchRollToRef=function(t,i,r,n){a.RotationYawPitchRollToRef(t,i,r,this._tempQuaternion),this._tempQuaternion.toRotationMatrix(n)},r.Scaling=function(t,i,n){var o=r.Zero();return r.ScalingToRef(t,i,n,o),o},r.ScalingToRef=function(t,i,r,n){n.m[0]=t,n.m[1]=0,n.m[2]=0,n.m[3]=0,n.m[4]=0,n.m[5]=i,n.m[6]=0,n.m[7]=0,n.m[8]=0,n.m[9]=0,n.m[10]=r,n.m[11]=0,n.m[12]=0,n.m[13]=0,n.m[14]=0,n.m[15]=1},r.Translation=function(t,i,n){var o=r.Identity();return r.TranslationToRef(t,i,n,o),o},r.TranslationToRef=function(t,i,n,o){r.FromValuesToRef(1,0,0,0,0,1,0,0,0,0,1,0,t,i,n,1,o)},r.Lerp=function(t,i,n){for(var o=r.Zero(),e=0;e<16;e++)o.m[e]=t.m[e]*(1-n)+i.m[e]*n;return o},r.DecomposeLerp=function(t,i,n){var o=new e(0,0,0),s=new a,h=new e(0,0,0);t.decompose(o,s,h);var u=new e(0,0,0),m=new a,y=new e(0,0,0);i.decompose(u,m,y);var c=e.Lerp(o,u,n),p=a.Slerp(s,m,n),f=e.Lerp(h,y,n);return r.Compose(c,p,f)},r.LookAtLH=function(t,i,n){var o=r.Zero();return r.LookAtLHToRef(t,i,n,o),o},r.LookAtLHToRef=function(t,i,n,o){i.subtractToRef(t,this._zAxis),this._zAxis.normalize(),e.CrossToRef(n,this._zAxis,this._xAxis),0===this._xAxis.lengthSquared()?this._xAxis.x=1:this._xAxis.normalize(),e.CrossToRef(this._zAxis,this._xAxis,this._yAxis),this._yAxis.normalize();var s=-e.Dot(this._xAxis,t),h=-e.Dot(this._yAxis,t),a=-e.Dot(this._zAxis,t);return r.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,s,h,a,1,o)},r.LookAtRH=function(t,i,n){var o=r.Zero();return r.LookAtRHToRef(t,i,n,o),o},r.LookAtRHToRef=function(t,i,n,o){t.subtractToRef(i,this._zAxis),this._zAxis.normalize(),e.CrossToRef(n,this._zAxis,this._xAxis),0===this._xAxis.lengthSquared()?this._xAxis.x=1:this._xAxis.normalize(),e.CrossToRef(this._zAxis,this._xAxis,this._yAxis),this._yAxis.normalize();var s=-e.Dot(this._xAxis,t),h=-e.Dot(this._yAxis,t),a=-e.Dot(this._zAxis,t);return r.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,s,h,a,1,o)},r.OrthoLH=function(t,i,n,o){var e=r.Zero();return r.OrthoLHToRef(t,i,n,o,e),e},r.OrthoLHToRef=function(i,r,n,o,e){var s=n,h=o,a=2/i,u=2/r,m=2/(h-s),y=-(h+s)/(h-s);t.Matrix.FromValuesToRef(a,0,0,0,0,u,0,0,0,0,m,0,0,0,y,1,e)},r.OrthoOffCenterLH=function(t,i,n,o,e,s){var h=r.Zero();return r.OrthoOffCenterLHToRef(t,i,n,o,e,s,h),h},r.OrthoOffCenterLHToRef=function(i,r,n,o,e,s,h){var a=e,u=s,m=2/(r-i),y=2/(o-n),c=2/(u-a),p=-(u+a)/(u-a),f=(i+r)/(i-r),x=(o+n)/(n-o);t.Matrix.FromValuesToRef(m,0,0,0,0,y,0,0,0,0,c,0,f,x,p,1,h)},r.OrthoOffCenterRH=function(t,i,n,o,e,s){var h=r.Zero();return r.OrthoOffCenterRHToRef(t,i,n,o,e,s,h),h},r.OrthoOffCenterRHToRef=function(t,i,n,o,e,s,h){r.OrthoOffCenterLHToRef(t,i,n,o,e,s,h),h.m[10]*=-1},r.PerspectiveLH=function(i,n,o,e){var s=r.Zero(),h=o,a=e,u=2*h/i,m=2*h/n,y=(a+h)/(a-h),c=-2*a*h/(a-h);return t.Matrix.FromValuesToRef(u,0,0,0,0,m,0,0,0,0,y,1,0,0,c,0,s),s},r.PerspectiveFovLH=function(t,i,n,o){var e=r.Zero();return r.PerspectiveFovLHToRef(t,i,n,o,e),e},r.PerspectiveFovLHToRef=function(i,r,n,o,e,s){void 0===s&&(s=!0);var h=n,a=o,u=1/Math.tan(.5*i),m=s?u/r:u,y=s?u:u*r,c=(a+h)/(a-h),p=-2*a*h/(a-h);t.Matrix.FromValuesToRef(m,0,0,0,0,y,0,0,0,0,c,1,0,0,p,0,e)},r.PerspectiveFovRH=function(t,i,n,o){var e=r.Zero();return r.PerspectiveFovRHToRef(t,i,n,o,e),e},r.PerspectiveFovRHToRef=function(i,r,n,o,e,s){void 0===s&&(s=!0);var h=n,a=o,u=1/Math.tan(.5*i),m=s?u/r:u,y=s?u:u*r,c=-(a+h)/(a-h),p=-2*a*h/(a-h);t.Matrix.FromValuesToRef(m,0,0,0,0,y,0,0,0,0,c,-1,0,0,p,0,e)},r.PerspectiveFovWebVRToRef=function(t,i,r,n,o){void 0===o&&(o=!0);var e=Math.tan(t.upDegrees*Math.PI/180),s=Math.tan(t.downDegrees*Math.PI/180),h=Math.tan(t.leftDegrees*Math.PI/180),a=Math.tan(t.rightDegrees*Math.PI/180),u=2/(h+a),m=2/(e+s);n.m[0]=u,n.m[1]=n.m[2]=n.m[3]=n.m[4]=0,n.m[5]=m,n.m[6]=n.m[7]=0,n.m[8]=(h-a)*u*.5,n.m[9]=-((e-s)*m*.5),n.m[10]=-(i+r)/(r-i),n.m[11]=1,n.m[12]=n.m[13]=n.m[15]=0,n.m[14]=-(2*r*i)/(r-i)},r.GetFinalMatrix=function(t,i,n,o,e,s){var h=t.width,a=t.height,u=t.x,m=t.y,y=r.FromValues(h/2,0,0,0,0,-a/2,0,0,0,0,s-e,0,u+h/2,a/2+m,e,1);return i.multiply(n).multiply(o).multiply(y)},r.GetAsMatrix2x2=function(t){return new Float32Array([t.m[0],t.m[1],t.m[4],t.m[5]])},r.GetAsMatrix3x3=function(t){return new Float32Array([t.m[0],t.m[1],t.m[2],t.m[4],t.m[5],t.m[6],t.m[8],t.m[9],t.m[10]])},r.Transpose=function(t){var i=new r;return i.m[0]=t.m[0],i.m[1]=t.m[4],i.m[2]=t.m[8],i.m[3]=t.m[12],i.m[4]=t.m[1],i.m[5]=t.m[5],i.m[6]=t.m[9],i.m[7]=t.m[13],i.m[8]=t.m[2],i.m[9]=t.m[6],i.m[10]=t.m[10],i.m[11]=t.m[14],i.m[12]=t.m[3],i.m[13]=t.m[7],i.m[14]=t.m[11],i.m[15]=t.m[15],i},r.Reflection=function(t){var i=new r;return r.ReflectionToRef(t,i),i},r.ReflectionToRef=function(t,i){t.normalize();var r=t.normal.x,n=t.normal.y,o=t.normal.z,e=-2*r,s=-2*n,h=-2*o;i.m[0]=e*r+1,i.m[1]=s*r,i.m[2]=h*r,i.m[3]=0,i.m[4]=e*n,i.m[5]=s*n+1,i.m[6]=h*n,i.m[7]=0,i.m[8]=e*o,i.m[9]=s*o,i.m[10]=h*o+1,i.m[11]=0,i.m[12]=e*t.d,i.m[13]=s*t.d,i.m[14]=h*t.d,i.m[15]=1},r.FromXYZAxesToRef=function(t,i,r,n){n.m[0]=t.x,n.m[1]=t.y,n.m[2]=t.z,n.m[3]=0,n.m[4]=i.x,n.m[5]=i.y,n.m[6]=i.z,n.m[7]=0,n.m[8]=r.x,n.m[9]=r.y,n.m[10]=r.z,n.m[11]=0,n.m[12]=0,n.m[13]=0,n.m[14]=0,n.m[15]=1},r.FromQuaternionToRef=function(t,i){var r=t.x*t.x,n=t.y*t.y,o=t.z*t.z,e=t.x*t.y,s=t.z*t.w,h=t.z*t.x,a=t.y*t.w,u=t.y*t.z,m=t.x*t.w;i.m[0]=1-2*(n+o),i.m[1]=2*(e+s),i.m[2]=2*(h-a),i.m[3]=0,i.m[4]=2*(e-s),i.m[5]=1-2*(o+r),i.m[6]=2*(u+m),i.m[7]=0,i.m[8]=2*(h+a),i.m[9]=2*(u-m),i.m[10]=1-2*(n+r),i.m[11]=0,i.m[12]=0,i.m[13]=0,i.m[14]=0,i.m[15]=1},r}();u._tempQuaternion=new a,u._xAxis=e.Zero(),u._yAxis=e.Zero(),u._zAxis=e.Zero(),t.Matrix=u;var m=function(){function t(t,i,r,n){this.normal=new e(t,i,r),this.d=n}return t.prototype.asArray=function(){return[this.normal.x,this.normal.y,this.normal.z,this.d]},t.prototype.clone=function(){return new t(this.normal.x,this.normal.y,this.normal.z,this.d)},t.prototype.getClassName=function(){return\"Plane\"},t.prototype.getHashCode=function(){var t=this.normal.getHashCode();return t=397*t^(this.d||0)},t.prototype.normalize=function(){var t=Math.sqrt(this.normal.x*this.normal.x+this.normal.y*this.normal.y+this.normal.z*this.normal.z),i=0;return 0!==t&&(i=1/t),this.normal.x*=i,this.normal.y*=i,this.normal.z*=i,this.d*=i,this},t.prototype.transform=function(i){var r=u.Transpose(i),n=this.normal.x,o=this.normal.y,e=this.normal.z,s=this.d,h=n*r.m[0]+o*r.m[1]+e*r.m[2]+s*r.m[3],a=n*r.m[4]+o*r.m[5]+e*r.m[6]+s*r.m[7],m=n*r.m[8]+o*r.m[9]+e*r.m[10]+s*r.m[11],y=n*r.m[12]+o*r.m[13]+e*r.m[14]+s*r.m[15];return new t(h,a,m,y)},t.prototype.dotCoordinate=function(t){return this.normal.x*t.x+this.normal.y*t.y+this.normal.z*t.z+this.d},t.prototype.copyFromPoints=function(t,i,r){var n,o=i.x-t.x,e=i.y-t.y,s=i.z-t.z,h=r.x-t.x,a=r.y-t.y,u=r.z-t.z,m=e*u-s*a,y=s*h-o*u,c=o*a-e*h,p=Math.sqrt(m*m+y*y+c*c);return n=0!==p?1/p:0,this.normal.x=m*n,this.normal.y=y*n,this.normal.z=c*n,this.d=-(this.normal.x*t.x+this.normal.y*t.y+this.normal.z*t.z),this},t.prototype.isFrontFacingTo=function(t,i){var r=e.Dot(this.normal,t);return r<=i},t.prototype.signedDistanceTo=function(t){return e.Dot(t,this.normal)+this.d},t.FromArray=function(i){return new t(i[0],i[1],i[2],i[3])},t.FromPoints=function(i,r,n){var o=new t(0,0,0,0);return o.copyFromPoints(i,r,n),o},t.FromPositionAndNormal=function(i,r){var n=new t(0,0,0,0);return r.normalize(),n.normal=r,n.d=-(r.x*i.x+r.y*i.y+r.z*i.z),n},t.SignedDistanceToPlaneFromPositionAndNormal=function(t,i,r){var n=-(i.x*t.x+i.y*t.y+i.z*t.z);return e.Dot(r,i)+n},t}();t.Plane=m;var y=function(){function t(t,i,r,n){this.x=t,this.y=i,this.width=r,this.height=n}return t.prototype.toGlobal=function(i,r){return new t(this.x*i,this.y*r,this.width*i,this.height*r)},t}();t.Viewport=y;var c=function(){function t(){}return t.GetPlanes=function(i){for(var r=[],n=0;n<6;n++)r.push(new m(0,0,0,0));return t.GetPlanesToRef(i,r),r},t.GetPlanesToRef=function(t,i){i[0].normal.x=t.m[3]+t.m[2],i[0].normal.y=t.m[7]+t.m[6],i[0].normal.z=t.m[11]+t.m[10],i[0].d=t.m[15]+t.m[14],i[0].normalize(),i[1].normal.x=t.m[3]-t.m[2],i[1].normal.y=t.m[7]-t.m[6],i[1].normal.z=t.m[11]-t.m[10],i[1].d=t.m[15]-t.m[14],i[1].normalize(),i[2].normal.x=t.m[3]+t.m[0],i[2].normal.y=t.m[7]+t.m[4],i[2].normal.z=t.m[11]+t.m[8],i[2].d=t.m[15]+t.m[12],i[2].normalize(),i[3].normal.x=t.m[3]-t.m[0],i[3].normal.y=t.m[7]-t.m[4],i[3].normal.z=t.m[11]-t.m[8],i[3].d=t.m[15]-t.m[12],i[3].normalize(),i[4].normal.x=t.m[3]-t.m[1],i[4].normal.y=t.m[7]-t.m[5],i[4].normal.z=t.m[11]-t.m[9],i[4].d=t.m[15]-t.m[13],i[4].normalize(),i[5].normal.x=t.m[3]+t.m[1],i[5].normal.y=t.m[7]+t.m[5],i[5].normal.z=t.m[11]+t.m[9],i[5].d=t.m[15]+t.m[13],i[5].normalize()},t}();t.Frustum=c;var p;!function(t){t[t.LOCAL=0]=\"LOCAL\",t[t.WORLD=1]=\"WORLD\"}(p=t.Space||(t.Space={}));var f=function(){function t(){}return t}();f.X=new e(1,0,0),f.Y=new e(0,1,0),f.Z=new e(0,0,1),t.Axis=f;var x=function(){function t(){}return t.interpolate=function(t,i,r,n,o){for(var e=1-3*n+3*i,s=3*n-6*i,h=3*i,a=t,u=0;u<5;u++){var m=a*a,y=m*a,c=e*y+s*m+h*a,p=1/(3*e*m+2*s*a+h);a-=(c-t)*p,a=Math.min(1,Math.max(0,a))}return 3*Math.pow(1-a,2)*a*r+3*(1-a)*Math.pow(a,2)*o+Math.pow(a,3)},t}();t.BezierCurve=x;var l;!function(t){t[t.CW=0]=\"CW\",t[t.CCW=1]=\"CCW\"}(l=t.Orientation||(t.Orientation={}));var z=function(){function t(t){var i=this;this.degrees=function(){return 180*i._radians/Math.PI},this.radians=function(){return i._radians},this._radians=t,this._radians<0&&(this._radians+=2*Math.PI)}return t.BetweenTwoPoints=function(i,r){var n=r.subtract(i),o=Math.atan2(n.y,n.x);return new t(o)},t.FromRadians=function(i){return new t(i)},t.FromDegrees=function(i){return new t(i*Math.PI/180)},t}();t.Angle=z;var w=function(){function t(t,i,r){this.startPoint=t,this.midPoint=i,this.endPoint=r;var n=Math.pow(i.x,2)+Math.pow(i.y,2),e=(Math.pow(t.x,2)+Math.pow(t.y,2)-n)/2,s=(n-Math.pow(r.x,2)-Math.pow(r.y,2))/2,h=(t.x-i.x)*(i.y-r.y)-(i.x-r.x)*(t.y-i.y);this.centerPoint=new o((e*(i.y-r.y)-s*(t.y-i.y))/h,((t.x-i.x)*s-(i.x-r.x)*e)/h),this.radius=this.centerPoint.subtract(this.startPoint).length(),this.startAngle=z.BetweenTwoPoints(this.centerPoint,this.startPoint);var a=this.startAngle.degrees(),u=z.BetweenTwoPoints(this.centerPoint,this.midPoint).degrees(),m=z.BetweenTwoPoints(this.centerPoint,this.endPoint).degrees();u-a>180&&(u-=360),u-a<-180&&(u+=360),m-u>180&&(m-=360),m-u<-180&&(m+=360),this.orientation=u-a<0?l.CW:l.CCW,this.angle=z.FromDegrees(this.orientation===l.CW?a-m:m-a)}return t}();t.Arc2=w;var v=function(){function t(t,i){this._points=new Array,this._length=0,this.closed=!1,this._points.push(new o(t,i))}return t.prototype.addLineTo=function(t,i){if(closed)return this;var r=new o(t,i),n=this._points[this._points.length-1];return this._points.push(r),this._length+=r.subtract(n).length(),this},t.prototype.addArcTo=function(t,i,r,n,e){if(void 0===e&&(e=36),closed)return this;var s=this._points[this._points.length-1],h=new o(t,i),a=new o(r,n),u=new w(s,h,a),m=u.angle.radians()/e;u.orientation===l.CW&&(m*=-1);for(var y=u.startAngle.radians()+m,c=0;c<e;c++){var p=Math.cos(y)*u.radius+u.centerPoint.x,f=Math.sin(y)*u.radius+u.centerPoint.y;this.addLineTo(p,f),y+=m}return this},t.prototype.close=function(){return this.closed=!0,this},t.prototype.length=function(){var t=this._length;if(!this.closed){var i=this._points[this._points.length-1],r=this._points[0];t+=r.subtract(i).length()}return t},t.prototype.getPoints=function(){return this._points},t.prototype.getPointAtLengthPosition=function(t){if(t<0||t>1)return o.Zero();for(var i=t*this.length(),r=0,n=0;n<this._points.length;n++){var e=(n+1)%this._points.length,s=this._points[n],h=this._points[e],a=h.subtract(s),u=a.length()+r;if(i>=r&&i<=u){var m=a.normalize(),y=i-r;return new o(s.x+m.x*y,s.y+m.y*y)}r=u}return o.Zero()},t.StartingAt=function(i,r){return new t(i,r)},t}();t.Path2=v;var d=function(){function r(t,i,r){this.path=t,this._curve=new Array,this._distances=new Array,this._tangents=new Array,this._normals=new Array,this._binormals=new Array;for(var n=0;n<t.length;n++)this._curve[n]=t[n].clone();this._raw=r||!1,this._compute(i)}return r.prototype.getCurve=function(){return this._curve},r.prototype.getTangents=function(){return this._tangents},r.prototype.getNormals=function(){return this._normals},r.prototype.getBinormals=function(){return this._binormals},r.prototype.getDistances=function(){return this._distances},r.prototype.update=function(t,i){for(var r=0;r<t.length;r++)this._curve[r].x=t[r].x,this._curve[r].y=t[r].y,this._curve[r].z=t[r].z;return this._compute(i),this},r.prototype._compute=function(t){var i=this._curve.length;this._tangents[0]=this._getFirstNonNullVector(0),this._raw||this._tangents[0].normalize(),this._tangents[i-1]=this._curve[i-1].subtract(this._curve[i-2]),this._raw||this._tangents[i-1].normalize();var r=this._tangents[0],n=this._normalVector(this._curve[0],r,t);this._normals[0]=n,this._raw||this._normals[0].normalize(),this._binormals[0]=e.Cross(r,this._normals[0]),this._raw||this._binormals[0].normalize(),this._distances[0]=0;for(var o,s,h,a,u=1;u<i;u++)o=this._getLastNonNullVector(u),u<i-1&&(s=this._getFirstNonNullVector(u),this._tangents[u]=o.add(s),this._tangents[u].normalize()),this._distances[u]=this._distances[u-1]+o.length(),h=this._tangents[u],a=this._binormals[u-1],this._normals[u]=e.Cross(a,h),this._raw||this._normals[u].normalize(),this._binormals[u]=e.Cross(h,this._normals[u]),this._raw||this._binormals[u].normalize()},r.prototype._getFirstNonNullVector=function(t){for(var i=1,r=this._curve[t+i].subtract(this._curve[t]);0===r.length()&&t+i+1<this._curve.length;)i++,r=this._curve[t+i].subtract(this._curve[t]);return r},r.prototype._getLastNonNullVector=function(t){for(var i=1,r=this._curve[t].subtract(this._curve[t-i]);0===r.length()&&t>i+1;)i++,r=this._curve[t].subtract(this._curve[t-i]);return r},r.prototype._normalVector=function(r,n,o){var s,h=n.length();if(0===h&&(h=1),void 0===o||null===o){var a;i.WithinEpsilon(Math.abs(n.y)/h,1,t.Epsilon)?i.WithinEpsilon(Math.abs(n.x)/h,1,t.Epsilon)?i.WithinEpsilon(Math.abs(n.z)/h,1,t.Epsilon)||(a=new e(0,0,1)):a=new e(1,0,0):a=new e(0,(-1),0),s=e.Cross(n,a)}else s=e.Cross(n,o),e.CrossToRef(s,n,s);return s.normalize(),s},r}();t.Path3D=d;var g=function(){function t(t){this._length=0,this._points=t,this._length=this._computeLength(t)}return t.CreateQuadraticBezier=function(i,r,n,o){o=o>2?o:3;for(var s=new Array,h=function(t,i,r,n){var o=(1-t)*(1-t)*i+2*t*(1-t)*r+t*t*n;return o},a=0;a<=o;a++)s.push(new e(h(a/o,i.x,r.x,n.x),h(a/o,i.y,r.y,n.y),h(a/o,i.z,r.z,n.z)));return new t(s)},t.CreateCubicBezier=function(i,r,n,o,s){s=s>3?s:4;for(var h=new Array,a=function(t,i,r,n,o){var e=(1-t)*(1-t)*(1-t)*i+3*t*(1-t)*(1-t)*r+3*t*t*(1-t)*n+t*t*t*o;return e},u=0;u<=s;u++)h.push(new e(a(u/s,i.x,r.x,n.x,o.x),a(u/s,i.y,r.y,n.y,o.y),a(u/s,i.z,r.z,n.z,o.z)));return new t(h)},t.CreateHermiteSpline=function(i,r,n,o,s){for(var h=new Array,a=1/s,u=0;u<=s;u++)h.push(e.Hermite(i,r,n,o,u*a));return new t(h)},t.prototype.getPoints=function(){return this._points},t.prototype.length=function(){return this._length},t.prototype[\"continue\"]=function(i){for(var r=this._points[this._points.length-1],n=this._points.slice(),o=i.getPoints(),e=1;e<o.length;e++)n.push(o[e].subtract(o[0]).add(r));var s=new t(n);return s},t.prototype._computeLength=function(t){for(var i=0,r=1;r<t.length;r++)i+=t[r].subtract(t[r-1]).length();return i},t}();t.Curve3=g;var R=function(){function t(){this.L00=e.Zero(),this.L1_1=e.Zero(),this.L10=e.Zero(),this.L11=e.Zero(),this.L2_2=e.Zero(),this.L2_1=e.Zero(),this.L20=e.Zero(),this.L21=e.Zero(),this.L22=e.Zero()}return t.prototype.addLight=function(t,i,r){var n=new e(i.r,i.g,i.b),o=n.scale(r);this.L00=this.L00.add(o.scale(.282095)),this.L1_1=this.L1_1.add(o.scale(.488603*t.y)),this.L10=this.L10.add(o.scale(.488603*t.z)),this.L11=this.L11.add(o.scale(.488603*t.x)),this.L2_2=this.L2_2.add(o.scale(1.092548*t.x*t.y)),this.L2_1=this.L2_1.add(o.scale(1.092548*t.y*t.z)),this.L21=this.L21.add(o.scale(1.092548*t.x*t.z)),this.L20=this.L20.add(o.scale(.315392*(3*t.z*t.z-1))),this.L22=this.L22.add(o.scale(.546274*(t.x*t.x-t.y*t.y)))},t.prototype.scale=function(t){this.L00=this.L00.scale(t),this.L1_1=this.L1_1.scale(t),this.L10=this.L10.scale(t),this.L11=this.L11.scale(t),this.L2_2=this.L2_2.scale(t),this.L2_1=this.L2_1.scale(t),this.L20=this.L20.scale(t),this.L21=this.L21.scale(t),this.L22=this.L22.scale(t)},t}();t.SphericalHarmonics=R;var T=function(){function t(){this.x=e.Zero(),this.y=e.Zero(),this.z=e.Zero(),this.xx=e.Zero(),this.yy=e.Zero(),this.zz=e.Zero(),this.xy=e.Zero(),this.yz=e.Zero(),this.zx=e.Zero()}return t.prototype.addAmbient=function(t){var i=new e(t.r,t.g,t.b);this.xx=this.xx.add(i),this.yy=this.yy.add(i),this.zz=this.zz.add(i)},t.getSphericalPolynomialFromHarmonics=function(i){var r=new t;return r.x=i.L11.scale(1.02333),r.y=i.L1_1.scale(1.02333),r.z=i.L10.scale(1.02333),r.xx=i.L00.scale(.886277).subtract(i.L20.scale(.247708)).add(i.L22.scale(.429043)),r.yy=i.L00.scale(.886277).subtract(i.L20.scale(.247708)).subtract(i.L22.scale(.429043)),r.zz=i.L00.scale(.886277).add(i.L20.scale(.495417)),r.yz=i.L2_1.scale(.858086),r.zx=i.L21.scale(.858086),r.xy=i.L2_2.scale(.858086),r},t}();t.SphericalPolynomial=T;var _=function(){function t(t,i){void 0===t&&(t=e.Zero()),void 0===i&&(i=e.Up()),this.position=t,this.normal=i}return t.prototype.clone=function(){return new t(this.position.clone(),this.normal.clone())},t}();t.PositionNormalVertex=_;var M=function(){function t(t,i,r){void 0===t&&(t=e.Zero()),void 0===i&&(i=e.Up()),void 0===r&&(r=o.Zero()),this.position=t,this.normal=i,this.uv=r}return t.prototype.clone=function(){return new t(this.position.clone(),this.normal.clone(),this.uv.clone())},t}();t.PositionNormalTextureVertex=M;var A=function(){function t(){}return t}();A.Color3=[r.Black(),r.Black(),r.Black()],A.Vector2=[o.Zero(),o.Zero(),o.Zero()],A.Vector3=[e.Zero(),e.Zero(),e.Zero(),e.Zero(),e.Zero(),e.Zero(),e.Zero(),e.Zero(),e.Zero()],A.Vector4=[s.Zero(),s.Zero(),s.Zero()],A.Quaternion=[new a(0,0,0,0)],A.Matrix=[u.Zero(),u.Zero(),u.Zero(),u.Zero(),u.Zero(),u.Zero(),u.Zero(),u.Zero()],t.Tmp=A}(BABYLON||(BABYLON={}));";
  55272. if (((typeof window != "undefined" && window.module) || (typeof module != "undefined")) && typeof module.exports != "undefined") {
  55273. module.exports = BABYLON;
  55274. };