babylon.max.js 2.8 MB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739287402874128742287432874428745287462874728748287492875028751287522875328754287552875628757287582875928760287612876228763287642876528766287672876828769287702877128772287732877428775287762877728778287792878028781287822878328784287852878628787287882878928790287912879228793287942879528796287972879828799288002880128802288032880428805288062880728808288092881028811288122881328814288152881628817288182881928820288212882228823288242882528826288272882828829288302883128832288332883428835288362883728838288392884028841288422884328844288452884628847288482884928850288512885228853288542885528856288572885828859288602886128862288632886428865288662886728868288692887028871288722887328874288752887628877288782887928880288812888228883288842888528886288872888828889288902889128892288932889428895288962889728898288992890028901289022890328904289052890628907289082890928910289112891228913289142891528916289172891828919289202892128922289232892428925289262892728928289292893028931289322893328934289352893628937289382893928940289412894228943289442894528946289472894828949289502895128952289532895428955289562895728958289592896028961289622896328964289652896628967289682896928970289712897228973289742897528976289772897828979289802898128982289832898428985289862898728988289892899028991289922899328994289952899628997289982899929000290012900229003290042900529006290072900829009290102901129012290132901429015290162901729018290192902029021290222902329024290252902629027290282902929030290312903229033290342903529036290372903829039290402904129042290432904429045290462904729048290492905029051290522905329054290552905629057290582905929060290612906229063290642906529066290672906829069290702907129072290732907429075290762907729078290792908029081290822908329084290852908629087290882908929090290912909229093290942909529096290972909829099291002910129102291032910429105291062910729108291092911029111291122911329114291152911629117291182911929120291212912229123291242912529126291272912829129291302913129132291332913429135291362913729138291392914029141291422914329144291452914629147291482914929150291512915229153291542915529156291572915829159291602916129162291632916429165291662916729168291692917029171291722917329174291752917629177291782917929180291812918229183291842918529186291872918829189291902919129192291932919429195291962919729198291992920029201292022920329204292052920629207292082920929210292112921229213292142921529216292172921829219292202922129222292232922429225292262922729228292292923029231292322923329234292352923629237292382923929240292412924229243292442924529246292472924829249292502925129252292532925429255292562925729258292592926029261292622926329264292652926629267292682926929270292712927229273292742927529276292772927829279292802928129282292832928429285292862928729288292892929029291292922929329294292952929629297292982929929300293012930229303293042930529306293072930829309293102931129312293132931429315293162931729318293192932029321293222932329324293252932629327293282932929330293312933229333293342933529336293372933829339293402934129342293432934429345293462934729348293492935029351293522935329354293552935629357293582935929360293612936229363293642936529366293672936829369293702937129372293732937429375293762937729378293792938029381293822938329384293852938629387293882938929390293912939229393293942939529396293972939829399294002940129402294032940429405294062940729408294092941029411294122941329414294152941629417294182941929420294212942229423294242942529426294272942829429294302943129432294332943429435294362943729438294392944029441294422944329444294452944629447294482944929450294512945229453294542945529456294572945829459294602946129462294632946429465294662946729468294692947029471294722947329474294752947629477294782947929480294812948229483294842948529486294872948829489294902949129492294932949429495294962949729498294992950029501295022950329504295052950629507295082950929510295112951229513295142951529516295172951829519295202952129522295232952429525295262952729528295292953029531295322953329534295352953629537295382953929540295412954229543295442954529546295472954829549295502955129552295532955429555295562955729558295592956029561295622956329564295652956629567295682956929570295712957229573295742957529576295772957829579295802958129582295832958429585295862958729588295892959029591295922959329594295952959629597295982959929600296012960229603296042960529606296072960829609296102961129612296132961429615296162961729618296192962029621296222962329624296252962629627296282962929630296312963229633296342963529636296372963829639296402964129642296432964429645296462964729648296492965029651296522965329654296552965629657296582965929660296612966229663296642966529666296672966829669296702967129672296732967429675296762967729678296792968029681296822968329684296852968629687296882968929690296912969229693296942969529696296972969829699297002970129702297032970429705297062970729708297092971029711297122971329714297152971629717297182971929720297212972229723297242972529726297272972829729297302973129732297332973429735297362973729738297392974029741297422974329744297452974629747297482974929750297512975229753297542975529756297572975829759297602976129762297632976429765297662976729768297692977029771297722977329774297752977629777297782977929780297812978229783297842978529786297872978829789297902979129792297932979429795297962979729798297992980029801298022980329804298052980629807298082980929810298112981229813298142981529816298172981829819298202982129822298232982429825298262982729828298292983029831298322983329834298352983629837298382983929840298412984229843298442984529846298472984829849298502985129852298532985429855298562985729858298592986029861298622986329864298652986629867298682986929870298712987229873298742987529876298772987829879298802988129882298832988429885298862988729888298892989029891298922989329894298952989629897298982989929900299012990229903299042990529906299072990829909299102991129912299132991429915299162991729918299192992029921299222992329924299252992629927299282992929930299312993229933299342993529936299372993829939299402994129942299432994429945299462994729948299492995029951299522995329954299552995629957299582995929960299612996229963299642996529966299672996829969299702997129972299732997429975299762997729978299792998029981299822998329984299852998629987299882998929990299912999229993299942999529996299972999829999300003000130002300033000430005300063000730008300093001030011300123001330014300153001630017300183001930020300213002230023300243002530026300273002830029300303003130032300333003430035300363003730038300393004030041300423004330044300453004630047300483004930050300513005230053300543005530056300573005830059300603006130062300633006430065300663006730068300693007030071300723007330074300753007630077300783007930080300813008230083300843008530086300873008830089300903009130092300933009430095300963009730098300993010030101301023010330104301053010630107301083010930110301113011230113301143011530116301173011830119301203012130122301233012430125301263012730128301293013030131301323013330134301353013630137301383013930140301413014230143301443014530146301473014830149301503015130152301533015430155301563015730158301593016030161301623016330164301653016630167301683016930170301713017230173301743017530176301773017830179301803018130182301833018430185301863018730188301893019030191301923019330194301953019630197301983019930200302013020230203302043020530206302073020830209302103021130212302133021430215302163021730218302193022030221302223022330224302253022630227302283022930230302313023230233302343023530236302373023830239302403024130242302433024430245302463024730248302493025030251302523025330254302553025630257302583025930260302613026230263302643026530266302673026830269302703027130272302733027430275302763027730278302793028030281302823028330284302853028630287302883028930290302913029230293302943029530296302973029830299303003030130302303033030430305303063030730308303093031030311303123031330314303153031630317303183031930320303213032230323303243032530326303273032830329303303033130332303333033430335303363033730338303393034030341303423034330344303453034630347303483034930350303513035230353303543035530356303573035830359303603036130362303633036430365303663036730368303693037030371303723037330374303753037630377303783037930380303813038230383303843038530386303873038830389303903039130392303933039430395303963039730398303993040030401304023040330404304053040630407304083040930410304113041230413304143041530416304173041830419304203042130422304233042430425304263042730428304293043030431304323043330434304353043630437304383043930440304413044230443304443044530446304473044830449304503045130452304533045430455304563045730458304593046030461304623046330464304653046630467304683046930470304713047230473304743047530476304773047830479304803048130482304833048430485304863048730488304893049030491304923049330494304953049630497304983049930500305013050230503305043050530506305073050830509305103051130512305133051430515305163051730518305193052030521305223052330524305253052630527305283052930530305313053230533305343053530536305373053830539305403054130542305433054430545305463054730548305493055030551305523055330554305553055630557305583055930560305613056230563305643056530566305673056830569305703057130572305733057430575305763057730578305793058030581305823058330584305853058630587305883058930590305913059230593305943059530596305973059830599306003060130602306033060430605306063060730608306093061030611306123061330614306153061630617306183061930620306213062230623306243062530626306273062830629306303063130632306333063430635306363063730638306393064030641306423064330644306453064630647306483064930650306513065230653306543065530656306573065830659306603066130662306633066430665306663066730668306693067030671306723067330674306753067630677306783067930680306813068230683306843068530686306873068830689306903069130692306933069430695306963069730698306993070030701307023070330704307053070630707307083070930710307113071230713307143071530716307173071830719307203072130722307233072430725307263072730728307293073030731307323073330734307353073630737307383073930740307413074230743307443074530746307473074830749307503075130752307533075430755307563075730758307593076030761307623076330764307653076630767307683076930770307713077230773307743077530776307773077830779307803078130782307833078430785307863078730788307893079030791307923079330794307953079630797307983079930800308013080230803308043080530806308073080830809308103081130812308133081430815308163081730818308193082030821308223082330824308253082630827308283082930830308313083230833308343083530836308373083830839308403084130842308433084430845308463084730848308493085030851308523085330854308553085630857308583085930860308613086230863308643086530866308673086830869308703087130872308733087430875308763087730878308793088030881308823088330884308853088630887308883088930890308913089230893308943089530896308973089830899309003090130902309033090430905309063090730908309093091030911309123091330914309153091630917309183091930920309213092230923309243092530926309273092830929309303093130932309333093430935309363093730938309393094030941309423094330944309453094630947309483094930950309513095230953309543095530956309573095830959309603096130962309633096430965309663096730968309693097030971309723097330974309753097630977309783097930980309813098230983309843098530986309873098830989309903099130992309933099430995309963099730998309993100031001310023100331004310053100631007310083100931010310113101231013310143101531016310173101831019310203102131022310233102431025310263102731028310293103031031310323103331034310353103631037310383103931040310413104231043310443104531046310473104831049310503105131052310533105431055310563105731058310593106031061310623106331064310653106631067310683106931070310713107231073310743107531076310773107831079310803108131082310833108431085310863108731088310893109031091310923109331094310953109631097310983109931100311013110231103311043110531106311073110831109311103111131112311133111431115311163111731118311193112031121311223112331124311253112631127311283112931130311313113231133311343113531136311373113831139311403114131142311433114431145311463114731148311493115031151311523115331154311553115631157311583115931160311613116231163311643116531166311673116831169311703117131172311733117431175311763117731178311793118031181311823118331184311853118631187311883118931190311913119231193311943119531196311973119831199312003120131202312033120431205312063120731208312093121031211312123121331214312153121631217312183121931220312213122231223312243122531226312273122831229312303123131232312333123431235312363123731238312393124031241312423124331244312453124631247312483124931250312513125231253312543125531256312573125831259312603126131262312633126431265312663126731268312693127031271312723127331274312753127631277312783127931280312813128231283312843128531286312873128831289312903129131292312933129431295312963129731298312993130031301313023130331304313053130631307313083130931310313113131231313313143131531316313173131831319313203132131322313233132431325313263132731328313293133031331313323133331334313353133631337313383133931340313413134231343313443134531346313473134831349313503135131352313533135431355313563135731358313593136031361313623136331364313653136631367313683136931370313713137231373313743137531376313773137831379313803138131382313833138431385313863138731388313893139031391313923139331394313953139631397313983139931400314013140231403314043140531406314073140831409314103141131412314133141431415314163141731418314193142031421314223142331424314253142631427314283142931430314313143231433314343143531436314373143831439314403144131442314433144431445314463144731448314493145031451314523145331454314553145631457314583145931460314613146231463314643146531466314673146831469314703147131472314733147431475314763147731478314793148031481314823148331484314853148631487314883148931490314913149231493314943149531496314973149831499315003150131502315033150431505315063150731508315093151031511315123151331514315153151631517315183151931520315213152231523315243152531526315273152831529315303153131532315333153431535315363153731538315393154031541315423154331544315453154631547315483154931550315513155231553315543155531556315573155831559315603156131562315633156431565315663156731568315693157031571315723157331574315753157631577315783157931580315813158231583315843158531586315873158831589315903159131592315933159431595315963159731598315993160031601316023160331604316053160631607316083160931610316113161231613316143161531616316173161831619316203162131622316233162431625316263162731628316293163031631316323163331634316353163631637316383163931640316413164231643316443164531646316473164831649316503165131652316533165431655316563165731658316593166031661316623166331664316653166631667316683166931670316713167231673316743167531676316773167831679316803168131682316833168431685316863168731688316893169031691316923169331694316953169631697316983169931700317013170231703317043170531706317073170831709317103171131712317133171431715317163171731718317193172031721317223172331724317253172631727317283172931730317313173231733317343173531736317373173831739317403174131742317433174431745317463174731748317493175031751317523175331754317553175631757317583175931760317613176231763317643176531766317673176831769317703177131772317733177431775317763177731778317793178031781317823178331784317853178631787317883178931790317913179231793317943179531796317973179831799318003180131802318033180431805318063180731808318093181031811318123181331814318153181631817318183181931820318213182231823318243182531826318273182831829318303183131832318333183431835318363183731838318393184031841318423184331844318453184631847318483184931850318513185231853318543185531856318573185831859318603186131862318633186431865318663186731868318693187031871318723187331874318753187631877318783187931880318813188231883318843188531886318873188831889318903189131892318933189431895318963189731898318993190031901319023190331904319053190631907319083190931910319113191231913319143191531916319173191831919319203192131922319233192431925319263192731928319293193031931319323193331934319353193631937319383193931940319413194231943319443194531946319473194831949319503195131952319533195431955319563195731958319593196031961319623196331964319653196631967319683196931970319713197231973319743197531976319773197831979319803198131982319833198431985319863198731988319893199031991319923199331994319953199631997319983199932000320013200232003320043200532006320073200832009320103201132012320133201432015320163201732018320193202032021320223202332024320253202632027320283202932030320313203232033320343203532036320373203832039320403204132042320433204432045320463204732048320493205032051320523205332054320553205632057320583205932060320613206232063320643206532066320673206832069320703207132072320733207432075320763207732078320793208032081320823208332084320853208632087320883208932090320913209232093320943209532096320973209832099321003210132102321033210432105321063210732108321093211032111321123211332114321153211632117321183211932120321213212232123321243212532126321273212832129321303213132132321333213432135321363213732138321393214032141321423214332144321453214632147321483214932150321513215232153321543215532156321573215832159321603216132162321633216432165321663216732168321693217032171321723217332174321753217632177321783217932180321813218232183321843218532186321873218832189321903219132192321933219432195321963219732198321993220032201322023220332204322053220632207322083220932210322113221232213322143221532216322173221832219322203222132222322233222432225322263222732228322293223032231322323223332234322353223632237322383223932240322413224232243322443224532246322473224832249322503225132252322533225432255322563225732258322593226032261322623226332264322653226632267322683226932270322713227232273322743227532276322773227832279322803228132282322833228432285322863228732288322893229032291322923229332294322953229632297322983229932300323013230232303323043230532306323073230832309323103231132312323133231432315323163231732318323193232032321323223232332324323253232632327323283232932330323313233232333323343233532336323373233832339323403234132342323433234432345323463234732348323493235032351323523235332354323553235632357323583235932360323613236232363323643236532366323673236832369323703237132372323733237432375323763237732378323793238032381323823238332384323853238632387323883238932390323913239232393323943239532396323973239832399324003240132402324033240432405324063240732408324093241032411324123241332414324153241632417324183241932420324213242232423324243242532426324273242832429324303243132432324333243432435324363243732438324393244032441324423244332444324453244632447324483244932450324513245232453324543245532456324573245832459324603246132462324633246432465324663246732468324693247032471324723247332474324753247632477324783247932480324813248232483324843248532486324873248832489324903249132492324933249432495324963249732498324993250032501325023250332504325053250632507325083250932510325113251232513325143251532516325173251832519325203252132522325233252432525325263252732528325293253032531325323253332534325353253632537325383253932540325413254232543325443254532546325473254832549325503255132552325533255432555325563255732558325593256032561325623256332564325653256632567325683256932570325713257232573325743257532576325773257832579325803258132582325833258432585325863258732588325893259032591325923259332594325953259632597325983259932600326013260232603326043260532606326073260832609326103261132612326133261432615326163261732618326193262032621326223262332624326253262632627326283262932630326313263232633326343263532636326373263832639326403264132642326433264432645326463264732648326493265032651326523265332654326553265632657326583265932660326613266232663326643266532666326673266832669326703267132672326733267432675326763267732678326793268032681326823268332684326853268632687326883268932690326913269232693326943269532696326973269832699327003270132702327033270432705327063270732708327093271032711327123271332714327153271632717327183271932720327213272232723327243272532726327273272832729327303273132732327333273432735327363273732738327393274032741327423274332744327453274632747327483274932750327513275232753327543275532756327573275832759327603276132762327633276432765327663276732768327693277032771327723277332774327753277632777327783277932780327813278232783327843278532786327873278832789327903279132792327933279432795327963279732798327993280032801328023280332804328053280632807328083280932810328113281232813328143281532816328173281832819328203282132822328233282432825328263282732828328293283032831328323283332834328353283632837328383283932840328413284232843328443284532846328473284832849328503285132852328533285432855328563285732858328593286032861328623286332864328653286632867328683286932870328713287232873328743287532876328773287832879328803288132882328833288432885328863288732888328893289032891328923289332894328953289632897328983289932900329013290232903329043290532906329073290832909329103291132912329133291432915329163291732918329193292032921329223292332924329253292632927329283292932930329313293232933329343293532936329373293832939329403294132942329433294432945329463294732948329493295032951329523295332954329553295632957329583295932960329613296232963329643296532966329673296832969329703297132972329733297432975329763297732978329793298032981329823298332984329853298632987329883298932990329913299232993329943299532996329973299832999330003300133002330033300433005330063300733008330093301033011330123301333014330153301633017330183301933020330213302233023330243302533026330273302833029330303303133032330333303433035330363303733038330393304033041330423304333044330453304633047330483304933050330513305233053330543305533056330573305833059330603306133062330633306433065330663306733068330693307033071330723307333074330753307633077330783307933080330813308233083330843308533086330873308833089330903309133092330933309433095330963309733098330993310033101331023310333104331053310633107331083310933110331113311233113331143311533116331173311833119331203312133122331233312433125331263312733128331293313033131331323313333134331353313633137331383313933140331413314233143331443314533146331473314833149331503315133152331533315433155331563315733158331593316033161331623316333164331653316633167331683316933170331713317233173331743317533176331773317833179331803318133182331833318433185331863318733188331893319033191331923319333194331953319633197331983319933200332013320233203332043320533206332073320833209332103321133212332133321433215332163321733218332193322033221332223322333224332253322633227332283322933230332313323233233332343323533236332373323833239332403324133242332433324433245332463324733248332493325033251332523325333254332553325633257332583325933260332613326233263332643326533266332673326833269332703327133272332733327433275332763327733278332793328033281332823328333284332853328633287332883328933290332913329233293332943329533296332973329833299333003330133302333033330433305333063330733308333093331033311333123331333314333153331633317333183331933320333213332233323333243332533326333273332833329333303333133332333333333433335333363333733338333393334033341333423334333344333453334633347333483334933350333513335233353333543335533356333573335833359333603336133362333633336433365333663336733368333693337033371333723337333374333753337633377333783337933380333813338233383333843338533386333873338833389333903339133392333933339433395333963339733398333993340033401334023340333404334053340633407334083340933410334113341233413334143341533416334173341833419334203342133422334233342433425334263342733428334293343033431334323343333434334353343633437334383343933440334413344233443334443344533446334473344833449334503345133452334533345433455334563345733458334593346033461334623346333464334653346633467334683346933470334713347233473334743347533476334773347833479334803348133482334833348433485334863348733488334893349033491334923349333494334953349633497334983349933500335013350233503335043350533506335073350833509335103351133512335133351433515335163351733518335193352033521335223352333524335253352633527335283352933530335313353233533335343353533536335373353833539335403354133542335433354433545335463354733548335493355033551335523355333554335553355633557335583355933560335613356233563335643356533566335673356833569335703357133572335733357433575335763357733578335793358033581335823358333584335853358633587335883358933590335913359233593335943359533596335973359833599336003360133602336033360433605336063360733608336093361033611336123361333614336153361633617336183361933620336213362233623336243362533626336273362833629336303363133632336333363433635336363363733638336393364033641336423364333644336453364633647336483364933650336513365233653336543365533656336573365833659336603366133662336633366433665336663366733668336693367033671336723367333674336753367633677336783367933680336813368233683336843368533686336873368833689336903369133692336933369433695336963369733698336993370033701337023370333704337053370633707337083370933710337113371233713337143371533716337173371833719337203372133722337233372433725337263372733728337293373033731337323373333734337353373633737337383373933740337413374233743337443374533746337473374833749337503375133752337533375433755337563375733758337593376033761337623376333764337653376633767337683376933770337713377233773337743377533776337773377833779337803378133782337833378433785337863378733788337893379033791337923379333794337953379633797337983379933800338013380233803338043380533806338073380833809338103381133812338133381433815338163381733818338193382033821338223382333824338253382633827338283382933830338313383233833338343383533836338373383833839338403384133842338433384433845338463384733848338493385033851338523385333854338553385633857338583385933860338613386233863338643386533866338673386833869338703387133872338733387433875338763387733878338793388033881338823388333884338853388633887338883388933890338913389233893338943389533896338973389833899339003390133902339033390433905339063390733908339093391033911339123391333914339153391633917339183391933920339213392233923339243392533926339273392833929339303393133932339333393433935339363393733938339393394033941339423394333944339453394633947339483394933950339513395233953339543395533956339573395833959339603396133962339633396433965339663396733968339693397033971339723397333974339753397633977339783397933980339813398233983339843398533986339873398833989339903399133992339933399433995339963399733998339993400034001340023400334004340053400634007340083400934010340113401234013340143401534016340173401834019340203402134022340233402434025340263402734028340293403034031340323403334034340353403634037340383403934040340413404234043340443404534046340473404834049340503405134052340533405434055340563405734058340593406034061340623406334064340653406634067340683406934070340713407234073340743407534076340773407834079340803408134082340833408434085340863408734088340893409034091340923409334094340953409634097340983409934100341013410234103341043410534106341073410834109341103411134112341133411434115341163411734118341193412034121341223412334124341253412634127341283412934130341313413234133341343413534136341373413834139341403414134142341433414434145341463414734148341493415034151341523415334154341553415634157341583415934160341613416234163341643416534166341673416834169341703417134172341733417434175341763417734178341793418034181341823418334184341853418634187341883418934190341913419234193341943419534196341973419834199342003420134202342033420434205342063420734208342093421034211342123421334214342153421634217342183421934220342213422234223342243422534226342273422834229342303423134232342333423434235342363423734238342393424034241342423424334244342453424634247342483424934250342513425234253342543425534256342573425834259342603426134262342633426434265342663426734268342693427034271342723427334274342753427634277342783427934280342813428234283342843428534286342873428834289342903429134292342933429434295342963429734298342993430034301343023430334304343053430634307343083430934310343113431234313343143431534316343173431834319343203432134322343233432434325343263432734328343293433034331343323433334334343353433634337343383433934340343413434234343343443434534346343473434834349343503435134352343533435434355343563435734358343593436034361343623436334364343653436634367343683436934370343713437234373343743437534376343773437834379343803438134382343833438434385343863438734388343893439034391343923439334394343953439634397343983439934400344013440234403344043440534406344073440834409344103441134412344133441434415344163441734418344193442034421344223442334424344253442634427344283442934430344313443234433344343443534436344373443834439344403444134442344433444434445344463444734448344493445034451344523445334454344553445634457344583445934460344613446234463344643446534466344673446834469344703447134472344733447434475344763447734478344793448034481344823448334484344853448634487344883448934490344913449234493344943449534496344973449834499345003450134502345033450434505345063450734508345093451034511345123451334514345153451634517345183451934520345213452234523345243452534526345273452834529345303453134532345333453434535345363453734538345393454034541345423454334544345453454634547345483454934550345513455234553345543455534556345573455834559345603456134562345633456434565345663456734568345693457034571345723457334574345753457634577345783457934580345813458234583345843458534586345873458834589345903459134592345933459434595345963459734598345993460034601346023460334604346053460634607346083460934610346113461234613346143461534616346173461834619346203462134622346233462434625346263462734628346293463034631346323463334634346353463634637346383463934640346413464234643346443464534646346473464834649346503465134652346533465434655346563465734658346593466034661346623466334664346653466634667346683466934670346713467234673346743467534676346773467834679346803468134682346833468434685346863468734688346893469034691346923469334694346953469634697346983469934700347013470234703347043470534706347073470834709347103471134712347133471434715347163471734718347193472034721347223472334724347253472634727347283472934730347313473234733347343473534736347373473834739347403474134742347433474434745347463474734748347493475034751347523475334754347553475634757347583475934760347613476234763347643476534766347673476834769347703477134772347733477434775347763477734778347793478034781347823478334784347853478634787347883478934790347913479234793347943479534796347973479834799348003480134802348033480434805348063480734808348093481034811348123481334814348153481634817348183481934820348213482234823348243482534826348273482834829348303483134832348333483434835348363483734838348393484034841348423484334844348453484634847348483484934850348513485234853348543485534856348573485834859348603486134862348633486434865348663486734868348693487034871348723487334874348753487634877348783487934880348813488234883348843488534886348873488834889348903489134892348933489434895348963489734898348993490034901349023490334904349053490634907349083490934910349113491234913349143491534916349173491834919349203492134922349233492434925349263492734928349293493034931349323493334934349353493634937349383493934940349413494234943349443494534946349473494834949349503495134952349533495434955349563495734958349593496034961349623496334964349653496634967349683496934970349713497234973349743497534976349773497834979349803498134982349833498434985349863498734988349893499034991349923499334994349953499634997349983499935000350013500235003350043500535006350073500835009350103501135012350133501435015350163501735018350193502035021350223502335024350253502635027350283502935030350313503235033350343503535036350373503835039350403504135042350433504435045350463504735048350493505035051350523505335054350553505635057350583505935060350613506235063350643506535066350673506835069350703507135072350733507435075350763507735078350793508035081350823508335084350853508635087350883508935090350913509235093350943509535096350973509835099351003510135102351033510435105351063510735108351093511035111351123511335114351153511635117351183511935120351213512235123351243512535126351273512835129351303513135132351333513435135351363513735138351393514035141351423514335144351453514635147351483514935150351513515235153351543515535156351573515835159351603516135162351633516435165351663516735168351693517035171351723517335174351753517635177351783517935180351813518235183351843518535186351873518835189351903519135192351933519435195351963519735198351993520035201352023520335204352053520635207352083520935210352113521235213352143521535216352173521835219352203522135222352233522435225352263522735228352293523035231352323523335234352353523635237352383523935240352413524235243352443524535246352473524835249352503525135252352533525435255352563525735258352593526035261352623526335264352653526635267352683526935270352713527235273352743527535276352773527835279352803528135282352833528435285352863528735288352893529035291352923529335294352953529635297352983529935300353013530235303353043530535306353073530835309353103531135312353133531435315353163531735318353193532035321353223532335324353253532635327353283532935330353313533235333353343533535336353373533835339353403534135342353433534435345353463534735348353493535035351353523535335354353553535635357353583535935360353613536235363353643536535366353673536835369353703537135372353733537435375353763537735378353793538035381353823538335384353853538635387353883538935390353913539235393353943539535396353973539835399354003540135402354033540435405354063540735408354093541035411354123541335414354153541635417354183541935420354213542235423354243542535426354273542835429354303543135432354333543435435354363543735438354393544035441354423544335444354453544635447354483544935450354513545235453354543545535456354573545835459354603546135462354633546435465354663546735468354693547035471354723547335474354753547635477354783547935480354813548235483354843548535486354873548835489354903549135492354933549435495354963549735498354993550035501355023550335504355053550635507355083550935510355113551235513355143551535516355173551835519355203552135522355233552435525355263552735528355293553035531355323553335534355353553635537355383553935540355413554235543355443554535546355473554835549355503555135552355533555435555355563555735558355593556035561355623556335564355653556635567355683556935570355713557235573355743557535576355773557835579355803558135582355833558435585355863558735588355893559035591355923559335594355953559635597355983559935600356013560235603356043560535606356073560835609356103561135612356133561435615356163561735618356193562035621356223562335624356253562635627356283562935630356313563235633356343563535636356373563835639356403564135642356433564435645356463564735648356493565035651356523565335654356553565635657356583565935660356613566235663356643566535666356673566835669356703567135672356733567435675356763567735678356793568035681356823568335684356853568635687356883568935690356913569235693356943569535696356973569835699357003570135702357033570435705357063570735708357093571035711357123571335714357153571635717357183571935720357213572235723357243572535726357273572835729357303573135732357333573435735357363573735738357393574035741357423574335744357453574635747357483574935750357513575235753357543575535756357573575835759357603576135762357633576435765357663576735768357693577035771357723577335774357753577635777357783577935780357813578235783357843578535786357873578835789357903579135792357933579435795357963579735798357993580035801358023580335804358053580635807358083580935810358113581235813358143581535816358173581835819358203582135822358233582435825358263582735828358293583035831358323583335834358353583635837358383583935840358413584235843358443584535846358473584835849358503585135852358533585435855358563585735858358593586035861358623586335864358653586635867358683586935870358713587235873358743587535876358773587835879358803588135882358833588435885358863588735888358893589035891358923589335894358953589635897358983589935900359013590235903359043590535906359073590835909359103591135912359133591435915359163591735918359193592035921359223592335924359253592635927359283592935930359313593235933359343593535936359373593835939359403594135942359433594435945359463594735948359493595035951359523595335954359553595635957359583595935960359613596235963359643596535966359673596835969359703597135972359733597435975359763597735978359793598035981359823598335984359853598635987359883598935990359913599235993359943599535996359973599835999360003600136002360033600436005360063600736008360093601036011360123601336014360153601636017360183601936020360213602236023360243602536026360273602836029360303603136032360333603436035360363603736038360393604036041360423604336044360453604636047360483604936050360513605236053360543605536056360573605836059360603606136062360633606436065360663606736068360693607036071360723607336074360753607636077360783607936080360813608236083360843608536086360873608836089360903609136092360933609436095360963609736098360993610036101361023610336104361053610636107361083610936110361113611236113361143611536116361173611836119361203612136122361233612436125361263612736128361293613036131361323613336134361353613636137361383613936140361413614236143361443614536146361473614836149361503615136152361533615436155361563615736158361593616036161361623616336164361653616636167361683616936170361713617236173361743617536176361773617836179361803618136182361833618436185361863618736188361893619036191361923619336194361953619636197361983619936200362013620236203362043620536206362073620836209362103621136212362133621436215362163621736218362193622036221362223622336224362253622636227362283622936230362313623236233362343623536236362373623836239362403624136242362433624436245362463624736248362493625036251362523625336254362553625636257362583625936260362613626236263362643626536266362673626836269362703627136272362733627436275362763627736278362793628036281362823628336284362853628636287362883628936290362913629236293362943629536296362973629836299363003630136302363033630436305363063630736308363093631036311363123631336314363153631636317363183631936320363213632236323363243632536326363273632836329363303633136332363333633436335363363633736338363393634036341363423634336344363453634636347363483634936350363513635236353363543635536356363573635836359363603636136362363633636436365363663636736368363693637036371363723637336374363753637636377363783637936380363813638236383363843638536386363873638836389363903639136392363933639436395363963639736398363993640036401364023640336404364053640636407364083640936410364113641236413364143641536416364173641836419364203642136422364233642436425364263642736428364293643036431364323643336434364353643636437364383643936440364413644236443364443644536446364473644836449364503645136452364533645436455364563645736458364593646036461364623646336464364653646636467364683646936470364713647236473364743647536476364773647836479364803648136482364833648436485364863648736488364893649036491364923649336494364953649636497364983649936500365013650236503365043650536506365073650836509365103651136512365133651436515365163651736518365193652036521365223652336524365253652636527365283652936530365313653236533365343653536536365373653836539365403654136542365433654436545365463654736548365493655036551365523655336554365553655636557365583655936560365613656236563365643656536566365673656836569365703657136572365733657436575365763657736578365793658036581365823658336584365853658636587365883658936590365913659236593365943659536596365973659836599366003660136602366033660436605366063660736608366093661036611366123661336614366153661636617366183661936620366213662236623366243662536626366273662836629366303663136632366333663436635366363663736638366393664036641366423664336644366453664636647366483664936650366513665236653366543665536656366573665836659366603666136662366633666436665366663666736668366693667036671366723667336674366753667636677366783667936680366813668236683366843668536686366873668836689366903669136692366933669436695366963669736698366993670036701367023670336704367053670636707367083670936710367113671236713367143671536716367173671836719367203672136722367233672436725367263672736728367293673036731367323673336734367353673636737367383673936740367413674236743367443674536746367473674836749367503675136752367533675436755367563675736758367593676036761367623676336764367653676636767367683676936770367713677236773367743677536776367773677836779367803678136782367833678436785367863678736788367893679036791367923679336794367953679636797367983679936800368013680236803368043680536806368073680836809368103681136812368133681436815368163681736818368193682036821368223682336824368253682636827368283682936830368313683236833368343683536836368373683836839368403684136842368433684436845368463684736848368493685036851368523685336854368553685636857368583685936860368613686236863368643686536866368673686836869368703687136872368733687436875368763687736878368793688036881368823688336884368853688636887368883688936890368913689236893368943689536896368973689836899369003690136902369033690436905369063690736908369093691036911369123691336914369153691636917369183691936920369213692236923369243692536926369273692836929369303693136932369333693436935369363693736938369393694036941369423694336944369453694636947369483694936950369513695236953369543695536956369573695836959369603696136962369633696436965369663696736968369693697036971369723697336974369753697636977369783697936980369813698236983369843698536986369873698836989369903699136992369933699436995369963699736998369993700037001370023700337004370053700637007370083700937010370113701237013370143701537016370173701837019370203702137022370233702437025370263702737028370293703037031370323703337034370353703637037370383703937040370413704237043370443704537046370473704837049370503705137052370533705437055370563705737058370593706037061370623706337064370653706637067370683706937070370713707237073370743707537076370773707837079370803708137082370833708437085370863708737088370893709037091370923709337094370953709637097370983709937100371013710237103371043710537106371073710837109371103711137112371133711437115371163711737118371193712037121371223712337124371253712637127371283712937130371313713237133371343713537136371373713837139371403714137142371433714437145371463714737148371493715037151371523715337154371553715637157371583715937160371613716237163371643716537166371673716837169371703717137172371733717437175371763717737178371793718037181371823718337184371853718637187371883718937190371913719237193371943719537196371973719837199372003720137202372033720437205372063720737208372093721037211372123721337214372153721637217372183721937220372213722237223372243722537226372273722837229372303723137232372333723437235372363723737238372393724037241372423724337244372453724637247372483724937250372513725237253372543725537256372573725837259372603726137262372633726437265372663726737268372693727037271372723727337274372753727637277372783727937280372813728237283372843728537286372873728837289372903729137292372933729437295372963729737298372993730037301373023730337304373053730637307373083730937310373113731237313373143731537316373173731837319373203732137322373233732437325373263732737328373293733037331373323733337334373353733637337373383733937340373413734237343373443734537346373473734837349373503735137352373533735437355373563735737358373593736037361373623736337364373653736637367373683736937370373713737237373373743737537376373773737837379373803738137382373833738437385373863738737388373893739037391373923739337394373953739637397373983739937400374013740237403374043740537406374073740837409374103741137412374133741437415374163741737418374193742037421374223742337424374253742637427374283742937430374313743237433374343743537436374373743837439374403744137442374433744437445374463744737448374493745037451374523745337454374553745637457374583745937460374613746237463374643746537466374673746837469374703747137472374733747437475374763747737478374793748037481374823748337484374853748637487374883748937490374913749237493374943749537496374973749837499375003750137502375033750437505375063750737508375093751037511375123751337514375153751637517375183751937520375213752237523375243752537526375273752837529375303753137532375333753437535375363753737538375393754037541375423754337544375453754637547375483754937550375513755237553375543755537556375573755837559375603756137562375633756437565375663756737568375693757037571375723757337574375753757637577375783757937580375813758237583375843758537586375873758837589375903759137592375933759437595375963759737598375993760037601376023760337604376053760637607376083760937610376113761237613376143761537616376173761837619376203762137622376233762437625376263762737628376293763037631376323763337634376353763637637376383763937640376413764237643376443764537646376473764837649376503765137652376533765437655376563765737658376593766037661376623766337664376653766637667376683766937670376713767237673376743767537676376773767837679376803768137682376833768437685376863768737688376893769037691376923769337694376953769637697376983769937700377013770237703377043770537706377073770837709377103771137712377133771437715377163771737718377193772037721377223772337724377253772637727377283772937730377313773237733377343773537736377373773837739377403774137742377433774437745377463774737748377493775037751377523775337754377553775637757377583775937760377613776237763377643776537766377673776837769377703777137772377733777437775377763777737778377793778037781377823778337784377853778637787377883778937790377913779237793377943779537796377973779837799378003780137802378033780437805378063780737808378093781037811378123781337814378153781637817378183781937820378213782237823378243782537826378273782837829378303783137832378333783437835378363783737838378393784037841378423784337844378453784637847378483784937850378513785237853378543785537856378573785837859378603786137862378633786437865378663786737868378693787037871378723787337874378753787637877378783787937880378813788237883378843788537886378873788837889378903789137892378933789437895378963789737898378993790037901379023790337904379053790637907379083790937910379113791237913379143791537916379173791837919379203792137922379233792437925379263792737928379293793037931379323793337934379353793637937379383793937940379413794237943379443794537946379473794837949379503795137952379533795437955379563795737958379593796037961379623796337964379653796637967379683796937970379713797237973379743797537976379773797837979379803798137982379833798437985379863798737988379893799037991379923799337994379953799637997379983799938000380013800238003380043800538006380073800838009380103801138012380133801438015380163801738018380193802038021380223802338024380253802638027380283802938030380313803238033380343803538036380373803838039380403804138042380433804438045380463804738048380493805038051380523805338054380553805638057380583805938060380613806238063380643806538066380673806838069380703807138072380733807438075380763807738078380793808038081380823808338084380853808638087380883808938090380913809238093380943809538096380973809838099381003810138102381033810438105381063810738108381093811038111381123811338114381153811638117381183811938120381213812238123381243812538126381273812838129381303813138132381333813438135381363813738138381393814038141381423814338144381453814638147381483814938150381513815238153381543815538156381573815838159381603816138162381633816438165381663816738168381693817038171381723817338174381753817638177381783817938180381813818238183381843818538186381873818838189381903819138192381933819438195381963819738198381993820038201382023820338204382053820638207382083820938210382113821238213382143821538216382173821838219382203822138222382233822438225382263822738228382293823038231382323823338234382353823638237382383823938240382413824238243382443824538246382473824838249382503825138252382533825438255382563825738258382593826038261382623826338264382653826638267382683826938270382713827238273382743827538276382773827838279382803828138282382833828438285382863828738288382893829038291382923829338294382953829638297382983829938300383013830238303383043830538306383073830838309383103831138312383133831438315383163831738318383193832038321383223832338324383253832638327383283832938330383313833238333383343833538336383373833838339383403834138342383433834438345383463834738348383493835038351383523835338354383553835638357383583835938360383613836238363383643836538366383673836838369383703837138372383733837438375383763837738378383793838038381383823838338384383853838638387383883838938390383913839238393383943839538396383973839838399384003840138402384033840438405384063840738408384093841038411384123841338414384153841638417384183841938420384213842238423384243842538426384273842838429384303843138432384333843438435384363843738438384393844038441384423844338444384453844638447384483844938450384513845238453384543845538456384573845838459384603846138462384633846438465384663846738468384693847038471384723847338474384753847638477384783847938480384813848238483384843848538486384873848838489384903849138492384933849438495384963849738498384993850038501385023850338504385053850638507385083850938510385113851238513385143851538516385173851838519385203852138522385233852438525385263852738528385293853038531385323853338534385353853638537385383853938540385413854238543385443854538546385473854838549385503855138552385533855438555385563855738558385593856038561385623856338564385653856638567385683856938570385713857238573385743857538576385773857838579385803858138582385833858438585385863858738588385893859038591385923859338594385953859638597385983859938600386013860238603386043860538606386073860838609386103861138612386133861438615386163861738618386193862038621386223862338624386253862638627386283862938630386313863238633386343863538636386373863838639386403864138642386433864438645386463864738648386493865038651386523865338654386553865638657386583865938660386613866238663386643866538666386673866838669386703867138672386733867438675386763867738678386793868038681386823868338684386853868638687386883868938690386913869238693386943869538696386973869838699387003870138702387033870438705387063870738708387093871038711387123871338714387153871638717387183871938720387213872238723387243872538726387273872838729387303873138732387333873438735387363873738738387393874038741387423874338744387453874638747387483874938750387513875238753387543875538756387573875838759387603876138762387633876438765387663876738768387693877038771387723877338774387753877638777387783877938780387813878238783387843878538786387873878838789387903879138792387933879438795387963879738798387993880038801388023880338804388053880638807388083880938810388113881238813388143881538816388173881838819388203882138822388233882438825388263882738828388293883038831388323883338834388353883638837388383883938840388413884238843388443884538846388473884838849388503885138852388533885438855388563885738858388593886038861388623886338864388653886638867388683886938870388713887238873388743887538876388773887838879388803888138882388833888438885388863888738888388893889038891388923889338894388953889638897388983889938900389013890238903389043890538906389073890838909389103891138912389133891438915389163891738918389193892038921389223892338924389253892638927389283892938930389313893238933389343893538936389373893838939389403894138942389433894438945389463894738948389493895038951389523895338954389553895638957389583895938960389613896238963389643896538966389673896838969389703897138972389733897438975389763897738978389793898038981389823898338984389853898638987389883898938990389913899238993389943899538996389973899838999390003900139002390033900439005390063900739008390093901039011390123901339014390153901639017390183901939020390213902239023390243902539026390273902839029390303903139032390333903439035390363903739038390393904039041390423904339044390453904639047390483904939050390513905239053390543905539056390573905839059390603906139062390633906439065390663906739068390693907039071390723907339074390753907639077390783907939080390813908239083390843908539086390873908839089390903909139092390933909439095390963909739098390993910039101391023910339104391053910639107391083910939110391113911239113391143911539116391173911839119391203912139122391233912439125391263912739128391293913039131391323913339134391353913639137391383913939140391413914239143391443914539146391473914839149391503915139152391533915439155391563915739158391593916039161391623916339164391653916639167391683916939170391713917239173391743917539176391773917839179391803918139182391833918439185391863918739188391893919039191391923919339194391953919639197391983919939200392013920239203392043920539206392073920839209392103921139212392133921439215392163921739218392193922039221392223922339224392253922639227392283922939230392313923239233392343923539236392373923839239392403924139242392433924439245392463924739248392493925039251392523925339254392553925639257392583925939260392613926239263392643926539266392673926839269392703927139272392733927439275392763927739278392793928039281392823928339284392853928639287392883928939290392913929239293392943929539296392973929839299393003930139302393033930439305393063930739308393093931039311393123931339314393153931639317393183931939320393213932239323393243932539326393273932839329393303933139332393333933439335393363933739338393393934039341393423934339344393453934639347393483934939350393513935239353393543935539356393573935839359393603936139362393633936439365393663936739368393693937039371393723937339374393753937639377393783937939380393813938239383393843938539386393873938839389393903939139392393933939439395393963939739398393993940039401394023940339404394053940639407394083940939410394113941239413394143941539416394173941839419394203942139422394233942439425394263942739428394293943039431394323943339434394353943639437394383943939440394413944239443394443944539446394473944839449394503945139452394533945439455394563945739458394593946039461394623946339464394653946639467394683946939470394713947239473394743947539476394773947839479394803948139482394833948439485394863948739488394893949039491394923949339494394953949639497394983949939500395013950239503395043950539506395073950839509395103951139512395133951439515395163951739518395193952039521395223952339524395253952639527395283952939530395313953239533395343953539536395373953839539395403954139542395433954439545395463954739548395493955039551395523955339554395553955639557395583955939560395613956239563395643956539566395673956839569395703957139572395733957439575395763957739578395793958039581395823958339584395853958639587395883958939590395913959239593395943959539596395973959839599396003960139602396033960439605396063960739608396093961039611396123961339614396153961639617396183961939620396213962239623396243962539626396273962839629396303963139632396333963439635396363963739638396393964039641396423964339644396453964639647396483964939650396513965239653396543965539656396573965839659396603966139662396633966439665396663966739668396693967039671396723967339674396753967639677396783967939680396813968239683396843968539686396873968839689396903969139692396933969439695396963969739698396993970039701397023970339704397053970639707397083970939710397113971239713397143971539716397173971839719397203972139722397233972439725397263972739728397293973039731397323973339734397353973639737397383973939740397413974239743397443974539746397473974839749397503975139752397533975439755397563975739758397593976039761397623976339764397653976639767397683976939770397713977239773397743977539776397773977839779397803978139782397833978439785397863978739788397893979039791397923979339794397953979639797397983979939800398013980239803398043980539806398073980839809398103981139812398133981439815398163981739818398193982039821398223982339824398253982639827398283982939830398313983239833398343983539836398373983839839398403984139842398433984439845398463984739848398493985039851398523985339854398553985639857398583985939860398613986239863398643986539866398673986839869398703987139872398733987439875398763987739878398793988039881398823988339884398853988639887398883988939890398913989239893398943989539896398973989839899399003990139902399033990439905399063990739908399093991039911399123991339914399153991639917399183991939920399213992239923399243992539926399273992839929399303993139932399333993439935399363993739938399393994039941399423994339944399453994639947399483994939950399513995239953399543995539956399573995839959399603996139962399633996439965399663996739968399693997039971399723997339974399753997639977399783997939980399813998239983399843998539986399873998839989399903999139992399933999439995399963999739998399994000040001400024000340004400054000640007400084000940010400114001240013400144001540016400174001840019400204002140022400234002440025400264002740028400294003040031400324003340034400354003640037400384003940040400414004240043400444004540046400474004840049400504005140052400534005440055400564005740058400594006040061400624006340064400654006640067400684006940070400714007240073400744007540076400774007840079400804008140082400834008440085400864008740088400894009040091400924009340094400954009640097400984009940100401014010240103401044010540106401074010840109401104011140112401134011440115401164011740118401194012040121401224012340124401254012640127401284012940130401314013240133401344013540136401374013840139401404014140142401434014440145401464014740148401494015040151401524015340154401554015640157401584015940160401614016240163401644016540166401674016840169401704017140172401734017440175401764017740178401794018040181401824018340184401854018640187401884018940190401914019240193401944019540196401974019840199402004020140202402034020440205402064020740208402094021040211402124021340214402154021640217402184021940220402214022240223402244022540226402274022840229402304023140232402334023440235402364023740238402394024040241402424024340244402454024640247402484024940250402514025240253402544025540256402574025840259402604026140262402634026440265402664026740268402694027040271402724027340274402754027640277402784027940280402814028240283402844028540286402874028840289402904029140292402934029440295402964029740298402994030040301403024030340304403054030640307403084030940310403114031240313403144031540316403174031840319403204032140322403234032440325403264032740328403294033040331403324033340334403354033640337403384033940340403414034240343403444034540346403474034840349403504035140352403534035440355403564035740358403594036040361403624036340364403654036640367403684036940370403714037240373403744037540376403774037840379403804038140382403834038440385403864038740388403894039040391403924039340394403954039640397403984039940400404014040240403404044040540406404074040840409404104041140412404134041440415404164041740418404194042040421404224042340424404254042640427404284042940430404314043240433404344043540436404374043840439404404044140442404434044440445404464044740448404494045040451404524045340454404554045640457404584045940460404614046240463404644046540466404674046840469404704047140472404734047440475404764047740478404794048040481404824048340484404854048640487404884048940490404914049240493404944049540496404974049840499405004050140502405034050440505405064050740508405094051040511405124051340514405154051640517405184051940520405214052240523405244052540526405274052840529405304053140532405334053440535405364053740538405394054040541405424054340544405454054640547405484054940550405514055240553405544055540556405574055840559405604056140562405634056440565405664056740568405694057040571405724057340574405754057640577405784057940580405814058240583405844058540586405874058840589405904059140592405934059440595405964059740598405994060040601406024060340604406054060640607406084060940610406114061240613406144061540616406174061840619406204062140622406234062440625406264062740628406294063040631406324063340634406354063640637406384063940640406414064240643406444064540646406474064840649406504065140652406534065440655406564065740658406594066040661406624066340664406654066640667406684066940670406714067240673406744067540676406774067840679406804068140682406834068440685406864068740688406894069040691406924069340694406954069640697406984069940700407014070240703407044070540706407074070840709407104071140712407134071440715407164071740718407194072040721407224072340724407254072640727407284072940730407314073240733407344073540736407374073840739407404074140742407434074440745407464074740748407494075040751407524075340754407554075640757407584075940760407614076240763407644076540766407674076840769407704077140772407734077440775407764077740778407794078040781407824078340784407854078640787407884078940790407914079240793407944079540796407974079840799408004080140802408034080440805408064080740808408094081040811408124081340814408154081640817408184081940820408214082240823408244082540826408274082840829408304083140832408334083440835408364083740838408394084040841408424084340844408454084640847408484084940850408514085240853408544085540856408574085840859408604086140862408634086440865408664086740868408694087040871408724087340874408754087640877408784087940880408814088240883408844088540886408874088840889408904089140892408934089440895408964089740898408994090040901409024090340904409054090640907409084090940910409114091240913409144091540916409174091840919409204092140922409234092440925409264092740928409294093040931409324093340934409354093640937409384093940940409414094240943409444094540946409474094840949409504095140952409534095440955409564095740958409594096040961409624096340964409654096640967409684096940970409714097240973409744097540976409774097840979409804098140982409834098440985409864098740988409894099040991409924099340994409954099640997409984099941000410014100241003410044100541006410074100841009410104101141012410134101441015410164101741018410194102041021410224102341024410254102641027410284102941030410314103241033410344103541036410374103841039410404104141042410434104441045410464104741048410494105041051410524105341054410554105641057410584105941060410614106241063410644106541066410674106841069410704107141072410734107441075410764107741078410794108041081410824108341084410854108641087410884108941090410914109241093410944109541096410974109841099411004110141102411034110441105411064110741108411094111041111411124111341114411154111641117411184111941120411214112241123411244112541126411274112841129411304113141132411334113441135411364113741138411394114041141411424114341144411454114641147411484114941150411514115241153411544115541156411574115841159411604116141162411634116441165411664116741168411694117041171411724117341174411754117641177411784117941180411814118241183411844118541186411874118841189411904119141192411934119441195411964119741198411994120041201412024120341204412054120641207412084120941210412114121241213412144121541216412174121841219412204122141222412234122441225412264122741228412294123041231412324123341234412354123641237412384123941240412414124241243412444124541246412474124841249412504125141252412534125441255412564125741258412594126041261412624126341264412654126641267412684126941270412714127241273412744127541276412774127841279412804128141282412834128441285412864128741288412894129041291412924129341294412954129641297412984129941300413014130241303413044130541306413074130841309413104131141312413134131441315413164131741318413194132041321413224132341324413254132641327413284132941330413314133241333413344133541336413374133841339413404134141342413434134441345413464134741348413494135041351413524135341354413554135641357413584135941360413614136241363413644136541366413674136841369413704137141372413734137441375413764137741378413794138041381413824138341384413854138641387413884138941390413914139241393413944139541396413974139841399414004140141402414034140441405414064140741408414094141041411414124141341414414154141641417414184141941420414214142241423414244142541426414274142841429414304143141432414334143441435414364143741438414394144041441414424144341444414454144641447414484144941450414514145241453414544145541456414574145841459414604146141462414634146441465414664146741468414694147041471414724147341474414754147641477414784147941480414814148241483414844148541486414874148841489414904149141492414934149441495414964149741498414994150041501415024150341504415054150641507415084150941510415114151241513415144151541516415174151841519415204152141522415234152441525415264152741528415294153041531415324153341534415354153641537415384153941540415414154241543415444154541546415474154841549415504155141552415534155441555415564155741558415594156041561415624156341564415654156641567415684156941570415714157241573415744157541576415774157841579415804158141582415834158441585415864158741588415894159041591415924159341594415954159641597415984159941600416014160241603416044160541606416074160841609416104161141612416134161441615416164161741618416194162041621416224162341624416254162641627416284162941630416314163241633416344163541636416374163841639416404164141642416434164441645416464164741648416494165041651416524165341654416554165641657416584165941660416614166241663416644166541666416674166841669416704167141672416734167441675416764167741678416794168041681416824168341684416854168641687416884168941690416914169241693416944169541696416974169841699417004170141702417034170441705417064170741708417094171041711417124171341714417154171641717417184171941720417214172241723417244172541726417274172841729417304173141732417334173441735417364173741738417394174041741417424174341744417454174641747417484174941750417514175241753417544175541756417574175841759417604176141762417634176441765417664176741768417694177041771417724177341774417754177641777417784177941780417814178241783417844178541786417874178841789417904179141792417934179441795417964179741798417994180041801418024180341804418054180641807418084180941810418114181241813418144181541816418174181841819418204182141822418234182441825418264182741828418294183041831418324183341834418354183641837418384183941840418414184241843418444184541846418474184841849418504185141852418534185441855418564185741858418594186041861418624186341864418654186641867418684186941870418714187241873418744187541876418774187841879418804188141882418834188441885418864188741888418894189041891418924189341894418954189641897418984189941900419014190241903419044190541906419074190841909419104191141912419134191441915419164191741918419194192041921419224192341924419254192641927419284192941930419314193241933419344193541936419374193841939419404194141942419434194441945419464194741948419494195041951419524195341954419554195641957419584195941960419614196241963419644196541966419674196841969419704197141972419734197441975419764197741978419794198041981419824198341984419854198641987419884198941990419914199241993419944199541996419974199841999420004200142002420034200442005420064200742008420094201042011420124201342014420154201642017420184201942020420214202242023420244202542026420274202842029420304203142032420334203442035420364203742038420394204042041420424204342044420454204642047420484204942050420514205242053420544205542056420574205842059420604206142062420634206442065420664206742068420694207042071420724207342074420754207642077420784207942080420814208242083420844208542086420874208842089420904209142092420934209442095420964209742098420994210042101421024210342104421054210642107421084210942110421114211242113421144211542116421174211842119421204212142122421234212442125421264212742128421294213042131421324213342134421354213642137421384213942140421414214242143421444214542146421474214842149421504215142152421534215442155421564215742158421594216042161421624216342164421654216642167421684216942170421714217242173421744217542176421774217842179421804218142182421834218442185421864218742188421894219042191421924219342194421954219642197421984219942200422014220242203422044220542206422074220842209422104221142212422134221442215422164221742218422194222042221422224222342224422254222642227422284222942230422314223242233422344223542236422374223842239422404224142242422434224442245422464224742248422494225042251422524225342254422554225642257422584225942260422614226242263422644226542266422674226842269422704227142272422734227442275422764227742278422794228042281422824228342284422854228642287422884228942290422914229242293422944229542296422974229842299423004230142302423034230442305423064230742308423094231042311423124231342314423154231642317423184231942320423214232242323423244232542326423274232842329423304233142332423334233442335423364233742338423394234042341423424234342344423454234642347423484234942350423514235242353423544235542356423574235842359423604236142362423634236442365423664236742368423694237042371423724237342374423754237642377423784237942380423814238242383423844238542386423874238842389423904239142392423934239442395423964239742398423994240042401424024240342404424054240642407424084240942410424114241242413424144241542416424174241842419424204242142422424234242442425424264242742428424294243042431424324243342434424354243642437424384243942440424414244242443424444244542446424474244842449424504245142452424534245442455424564245742458424594246042461424624246342464424654246642467424684246942470424714247242473424744247542476424774247842479424804248142482424834248442485424864248742488424894249042491424924249342494424954249642497424984249942500425014250242503425044250542506425074250842509425104251142512425134251442515425164251742518425194252042521425224252342524425254252642527425284252942530425314253242533425344253542536425374253842539425404254142542425434254442545425464254742548425494255042551425524255342554425554255642557425584255942560425614256242563425644256542566425674256842569425704257142572425734257442575425764257742578425794258042581425824258342584425854258642587425884258942590425914259242593425944259542596425974259842599426004260142602426034260442605426064260742608426094261042611426124261342614426154261642617426184261942620426214262242623426244262542626426274262842629426304263142632426334263442635426364263742638426394264042641426424264342644426454264642647426484264942650426514265242653426544265542656426574265842659426604266142662426634266442665426664266742668426694267042671426724267342674426754267642677426784267942680426814268242683426844268542686426874268842689426904269142692426934269442695426964269742698426994270042701427024270342704427054270642707427084270942710427114271242713427144271542716427174271842719427204272142722427234272442725427264272742728427294273042731427324273342734427354273642737427384273942740427414274242743427444274542746427474274842749427504275142752427534275442755427564275742758427594276042761427624276342764427654276642767427684276942770427714277242773427744277542776427774277842779427804278142782427834278442785427864278742788427894279042791427924279342794427954279642797427984279942800428014280242803428044280542806428074280842809428104281142812428134281442815428164281742818428194282042821428224282342824428254282642827428284282942830428314283242833428344283542836428374283842839428404284142842428434284442845428464284742848428494285042851428524285342854428554285642857428584285942860428614286242863428644286542866428674286842869428704287142872428734287442875428764287742878428794288042881428824288342884428854288642887428884288942890428914289242893428944289542896428974289842899429004290142902429034290442905429064290742908429094291042911429124291342914429154291642917429184291942920429214292242923429244292542926429274292842929429304293142932429334293442935429364293742938429394294042941429424294342944429454294642947429484294942950429514295242953429544295542956429574295842959429604296142962429634296442965429664296742968429694297042971429724297342974429754297642977429784297942980429814298242983429844298542986429874298842989429904299142992429934299442995429964299742998429994300043001430024300343004430054300643007430084300943010430114301243013430144301543016430174301843019430204302143022430234302443025430264302743028430294303043031430324303343034430354303643037430384303943040430414304243043430444304543046430474304843049430504305143052430534305443055430564305743058430594306043061430624306343064430654306643067430684306943070430714307243073430744307543076430774307843079430804308143082430834308443085430864308743088430894309043091430924309343094430954309643097430984309943100431014310243103431044310543106431074310843109431104311143112431134311443115431164311743118431194312043121431224312343124431254312643127431284312943130431314313243133431344313543136431374313843139431404314143142431434314443145431464314743148431494315043151431524315343154431554315643157431584315943160431614316243163431644316543166431674316843169431704317143172431734317443175431764317743178431794318043181431824318343184431854318643187431884318943190431914319243193431944319543196431974319843199432004320143202432034320443205432064320743208432094321043211432124321343214432154321643217432184321943220432214322243223432244322543226432274322843229432304323143232432334323443235432364323743238432394324043241432424324343244432454324643247432484324943250432514325243253432544325543256432574325843259432604326143262432634326443265432664326743268432694327043271432724327343274432754327643277432784327943280432814328243283432844328543286432874328843289432904329143292432934329443295432964329743298432994330043301433024330343304433054330643307433084330943310433114331243313433144331543316433174331843319433204332143322433234332443325433264332743328433294333043331433324333343334433354333643337433384333943340433414334243343433444334543346433474334843349433504335143352433534335443355433564335743358433594336043361433624336343364433654336643367433684336943370433714337243373433744337543376433774337843379433804338143382433834338443385433864338743388433894339043391433924339343394433954339643397433984339943400434014340243403434044340543406434074340843409434104341143412434134341443415434164341743418434194342043421434224342343424434254342643427434284342943430434314343243433434344343543436434374343843439434404344143442434434344443445434464344743448434494345043451434524345343454434554345643457434584345943460434614346243463434644346543466434674346843469434704347143472434734347443475434764347743478434794348043481434824348343484434854348643487434884348943490434914349243493434944349543496434974349843499435004350143502435034350443505435064350743508435094351043511435124351343514435154351643517435184351943520435214352243523435244352543526435274352843529435304353143532435334353443535435364353743538435394354043541435424354343544435454354643547435484354943550435514355243553435544355543556435574355843559435604356143562435634356443565435664356743568435694357043571435724357343574435754357643577435784357943580435814358243583435844358543586435874358843589435904359143592435934359443595435964359743598435994360043601436024360343604436054360643607436084360943610436114361243613436144361543616436174361843619436204362143622436234362443625436264362743628436294363043631436324363343634436354363643637436384363943640436414364243643436444364543646436474364843649436504365143652436534365443655436564365743658436594366043661436624366343664436654366643667436684366943670436714367243673436744367543676436774367843679436804368143682436834368443685436864368743688436894369043691436924369343694436954369643697436984369943700437014370243703437044370543706437074370843709437104371143712437134371443715437164371743718437194372043721437224372343724437254372643727437284372943730437314373243733437344373543736437374373843739437404374143742437434374443745437464374743748437494375043751437524375343754437554375643757437584375943760437614376243763437644376543766437674376843769437704377143772437734377443775437764377743778437794378043781437824378343784437854378643787437884378943790437914379243793437944379543796437974379843799438004380143802438034380443805438064380743808438094381043811438124381343814438154381643817438184381943820438214382243823438244382543826438274382843829438304383143832438334383443835438364383743838438394384043841438424384343844438454384643847438484384943850438514385243853438544385543856438574385843859438604386143862438634386443865438664386743868438694387043871438724387343874438754387643877438784387943880438814388243883438844388543886438874388843889438904389143892438934389443895438964389743898438994390043901439024390343904439054390643907439084390943910439114391243913439144391543916439174391843919439204392143922439234392443925439264392743928439294393043931439324393343934439354393643937439384393943940439414394243943439444394543946439474394843949439504395143952439534395443955439564395743958439594396043961439624396343964439654396643967439684396943970439714397243973439744397543976439774397843979439804398143982439834398443985439864398743988439894399043991439924399343994439954399643997439984399944000440014400244003440044400544006440074400844009440104401144012440134401444015440164401744018440194402044021440224402344024440254402644027440284402944030440314403244033440344403544036440374403844039440404404144042440434404444045440464404744048440494405044051440524405344054440554405644057440584405944060440614406244063440644406544066440674406844069440704407144072440734407444075440764407744078440794408044081440824408344084440854408644087440884408944090440914409244093440944409544096440974409844099441004410144102441034410444105441064410744108441094411044111441124411344114441154411644117441184411944120441214412244123441244412544126441274412844129441304413144132441334413444135441364413744138441394414044141441424414344144441454414644147441484414944150441514415244153441544415544156441574415844159441604416144162441634416444165441664416744168441694417044171441724417344174441754417644177441784417944180441814418244183441844418544186441874418844189441904419144192441934419444195441964419744198441994420044201442024420344204442054420644207442084420944210442114421244213442144421544216442174421844219442204422144222442234422444225442264422744228442294423044231442324423344234442354423644237442384423944240442414424244243442444424544246442474424844249442504425144252442534425444255442564425744258442594426044261442624426344264442654426644267442684426944270442714427244273442744427544276442774427844279442804428144282442834428444285442864428744288442894429044291442924429344294442954429644297442984429944300443014430244303443044430544306443074430844309443104431144312443134431444315443164431744318443194432044321443224432344324443254432644327443284432944330443314433244333443344433544336443374433844339443404434144342443434434444345443464434744348443494435044351443524435344354443554435644357443584435944360443614436244363443644436544366443674436844369443704437144372443734437444375443764437744378443794438044381443824438344384443854438644387443884438944390443914439244393443944439544396443974439844399444004440144402444034440444405444064440744408444094441044411444124441344414444154441644417444184441944420444214442244423444244442544426444274442844429444304443144432444334443444435444364443744438444394444044441444424444344444444454444644447444484444944450444514445244453444544445544456444574445844459444604446144462444634446444465444664446744468444694447044471444724447344474444754447644477444784447944480444814448244483444844448544486444874448844489444904449144492444934449444495444964449744498444994450044501445024450344504445054450644507445084450944510445114451244513445144451544516445174451844519445204452144522445234452444525445264452744528445294453044531445324453344534445354453644537445384453944540445414454244543445444454544546445474454844549445504455144552445534455444555445564455744558445594456044561445624456344564445654456644567445684456944570445714457244573445744457544576445774457844579445804458144582445834458444585445864458744588445894459044591445924459344594445954459644597445984459944600446014460244603446044460544606446074460844609446104461144612446134461444615446164461744618446194462044621446224462344624446254462644627446284462944630446314463244633446344463544636446374463844639446404464144642446434464444645446464464744648446494465044651446524465344654446554465644657446584465944660446614466244663446644466544666446674466844669446704467144672446734467444675446764467744678446794468044681446824468344684446854468644687446884468944690446914469244693446944469544696446974469844699447004470144702447034470444705447064470744708447094471044711447124471344714447154471644717447184471944720447214472244723447244472544726447274472844729447304473144732447334473444735447364473744738447394474044741447424474344744447454474644747447484474944750447514475244753447544475544756447574475844759447604476144762447634476444765447664476744768447694477044771447724477344774447754477644777447784477944780447814478244783447844478544786447874478844789447904479144792447934479444795447964479744798447994480044801448024480344804448054480644807448084480944810448114481244813448144481544816448174481844819448204482144822448234482444825448264482744828448294483044831448324483344834448354483644837448384483944840448414484244843448444484544846448474484844849448504485144852448534485444855448564485744858448594486044861448624486344864448654486644867448684486944870448714487244873448744487544876448774487844879448804488144882448834488444885448864488744888448894489044891448924489344894448954489644897448984489944900449014490244903449044490544906449074490844909449104491144912449134491444915449164491744918449194492044921449224492344924449254492644927449284492944930449314493244933449344493544936449374493844939449404494144942449434494444945449464494744948449494495044951449524495344954449554495644957449584495944960449614496244963449644496544966449674496844969449704497144972449734497444975449764497744978449794498044981449824498344984449854498644987449884498944990449914499244993449944499544996449974499844999450004500145002450034500445005450064500745008450094501045011450124501345014450154501645017450184501945020450214502245023450244502545026450274502845029450304503145032450334503445035450364503745038450394504045041450424504345044450454504645047450484504945050450514505245053450544505545056450574505845059450604506145062450634506445065450664506745068450694507045071450724507345074450754507645077450784507945080450814508245083450844508545086450874508845089450904509145092450934509445095450964509745098450994510045101451024510345104451054510645107451084510945110451114511245113451144511545116451174511845119451204512145122451234512445125451264512745128451294513045131451324513345134451354513645137451384513945140451414514245143451444514545146451474514845149451504515145152451534515445155451564515745158451594516045161451624516345164451654516645167451684516945170451714517245173451744517545176451774517845179451804518145182451834518445185451864518745188451894519045191451924519345194451954519645197451984519945200452014520245203452044520545206452074520845209452104521145212452134521445215452164521745218452194522045221452224522345224452254522645227452284522945230452314523245233452344523545236452374523845239452404524145242452434524445245452464524745248452494525045251452524525345254452554525645257452584525945260452614526245263452644526545266452674526845269452704527145272452734527445275452764527745278452794528045281452824528345284452854528645287452884528945290452914529245293452944529545296452974529845299453004530145302453034530445305453064530745308453094531045311453124531345314453154531645317453184531945320453214532245323453244532545326453274532845329453304533145332453334533445335453364533745338453394534045341453424534345344453454534645347453484534945350453514535245353453544535545356453574535845359453604536145362453634536445365453664536745368453694537045371453724537345374453754537645377453784537945380453814538245383453844538545386453874538845389453904539145392453934539445395453964539745398453994540045401454024540345404454054540645407454084540945410454114541245413454144541545416454174541845419454204542145422454234542445425454264542745428454294543045431454324543345434454354543645437454384543945440454414544245443454444544545446454474544845449454504545145452454534545445455454564545745458454594546045461454624546345464454654546645467454684546945470454714547245473454744547545476454774547845479454804548145482454834548445485454864548745488454894549045491454924549345494454954549645497454984549945500455014550245503455044550545506455074550845509455104551145512455134551445515455164551745518455194552045521455224552345524455254552645527455284552945530455314553245533455344553545536455374553845539455404554145542455434554445545455464554745548455494555045551455524555345554455554555645557455584555945560455614556245563455644556545566455674556845569455704557145572455734557445575455764557745578455794558045581455824558345584455854558645587455884558945590455914559245593455944559545596455974559845599456004560145602456034560445605456064560745608456094561045611456124561345614456154561645617456184561945620456214562245623456244562545626456274562845629456304563145632456334563445635456364563745638456394564045641456424564345644456454564645647456484564945650456514565245653456544565545656456574565845659456604566145662456634566445665456664566745668456694567045671456724567345674456754567645677456784567945680456814568245683456844568545686456874568845689456904569145692456934569445695456964569745698456994570045701457024570345704457054570645707457084570945710457114571245713457144571545716457174571845719457204572145722457234572445725457264572745728457294573045731457324573345734457354573645737457384573945740457414574245743457444574545746457474574845749457504575145752457534575445755457564575745758457594576045761457624576345764457654576645767457684576945770457714577245773457744577545776457774577845779457804578145782457834578445785457864578745788457894579045791457924579345794457954579645797457984579945800458014580245803458044580545806458074580845809458104581145812458134581445815458164581745818458194582045821458224582345824458254582645827458284582945830458314583245833458344583545836458374583845839458404584145842458434584445845458464584745848458494585045851458524585345854458554585645857458584585945860458614586245863458644586545866458674586845869458704587145872458734587445875458764587745878458794588045881458824588345884458854588645887458884588945890458914589245893458944589545896458974589845899459004590145902459034590445905459064590745908459094591045911459124591345914459154591645917459184591945920459214592245923459244592545926459274592845929459304593145932459334593445935459364593745938459394594045941459424594345944459454594645947459484594945950459514595245953459544595545956459574595845959459604596145962459634596445965459664596745968459694597045971459724597345974459754597645977459784597945980459814598245983459844598545986459874598845989459904599145992459934599445995459964599745998459994600046001460024600346004460054600646007460084600946010460114601246013460144601546016460174601846019460204602146022460234602446025460264602746028460294603046031460324603346034460354603646037460384603946040460414604246043460444604546046460474604846049460504605146052460534605446055460564605746058460594606046061460624606346064460654606646067460684606946070460714607246073460744607546076460774607846079460804608146082460834608446085460864608746088460894609046091460924609346094460954609646097460984609946100461014610246103461044610546106461074610846109461104611146112461134611446115461164611746118461194612046121461224612346124461254612646127461284612946130461314613246133461344613546136461374613846139461404614146142461434614446145461464614746148461494615046151461524615346154461554615646157461584615946160461614616246163461644616546166461674616846169461704617146172461734617446175461764617746178461794618046181461824618346184461854618646187461884618946190461914619246193461944619546196461974619846199462004620146202462034620446205462064620746208462094621046211462124621346214462154621646217462184621946220462214622246223462244622546226462274622846229462304623146232462334623446235462364623746238462394624046241462424624346244462454624646247462484624946250462514625246253462544625546256462574625846259462604626146262462634626446265462664626746268462694627046271462724627346274462754627646277462784627946280462814628246283462844628546286462874628846289462904629146292462934629446295462964629746298462994630046301463024630346304463054630646307463084630946310463114631246313463144631546316463174631846319463204632146322463234632446325463264632746328463294633046331463324633346334463354633646337463384633946340463414634246343463444634546346463474634846349463504635146352463534635446355463564635746358463594636046361463624636346364463654636646367463684636946370463714637246373463744637546376463774637846379463804638146382463834638446385463864638746388463894639046391463924639346394463954639646397463984639946400464014640246403464044640546406464074640846409464104641146412464134641446415464164641746418464194642046421464224642346424464254642646427464284642946430464314643246433464344643546436464374643846439464404644146442464434644446445464464644746448464494645046451464524645346454464554645646457464584645946460464614646246463464644646546466464674646846469464704647146472464734647446475464764647746478464794648046481464824648346484464854648646487464884648946490464914649246493464944649546496464974649846499465004650146502465034650446505465064650746508465094651046511465124651346514465154651646517465184651946520465214652246523465244652546526465274652846529465304653146532465334653446535465364653746538465394654046541465424654346544465454654646547465484654946550465514655246553465544655546556465574655846559465604656146562465634656446565465664656746568465694657046571465724657346574465754657646577465784657946580465814658246583465844658546586465874658846589465904659146592465934659446595465964659746598465994660046601466024660346604466054660646607466084660946610466114661246613466144661546616466174661846619466204662146622466234662446625466264662746628466294663046631466324663346634466354663646637466384663946640466414664246643466444664546646466474664846649466504665146652466534665446655466564665746658466594666046661466624666346664466654666646667466684666946670466714667246673466744667546676466774667846679466804668146682466834668446685466864668746688466894669046691466924669346694466954669646697466984669946700467014670246703467044670546706467074670846709467104671146712467134671446715467164671746718467194672046721467224672346724467254672646727467284672946730467314673246733467344673546736467374673846739467404674146742467434674446745467464674746748467494675046751467524675346754467554675646757467584675946760467614676246763467644676546766467674676846769467704677146772467734677446775467764677746778467794678046781467824678346784467854678646787467884678946790467914679246793467944679546796467974679846799468004680146802468034680446805468064680746808468094681046811468124681346814468154681646817468184681946820468214682246823468244682546826468274682846829468304683146832468334683446835468364683746838468394684046841468424684346844468454684646847468484684946850468514685246853468544685546856468574685846859468604686146862468634686446865468664686746868468694687046871468724687346874468754687646877468784687946880468814688246883468844688546886468874688846889468904689146892468934689446895468964689746898468994690046901469024690346904469054690646907469084690946910469114691246913469144691546916469174691846919469204692146922469234692446925469264692746928469294693046931469324693346934469354693646937469384693946940469414694246943469444694546946469474694846949469504695146952469534695446955469564695746958469594696046961469624696346964469654696646967469684696946970469714697246973469744697546976469774697846979469804698146982469834698446985469864698746988469894699046991469924699346994469954699646997469984699947000470014700247003470044700547006470074700847009470104701147012470134701447015470164701747018470194702047021470224702347024470254702647027470284702947030470314703247033470344703547036470374703847039470404704147042470434704447045470464704747048470494705047051470524705347054470554705647057470584705947060470614706247063470644706547066470674706847069470704707147072470734707447075470764707747078470794708047081470824708347084470854708647087470884708947090470914709247093470944709547096470974709847099471004710147102471034710447105471064710747108471094711047111471124711347114471154711647117471184711947120471214712247123471244712547126471274712847129471304713147132471334713447135471364713747138471394714047141471424714347144471454714647147471484714947150471514715247153471544715547156471574715847159471604716147162471634716447165471664716747168471694717047171471724717347174471754717647177471784717947180471814718247183471844718547186471874718847189471904719147192471934719447195471964719747198471994720047201472024720347204472054720647207472084720947210472114721247213472144721547216472174721847219472204722147222472234722447225472264722747228472294723047231472324723347234472354723647237472384723947240472414724247243472444724547246472474724847249472504725147252472534725447255472564725747258472594726047261472624726347264472654726647267472684726947270472714727247273472744727547276472774727847279472804728147282472834728447285472864728747288472894729047291472924729347294472954729647297472984729947300473014730247303473044730547306473074730847309473104731147312473134731447315473164731747318473194732047321473224732347324473254732647327473284732947330473314733247333473344733547336473374733847339473404734147342473434734447345473464734747348473494735047351473524735347354473554735647357473584735947360473614736247363473644736547366473674736847369473704737147372473734737447375473764737747378473794738047381473824738347384473854738647387473884738947390473914739247393473944739547396473974739847399474004740147402474034740447405474064740747408474094741047411474124741347414474154741647417474184741947420474214742247423474244742547426474274742847429474304743147432474334743447435474364743747438474394744047441474424744347444474454744647447474484744947450474514745247453474544745547456474574745847459474604746147462474634746447465474664746747468474694747047471474724747347474474754747647477474784747947480474814748247483474844748547486474874748847489474904749147492474934749447495474964749747498474994750047501475024750347504475054750647507475084750947510475114751247513475144751547516475174751847519475204752147522475234752447525475264752747528475294753047531475324753347534475354753647537475384753947540475414754247543475444754547546475474754847549475504755147552475534755447555475564755747558475594756047561475624756347564475654756647567475684756947570475714757247573475744757547576475774757847579475804758147582475834758447585475864758747588475894759047591475924759347594475954759647597475984759947600476014760247603476044760547606476074760847609476104761147612476134761447615476164761747618476194762047621476224762347624476254762647627476284762947630476314763247633476344763547636476374763847639476404764147642476434764447645476464764747648476494765047651476524765347654476554765647657476584765947660476614766247663476644766547666476674766847669476704767147672476734767447675476764767747678476794768047681476824768347684476854768647687476884768947690476914769247693476944769547696476974769847699477004770147702477034770447705477064770747708477094771047711477124771347714477154771647717477184771947720477214772247723477244772547726477274772847729477304773147732477334773447735477364773747738477394774047741477424774347744477454774647747477484774947750477514775247753477544775547756477574775847759477604776147762477634776447765477664776747768477694777047771477724777347774477754777647777477784777947780477814778247783477844778547786477874778847789477904779147792477934779447795477964779747798477994780047801478024780347804478054780647807478084780947810478114781247813478144781547816478174781847819478204782147822478234782447825478264782747828478294783047831478324783347834478354783647837478384783947840478414784247843478444784547846478474784847849478504785147852478534785447855478564785747858478594786047861478624786347864478654786647867478684786947870478714787247873478744787547876478774787847879478804788147882478834788447885478864788747888478894789047891478924789347894478954789647897478984789947900479014790247903479044790547906479074790847909479104791147912479134791447915479164791747918479194792047921479224792347924479254792647927479284792947930479314793247933479344793547936479374793847939479404794147942479434794447945479464794747948479494795047951479524795347954479554795647957479584795947960479614796247963479644796547966479674796847969479704797147972479734797447975479764797747978479794798047981479824798347984479854798647987479884798947990479914799247993479944799547996479974799847999480004800148002480034800448005480064800748008480094801048011480124801348014480154801648017480184801948020480214802248023480244802548026480274802848029480304803148032480334803448035480364803748038480394804048041480424804348044480454804648047480484804948050480514805248053480544805548056480574805848059480604806148062480634806448065480664806748068480694807048071480724807348074480754807648077480784807948080480814808248083480844808548086480874808848089480904809148092480934809448095480964809748098480994810048101481024810348104481054810648107481084810948110481114811248113481144811548116481174811848119481204812148122481234812448125481264812748128481294813048131481324813348134481354813648137481384813948140481414814248143481444814548146481474814848149481504815148152481534815448155481564815748158481594816048161481624816348164481654816648167481684816948170481714817248173481744817548176481774817848179481804818148182481834818448185481864818748188481894819048191481924819348194481954819648197481984819948200482014820248203482044820548206482074820848209482104821148212482134821448215482164821748218482194822048221482224822348224482254822648227482284822948230482314823248233482344823548236482374823848239482404824148242482434824448245482464824748248482494825048251482524825348254482554825648257482584825948260482614826248263482644826548266482674826848269482704827148272482734827448275482764827748278482794828048281482824828348284482854828648287482884828948290482914829248293482944829548296482974829848299483004830148302483034830448305483064830748308483094831048311483124831348314483154831648317483184831948320483214832248323483244832548326483274832848329483304833148332483334833448335483364833748338483394834048341483424834348344483454834648347483484834948350483514835248353483544835548356483574835848359483604836148362483634836448365483664836748368483694837048371483724837348374483754837648377483784837948380483814838248383483844838548386483874838848389483904839148392483934839448395483964839748398483994840048401484024840348404484054840648407484084840948410484114841248413484144841548416484174841848419484204842148422484234842448425484264842748428484294843048431484324843348434484354843648437484384843948440484414844248443484444844548446484474844848449484504845148452484534845448455484564845748458484594846048461484624846348464484654846648467484684846948470484714847248473484744847548476484774847848479484804848148482484834848448485484864848748488484894849048491484924849348494484954849648497484984849948500485014850248503485044850548506485074850848509485104851148512485134851448515485164851748518485194852048521485224852348524485254852648527485284852948530485314853248533485344853548536485374853848539485404854148542485434854448545485464854748548485494855048551485524855348554485554855648557485584855948560485614856248563485644856548566485674856848569485704857148572485734857448575485764857748578485794858048581485824858348584485854858648587485884858948590485914859248593485944859548596485974859848599486004860148602486034860448605486064860748608486094861048611486124861348614486154861648617486184861948620486214862248623486244862548626486274862848629486304863148632486334863448635486364863748638486394864048641486424864348644486454864648647486484864948650486514865248653486544865548656486574865848659486604866148662486634866448665486664866748668486694867048671486724867348674486754867648677486784867948680486814868248683486844868548686486874868848689486904869148692486934869448695486964869748698486994870048701487024870348704487054870648707487084870948710487114871248713487144871548716487174871848719487204872148722487234872448725487264872748728487294873048731487324873348734487354873648737487384873948740487414874248743487444874548746487474874848749487504875148752487534875448755487564875748758487594876048761487624876348764487654876648767487684876948770487714877248773487744877548776487774877848779487804878148782487834878448785487864878748788487894879048791487924879348794487954879648797487984879948800488014880248803488044880548806488074880848809488104881148812488134881448815488164881748818488194882048821488224882348824488254882648827488284882948830488314883248833488344883548836488374883848839488404884148842488434884448845488464884748848488494885048851488524885348854488554885648857488584885948860488614886248863488644886548866488674886848869488704887148872488734887448875488764887748878488794888048881488824888348884488854888648887488884888948890488914889248893488944889548896488974889848899489004890148902489034890448905489064890748908489094891048911489124891348914489154891648917489184891948920489214892248923489244892548926489274892848929489304893148932489334893448935489364893748938489394894048941489424894348944489454894648947489484894948950489514895248953489544895548956489574895848959489604896148962489634896448965489664896748968489694897048971489724897348974489754897648977489784897948980489814898248983489844898548986489874898848989489904899148992489934899448995489964899748998489994900049001490024900349004490054900649007490084900949010490114901249013490144901549016490174901849019490204902149022490234902449025490264902749028490294903049031490324903349034490354903649037490384903949040490414904249043490444904549046490474904849049490504905149052490534905449055490564905749058490594906049061490624906349064490654906649067490684906949070490714907249073490744907549076490774907849079490804908149082490834908449085490864908749088490894909049091490924909349094490954909649097490984909949100491014910249103491044910549106491074910849109491104911149112491134911449115491164911749118491194912049121491224912349124491254912649127491284912949130491314913249133491344913549136491374913849139491404914149142491434914449145491464914749148491494915049151491524915349154491554915649157491584915949160491614916249163491644916549166491674916849169491704917149172491734917449175491764917749178491794918049181491824918349184491854918649187491884918949190491914919249193491944919549196491974919849199492004920149202492034920449205492064920749208492094921049211492124921349214492154921649217492184921949220492214922249223492244922549226492274922849229492304923149232492334923449235492364923749238492394924049241492424924349244492454924649247492484924949250492514925249253492544925549256492574925849259492604926149262492634926449265492664926749268492694927049271492724927349274492754927649277492784927949280492814928249283492844928549286492874928849289492904929149292492934929449295492964929749298492994930049301493024930349304493054930649307493084930949310493114931249313493144931549316493174931849319493204932149322493234932449325493264932749328493294933049331493324933349334493354933649337493384933949340493414934249343493444934549346493474934849349493504935149352493534935449355493564935749358493594936049361493624936349364493654936649367493684936949370493714937249373493744937549376493774937849379493804938149382493834938449385493864938749388493894939049391493924939349394493954939649397493984939949400494014940249403494044940549406494074940849409494104941149412494134941449415494164941749418494194942049421494224942349424494254942649427494284942949430494314943249433494344943549436494374943849439494404944149442494434944449445494464944749448494494945049451494524945349454494554945649457494584945949460494614946249463494644946549466494674946849469494704947149472494734947449475494764947749478494794948049481494824948349484494854948649487494884948949490494914949249493494944949549496494974949849499495004950149502495034950449505495064950749508495094951049511495124951349514495154951649517495184951949520495214952249523495244952549526495274952849529495304953149532495334953449535495364953749538495394954049541495424954349544495454954649547495484954949550495514955249553495544955549556495574955849559495604956149562495634956449565495664956749568495694957049571495724957349574495754957649577495784957949580495814958249583495844958549586495874958849589495904959149592495934959449595495964959749598495994960049601496024960349604496054960649607496084960949610496114961249613496144961549616496174961849619496204962149622496234962449625496264962749628496294963049631496324963349634496354963649637496384963949640496414964249643496444964549646496474964849649496504965149652496534965449655496564965749658496594966049661496624966349664496654966649667496684966949670496714967249673496744967549676496774967849679496804968149682496834968449685496864968749688496894969049691496924969349694496954969649697496984969949700497014970249703497044970549706497074970849709497104971149712497134971449715497164971749718497194972049721497224972349724497254972649727497284972949730497314973249733497344973549736497374973849739497404974149742497434974449745497464974749748497494975049751497524975349754497554975649757497584975949760497614976249763497644976549766497674976849769497704977149772497734977449775497764977749778497794978049781497824978349784497854978649787497884978949790497914979249793497944979549796497974979849799498004980149802498034980449805498064980749808498094981049811498124981349814498154981649817498184981949820498214982249823498244982549826498274982849829498304983149832498334983449835498364983749838498394984049841498424984349844498454984649847498484984949850498514985249853498544985549856498574985849859498604986149862498634986449865498664986749868498694987049871498724987349874498754987649877498784987949880498814988249883498844988549886498874988849889498904989149892498934989449895498964989749898498994990049901499024990349904499054990649907499084990949910499114991249913499144991549916499174991849919499204992149922499234992449925499264992749928499294993049931499324993349934499354993649937499384993949940499414994249943499444994549946499474994849949499504995149952499534995449955499564995749958499594996049961499624996349964499654996649967499684996949970499714997249973499744997549976499774997849979499804998149982499834998449985499864998749988499894999049991499924999349994499954999649997499984999950000500015000250003500045000550006500075000850009500105001150012500135001450015500165001750018500195002050021500225002350024500255002650027500285002950030500315003250033500345003550036500375003850039500405004150042500435004450045500465004750048500495005050051500525005350054500555005650057500585005950060500615006250063500645006550066500675006850069500705007150072500735007450075500765007750078500795008050081500825008350084500855008650087500885008950090500915009250093500945009550096500975009850099501005010150102501035010450105501065010750108501095011050111501125011350114501155011650117501185011950120501215012250123501245012550126501275012850129501305013150132501335013450135501365013750138501395014050141501425014350144501455014650147501485014950150501515015250153501545015550156501575015850159501605016150162501635016450165501665016750168501695017050171501725017350174501755017650177501785017950180501815018250183501845018550186501875018850189501905019150192501935019450195501965019750198501995020050201502025020350204502055020650207502085020950210502115021250213502145021550216502175021850219502205022150222502235022450225502265022750228502295023050231502325023350234502355023650237502385023950240502415024250243502445024550246502475024850249502505025150252502535025450255502565025750258502595026050261502625026350264502655026650267502685026950270502715027250273502745027550276502775027850279502805028150282502835028450285502865028750288502895029050291502925029350294502955029650297502985029950300503015030250303503045030550306503075030850309503105031150312503135031450315503165031750318503195032050321503225032350324503255032650327503285032950330503315033250333503345033550336503375033850339503405034150342503435034450345503465034750348503495035050351503525035350354503555035650357503585035950360503615036250363503645036550366503675036850369503705037150372503735037450375503765037750378503795038050381503825038350384503855038650387503885038950390503915039250393503945039550396503975039850399504005040150402504035040450405504065040750408504095041050411504125041350414504155041650417504185041950420504215042250423504245042550426504275042850429504305043150432504335043450435504365043750438504395044050441504425044350444504455044650447504485044950450504515045250453504545045550456504575045850459504605046150462504635046450465504665046750468504695047050471504725047350474504755047650477504785047950480504815048250483504845048550486504875048850489504905049150492504935049450495504965049750498504995050050501505025050350504505055050650507505085050950510505115051250513505145051550516505175051850519505205052150522505235052450525505265052750528505295053050531505325053350534505355053650537505385053950540505415054250543505445054550546505475054850549505505055150552505535055450555505565055750558505595056050561505625056350564505655056650567505685056950570505715057250573505745057550576505775057850579505805058150582505835058450585505865058750588505895059050591505925059350594505955059650597505985059950600506015060250603506045060550606506075060850609506105061150612506135061450615506165061750618506195062050621506225062350624506255062650627506285062950630506315063250633506345063550636506375063850639506405064150642506435064450645506465064750648506495065050651506525065350654506555065650657506585065950660506615066250663506645066550666506675066850669506705067150672506735067450675506765067750678506795068050681506825068350684506855068650687506885068950690506915069250693506945069550696506975069850699507005070150702507035070450705507065070750708507095071050711507125071350714507155071650717507185071950720507215072250723507245072550726507275072850729507305073150732507335073450735507365073750738507395074050741507425074350744507455074650747507485074950750507515075250753507545075550756507575075850759507605076150762507635076450765507665076750768507695077050771507725077350774507755077650777507785077950780507815078250783507845078550786507875078850789507905079150792507935079450795507965079750798507995080050801508025080350804508055080650807508085080950810508115081250813508145081550816508175081850819508205082150822508235082450825508265082750828508295083050831508325083350834508355083650837508385083950840508415084250843508445084550846508475084850849508505085150852508535085450855508565085750858508595086050861508625086350864508655086650867508685086950870508715087250873508745087550876508775087850879508805088150882508835088450885508865088750888508895089050891508925089350894508955089650897508985089950900509015090250903509045090550906509075090850909509105091150912509135091450915509165091750918509195092050921509225092350924509255092650927509285092950930509315093250933509345093550936509375093850939509405094150942509435094450945509465094750948509495095050951509525095350954509555095650957509585095950960509615096250963509645096550966509675096850969509705097150972509735097450975509765097750978509795098050981509825098350984509855098650987509885098950990509915099250993509945099550996509975099850999510005100151002510035100451005510065100751008510095101051011510125101351014510155101651017510185101951020510215102251023510245102551026510275102851029510305103151032510335103451035510365103751038510395104051041510425104351044510455104651047510485104951050510515105251053510545105551056510575105851059510605106151062510635106451065510665106751068510695107051071510725107351074510755107651077510785107951080510815108251083510845108551086510875108851089510905109151092510935109451095510965109751098510995110051101511025110351104511055110651107511085110951110511115111251113511145111551116511175111851119511205112151122511235112451125511265112751128511295113051131511325113351134511355113651137511385113951140511415114251143511445114551146511475114851149511505115151152511535115451155511565115751158511595116051161511625116351164511655116651167511685116951170511715117251173511745117551176511775117851179511805118151182511835118451185511865118751188511895119051191511925119351194511955119651197511985119951200512015120251203512045120551206512075120851209512105121151212512135121451215512165121751218512195122051221512225122351224512255122651227512285122951230512315123251233512345123551236512375123851239512405124151242512435124451245512465124751248512495125051251512525125351254512555125651257512585125951260512615126251263512645126551266512675126851269512705127151272512735127451275512765127751278512795128051281512825128351284512855128651287512885128951290512915129251293512945129551296512975129851299513005130151302513035130451305513065130751308513095131051311513125131351314513155131651317513185131951320513215132251323513245132551326513275132851329513305133151332513335133451335513365133751338513395134051341513425134351344513455134651347513485134951350513515135251353513545135551356513575135851359513605136151362513635136451365513665136751368513695137051371513725137351374513755137651377513785137951380513815138251383513845138551386513875138851389513905139151392513935139451395513965139751398513995140051401514025140351404514055140651407514085140951410514115141251413514145141551416514175141851419514205142151422514235142451425514265142751428514295143051431514325143351434514355143651437514385143951440514415144251443514445144551446514475144851449514505145151452514535145451455514565145751458514595146051461514625146351464514655146651467514685146951470514715147251473514745147551476514775147851479514805148151482514835148451485514865148751488514895149051491514925149351494514955149651497514985149951500515015150251503515045150551506515075150851509515105151151512515135151451515515165151751518515195152051521515225152351524515255152651527515285152951530515315153251533515345153551536515375153851539515405154151542515435154451545515465154751548515495155051551515525155351554515555155651557515585155951560515615156251563515645156551566515675156851569515705157151572515735157451575515765157751578515795158051581515825158351584515855158651587515885158951590515915159251593515945159551596515975159851599516005160151602516035160451605516065160751608516095161051611516125161351614516155161651617516185161951620516215162251623516245162551626516275162851629516305163151632516335163451635516365163751638516395164051641516425164351644516455164651647516485164951650516515165251653516545165551656516575165851659516605166151662516635166451665516665166751668516695167051671516725167351674516755167651677516785167951680516815168251683516845168551686516875168851689516905169151692516935169451695516965169751698516995170051701517025170351704517055170651707517085170951710517115171251713517145171551716517175171851719517205172151722517235172451725517265172751728517295173051731517325173351734517355173651737517385173951740517415174251743517445174551746517475174851749517505175151752517535175451755517565175751758517595176051761517625176351764517655176651767517685176951770517715177251773517745177551776517775177851779517805178151782517835178451785517865178751788517895179051791517925179351794517955179651797517985179951800518015180251803518045180551806518075180851809518105181151812518135181451815518165181751818518195182051821518225182351824518255182651827518285182951830518315183251833518345183551836518375183851839518405184151842518435184451845518465184751848518495185051851518525185351854518555185651857518585185951860518615186251863518645186551866518675186851869518705187151872518735187451875518765187751878518795188051881518825188351884518855188651887518885188951890518915189251893518945189551896518975189851899519005190151902519035190451905519065190751908519095191051911519125191351914519155191651917519185191951920519215192251923519245192551926519275192851929519305193151932519335193451935519365193751938519395194051941519425194351944519455194651947519485194951950519515195251953519545195551956519575195851959519605196151962519635196451965519665196751968519695197051971519725197351974519755197651977519785197951980519815198251983519845198551986519875198851989519905199151992519935199451995519965199751998519995200052001520025200352004520055200652007520085200952010520115201252013520145201552016520175201852019520205202152022520235202452025520265202752028520295203052031520325203352034520355203652037520385203952040520415204252043520445204552046520475204852049520505205152052520535205452055520565205752058520595206052061520625206352064520655206652067520685206952070520715207252073520745207552076520775207852079520805208152082520835208452085520865208752088520895209052091520925209352094520955209652097520985209952100521015210252103521045210552106521075210852109521105211152112521135211452115521165211752118521195212052121521225212352124521255212652127521285212952130521315213252133521345213552136521375213852139521405214152142521435214452145521465214752148521495215052151521525215352154521555215652157521585215952160521615216252163521645216552166521675216852169521705217152172521735217452175521765217752178521795218052181521825218352184521855218652187521885218952190521915219252193521945219552196521975219852199522005220152202522035220452205522065220752208522095221052211522125221352214522155221652217522185221952220522215222252223522245222552226522275222852229522305223152232522335223452235522365223752238522395224052241522425224352244522455224652247522485224952250522515225252253522545225552256522575225852259522605226152262522635226452265522665226752268522695227052271522725227352274522755227652277522785227952280522815228252283522845228552286522875228852289522905229152292522935229452295522965229752298522995230052301523025230352304523055230652307523085230952310523115231252313523145231552316523175231852319523205232152322523235232452325523265232752328523295233052331523325233352334523355233652337523385233952340523415234252343523445234552346523475234852349523505235152352523535235452355523565235752358523595236052361523625236352364523655236652367523685236952370523715237252373523745237552376523775237852379523805238152382523835238452385523865238752388523895239052391523925239352394523955239652397523985239952400524015240252403524045240552406524075240852409524105241152412524135241452415524165241752418524195242052421524225242352424524255242652427524285242952430524315243252433524345243552436524375243852439524405244152442524435244452445524465244752448524495245052451524525245352454524555245652457524585245952460524615246252463524645246552466524675246852469524705247152472524735247452475524765247752478524795248052481524825248352484524855248652487524885248952490524915249252493524945249552496524975249852499525005250152502525035250452505525065250752508525095251052511525125251352514525155251652517525185251952520525215252252523525245252552526525275252852529525305253152532525335253452535525365253752538525395254052541525425254352544525455254652547525485254952550525515255252553525545255552556525575255852559525605256152562525635256452565525665256752568525695257052571525725257352574525755257652577525785257952580525815258252583525845258552586525875258852589525905259152592525935259452595525965259752598525995260052601526025260352604526055260652607526085260952610526115261252613526145261552616526175261852619526205262152622526235262452625526265262752628526295263052631526325263352634526355263652637526385263952640526415264252643526445264552646526475264852649526505265152652526535265452655526565265752658526595266052661526625266352664526655266652667526685266952670526715267252673526745267552676526775267852679526805268152682526835268452685526865268752688526895269052691526925269352694526955269652697526985269952700527015270252703527045270552706527075270852709527105271152712527135271452715527165271752718527195272052721527225272352724527255272652727527285272952730527315273252733527345273552736527375273852739527405274152742527435274452745527465274752748527495275052751527525275352754527555275652757527585275952760527615276252763527645276552766527675276852769527705277152772527735277452775527765277752778527795278052781527825278352784527855278652787527885278952790527915279252793527945279552796527975279852799528005280152802528035280452805528065280752808528095281052811528125281352814528155281652817528185281952820528215282252823528245282552826528275282852829528305283152832528335283452835528365283752838528395284052841528425284352844528455284652847528485284952850528515285252853528545285552856528575285852859528605286152862528635286452865528665286752868528695287052871528725287352874528755287652877528785287952880528815288252883528845288552886528875288852889528905289152892528935289452895528965289752898528995290052901529025290352904529055290652907529085290952910529115291252913529145291552916529175291852919529205292152922529235292452925529265292752928529295293052931529325293352934529355293652937529385293952940529415294252943529445294552946529475294852949529505295152952529535295452955529565295752958529595296052961529625296352964529655296652967529685296952970529715297252973529745297552976529775297852979529805298152982529835298452985529865298752988529895299052991529925299352994529955299652997529985299953000530015300253003530045300553006530075300853009530105301153012530135301453015530165301753018530195302053021530225302353024530255302653027530285302953030530315303253033530345303553036530375303853039530405304153042530435304453045530465304753048530495305053051530525305353054530555305653057530585305953060530615306253063530645306553066530675306853069530705307153072530735307453075530765307753078530795308053081530825308353084530855308653087530885308953090530915309253093530945309553096530975309853099531005310153102531035310453105531065310753108531095311053111531125311353114531155311653117531185311953120531215312253123531245312553126531275312853129531305313153132531335313453135531365313753138531395314053141531425314353144531455314653147531485314953150531515315253153531545315553156531575315853159531605316153162531635316453165531665316753168531695317053171531725317353174531755317653177531785317953180531815318253183531845318553186531875318853189531905319153192531935319453195531965319753198531995320053201532025320353204532055320653207532085320953210532115321253213532145321553216532175321853219532205322153222532235322453225532265322753228532295323053231532325323353234532355323653237532385323953240532415324253243532445324553246532475324853249532505325153252532535325453255532565325753258532595326053261532625326353264532655326653267532685326953270532715327253273532745327553276532775327853279532805328153282532835328453285532865328753288532895329053291532925329353294532955329653297532985329953300533015330253303533045330553306533075330853309533105331153312533135331453315533165331753318533195332053321533225332353324533255332653327533285332953330533315333253333533345333553336533375333853339533405334153342533435334453345533465334753348533495335053351533525335353354533555335653357533585335953360533615336253363533645336553366533675336853369533705337153372533735337453375533765337753378533795338053381533825338353384533855338653387533885338953390533915339253393533945339553396533975339853399534005340153402534035340453405534065340753408534095341053411534125341353414534155341653417534185341953420534215342253423534245342553426534275342853429534305343153432534335343453435534365343753438534395344053441534425344353444534455344653447534485344953450534515345253453534545345553456534575345853459534605346153462534635346453465534665346753468534695347053471534725347353474534755347653477534785347953480534815348253483534845348553486534875348853489534905349153492534935349453495534965349753498534995350053501535025350353504535055350653507535085350953510535115351253513535145351553516535175351853519535205352153522535235352453525535265352753528535295353053531535325353353534535355353653537535385353953540535415354253543535445354553546535475354853549535505355153552535535355453555535565355753558535595356053561535625356353564535655356653567535685356953570535715357253573535745357553576535775357853579535805358153582535835358453585535865358753588535895359053591535925359353594535955359653597535985359953600536015360253603536045360553606536075360853609536105361153612536135361453615536165361753618536195362053621536225362353624536255362653627536285362953630536315363253633536345363553636536375363853639536405364153642536435364453645536465364753648536495365053651536525365353654536555365653657536585365953660536615366253663536645366553666536675366853669536705367153672536735367453675536765367753678536795368053681536825368353684536855368653687536885368953690536915369253693536945369553696536975369853699537005370153702537035370453705537065370753708537095371053711537125371353714537155371653717537185371953720537215372253723537245372553726537275372853729537305373153732537335373453735537365373753738537395374053741537425374353744537455374653747537485374953750537515375253753537545375553756537575375853759537605376153762537635376453765537665376753768537695377053771537725377353774537755377653777537785377953780537815378253783537845378553786537875378853789537905379153792537935379453795537965379753798537995380053801538025380353804538055380653807538085380953810538115381253813538145381553816538175381853819538205382153822538235382453825538265382753828538295383053831538325383353834538355383653837538385383953840538415384253843538445384553846538475384853849538505385153852538535385453855538565385753858538595386053861538625386353864538655386653867538685386953870538715387253873538745387553876538775387853879538805388153882538835388453885538865388753888538895389053891538925389353894538955389653897538985389953900539015390253903539045390553906539075390853909539105391153912539135391453915539165391753918539195392053921539225392353924539255392653927539285392953930539315393253933539345393553936539375393853939539405394153942539435394453945539465394753948539495395053951539525395353954539555395653957539585395953960539615396253963539645396553966539675396853969539705397153972539735397453975539765397753978539795398053981539825398353984539855398653987539885398953990539915399253993539945399553996539975399853999540005400154002540035400454005540065400754008540095401054011540125401354014540155401654017540185401954020540215402254023540245402554026540275402854029540305403154032540335403454035540365403754038540395404054041540425404354044540455404654047540485404954050540515405254053540545405554056540575405854059540605406154062540635406454065540665406754068540695407054071540725407354074540755407654077540785407954080540815408254083540845408554086540875408854089540905409154092540935409454095540965409754098540995410054101541025410354104541055410654107541085410954110541115411254113541145411554116541175411854119541205412154122541235412454125541265412754128541295413054131541325413354134541355413654137541385413954140541415414254143541445414554146541475414854149541505415154152541535415454155541565415754158541595416054161541625416354164541655416654167541685416954170541715417254173541745417554176541775417854179541805418154182541835418454185541865418754188541895419054191541925419354194541955419654197541985419954200542015420254203542045420554206542075420854209542105421154212542135421454215542165421754218542195422054221542225422354224542255422654227542285422954230542315423254233542345423554236542375423854239542405424154242542435424454245542465424754248542495425054251542525425354254542555425654257542585425954260542615426254263542645426554266542675426854269542705427154272542735427454275542765427754278542795428054281542825428354284542855428654287542885428954290542915429254293542945429554296542975429854299543005430154302543035430454305543065430754308543095431054311543125431354314543155431654317543185431954320543215432254323543245432554326543275432854329543305433154332543335433454335543365433754338543395434054341543425434354344543455434654347543485434954350543515435254353543545435554356543575435854359543605436154362543635436454365543665436754368543695437054371543725437354374543755437654377543785437954380543815438254383543845438554386543875438854389543905439154392543935439454395543965439754398543995440054401544025440354404544055440654407544085440954410544115441254413544145441554416544175441854419544205442154422544235442454425544265442754428544295443054431544325443354434544355443654437544385443954440544415444254443544445444554446544475444854449544505445154452544535445454455544565445754458544595446054461544625446354464544655446654467544685446954470544715447254473544745447554476544775447854479544805448154482544835448454485544865448754488544895449054491544925449354494544955449654497544985449954500545015450254503545045450554506545075450854509545105451154512545135451454515545165451754518545195452054521545225452354524545255452654527545285452954530545315453254533545345453554536545375453854539545405454154542545435454454545545465454754548545495455054551545525455354554545555455654557545585455954560545615456254563545645456554566545675456854569545705457154572545735457454575545765457754578545795458054581545825458354584545855458654587545885458954590545915459254593545945459554596545975459854599546005460154602546035460454605546065460754608546095461054611546125461354614546155461654617546185461954620546215462254623546245462554626546275462854629546305463154632546335463454635546365463754638546395464054641546425464354644546455464654647546485464954650546515465254653546545465554656546575465854659546605466154662546635466454665546665466754668546695467054671546725467354674546755467654677546785467954680546815468254683546845468554686546875468854689546905469154692546935469454695546965469754698546995470054701547025470354704547055470654707547085470954710547115471254713547145471554716547175471854719547205472154722547235472454725547265472754728547295473054731547325473354734547355473654737547385473954740547415474254743547445474554746547475474854749547505475154752547535475454755547565475754758547595476054761547625476354764547655476654767547685476954770547715477254773547745477554776547775477854779547805478154782547835478454785547865478754788547895479054791547925479354794547955479654797547985479954800548015480254803548045480554806548075480854809548105481154812548135481454815548165481754818548195482054821548225482354824548255482654827548285482954830548315483254833548345483554836548375483854839548405484154842548435484454845548465484754848548495485054851548525485354854548555485654857548585485954860548615486254863548645486554866548675486854869548705487154872548735487454875548765487754878548795488054881548825488354884548855488654887548885488954890548915489254893548945489554896548975489854899549005490154902549035490454905549065490754908549095491054911549125491354914549155491654917549185491954920549215492254923549245492554926549275492854929549305493154932549335493454935549365493754938549395494054941549425494354944549455494654947549485494954950549515495254953549545495554956549575495854959549605496154962549635496454965549665496754968549695497054971549725497354974549755497654977549785497954980549815498254983549845498554986549875498854989549905499154992549935499454995549965499754998549995500055001550025500355004550055500655007550085500955010550115501255013550145501555016550175501855019550205502155022550235502455025550265502755028550295503055031550325503355034550355503655037550385503955040550415504255043550445504555046550475504855049550505505155052550535505455055550565505755058550595506055061550625506355064550655506655067550685506955070550715507255073550745507555076550775507855079550805508155082550835508455085550865508755088550895509055091550925509355094550955509655097550985509955100551015510255103551045510555106551075510855109551105511155112551135511455115551165511755118551195512055121551225512355124551255512655127551285512955130551315513255133551345513555136551375513855139551405514155142551435514455145551465514755148551495515055151551525515355154551555515655157551585515955160551615516255163551645516555166551675516855169551705517155172551735517455175551765517755178551795518055181551825518355184551855518655187551885518955190551915519255193551945519555196551975519855199552005520155202552035520455205552065520755208552095521055211552125521355214552155521655217552185521955220552215522255223552245522555226552275522855229552305523155232552335523455235552365523755238552395524055241552425524355244552455524655247552485524955250552515525255253552545525555256552575525855259552605526155262552635526455265552665526755268552695527055271552725527355274552755527655277552785527955280552815528255283552845528555286552875528855289552905529155292552935529455295552965529755298552995530055301553025530355304553055530655307553085530955310553115531255313553145531555316553175531855319553205532155322553235532455325553265532755328553295533055331553325533355334553355533655337553385533955340553415534255343553445534555346553475534855349553505535155352553535535455355553565535755358553595536055361553625536355364553655536655367553685536955370553715537255373553745537555376553775537855379553805538155382553835538455385553865538755388553895539055391553925539355394553955539655397553985539955400554015540255403554045540555406554075540855409554105541155412554135541455415554165541755418554195542055421554225542355424554255542655427554285542955430554315543255433554345543555436554375543855439554405544155442554435544455445554465544755448554495545055451554525545355454554555545655457554585545955460554615546255463554645546555466554675546855469554705547155472554735547455475554765547755478554795548055481554825548355484554855548655487554885548955490554915549255493554945549555496554975549855499555005550155502555035550455505555065550755508555095551055511555125551355514555155551655517555185551955520555215552255523555245552555526555275552855529555305553155532555335553455535555365553755538555395554055541555425554355544555455554655547555485554955550555515555255553555545555555556555575555855559555605556155562555635556455565555665556755568555695557055571555725557355574555755557655577555785557955580555815558255583555845558555586555875558855589555905559155592555935559455595555965559755598555995560055601556025560355604556055560655607556085560955610556115561255613556145561555616556175561855619556205562155622556235562455625556265562755628556295563055631556325563355634556355563655637556385563955640556415564255643556445564555646556475564855649556505565155652556535565455655556565565755658556595566055661556625566355664556655566655667556685566955670556715567255673556745567555676556775567855679556805568155682556835568455685556865568755688556895569055691556925569355694556955569655697556985569955700557015570255703557045570555706557075570855709557105571155712557135571455715557165571755718557195572055721557225572355724557255572655727557285572955730557315573255733557345573555736557375573855739557405574155742557435574455745557465574755748557495575055751557525575355754557555575655757557585575955760557615576255763557645576555766557675576855769557705577155772557735577455775557765577755778557795578055781557825578355784557855578655787557885578955790557915579255793557945579555796557975579855799558005580155802558035580455805558065580755808558095581055811558125581355814558155581655817558185581955820558215582255823558245582555826558275582855829558305583155832558335583455835558365583755838558395584055841558425584355844558455584655847558485584955850558515585255853558545585555856558575585855859558605586155862558635586455865558665586755868558695587055871558725587355874558755587655877558785587955880558815588255883558845588555886558875588855889558905589155892558935589455895558965589755898558995590055901559025590355904559055590655907559085590955910559115591255913559145591555916559175591855919559205592155922559235592455925559265592755928559295593055931559325593355934559355593655937559385593955940559415594255943559445594555946559475594855949559505595155952559535595455955559565595755958559595596055961559625596355964559655596655967559685596955970559715597255973559745597555976559775597855979559805598155982559835598455985559865598755988559895599055991559925599355994559955599655997559985599956000560015600256003560045600556006560075600856009560105601156012560135601456015560165601756018560195602056021560225602356024560255602656027560285602956030560315603256033560345603556036560375603856039560405604156042560435604456045560465604756048560495605056051560525605356054560555605656057560585605956060560615606256063560645606556066560675606856069560705607156072
  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, 1, 0, cx + cw / 2.0, ch / 2.0 + cy, 0, 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.fillStyle = camera.getScene().clearColor.toHexString();
  5266. renderContext.fillRect(0, 0, width, height);
  5267. renderContext.drawImage(engine.getRenderingCanvas(), offsetX, offsetY, newWidth, newHeight);
  5268. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  5269. };
  5270. Tools.CreateScreenshotUsingRenderTarget = function (engine, camera, size, successCallback, mimeType) {
  5271. if (mimeType === void 0) { mimeType = "image/png"; }
  5272. var width;
  5273. var height;
  5274. //If a precision value is specified
  5275. if (size.precision) {
  5276. width = Math.round(engine.getRenderWidth() * size.precision);
  5277. height = Math.round(width / engine.getAspectRatio(camera));
  5278. size = { width: width, height: height };
  5279. }
  5280. else if (size.width && size.height) {
  5281. width = size.width;
  5282. height = size.height;
  5283. }
  5284. else if (size.width && !size.height) {
  5285. width = size.width;
  5286. height = Math.round(width / engine.getAspectRatio(camera));
  5287. size = { width: width, height: height };
  5288. }
  5289. else if (size.height && !size.width) {
  5290. height = size.height;
  5291. width = Math.round(height * engine.getAspectRatio(camera));
  5292. size = { width: width, height: height };
  5293. }
  5294. else if (!isNaN(size)) {
  5295. height = size;
  5296. width = size;
  5297. }
  5298. else {
  5299. Tools.Error("Invalid 'size' parameter !");
  5300. return;
  5301. }
  5302. var scene = camera.getScene();
  5303. var previousCamera = null;
  5304. if (scene.activeCamera !== camera) {
  5305. previousCamera = scene.activeCamera;
  5306. scene.activeCamera = camera;
  5307. }
  5308. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  5309. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  5310. texture.renderList = scene.meshes;
  5311. texture.onAfterRenderObservable.add(function () {
  5312. Tools.DumpFramebuffer(width, height, engine, successCallback, mimeType);
  5313. });
  5314. scene.incrementRenderId();
  5315. scene.resetCachedMaterial();
  5316. texture.render(true);
  5317. texture.dispose();
  5318. if (previousCamera) {
  5319. scene.activeCamera = previousCamera;
  5320. }
  5321. camera.getProjectionMatrix(true); // Force cache refresh;
  5322. };
  5323. // XHR response validator for local file scenario
  5324. Tools.ValidateXHRData = function (xhr, dataType) {
  5325. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  5326. if (dataType === void 0) { dataType = 7; }
  5327. try {
  5328. if (dataType & 1) {
  5329. if (xhr.responseText && xhr.responseText.length > 0) {
  5330. return true;
  5331. }
  5332. else if (dataType === 1) {
  5333. return false;
  5334. }
  5335. }
  5336. if (dataType & 2) {
  5337. // Check header width and height since there is no "TGA" magic number
  5338. var tgaHeader = BABYLON.Internals.TGATools.GetTGAHeader(xhr.response);
  5339. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  5340. return true;
  5341. }
  5342. else if (dataType === 2) {
  5343. return false;
  5344. }
  5345. }
  5346. if (dataType & 4) {
  5347. // Check for the "DDS" magic number
  5348. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  5349. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  5350. return true;
  5351. }
  5352. else {
  5353. return false;
  5354. }
  5355. }
  5356. }
  5357. catch (e) {
  5358. }
  5359. return false;
  5360. };
  5361. /**
  5362. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  5363. * Be aware Math.random() could cause collisions, but:
  5364. * "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"
  5365. */
  5366. Tools.RandomId = function () {
  5367. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  5368. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  5369. return v.toString(16);
  5370. });
  5371. };
  5372. Object.defineProperty(Tools, "NoneLogLevel", {
  5373. get: function () {
  5374. return Tools._NoneLogLevel;
  5375. },
  5376. enumerable: true,
  5377. configurable: true
  5378. });
  5379. Object.defineProperty(Tools, "MessageLogLevel", {
  5380. get: function () {
  5381. return Tools._MessageLogLevel;
  5382. },
  5383. enumerable: true,
  5384. configurable: true
  5385. });
  5386. Object.defineProperty(Tools, "WarningLogLevel", {
  5387. get: function () {
  5388. return Tools._WarningLogLevel;
  5389. },
  5390. enumerable: true,
  5391. configurable: true
  5392. });
  5393. Object.defineProperty(Tools, "ErrorLogLevel", {
  5394. get: function () {
  5395. return Tools._ErrorLogLevel;
  5396. },
  5397. enumerable: true,
  5398. configurable: true
  5399. });
  5400. Object.defineProperty(Tools, "AllLogLevel", {
  5401. get: function () {
  5402. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  5403. },
  5404. enumerable: true,
  5405. configurable: true
  5406. });
  5407. Tools._AddLogEntry = function (entry) {
  5408. Tools._LogCache = entry + Tools._LogCache;
  5409. if (Tools.OnNewCacheEntry) {
  5410. Tools.OnNewCacheEntry(entry);
  5411. }
  5412. };
  5413. Tools._FormatMessage = function (message) {
  5414. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  5415. var date = new Date();
  5416. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  5417. };
  5418. Tools._LogDisabled = function (message) {
  5419. // nothing to do
  5420. };
  5421. Tools._LogEnabled = function (message) {
  5422. var formattedMessage = Tools._FormatMessage(message);
  5423. console.log("BJS - " + formattedMessage);
  5424. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  5425. Tools._AddLogEntry(entry);
  5426. };
  5427. Tools._WarnDisabled = function (message) {
  5428. // nothing to do
  5429. };
  5430. Tools._WarnEnabled = function (message) {
  5431. var formattedMessage = Tools._FormatMessage(message);
  5432. console.warn("BJS - " + formattedMessage);
  5433. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  5434. Tools._AddLogEntry(entry);
  5435. };
  5436. Tools._ErrorDisabled = function (message) {
  5437. // nothing to do
  5438. };
  5439. Tools._ErrorEnabled = function (message) {
  5440. Tools.errorsCount++;
  5441. var formattedMessage = Tools._FormatMessage(message);
  5442. console.error("BJS - " + formattedMessage);
  5443. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  5444. Tools._AddLogEntry(entry);
  5445. };
  5446. Object.defineProperty(Tools, "LogCache", {
  5447. get: function () {
  5448. return Tools._LogCache;
  5449. },
  5450. enumerable: true,
  5451. configurable: true
  5452. });
  5453. Tools.ClearLogCache = function () {
  5454. Tools._LogCache = "";
  5455. Tools.errorsCount = 0;
  5456. };
  5457. Object.defineProperty(Tools, "LogLevels", {
  5458. set: function (level) {
  5459. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  5460. Tools.Log = Tools._LogEnabled;
  5461. }
  5462. else {
  5463. Tools.Log = Tools._LogDisabled;
  5464. }
  5465. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  5466. Tools.Warn = Tools._WarnEnabled;
  5467. }
  5468. else {
  5469. Tools.Warn = Tools._WarnDisabled;
  5470. }
  5471. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  5472. Tools.Error = Tools._ErrorEnabled;
  5473. }
  5474. else {
  5475. Tools.Error = Tools._ErrorDisabled;
  5476. }
  5477. },
  5478. enumerable: true,
  5479. configurable: true
  5480. });
  5481. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  5482. get: function () {
  5483. return Tools._PerformanceNoneLogLevel;
  5484. },
  5485. enumerable: true,
  5486. configurable: true
  5487. });
  5488. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  5489. get: function () {
  5490. return Tools._PerformanceUserMarkLogLevel;
  5491. },
  5492. enumerable: true,
  5493. configurable: true
  5494. });
  5495. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  5496. get: function () {
  5497. return Tools._PerformanceConsoleLogLevel;
  5498. },
  5499. enumerable: true,
  5500. configurable: true
  5501. });
  5502. Object.defineProperty(Tools, "PerformanceLogLevel", {
  5503. set: function (level) {
  5504. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  5505. Tools.StartPerformanceCounter = Tools._StartUserMark;
  5506. Tools.EndPerformanceCounter = Tools._EndUserMark;
  5507. return;
  5508. }
  5509. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  5510. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  5511. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  5512. return;
  5513. }
  5514. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  5515. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  5516. },
  5517. enumerable: true,
  5518. configurable: true
  5519. });
  5520. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  5521. };
  5522. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  5523. };
  5524. Tools._StartUserMark = function (counterName, condition) {
  5525. if (condition === void 0) { condition = true; }
  5526. if (!condition || !Tools._performance.mark) {
  5527. return;
  5528. }
  5529. Tools._performance.mark(counterName + "-Begin");
  5530. };
  5531. Tools._EndUserMark = function (counterName, condition) {
  5532. if (condition === void 0) { condition = true; }
  5533. if (!condition || !Tools._performance.mark) {
  5534. return;
  5535. }
  5536. Tools._performance.mark(counterName + "-End");
  5537. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  5538. };
  5539. Tools._StartPerformanceConsole = function (counterName, condition) {
  5540. if (condition === void 0) { condition = true; }
  5541. if (!condition) {
  5542. return;
  5543. }
  5544. Tools._StartUserMark(counterName, condition);
  5545. if (console.time) {
  5546. console.time(counterName);
  5547. }
  5548. };
  5549. Tools._EndPerformanceConsole = function (counterName, condition) {
  5550. if (condition === void 0) { condition = true; }
  5551. if (!condition) {
  5552. return;
  5553. }
  5554. Tools._EndUserMark(counterName, condition);
  5555. if (console.time) {
  5556. console.timeEnd(counterName);
  5557. }
  5558. };
  5559. Object.defineProperty(Tools, "Now", {
  5560. get: function () {
  5561. if (window.performance && window.performance.now) {
  5562. return window.performance.now();
  5563. }
  5564. return new Date().getTime();
  5565. },
  5566. enumerable: true,
  5567. configurable: true
  5568. });
  5569. /**
  5570. * This method will return the name of the class used to create the instance of the given object.
  5571. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  5572. * @param object the object to get the class name from
  5573. * @return the name of the class, will be "object" for a custom data type not using the @className decorator
  5574. */
  5575. Tools.getClassName = function (object, isType) {
  5576. if (isType === void 0) { isType = false; }
  5577. var name = null;
  5578. if (!isType && object.getClassName) {
  5579. name = object.getClassName();
  5580. }
  5581. else {
  5582. if (object instanceof Object) {
  5583. var classObj = isType ? object : Object.getPrototypeOf(object);
  5584. name = classObj.constructor["__bjsclassName__"];
  5585. }
  5586. if (!name) {
  5587. name = typeof object;
  5588. }
  5589. }
  5590. return name;
  5591. };
  5592. Tools.first = function (array, predicate) {
  5593. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  5594. var el = array_1[_i];
  5595. if (predicate(el)) {
  5596. return el;
  5597. }
  5598. }
  5599. };
  5600. /**
  5601. * This method will return the name of the full name of the class, including its owning module (if any).
  5602. * 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).
  5603. * @param object the object to get the class name from
  5604. * @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.
  5605. */
  5606. Tools.getFullClassName = function (object, isType) {
  5607. if (isType === void 0) { isType = false; }
  5608. var className = null;
  5609. var moduleName = null;
  5610. if (!isType && object.getClassName) {
  5611. className = object.getClassName();
  5612. }
  5613. else {
  5614. if (object instanceof Object) {
  5615. var classObj = isType ? object : Object.getPrototypeOf(object);
  5616. className = classObj.constructor["__bjsclassName__"];
  5617. moduleName = classObj.constructor["__bjsmoduleName__"];
  5618. }
  5619. if (!className) {
  5620. className = typeof object;
  5621. }
  5622. }
  5623. if (!className) {
  5624. return null;
  5625. }
  5626. return ((moduleName != null) ? (moduleName + ".") : "") + className;
  5627. };
  5628. /**
  5629. * 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.
  5630. * @param array
  5631. */
  5632. Tools.arrayOrStringFeeder = function (array) {
  5633. return function (index) {
  5634. if (index >= array.length) {
  5635. return null;
  5636. }
  5637. var val = array.charCodeAt ? array.charCodeAt(index) : array[index];
  5638. if (val && val.getHashCode) {
  5639. val = val.getHashCode();
  5640. }
  5641. if (typeof val === "string") {
  5642. return Tools.hashCodeFromStream(Tools.arrayOrStringFeeder(val));
  5643. }
  5644. return val;
  5645. };
  5646. };
  5647. /**
  5648. * Compute the hashCode of a stream of number
  5649. * To compute the HashCode on a string or an Array of data types implementing the getHashCode() method, use the arrayOrStringFeeder method.
  5650. * @param feeder a callback that will be called until it returns null, each valid returned values will be used to compute the hash code.
  5651. * @return the hash code computed
  5652. */
  5653. Tools.hashCodeFromStream = function (feeder) {
  5654. // Based from here: http://stackoverflow.com/a/7616484/802124
  5655. var hash = 0;
  5656. var index = 0;
  5657. var chr = feeder(index++);
  5658. while (chr != null) {
  5659. hash = ((hash << 5) - hash) + chr;
  5660. hash |= 0; // Convert to 32bit integer
  5661. chr = feeder(index++);
  5662. }
  5663. return hash;
  5664. };
  5665. return Tools;
  5666. }());
  5667. Tools.BaseUrl = "";
  5668. Tools.CorsBehavior = "anonymous";
  5669. Tools.UseFallbackTexture = true;
  5670. // Used in case of a texture loading problem
  5671. 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";
  5672. // Logs
  5673. Tools._NoneLogLevel = 0;
  5674. Tools._MessageLogLevel = 1;
  5675. Tools._WarningLogLevel = 2;
  5676. Tools._ErrorLogLevel = 4;
  5677. Tools._LogCache = "";
  5678. Tools.errorsCount = 0;
  5679. Tools.Log = Tools._LogEnabled;
  5680. Tools.Warn = Tools._WarnEnabled;
  5681. Tools.Error = Tools._ErrorEnabled;
  5682. // Performances
  5683. Tools._PerformanceNoneLogLevel = 0;
  5684. Tools._PerformanceUserMarkLogLevel = 1;
  5685. Tools._PerformanceConsoleLogLevel = 2;
  5686. Tools._performance = window.performance;
  5687. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  5688. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  5689. BABYLON.Tools = Tools;
  5690. /**
  5691. * This class is used to track a performance counter which is number based.
  5692. * The user has access to many properties which give statistics of different nature
  5693. *
  5694. * The implementer can track two kinds of Performance Counter: time and count
  5695. * 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.
  5696. * 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.
  5697. */
  5698. var PerfCounter = (function () {
  5699. function PerfCounter() {
  5700. this._startMonitoringTime = 0;
  5701. this._min = 0;
  5702. this._max = 0;
  5703. this._average = 0;
  5704. this._lastSecAverage = 0;
  5705. this._current = 0;
  5706. this._totalValueCount = 0;
  5707. this._totalAccumulated = 0;
  5708. this._lastSecAccumulated = 0;
  5709. this._lastSecTime = 0;
  5710. this._lastSecValueCount = 0;
  5711. }
  5712. Object.defineProperty(PerfCounter.prototype, "min", {
  5713. /**
  5714. * Returns the smallest value ever
  5715. */
  5716. get: function () {
  5717. return this._min;
  5718. },
  5719. enumerable: true,
  5720. configurable: true
  5721. });
  5722. Object.defineProperty(PerfCounter.prototype, "max", {
  5723. /**
  5724. * Returns the biggest value ever
  5725. */
  5726. get: function () {
  5727. return this._max;
  5728. },
  5729. enumerable: true,
  5730. configurable: true
  5731. });
  5732. Object.defineProperty(PerfCounter.prototype, "average", {
  5733. /**
  5734. * Returns the average value since the performance counter is running
  5735. */
  5736. get: function () {
  5737. return this._average;
  5738. },
  5739. enumerable: true,
  5740. configurable: true
  5741. });
  5742. Object.defineProperty(PerfCounter.prototype, "lastSecAverage", {
  5743. /**
  5744. * Returns the average value of the last second the counter was monitored
  5745. */
  5746. get: function () {
  5747. return this._lastSecAverage;
  5748. },
  5749. enumerable: true,
  5750. configurable: true
  5751. });
  5752. Object.defineProperty(PerfCounter.prototype, "current", {
  5753. /**
  5754. * Returns the current value
  5755. */
  5756. get: function () {
  5757. return this._current;
  5758. },
  5759. enumerable: true,
  5760. configurable: true
  5761. });
  5762. Object.defineProperty(PerfCounter.prototype, "total", {
  5763. get: function () {
  5764. return this._totalAccumulated;
  5765. },
  5766. enumerable: true,
  5767. configurable: true
  5768. });
  5769. /**
  5770. * Call this method to start monitoring a new frame.
  5771. * 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.
  5772. */
  5773. PerfCounter.prototype.fetchNewFrame = function () {
  5774. this._totalValueCount++;
  5775. this._current = 0;
  5776. this._lastSecValueCount++;
  5777. };
  5778. /**
  5779. * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)
  5780. * @param newCount the count value to add to the monitored count
  5781. * @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.
  5782. */
  5783. PerfCounter.prototype.addCount = function (newCount, fetchResult) {
  5784. this._current += newCount;
  5785. if (fetchResult) {
  5786. this._fetchResult();
  5787. }
  5788. };
  5789. /**
  5790. * Start monitoring this performance counter
  5791. */
  5792. PerfCounter.prototype.beginMonitoring = function () {
  5793. this._startMonitoringTime = Tools.Now;
  5794. };
  5795. /**
  5796. * Compute the time lapsed since the previous beginMonitoring() call.
  5797. * @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
  5798. */
  5799. PerfCounter.prototype.endMonitoring = function (newFrame) {
  5800. if (newFrame === void 0) { newFrame = true; }
  5801. if (newFrame) {
  5802. this.fetchNewFrame();
  5803. }
  5804. var currentTime = Tools.Now;
  5805. this._current = currentTime - this._startMonitoringTime;
  5806. if (newFrame) {
  5807. this._fetchResult();
  5808. }
  5809. };
  5810. PerfCounter.prototype._fetchResult = function () {
  5811. this._totalAccumulated += this._current;
  5812. this._lastSecAccumulated += this._current;
  5813. // Min/Max update
  5814. this._min = Math.min(this._min, this._current);
  5815. this._max = Math.max(this._max, this._current);
  5816. this._average = this._totalAccumulated / this._totalValueCount;
  5817. // Reset last sec?
  5818. var now = Tools.Now;
  5819. if ((now - this._lastSecTime) > 1000) {
  5820. this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
  5821. this._lastSecTime = now;
  5822. this._lastSecAccumulated = 0;
  5823. this._lastSecValueCount = 0;
  5824. }
  5825. };
  5826. return PerfCounter;
  5827. }());
  5828. BABYLON.PerfCounter = PerfCounter;
  5829. /**
  5830. * Use this className as a decorator on a given class definition to add it a name and optionally its module.
  5831. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  5832. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  5833. * @param name The name of the class, case should be preserved
  5834. * @param module The name of the Module hosting the class, optional, but strongly recommended to specify if possible. Case should be preserved.
  5835. */
  5836. function className(name, module) {
  5837. return function (target) {
  5838. target["__bjsclassName__"] = name;
  5839. target["__bjsmoduleName__"] = (module != null) ? module : null;
  5840. };
  5841. }
  5842. BABYLON.className = className;
  5843. /**
  5844. * An implementation of a loop for asynchronous functions.
  5845. */
  5846. var AsyncLoop = (function () {
  5847. /**
  5848. * Constroctor.
  5849. * @param iterations the number of iterations.
  5850. * @param _fn the function to run each iteration
  5851. * @param _successCallback the callback that will be called upon succesful execution
  5852. * @param offset starting offset.
  5853. */
  5854. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  5855. if (offset === void 0) { offset = 0; }
  5856. this.iterations = iterations;
  5857. this._fn = _fn;
  5858. this._successCallback = _successCallback;
  5859. this.index = offset - 1;
  5860. this._done = false;
  5861. }
  5862. /**
  5863. * Execute the next iteration. Must be called after the last iteration was finished.
  5864. */
  5865. AsyncLoop.prototype.executeNext = function () {
  5866. if (!this._done) {
  5867. if (this.index + 1 < this.iterations) {
  5868. ++this.index;
  5869. this._fn(this);
  5870. }
  5871. else {
  5872. this.breakLoop();
  5873. }
  5874. }
  5875. };
  5876. /**
  5877. * Break the loop and run the success callback.
  5878. */
  5879. AsyncLoop.prototype.breakLoop = function () {
  5880. this._done = true;
  5881. this._successCallback();
  5882. };
  5883. /**
  5884. * Helper function
  5885. */
  5886. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  5887. if (offset === void 0) { offset = 0; }
  5888. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  5889. loop.executeNext();
  5890. return loop;
  5891. };
  5892. /**
  5893. * A for-loop that will run a given number of iterations synchronous and the rest async.
  5894. * @param iterations total number of iterations
  5895. * @param syncedIterations number of synchronous iterations in each async iteration.
  5896. * @param fn the function to call each iteration.
  5897. * @param callback a success call back that will be called when iterating stops.
  5898. * @param breakFunction a break condition (optional)
  5899. * @param timeout timeout settings for the setTimeout function. default - 0.
  5900. * @constructor
  5901. */
  5902. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  5903. if (timeout === void 0) { timeout = 0; }
  5904. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  5905. if (breakFunction && breakFunction())
  5906. loop.breakLoop();
  5907. else {
  5908. setTimeout(function () {
  5909. for (var i = 0; i < syncedIterations; ++i) {
  5910. var iteration = (loop.index * syncedIterations) + i;
  5911. if (iteration >= iterations)
  5912. break;
  5913. fn(iteration);
  5914. if (breakFunction && breakFunction()) {
  5915. loop.breakLoop();
  5916. break;
  5917. }
  5918. }
  5919. loop.executeNext();
  5920. }, timeout);
  5921. }
  5922. }, callback);
  5923. };
  5924. return AsyncLoop;
  5925. }());
  5926. BABYLON.AsyncLoop = AsyncLoop;
  5927. })(BABYLON || (BABYLON = {}));
  5928. //# sourceMappingURL=babylon.tools.js.map
  5929. var BABYLON;
  5930. (function (BABYLON) {
  5931. var Internals;
  5932. (function (Internals) {
  5933. var _AlphaState = (function () {
  5934. /**
  5935. * Initializes the state.
  5936. */
  5937. function _AlphaState() {
  5938. this._isAlphaBlendDirty = false;
  5939. this._isBlendFunctionParametersDirty = false;
  5940. this._alphaBlend = false;
  5941. this._blendFunctionParameters = new Array(4);
  5942. this.reset();
  5943. }
  5944. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  5945. get: function () {
  5946. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  5947. },
  5948. enumerable: true,
  5949. configurable: true
  5950. });
  5951. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  5952. get: function () {
  5953. return this._alphaBlend;
  5954. },
  5955. set: function (value) {
  5956. if (this._alphaBlend === value) {
  5957. return;
  5958. }
  5959. this._alphaBlend = value;
  5960. this._isAlphaBlendDirty = true;
  5961. },
  5962. enumerable: true,
  5963. configurable: true
  5964. });
  5965. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  5966. if (this._blendFunctionParameters[0] === value0 &&
  5967. this._blendFunctionParameters[1] === value1 &&
  5968. this._blendFunctionParameters[2] === value2 &&
  5969. this._blendFunctionParameters[3] === value3) {
  5970. return;
  5971. }
  5972. this._blendFunctionParameters[0] = value0;
  5973. this._blendFunctionParameters[1] = value1;
  5974. this._blendFunctionParameters[2] = value2;
  5975. this._blendFunctionParameters[3] = value3;
  5976. this._isBlendFunctionParametersDirty = true;
  5977. };
  5978. _AlphaState.prototype.reset = function () {
  5979. this._alphaBlend = false;
  5980. this._blendFunctionParameters[0] = null;
  5981. this._blendFunctionParameters[1] = null;
  5982. this._blendFunctionParameters[2] = null;
  5983. this._blendFunctionParameters[3] = null;
  5984. this._isAlphaBlendDirty = true;
  5985. this._isBlendFunctionParametersDirty = false;
  5986. };
  5987. _AlphaState.prototype.apply = function (gl) {
  5988. if (!this.isDirty) {
  5989. return;
  5990. }
  5991. // Alpha blend
  5992. if (this._isAlphaBlendDirty) {
  5993. if (this._alphaBlend) {
  5994. gl.enable(gl.BLEND);
  5995. }
  5996. else {
  5997. gl.disable(gl.BLEND);
  5998. }
  5999. this._isAlphaBlendDirty = false;
  6000. }
  6001. // Alpha function
  6002. if (this._isBlendFunctionParametersDirty) {
  6003. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  6004. this._isBlendFunctionParametersDirty = false;
  6005. }
  6006. };
  6007. return _AlphaState;
  6008. }());
  6009. Internals._AlphaState = _AlphaState;
  6010. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  6011. })(BABYLON || (BABYLON = {}));
  6012. //# sourceMappingURL=babylon.alphaCullingState.js.map
  6013. var BABYLON;
  6014. (function (BABYLON) {
  6015. var Internals;
  6016. (function (Internals) {
  6017. var _DepthCullingState = (function () {
  6018. /**
  6019. * Initializes the state.
  6020. */
  6021. function _DepthCullingState() {
  6022. this._isDepthTestDirty = false;
  6023. this._isDepthMaskDirty = false;
  6024. this._isDepthFuncDirty = false;
  6025. this._isCullFaceDirty = false;
  6026. this._isCullDirty = false;
  6027. this._isZOffsetDirty = false;
  6028. this.reset();
  6029. }
  6030. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  6031. get: function () {
  6032. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty;
  6033. },
  6034. enumerable: true,
  6035. configurable: true
  6036. });
  6037. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  6038. get: function () {
  6039. return this._zOffset;
  6040. },
  6041. set: function (value) {
  6042. if (this._zOffset === value) {
  6043. return;
  6044. }
  6045. this._zOffset = value;
  6046. this._isZOffsetDirty = true;
  6047. },
  6048. enumerable: true,
  6049. configurable: true
  6050. });
  6051. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  6052. get: function () {
  6053. return this._cullFace;
  6054. },
  6055. set: function (value) {
  6056. if (this._cullFace === value) {
  6057. return;
  6058. }
  6059. this._cullFace = value;
  6060. this._isCullFaceDirty = true;
  6061. },
  6062. enumerable: true,
  6063. configurable: true
  6064. });
  6065. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  6066. get: function () {
  6067. return this._cull;
  6068. },
  6069. set: function (value) {
  6070. if (this._cull === value) {
  6071. return;
  6072. }
  6073. this._cull = value;
  6074. this._isCullDirty = true;
  6075. },
  6076. enumerable: true,
  6077. configurable: true
  6078. });
  6079. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  6080. get: function () {
  6081. return this._depthFunc;
  6082. },
  6083. set: function (value) {
  6084. if (this._depthFunc === value) {
  6085. return;
  6086. }
  6087. this._depthFunc = value;
  6088. this._isDepthFuncDirty = true;
  6089. },
  6090. enumerable: true,
  6091. configurable: true
  6092. });
  6093. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  6094. get: function () {
  6095. return this._depthMask;
  6096. },
  6097. set: function (value) {
  6098. if (this._depthMask === value) {
  6099. return;
  6100. }
  6101. this._depthMask = value;
  6102. this._isDepthMaskDirty = true;
  6103. },
  6104. enumerable: true,
  6105. configurable: true
  6106. });
  6107. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  6108. get: function () {
  6109. return this._depthTest;
  6110. },
  6111. set: function (value) {
  6112. if (this._depthTest === value) {
  6113. return;
  6114. }
  6115. this._depthTest = value;
  6116. this._isDepthTestDirty = true;
  6117. },
  6118. enumerable: true,
  6119. configurable: true
  6120. });
  6121. _DepthCullingState.prototype.reset = function () {
  6122. this._depthMask = true;
  6123. this._depthTest = true;
  6124. this._depthFunc = null;
  6125. this._cullFace = null;
  6126. this._cull = null;
  6127. this._zOffset = 0;
  6128. this._isDepthTestDirty = true;
  6129. this._isDepthMaskDirty = true;
  6130. this._isDepthFuncDirty = false;
  6131. this._isCullFaceDirty = false;
  6132. this._isCullDirty = false;
  6133. this._isZOffsetDirty = false;
  6134. };
  6135. _DepthCullingState.prototype.apply = function (gl) {
  6136. if (!this.isDirty) {
  6137. return;
  6138. }
  6139. // Cull
  6140. if (this._isCullDirty) {
  6141. if (this.cull) {
  6142. gl.enable(gl.CULL_FACE);
  6143. }
  6144. else {
  6145. gl.disable(gl.CULL_FACE);
  6146. }
  6147. this._isCullDirty = false;
  6148. }
  6149. // Cull face
  6150. if (this._isCullFaceDirty) {
  6151. gl.cullFace(this.cullFace);
  6152. this._isCullFaceDirty = false;
  6153. }
  6154. // Depth mask
  6155. if (this._isDepthMaskDirty) {
  6156. gl.depthMask(this.depthMask);
  6157. this._isDepthMaskDirty = false;
  6158. }
  6159. // Depth test
  6160. if (this._isDepthTestDirty) {
  6161. if (this.depthTest) {
  6162. gl.enable(gl.DEPTH_TEST);
  6163. }
  6164. else {
  6165. gl.disable(gl.DEPTH_TEST);
  6166. }
  6167. this._isDepthTestDirty = false;
  6168. }
  6169. // Depth func
  6170. if (this._isDepthFuncDirty) {
  6171. gl.depthFunc(this.depthFunc);
  6172. this._isDepthFuncDirty = false;
  6173. }
  6174. // zOffset
  6175. if (this._isZOffsetDirty) {
  6176. if (this.zOffset) {
  6177. gl.enable(gl.POLYGON_OFFSET_FILL);
  6178. gl.polygonOffset(this.zOffset, 0);
  6179. }
  6180. else {
  6181. gl.disable(gl.POLYGON_OFFSET_FILL);
  6182. }
  6183. this._isZOffsetDirty = false;
  6184. }
  6185. };
  6186. return _DepthCullingState;
  6187. }());
  6188. Internals._DepthCullingState = _DepthCullingState;
  6189. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  6190. })(BABYLON || (BABYLON = {}));
  6191. //# sourceMappingURL=babylon.depthCullingState.js.map
  6192. var BABYLON;
  6193. (function (BABYLON) {
  6194. var Internals;
  6195. (function (Internals) {
  6196. var _StencilState = (function () {
  6197. function _StencilState() {
  6198. this._isStencilTestDirty = false;
  6199. this._isStencilMaskDirty = false;
  6200. this._isStencilFuncDirty = false;
  6201. this._isStencilOpDirty = false;
  6202. this.reset();
  6203. }
  6204. Object.defineProperty(_StencilState.prototype, "isDirty", {
  6205. get: function () {
  6206. return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty;
  6207. },
  6208. enumerable: true,
  6209. configurable: true
  6210. });
  6211. Object.defineProperty(_StencilState.prototype, "stencilFunc", {
  6212. get: function () {
  6213. return this._stencilFunc;
  6214. },
  6215. set: function (value) {
  6216. if (this._stencilFunc === value) {
  6217. return;
  6218. }
  6219. this._stencilFunc = value;
  6220. this._isStencilFuncDirty = true;
  6221. },
  6222. enumerable: true,
  6223. configurable: true
  6224. });
  6225. Object.defineProperty(_StencilState.prototype, "stencilFuncRef", {
  6226. get: function () {
  6227. return this._stencilFuncRef;
  6228. },
  6229. set: function (value) {
  6230. if (this._stencilFuncRef === value) {
  6231. return;
  6232. }
  6233. this._stencilFuncRef = value;
  6234. this._isStencilFuncDirty = true;
  6235. },
  6236. enumerable: true,
  6237. configurable: true
  6238. });
  6239. Object.defineProperty(_StencilState.prototype, "stencilFuncMask", {
  6240. get: function () {
  6241. return this._stencilFuncMask;
  6242. },
  6243. set: function (value) {
  6244. if (this._stencilFuncMask === value) {
  6245. return;
  6246. }
  6247. this._stencilFuncMask = value;
  6248. this._isStencilFuncDirty = true;
  6249. },
  6250. enumerable: true,
  6251. configurable: true
  6252. });
  6253. Object.defineProperty(_StencilState.prototype, "stencilOpStencilFail", {
  6254. get: function () {
  6255. return this._stencilOpStencilFail;
  6256. },
  6257. set: function (value) {
  6258. if (this._stencilOpStencilFail === value) {
  6259. return;
  6260. }
  6261. this._stencilOpStencilFail = value;
  6262. this._isStencilOpDirty = true;
  6263. },
  6264. enumerable: true,
  6265. configurable: true
  6266. });
  6267. Object.defineProperty(_StencilState.prototype, "stencilOpDepthFail", {
  6268. get: function () {
  6269. return this._stencilOpDepthFail;
  6270. },
  6271. set: function (value) {
  6272. if (this._stencilOpDepthFail === value) {
  6273. return;
  6274. }
  6275. this._stencilOpDepthFail = value;
  6276. this._isStencilOpDirty = true;
  6277. },
  6278. enumerable: true,
  6279. configurable: true
  6280. });
  6281. Object.defineProperty(_StencilState.prototype, "stencilOpStencilDepthPass", {
  6282. get: function () {
  6283. return this._stencilOpStencilDepthPass;
  6284. },
  6285. set: function (value) {
  6286. if (this._stencilOpStencilDepthPass === value) {
  6287. return;
  6288. }
  6289. this._stencilOpStencilDepthPass = value;
  6290. this._isStencilOpDirty = true;
  6291. },
  6292. enumerable: true,
  6293. configurable: true
  6294. });
  6295. Object.defineProperty(_StencilState.prototype, "stencilMask", {
  6296. get: function () {
  6297. return this._stencilMask;
  6298. },
  6299. set: function (value) {
  6300. if (this._stencilMask === value) {
  6301. return;
  6302. }
  6303. this._stencilMask = value;
  6304. this._isStencilMaskDirty = true;
  6305. },
  6306. enumerable: true,
  6307. configurable: true
  6308. });
  6309. Object.defineProperty(_StencilState.prototype, "stencilTest", {
  6310. get: function () {
  6311. return this._stencilTest;
  6312. },
  6313. set: function (value) {
  6314. if (this._stencilTest === value) {
  6315. return;
  6316. }
  6317. this._stencilTest = value;
  6318. this._isStencilTestDirty = true;
  6319. },
  6320. enumerable: true,
  6321. configurable: true
  6322. });
  6323. _StencilState.prototype.reset = function () {
  6324. this._stencilTest = false;
  6325. this._stencilMask = 0xFF;
  6326. this._stencilFunc = BABYLON.Engine.ALWAYS;
  6327. this._stencilFuncRef = 1;
  6328. this._stencilFuncMask = 0xFF;
  6329. this._stencilOpStencilFail = BABYLON.Engine.KEEP;
  6330. this._stencilOpDepthFail = BABYLON.Engine.KEEP;
  6331. this._stencilOpStencilDepthPass = BABYLON.Engine.REPLACE;
  6332. this._isStencilTestDirty = true;
  6333. this._isStencilMaskDirty = true;
  6334. this._isStencilFuncDirty = true;
  6335. this._isStencilOpDirty = true;
  6336. };
  6337. _StencilState.prototype.apply = function (gl) {
  6338. if (!this.isDirty) {
  6339. return;
  6340. }
  6341. // Stencil test
  6342. if (this._isStencilTestDirty) {
  6343. if (this.stencilTest) {
  6344. gl.enable(gl.STENCIL_TEST);
  6345. }
  6346. else {
  6347. gl.disable(gl.STENCIL_TEST);
  6348. }
  6349. this._isStencilTestDirty = false;
  6350. }
  6351. // Stencil mask
  6352. if (this._isStencilMaskDirty) {
  6353. gl.stencilMask(this.stencilMask);
  6354. this._isStencilMaskDirty = false;
  6355. }
  6356. // Stencil func
  6357. if (this._isStencilFuncDirty) {
  6358. gl.stencilFunc(this.stencilFunc, this.stencilFuncRef, this.stencilFuncMask);
  6359. this._isStencilFuncDirty = false;
  6360. }
  6361. // Stencil op
  6362. if (this._isStencilOpDirty) {
  6363. gl.stencilOp(this.stencilOpStencilFail, this.stencilOpDepthFail, this.stencilOpStencilDepthPass);
  6364. this._isStencilOpDirty = false;
  6365. }
  6366. };
  6367. return _StencilState;
  6368. }());
  6369. Internals._StencilState = _StencilState;
  6370. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  6371. })(BABYLON || (BABYLON = {}));
  6372. //# sourceMappingURL=babylon.stencilState.js.map
  6373. var BABYLON;
  6374. (function (BABYLON) {
  6375. var compileShader = function (gl, source, type, defines, shaderVersion) {
  6376. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  6377. gl.shaderSource(shader, shaderVersion + (defines ? defines + "\n" : "") + source);
  6378. gl.compileShader(shader);
  6379. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  6380. throw new Error(gl.getShaderInfoLog(shader));
  6381. }
  6382. return shader;
  6383. };
  6384. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  6385. var magFilter = gl.NEAREST;
  6386. var minFilter = gl.NEAREST;
  6387. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  6388. magFilter = gl.LINEAR;
  6389. if (generateMipMaps) {
  6390. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  6391. }
  6392. else {
  6393. minFilter = gl.LINEAR;
  6394. }
  6395. }
  6396. else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  6397. magFilter = gl.LINEAR;
  6398. if (generateMipMaps) {
  6399. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  6400. }
  6401. else {
  6402. minFilter = gl.LINEAR;
  6403. }
  6404. }
  6405. else if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  6406. magFilter = gl.NEAREST;
  6407. if (generateMipMaps) {
  6408. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  6409. }
  6410. else {
  6411. minFilter = gl.NEAREST;
  6412. }
  6413. }
  6414. return {
  6415. min: minFilter,
  6416. mag: magFilter
  6417. };
  6418. };
  6419. var prepareWebGLTexture = function (texture, gl, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  6420. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  6421. var engine = scene.getEngine();
  6422. var potWidth = BABYLON.Tools.GetExponentOfTwo(width, engine.getCaps().maxTextureSize);
  6423. var potHeight = BABYLON.Tools.GetExponentOfTwo(height, engine.getCaps().maxTextureSize);
  6424. engine._bindTextureDirectly(gl.TEXTURE_2D, texture);
  6425. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  6426. texture._baseWidth = width;
  6427. texture._baseHeight = height;
  6428. texture._width = potWidth;
  6429. texture._height = potHeight;
  6430. texture.isReady = true;
  6431. processFunction(potWidth, potHeight);
  6432. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  6433. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  6434. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  6435. if (!noMipmap && !isCompressed) {
  6436. gl.generateMipmap(gl.TEXTURE_2D);
  6437. }
  6438. engine._bindTextureDirectly(gl.TEXTURE_2D, null);
  6439. engine.resetTextureCache();
  6440. scene._removePendingData(texture);
  6441. texture.onLoadedCallbacks.forEach(function (callback) {
  6442. callback();
  6443. });
  6444. texture.onLoadedCallbacks = [];
  6445. };
  6446. var partialLoad = function (url, index, loadedImages, scene, onfinish, onErrorCallBack) {
  6447. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  6448. var img;
  6449. var onload = function () {
  6450. loadedImages[index] = img;
  6451. loadedImages._internalCount++;
  6452. scene._removePendingData(img);
  6453. if (loadedImages._internalCount === 6) {
  6454. onfinish(loadedImages);
  6455. }
  6456. };
  6457. var onerror = function () {
  6458. scene._removePendingData(img);
  6459. if (onErrorCallBack) {
  6460. onErrorCallBack();
  6461. }
  6462. };
  6463. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  6464. scene._addPendingData(img);
  6465. };
  6466. var cascadeLoad = function (rootUrl, scene, onfinish, files, onError) {
  6467. if (onError === void 0) { onError = null; }
  6468. var loadedImages = [];
  6469. loadedImages._internalCount = 0;
  6470. for (var index = 0; index < 6; index++) {
  6471. partialLoad(files[index], index, loadedImages, scene, onfinish, onError);
  6472. }
  6473. };
  6474. var InstancingAttributeInfo = (function () {
  6475. function InstancingAttributeInfo() {
  6476. }
  6477. return InstancingAttributeInfo;
  6478. }());
  6479. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  6480. var EngineCapabilities = (function () {
  6481. function EngineCapabilities() {
  6482. }
  6483. return EngineCapabilities;
  6484. }());
  6485. BABYLON.EngineCapabilities = EngineCapabilities;
  6486. /**
  6487. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
  6488. */
  6489. var Engine = (function () {
  6490. /**
  6491. * @constructor
  6492. * @param {HTMLCanvasElement} canvas - the canvas to be used for rendering
  6493. * @param {boolean} [antialias] - enable antialias
  6494. * @param options - further options to be sent to the getContext function
  6495. */
  6496. function Engine(canvas, antialias, options, adaptToDeviceRatio) {
  6497. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = false; }
  6498. var _this = this;
  6499. // Public members
  6500. this.isFullscreen = false;
  6501. this.isPointerLock = false;
  6502. this.cullBackFaces = true;
  6503. this.renderEvenInBackground = true;
  6504. // To enable/disable IDB support and avoid XHR on .manifest
  6505. this.enableOfflineSupport = true;
  6506. this.scenes = new Array();
  6507. this._windowIsBackground = false;
  6508. this._webGLVersion = 1.0;
  6509. this._badOS = false;
  6510. this._drawCalls = new BABYLON.PerfCounter();
  6511. this._renderingQueueLaunched = false;
  6512. this._activeRenderLoops = [];
  6513. // FPS
  6514. this.fpsRange = 60;
  6515. this.previousFramesDuration = [];
  6516. this.fps = 60;
  6517. this.deltaTime = 0;
  6518. // States
  6519. this._depthCullingState = new BABYLON.Internals._DepthCullingState();
  6520. this._stencilState = new BABYLON.Internals._StencilState();
  6521. this._alphaState = new BABYLON.Internals._AlphaState();
  6522. this._alphaMode = Engine.ALPHA_DISABLE;
  6523. // Cache
  6524. this._loadedTexturesCache = new Array();
  6525. this._maxTextureChannels = 16;
  6526. this._activeTexturesCache = new Array(this._maxTextureChannels);
  6527. this._compiledEffects = {};
  6528. this._vertexAttribArraysEnabled = [];
  6529. this._uintIndicesCurrentlySet = false;
  6530. this._currentBoundBuffer = new Array();
  6531. this._currentBufferPointers = [];
  6532. this._currentInstanceLocations = new Array();
  6533. this._currentInstanceBuffers = new Array();
  6534. this._vaoRecordInProgress = false;
  6535. this._mustWipeVertexAttributes = false;
  6536. // Hardware supported Compressed Textures
  6537. this._texturesSupported = new Array();
  6538. this._onVRFullScreenTriggered = function () {
  6539. if (_this._vrDisplayEnabled && _this._vrDisplayEnabled.isPresenting) {
  6540. //get the old size before we change
  6541. _this._oldSize = new BABYLON.Size(_this.getRenderWidth(), _this.getRenderHeight());
  6542. _this._oldHardwareScaleFactor = _this.getHardwareScalingLevel();
  6543. //according to the WebVR specs, requestAnimationFrame should be triggered only once.
  6544. //But actually, no browser follow the specs...
  6545. //this._vrAnimationFrameHandler = this._vrDisplayEnabled.requestAnimationFrame(this._bindedRenderFunction);
  6546. //get the width and height, change the render size
  6547. var leftEye = _this._vrDisplayEnabled.getEyeParameters('left');
  6548. var width, height;
  6549. _this.setHardwareScalingLevel(1);
  6550. _this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  6551. }
  6552. else {
  6553. //When the specs are implemented, need to uncomment this.
  6554. //this._vrDisplayEnabled.cancelAnimationFrame(this._vrAnimationFrameHandler);
  6555. _this.setHardwareScalingLevel(_this._oldHardwareScaleFactor);
  6556. _this.setSize(_this._oldSize.width, _this._oldSize.height);
  6557. _this._vrDisplayEnabled = undefined;
  6558. }
  6559. };
  6560. this._renderingCanvas = canvas;
  6561. this._externalData = new BABYLON.StringDictionary();
  6562. options = options || {};
  6563. if (antialias != null) {
  6564. options.antialias = antialias;
  6565. }
  6566. if (options.preserveDrawingBuffer === undefined) {
  6567. options.preserveDrawingBuffer = false;
  6568. }
  6569. // GL
  6570. if (!options.disableWebGL2Support) {
  6571. try {
  6572. this._gl = (canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  6573. if (this._gl) {
  6574. this._webGLVersion = 2.0;
  6575. }
  6576. }
  6577. catch (e) {
  6578. }
  6579. }
  6580. if (!this._gl) {
  6581. if (!canvas) {
  6582. throw new Error("The provided canvas is null or undefined.");
  6583. }
  6584. try {
  6585. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  6586. }
  6587. catch (e) {
  6588. throw new Error("WebGL not supported");
  6589. }
  6590. }
  6591. if (!this._gl) {
  6592. throw new Error("WebGL not supported");
  6593. }
  6594. this._onBlur = function () {
  6595. _this._windowIsBackground = true;
  6596. };
  6597. this._onFocus = function () {
  6598. _this._windowIsBackground = false;
  6599. };
  6600. window.addEventListener("blur", this._onBlur);
  6601. window.addEventListener("focus", this._onFocus);
  6602. // Viewport
  6603. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  6604. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  6605. this.resize();
  6606. // Caps
  6607. this._isStencilEnable = options.stencil;
  6608. this._caps = new EngineCapabilities();
  6609. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  6610. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  6611. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  6612. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  6613. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  6614. this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS);
  6615. this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  6616. this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS);
  6617. // Infos
  6618. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  6619. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  6620. if (rendererInfo != null) {
  6621. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  6622. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  6623. }
  6624. if (!this._glVendor) {
  6625. this._glVendor = "Unknown vendor";
  6626. }
  6627. if (!this._glRenderer) {
  6628. this._glRenderer = "Unknown renderer";
  6629. }
  6630. // Extensions
  6631. this._caps.standardDerivatives = this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null);
  6632. this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc');
  6633. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  6634. this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  6635. this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1');
  6636. this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc') ||
  6637. this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // also a requirement of OpenGL ES 3
  6638. this._caps.atc = this._gl.getExtension('WEBGL_compressed_texture_atc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_atc');
  6639. 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');
  6640. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  6641. this._caps.uintIndices = this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null;
  6642. this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null;
  6643. this._caps.highPrecisionShaderSupported = true;
  6644. this._caps.drawBuffersExtension = this._webGLVersion > 1 || this._gl.getExtension('WEBGL_draw_buffers');
  6645. // Checks if some of the format renders first to allow the use of webgl inspector.
  6646. this._caps.colorBufferFloat = this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float');
  6647. this._caps.textureFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float');
  6648. this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear');
  6649. this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer();
  6650. this._caps.textureHalfFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float');
  6651. this._caps.textureHalfFloatLinearFiltering = this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'));
  6652. this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
  6653. this._caps.textureLOD = this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod');
  6654. // Vertex array object
  6655. if (this._webGLVersion > 1) {
  6656. this._caps.vertexArrayObject = true;
  6657. }
  6658. else {
  6659. var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object');
  6660. if (vertexArrayObjectExtension != null) {
  6661. this._caps.vertexArrayObject = true;
  6662. this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
  6663. this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
  6664. this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
  6665. }
  6666. else {
  6667. this._caps.vertexArrayObject = false;
  6668. }
  6669. }
  6670. // Instances count
  6671. if (this._webGLVersion > 1) {
  6672. this._caps.instancedArrays = true;
  6673. }
  6674. else {
  6675. var instanceExtension = this._gl.getExtension('ANGLE_instanced_arrays');
  6676. if (instanceExtension != null) {
  6677. this._caps.instancedArrays = true;
  6678. this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
  6679. this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
  6680. this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
  6681. }
  6682. else {
  6683. this._caps.instancedArrays = false;
  6684. }
  6685. }
  6686. // Intelligently add supported compressed formats in order to check for.
  6687. // Check for ASTC support first as it is most powerful and to be very cross platform.
  6688. // Next PVRTC & DXT, which are probably superior to ETC1/2.
  6689. // Likely no hardware which supports both PVR & DXT, so order matters little.
  6690. // ETC2 is newer and handles ETC1 (no alpha capability), so check for first.
  6691. // ATC before ETC1, since both old (widely supported), but ATC supports alpha, but ETC1 does not
  6692. if (this._caps.astc)
  6693. this.texturesSupported.push('-astc.ktx');
  6694. if (this._caps.s3tc)
  6695. this.texturesSupported.push('-dxt.ktx');
  6696. if (this._caps.pvrtc)
  6697. this.texturesSupported.push('-pvrtc.ktx');
  6698. if (this._caps.etc2)
  6699. this.texturesSupported.push('-etc2.ktx');
  6700. if (this._caps.atc)
  6701. this.texturesSupported.push('-atc.ktx');
  6702. if (this._caps.etc1)
  6703. this.texturesSupported.push('-etc1.ktx');
  6704. if (this._gl.getShaderPrecisionFormat) {
  6705. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  6706. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  6707. }
  6708. // Depth buffer
  6709. this.setDepthBuffer(true);
  6710. this.setDepthFunctionToLessOrEqual();
  6711. this.setDepthWrite(true);
  6712. // Fullscreen
  6713. this._onFullscreenChange = function () {
  6714. if (document.fullscreen !== undefined) {
  6715. _this.isFullscreen = document.fullscreen;
  6716. }
  6717. else if (document.mozFullScreen !== undefined) {
  6718. _this.isFullscreen = document.mozFullScreen;
  6719. }
  6720. else if (document.webkitIsFullScreen !== undefined) {
  6721. _this.isFullscreen = document.webkitIsFullScreen;
  6722. }
  6723. else if (document.msIsFullScreen !== undefined) {
  6724. _this.isFullscreen = document.msIsFullScreen;
  6725. }
  6726. // Pointer lock
  6727. if (_this.isFullscreen && _this._pointerLockRequested) {
  6728. canvas.requestPointerLock = canvas.requestPointerLock ||
  6729. canvas.msRequestPointerLock ||
  6730. canvas.mozRequestPointerLock ||
  6731. canvas.webkitRequestPointerLock;
  6732. if (canvas.requestPointerLock) {
  6733. canvas.requestPointerLock();
  6734. }
  6735. }
  6736. };
  6737. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  6738. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  6739. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  6740. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  6741. // Pointer lock
  6742. this._onPointerLockChange = function () {
  6743. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  6744. document.webkitPointerLockElement === canvas ||
  6745. document.msPointerLockElement === canvas ||
  6746. document.pointerLockElement === canvas);
  6747. };
  6748. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  6749. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  6750. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  6751. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  6752. if (BABYLON.AudioEngine && !Engine.audioEngine) {
  6753. Engine.audioEngine = new BABYLON.AudioEngine();
  6754. }
  6755. //default loading screen
  6756. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  6757. //Load WebVR Devices
  6758. if (options.autoEnableWebVR) {
  6759. this.initWebVR();
  6760. }
  6761. //Detect if we are running on a faulty buggy OS.
  6762. var regexp = /AppleWebKit.*10.[\d] Mobile/;
  6763. //ua sniffing is the tool of the devil.
  6764. this._badOS = regexp.test(navigator.userAgent);
  6765. BABYLON.Tools.Log("Babylon.js engine (v" + Engine.Version + ") launched");
  6766. }
  6767. Object.defineProperty(Engine, "NEVER", {
  6768. get: function () {
  6769. return Engine._NEVER;
  6770. },
  6771. enumerable: true,
  6772. configurable: true
  6773. });
  6774. Object.defineProperty(Engine, "ALWAYS", {
  6775. get: function () {
  6776. return Engine._ALWAYS;
  6777. },
  6778. enumerable: true,
  6779. configurable: true
  6780. });
  6781. Object.defineProperty(Engine, "LESS", {
  6782. get: function () {
  6783. return Engine._LESS;
  6784. },
  6785. enumerable: true,
  6786. configurable: true
  6787. });
  6788. Object.defineProperty(Engine, "EQUAL", {
  6789. get: function () {
  6790. return Engine._EQUAL;
  6791. },
  6792. enumerable: true,
  6793. configurable: true
  6794. });
  6795. Object.defineProperty(Engine, "LEQUAL", {
  6796. get: function () {
  6797. return Engine._LEQUAL;
  6798. },
  6799. enumerable: true,
  6800. configurable: true
  6801. });
  6802. Object.defineProperty(Engine, "GREATER", {
  6803. get: function () {
  6804. return Engine._GREATER;
  6805. },
  6806. enumerable: true,
  6807. configurable: true
  6808. });
  6809. Object.defineProperty(Engine, "GEQUAL", {
  6810. get: function () {
  6811. return Engine._GEQUAL;
  6812. },
  6813. enumerable: true,
  6814. configurable: true
  6815. });
  6816. Object.defineProperty(Engine, "NOTEQUAL", {
  6817. get: function () {
  6818. return Engine._NOTEQUAL;
  6819. },
  6820. enumerable: true,
  6821. configurable: true
  6822. });
  6823. Object.defineProperty(Engine, "KEEP", {
  6824. get: function () {
  6825. return Engine._KEEP;
  6826. },
  6827. enumerable: true,
  6828. configurable: true
  6829. });
  6830. Object.defineProperty(Engine, "REPLACE", {
  6831. get: function () {
  6832. return Engine._REPLACE;
  6833. },
  6834. enumerable: true,
  6835. configurable: true
  6836. });
  6837. Object.defineProperty(Engine, "INCR", {
  6838. get: function () {
  6839. return Engine._INCR;
  6840. },
  6841. enumerable: true,
  6842. configurable: true
  6843. });
  6844. Object.defineProperty(Engine, "DECR", {
  6845. get: function () {
  6846. return Engine._DECR;
  6847. },
  6848. enumerable: true,
  6849. configurable: true
  6850. });
  6851. Object.defineProperty(Engine, "INVERT", {
  6852. get: function () {
  6853. return Engine._INVERT;
  6854. },
  6855. enumerable: true,
  6856. configurable: true
  6857. });
  6858. Object.defineProperty(Engine, "INCR_WRAP", {
  6859. get: function () {
  6860. return Engine._INCR_WRAP;
  6861. },
  6862. enumerable: true,
  6863. configurable: true
  6864. });
  6865. Object.defineProperty(Engine, "DECR_WRAP", {
  6866. get: function () {
  6867. return Engine._DECR_WRAP;
  6868. },
  6869. enumerable: true,
  6870. configurable: true
  6871. });
  6872. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  6873. get: function () {
  6874. return Engine._ALPHA_DISABLE;
  6875. },
  6876. enumerable: true,
  6877. configurable: true
  6878. });
  6879. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  6880. get: function () {
  6881. return Engine._ALPHA_ONEONE;
  6882. },
  6883. enumerable: true,
  6884. configurable: true
  6885. });
  6886. Object.defineProperty(Engine, "ALPHA_ADD", {
  6887. get: function () {
  6888. return Engine._ALPHA_ADD;
  6889. },
  6890. enumerable: true,
  6891. configurable: true
  6892. });
  6893. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  6894. get: function () {
  6895. return Engine._ALPHA_COMBINE;
  6896. },
  6897. enumerable: true,
  6898. configurable: true
  6899. });
  6900. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  6901. get: function () {
  6902. return Engine._ALPHA_SUBTRACT;
  6903. },
  6904. enumerable: true,
  6905. configurable: true
  6906. });
  6907. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  6908. get: function () {
  6909. return Engine._ALPHA_MULTIPLY;
  6910. },
  6911. enumerable: true,
  6912. configurable: true
  6913. });
  6914. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  6915. get: function () {
  6916. return Engine._ALPHA_MAXIMIZED;
  6917. },
  6918. enumerable: true,
  6919. configurable: true
  6920. });
  6921. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED", {
  6922. get: function () {
  6923. return Engine._ALPHA_PREMULTIPLIED;
  6924. },
  6925. enumerable: true,
  6926. configurable: true
  6927. });
  6928. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  6929. get: function () {
  6930. return Engine._DELAYLOADSTATE_NONE;
  6931. },
  6932. enumerable: true,
  6933. configurable: true
  6934. });
  6935. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  6936. get: function () {
  6937. return Engine._DELAYLOADSTATE_LOADED;
  6938. },
  6939. enumerable: true,
  6940. configurable: true
  6941. });
  6942. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  6943. get: function () {
  6944. return Engine._DELAYLOADSTATE_LOADING;
  6945. },
  6946. enumerable: true,
  6947. configurable: true
  6948. });
  6949. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  6950. get: function () {
  6951. return Engine._DELAYLOADSTATE_NOTLOADED;
  6952. },
  6953. enumerable: true,
  6954. configurable: true
  6955. });
  6956. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  6957. get: function () {
  6958. return Engine._TEXTUREFORMAT_ALPHA;
  6959. },
  6960. enumerable: true,
  6961. configurable: true
  6962. });
  6963. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  6964. get: function () {
  6965. return Engine._TEXTUREFORMAT_LUMINANCE;
  6966. },
  6967. enumerable: true,
  6968. configurable: true
  6969. });
  6970. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  6971. get: function () {
  6972. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  6973. },
  6974. enumerable: true,
  6975. configurable: true
  6976. });
  6977. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  6978. get: function () {
  6979. return Engine._TEXTUREFORMAT_RGB;
  6980. },
  6981. enumerable: true,
  6982. configurable: true
  6983. });
  6984. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  6985. get: function () {
  6986. return Engine._TEXTUREFORMAT_RGBA;
  6987. },
  6988. enumerable: true,
  6989. configurable: true
  6990. });
  6991. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  6992. get: function () {
  6993. return Engine._TEXTURETYPE_UNSIGNED_INT;
  6994. },
  6995. enumerable: true,
  6996. configurable: true
  6997. });
  6998. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  6999. get: function () {
  7000. return Engine._TEXTURETYPE_FLOAT;
  7001. },
  7002. enumerable: true,
  7003. configurable: true
  7004. });
  7005. Object.defineProperty(Engine, "TEXTURETYPE_HALF_FLOAT", {
  7006. get: function () {
  7007. return Engine._TEXTURETYPE_HALF_FLOAT;
  7008. },
  7009. enumerable: true,
  7010. configurable: true
  7011. });
  7012. Object.defineProperty(Engine, "Version", {
  7013. get: function () {
  7014. return "2.6-alpha";
  7015. },
  7016. enumerable: true,
  7017. configurable: true
  7018. });
  7019. Object.defineProperty(Engine.prototype, "texturesSupported", {
  7020. get: function () {
  7021. return this._texturesSupported;
  7022. },
  7023. enumerable: true,
  7024. configurable: true
  7025. });
  7026. Object.defineProperty(Engine.prototype, "textureFormatInUse", {
  7027. get: function () {
  7028. return this._textureFormatInUse;
  7029. },
  7030. enumerable: true,
  7031. configurable: true
  7032. });
  7033. Object.defineProperty(Engine.prototype, "webGLVersion", {
  7034. get: function () {
  7035. return this._webGLVersion;
  7036. },
  7037. enumerable: true,
  7038. configurable: true
  7039. });
  7040. Object.defineProperty(Engine.prototype, "isStencilEnable", {
  7041. /**
  7042. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  7043. */
  7044. get: function () {
  7045. return this._isStencilEnable;
  7046. },
  7047. enumerable: true,
  7048. configurable: true
  7049. });
  7050. Engine.prototype._prepareWorkingCanvas = function () {
  7051. if (this._workingCanvas) {
  7052. return;
  7053. }
  7054. this._workingCanvas = document.createElement("canvas");
  7055. this._workingContext = this._workingCanvas.getContext("2d");
  7056. };
  7057. Engine.prototype.resetTextureCache = function () {
  7058. for (var index = 0; index < this._maxTextureChannels; index++) {
  7059. this._activeTexturesCache[index] = null;
  7060. }
  7061. };
  7062. Engine.prototype.getGlInfo = function () {
  7063. return {
  7064. vendor: this._glVendor,
  7065. renderer: this._glRenderer,
  7066. version: this._glVersion
  7067. };
  7068. };
  7069. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  7070. if (useScreen === void 0) { useScreen = false; }
  7071. var viewport = camera.viewport;
  7072. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  7073. };
  7074. Engine.prototype.getRenderWidth = function (useScreen) {
  7075. if (useScreen === void 0) { useScreen = false; }
  7076. if (!useScreen && this._currentRenderTarget) {
  7077. return this._currentRenderTarget._width;
  7078. }
  7079. return this._renderingCanvas.width;
  7080. };
  7081. Engine.prototype.getRenderHeight = function (useScreen) {
  7082. if (useScreen === void 0) { useScreen = false; }
  7083. if (!useScreen && this._currentRenderTarget) {
  7084. return this._currentRenderTarget._height;
  7085. }
  7086. return this._renderingCanvas.height;
  7087. };
  7088. Engine.prototype.getRenderingCanvas = function () {
  7089. return this._renderingCanvas;
  7090. };
  7091. Engine.prototype.getRenderingCanvasClientRect = function () {
  7092. return this._renderingCanvas.getBoundingClientRect();
  7093. };
  7094. Engine.prototype.setHardwareScalingLevel = function (level) {
  7095. this._hardwareScalingLevel = level;
  7096. this.resize();
  7097. };
  7098. Engine.prototype.getHardwareScalingLevel = function () {
  7099. return this._hardwareScalingLevel;
  7100. };
  7101. Engine.prototype.getLoadedTexturesCache = function () {
  7102. return this._loadedTexturesCache;
  7103. };
  7104. Engine.prototype.getCaps = function () {
  7105. return this._caps;
  7106. };
  7107. Object.defineProperty(Engine.prototype, "drawCalls", {
  7108. get: function () {
  7109. return this._drawCalls.current;
  7110. },
  7111. enumerable: true,
  7112. configurable: true
  7113. });
  7114. Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
  7115. get: function () {
  7116. return this._drawCalls;
  7117. },
  7118. enumerable: true,
  7119. configurable: true
  7120. });
  7121. Engine.prototype.getDepthFunction = function () {
  7122. return this._depthCullingState.depthFunc;
  7123. };
  7124. Engine.prototype.setDepthFunction = function (depthFunc) {
  7125. this._depthCullingState.depthFunc = depthFunc;
  7126. };
  7127. Engine.prototype.setDepthFunctionToGreater = function () {
  7128. this._depthCullingState.depthFunc = this._gl.GREATER;
  7129. };
  7130. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  7131. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  7132. };
  7133. Engine.prototype.setDepthFunctionToLess = function () {
  7134. this._depthCullingState.depthFunc = this._gl.LESS;
  7135. };
  7136. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  7137. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  7138. };
  7139. Engine.prototype.getStencilBuffer = function () {
  7140. return this._stencilState.stencilTest;
  7141. };
  7142. Engine.prototype.setStencilBuffer = function (enable) {
  7143. this._stencilState.stencilTest = enable;
  7144. };
  7145. Engine.prototype.getStencilMask = function () {
  7146. return this._stencilState.stencilMask;
  7147. };
  7148. Engine.prototype.setStencilMask = function (mask) {
  7149. this._stencilState.stencilMask = mask;
  7150. };
  7151. Engine.prototype.getStencilFunction = function () {
  7152. return this._stencilState.stencilFunc;
  7153. };
  7154. Engine.prototype.getStencilFunctionReference = function () {
  7155. return this._stencilState.stencilFuncRef;
  7156. };
  7157. Engine.prototype.getStencilFunctionMask = function () {
  7158. return this._stencilState.stencilFuncMask;
  7159. };
  7160. Engine.prototype.setStencilFunction = function (stencilFunc) {
  7161. this._stencilState.stencilFunc = stencilFunc;
  7162. };
  7163. Engine.prototype.setStencilFunctionReference = function (reference) {
  7164. this._stencilState.stencilFuncRef = reference;
  7165. };
  7166. Engine.prototype.setStencilFunctionMask = function (mask) {
  7167. this._stencilState.stencilFuncMask = mask;
  7168. };
  7169. Engine.prototype.getStencilOperationFail = function () {
  7170. return this._stencilState.stencilOpStencilFail;
  7171. };
  7172. Engine.prototype.getStencilOperationDepthFail = function () {
  7173. return this._stencilState.stencilOpDepthFail;
  7174. };
  7175. Engine.prototype.getStencilOperationPass = function () {
  7176. return this._stencilState.stencilOpStencilDepthPass;
  7177. };
  7178. Engine.prototype.setStencilOperationFail = function (operation) {
  7179. this._stencilState.stencilOpStencilFail = operation;
  7180. };
  7181. Engine.prototype.setStencilOperationDepthFail = function (operation) {
  7182. this._stencilState.stencilOpDepthFail = operation;
  7183. };
  7184. Engine.prototype.setStencilOperationPass = function (operation) {
  7185. this._stencilState.stencilOpStencilDepthPass = operation;
  7186. };
  7187. /**
  7188. * stop executing a render loop function and remove it from the execution array
  7189. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  7190. */
  7191. Engine.prototype.stopRenderLoop = function (renderFunction) {
  7192. if (!renderFunction) {
  7193. this._activeRenderLoops = [];
  7194. return;
  7195. }
  7196. var index = this._activeRenderLoops.indexOf(renderFunction);
  7197. if (index >= 0) {
  7198. this._activeRenderLoops.splice(index, 1);
  7199. }
  7200. };
  7201. Engine.prototype._renderLoop = function () {
  7202. var shouldRender = true;
  7203. if (!this.renderEvenInBackground && this._windowIsBackground) {
  7204. shouldRender = false;
  7205. }
  7206. if (shouldRender) {
  7207. // Start new frame
  7208. this.beginFrame();
  7209. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  7210. var renderFunction = this._activeRenderLoops[index];
  7211. renderFunction();
  7212. }
  7213. // Present
  7214. this.endFrame();
  7215. }
  7216. if (this._activeRenderLoops.length > 0) {
  7217. // Register new frame
  7218. BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction, this._vrDisplayEnabled);
  7219. }
  7220. else {
  7221. this._renderingQueueLaunched = false;
  7222. }
  7223. };
  7224. /**
  7225. * Register and execute a render loop. The engine can have more than one render function.
  7226. * @param {Function} renderFunction - the function to continuously execute starting the next render loop.
  7227. * @example
  7228. * engine.runRenderLoop(function () {
  7229. * scene.render()
  7230. * })
  7231. */
  7232. Engine.prototype.runRenderLoop = function (renderFunction) {
  7233. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  7234. return;
  7235. }
  7236. this._activeRenderLoops.push(renderFunction);
  7237. if (!this._renderingQueueLaunched) {
  7238. this._renderingQueueLaunched = true;
  7239. this._bindedRenderFunction = this._renderLoop.bind(this);
  7240. BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  7241. }
  7242. };
  7243. /**
  7244. * Toggle full screen mode.
  7245. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  7246. * @param {any} options - an options object to be sent to the requestFullscreen function
  7247. */
  7248. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  7249. if (this.isFullscreen) {
  7250. BABYLON.Tools.ExitFullscreen();
  7251. }
  7252. else {
  7253. this._pointerLockRequested = requestPointerLock;
  7254. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  7255. }
  7256. };
  7257. Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
  7258. if (stencil === void 0) { stencil = false; }
  7259. this.applyStates();
  7260. var mode = 0;
  7261. if (backBuffer && color) {
  7262. this._gl.clearColor(color.r, color.g, color.b, color.a);
  7263. mode |= this._gl.COLOR_BUFFER_BIT;
  7264. }
  7265. if (depth) {
  7266. this._gl.clearDepth(1.0);
  7267. mode |= this._gl.DEPTH_BUFFER_BIT;
  7268. }
  7269. if (stencil) {
  7270. this._gl.clearStencil(0);
  7271. mode |= this._gl.STENCIL_BUFFER_BIT;
  7272. }
  7273. this._gl.clear(mode);
  7274. };
  7275. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  7276. var gl = this._gl;
  7277. // Save state
  7278. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  7279. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  7280. // Change state
  7281. gl.enable(gl.SCISSOR_TEST);
  7282. gl.scissor(x, y, width, height);
  7283. // Clear
  7284. this.clear(clearColor, true, true, true);
  7285. // Restore state
  7286. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  7287. if (curScissor === true) {
  7288. gl.enable(gl.SCISSOR_TEST);
  7289. }
  7290. else {
  7291. gl.disable(gl.SCISSOR_TEST);
  7292. }
  7293. };
  7294. /**
  7295. * Set the WebGL's viewport
  7296. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  7297. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  7298. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  7299. */
  7300. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  7301. var width = requiredWidth || (navigator.isCocoonJS ? window.innerWidth : this.getRenderWidth());
  7302. var height = requiredHeight || (navigator.isCocoonJS ? window.innerHeight : this.getRenderHeight());
  7303. var x = viewport.x || 0;
  7304. var y = viewport.y || 0;
  7305. this._cachedViewport = viewport;
  7306. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  7307. };
  7308. /**
  7309. * Directly set the WebGL Viewport
  7310. * The x, y, width & height are directly passed to the WebGL call
  7311. * @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.
  7312. */
  7313. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  7314. var currentViewport = this._cachedViewport;
  7315. this._cachedViewport = null;
  7316. this._gl.viewport(x, y, width, height);
  7317. return currentViewport;
  7318. };
  7319. Engine.prototype.beginFrame = function () {
  7320. this._measureFps();
  7321. };
  7322. Engine.prototype.endFrame = function () {
  7323. //force a flush in case we are using a bad OS.
  7324. if (this._badOS) {
  7325. this.flushFramebuffer();
  7326. }
  7327. //submit frame to the vr device, if enabled
  7328. if (this._vrDisplayEnabled && this._vrDisplayEnabled.isPresenting) {
  7329. this._vrDisplayEnabled.submitFrame();
  7330. }
  7331. };
  7332. /**
  7333. * resize the view according to the canvas' size.
  7334. * @example
  7335. * window.addEventListener("resize", function () {
  7336. * engine.resize();
  7337. * });
  7338. */
  7339. Engine.prototype.resize = function () {
  7340. var width = navigator.isCocoonJS ? window.innerWidth : this._renderingCanvas.clientWidth;
  7341. var height = navigator.isCocoonJS ? window.innerHeight : this._renderingCanvas.clientHeight;
  7342. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  7343. };
  7344. /**
  7345. * force a specific size of the canvas
  7346. * @param {number} width - the new canvas' width
  7347. * @param {number} height - the new canvas' height
  7348. */
  7349. Engine.prototype.setSize = function (width, height) {
  7350. this._renderingCanvas.width = width;
  7351. this._renderingCanvas.height = height;
  7352. for (var index = 0; index < this.scenes.length; index++) {
  7353. var scene = this.scenes[index];
  7354. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  7355. var cam = scene.cameras[camIndex];
  7356. cam._currentRenderId = 0;
  7357. }
  7358. }
  7359. };
  7360. //WebVR functions
  7361. Engine.prototype.initWebVR = function () {
  7362. if (!this.vrDisplaysPromise) {
  7363. this._getVRDisplays();
  7364. }
  7365. };
  7366. Engine.prototype.enableVR = function (vrDevice) {
  7367. this._vrDisplayEnabled = vrDevice;
  7368. this._vrDisplayEnabled.requestPresent([{ source: this.getRenderingCanvas() }]).then(this._onVRFullScreenTriggered);
  7369. };
  7370. Engine.prototype.disableVR = function () {
  7371. if (this._vrDisplayEnabled) {
  7372. this._vrDisplayEnabled.exitPresent().then(this._onVRFullScreenTriggered);
  7373. }
  7374. };
  7375. Engine.prototype._getVRDisplays = function () {
  7376. var _this = this;
  7377. var getWebVRDevices = function (devices) {
  7378. var size = devices.length;
  7379. var i = 0;
  7380. _this._vrDisplays = devices.filter(function (device) {
  7381. return devices[i] instanceof VRDisplay;
  7382. });
  7383. return _this._vrDisplays;
  7384. };
  7385. //using a key due to typescript
  7386. if (navigator.getVRDisplays) {
  7387. this.vrDisplaysPromise = navigator.getVRDisplays().then(getWebVRDevices);
  7388. }
  7389. };
  7390. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight) {
  7391. this._currentRenderTarget = texture;
  7392. this.bindUnboundFramebuffer(texture._framebuffer);
  7393. var gl = this._gl;
  7394. if (texture.isCube) {
  7395. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture, 0);
  7396. }
  7397. gl.viewport(0, 0, requiredWidth || texture._width, requiredHeight || texture._height);
  7398. this.wipeCaches();
  7399. };
  7400. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  7401. if (this._currentFramebuffer !== framebuffer) {
  7402. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  7403. this._currentFramebuffer = framebuffer;
  7404. }
  7405. };
  7406. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps) {
  7407. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  7408. this._currentRenderTarget = null;
  7409. if (texture.generateMipMaps && !disableGenerateMipMaps) {
  7410. var gl = this._gl;
  7411. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  7412. gl.generateMipmap(gl.TEXTURE_2D);
  7413. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  7414. }
  7415. this.bindUnboundFramebuffer(null);
  7416. };
  7417. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  7418. if (texture.generateMipMaps) {
  7419. var gl = this._gl;
  7420. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  7421. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  7422. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  7423. }
  7424. };
  7425. Engine.prototype.flushFramebuffer = function () {
  7426. this._gl.flush();
  7427. };
  7428. Engine.prototype.restoreDefaultFramebuffer = function () {
  7429. this._currentRenderTarget = null;
  7430. this.bindUnboundFramebuffer(null);
  7431. this.setViewport(this._cachedViewport);
  7432. this.wipeCaches();
  7433. };
  7434. // VBOs
  7435. Engine.prototype._resetVertexBufferBinding = function () {
  7436. this.bindArrayBuffer(null);
  7437. this._cachedVertexBuffers = null;
  7438. };
  7439. Engine.prototype.createVertexBuffer = function (vertices) {
  7440. var vbo = this._gl.createBuffer();
  7441. this.bindArrayBuffer(vbo);
  7442. if (vertices instanceof Float32Array) {
  7443. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.STATIC_DRAW);
  7444. }
  7445. else {
  7446. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  7447. }
  7448. this._resetVertexBufferBinding();
  7449. vbo.references = 1;
  7450. return vbo;
  7451. };
  7452. Engine.prototype.createDynamicVertexBuffer = function (vertices) {
  7453. var vbo = this._gl.createBuffer();
  7454. this.bindArrayBuffer(vbo);
  7455. if (vertices instanceof Float32Array) {
  7456. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.DYNAMIC_DRAW);
  7457. }
  7458. else {
  7459. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.DYNAMIC_DRAW);
  7460. }
  7461. this._resetVertexBufferBinding();
  7462. vbo.references = 1;
  7463. return vbo;
  7464. };
  7465. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset, count) {
  7466. this.bindArrayBuffer(vertexBuffer);
  7467. if (offset === undefined) {
  7468. offset = 0;
  7469. }
  7470. if (count === undefined) {
  7471. if (vertices instanceof Float32Array) {
  7472. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  7473. }
  7474. else {
  7475. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  7476. }
  7477. }
  7478. else {
  7479. if (vertices instanceof Float32Array) {
  7480. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, vertices.subarray(offset, offset + count));
  7481. }
  7482. else {
  7483. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(vertices).subarray(offset, offset + count));
  7484. }
  7485. }
  7486. this._resetVertexBufferBinding();
  7487. };
  7488. Engine.prototype._resetIndexBufferBinding = function () {
  7489. this.bindIndexBuffer(null);
  7490. this._cachedIndexBuffer = null;
  7491. };
  7492. Engine.prototype.createIndexBuffer = function (indices) {
  7493. var vbo = this._gl.createBuffer();
  7494. this.bindIndexBuffer(vbo);
  7495. // Check for 32 bits indices
  7496. var arrayBuffer;
  7497. var need32Bits = false;
  7498. if (this._caps.uintIndices) {
  7499. for (var index = 0; index < indices.length; index++) {
  7500. if (indices[index] > 65535) {
  7501. need32Bits = true;
  7502. break;
  7503. }
  7504. }
  7505. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  7506. }
  7507. else {
  7508. arrayBuffer = new Uint16Array(indices);
  7509. }
  7510. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.STATIC_DRAW);
  7511. this._resetIndexBufferBinding();
  7512. vbo.references = 1;
  7513. vbo.is32Bits = need32Bits;
  7514. return vbo;
  7515. };
  7516. Engine.prototype.bindArrayBuffer = function (buffer) {
  7517. if (!this._vaoRecordInProgress) {
  7518. this._unBindVertexArrayObject();
  7519. }
  7520. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  7521. };
  7522. Engine.prototype.bindIndexBuffer = function (buffer) {
  7523. if (!this._vaoRecordInProgress) {
  7524. this._unBindVertexArrayObject();
  7525. }
  7526. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  7527. };
  7528. Engine.prototype.bindBuffer = function (buffer, target) {
  7529. if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
  7530. this._gl.bindBuffer(target, buffer);
  7531. this._currentBoundBuffer[target] = buffer;
  7532. }
  7533. };
  7534. Engine.prototype.updateArrayBuffer = function (data) {
  7535. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  7536. };
  7537. Engine.prototype.vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  7538. var pointer = this._currentBufferPointers[indx];
  7539. var changed = false;
  7540. if (!pointer) {
  7541. changed = true;
  7542. this._currentBufferPointers[indx] = { indx: indx, size: size, type: type, normalized: normalized, stride: stride, offset: offset, buffer: buffer };
  7543. }
  7544. else {
  7545. if (pointer.buffer !== buffer) {
  7546. pointer.buffer = buffer;
  7547. changed = true;
  7548. }
  7549. if (pointer.size !== size) {
  7550. pointer.size = size;
  7551. changed = true;
  7552. }
  7553. if (pointer.type !== type) {
  7554. pointer.type = type;
  7555. changed = true;
  7556. }
  7557. if (pointer.normalized !== normalized) {
  7558. pointer.normalized = normalized;
  7559. changed = true;
  7560. }
  7561. if (pointer.stride !== stride) {
  7562. pointer.stride = stride;
  7563. changed = true;
  7564. }
  7565. if (pointer.offset !== offset) {
  7566. pointer.offset = offset;
  7567. changed = true;
  7568. }
  7569. }
  7570. if (changed || this._vaoRecordInProgress) {
  7571. this.bindArrayBuffer(buffer);
  7572. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  7573. }
  7574. };
  7575. Engine.prototype._bindIndexBufferWithCache = function (indexBuffer) {
  7576. if (indexBuffer == null) {
  7577. return;
  7578. }
  7579. if (this._cachedIndexBuffer !== indexBuffer) {
  7580. this._cachedIndexBuffer = indexBuffer;
  7581. this.bindIndexBuffer(indexBuffer);
  7582. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  7583. }
  7584. };
  7585. Engine.prototype._bindVertexBuffersAttributes = function (vertexBuffers, effect) {
  7586. var attributes = effect.getAttributesNames();
  7587. if (!this._vaoRecordInProgress) {
  7588. this._unBindVertexArrayObject();
  7589. }
  7590. this.unbindAllAttributes();
  7591. for (var index = 0; index < attributes.length; index++) {
  7592. var order = effect.getAttributeLocation(index);
  7593. if (order >= 0) {
  7594. var vertexBuffer = vertexBuffers[attributes[index]];
  7595. if (!vertexBuffer) {
  7596. continue;
  7597. }
  7598. this._gl.enableVertexAttribArray(order);
  7599. if (!this._vaoRecordInProgress) {
  7600. this._vertexAttribArraysEnabled[order] = true;
  7601. }
  7602. var buffer = vertexBuffer.getBuffer();
  7603. this.vertexAttribPointer(buffer, order, vertexBuffer.getSize(), this._gl.FLOAT, false, vertexBuffer.getStrideSize() * 4, vertexBuffer.getOffset() * 4);
  7604. if (vertexBuffer.getIsInstanced()) {
  7605. this._gl.vertexAttribDivisor(order, 1);
  7606. if (!this._vaoRecordInProgress) {
  7607. this._currentInstanceLocations.push(order);
  7608. this._currentInstanceBuffers.push(buffer);
  7609. }
  7610. }
  7611. }
  7612. }
  7613. };
  7614. Engine.prototype.recordVertexArrayObject = function (vertexBuffers, indexBuffer, effect) {
  7615. var vao = this._gl.createVertexArray();
  7616. this._vaoRecordInProgress = true;
  7617. this._gl.bindVertexArray(vao);
  7618. this._mustWipeVertexAttributes = true;
  7619. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  7620. this.bindIndexBuffer(indexBuffer);
  7621. this._vaoRecordInProgress = false;
  7622. this._gl.bindVertexArray(null);
  7623. return vao;
  7624. };
  7625. Engine.prototype.bindVertexArrayObject = function (vertexArrayObject, indexBuffer) {
  7626. if (this._cachedVertexArrayObject !== vertexArrayObject) {
  7627. this._cachedVertexArrayObject = vertexArrayObject;
  7628. this._gl.bindVertexArray(vertexArrayObject);
  7629. this._cachedVertexBuffers = null;
  7630. this._cachedIndexBuffer = null;
  7631. this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
  7632. this._mustWipeVertexAttributes = true;
  7633. }
  7634. };
  7635. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  7636. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  7637. this._cachedVertexBuffers = vertexBuffer;
  7638. this._cachedEffectForVertexBuffers = effect;
  7639. var attributesCount = effect.getAttributesCount();
  7640. this._unBindVertexArrayObject();
  7641. this.unbindAllAttributes();
  7642. var offset = 0;
  7643. for (var index = 0; index < attributesCount; index++) {
  7644. if (index < vertexDeclaration.length) {
  7645. var order = effect.getAttributeLocation(index);
  7646. if (order >= 0) {
  7647. this._gl.enableVertexAttribArray(order);
  7648. this._vertexAttribArraysEnabled[order] = true;
  7649. this.vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  7650. }
  7651. offset += vertexDeclaration[index] * 4;
  7652. }
  7653. }
  7654. }
  7655. this._bindIndexBufferWithCache(indexBuffer);
  7656. };
  7657. Engine.prototype._unBindVertexArrayObject = function () {
  7658. if (!this._cachedVertexArrayObject) {
  7659. return;
  7660. }
  7661. this._cachedVertexArrayObject = null;
  7662. this._gl.bindVertexArray(null);
  7663. };
  7664. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  7665. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  7666. this._cachedVertexBuffers = vertexBuffers;
  7667. this._cachedEffectForVertexBuffers = effect;
  7668. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  7669. }
  7670. this._bindIndexBufferWithCache(indexBuffer);
  7671. };
  7672. Engine.prototype.unbindInstanceAttributes = function () {
  7673. var boundBuffer;
  7674. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  7675. var instancesBuffer = this._currentInstanceBuffers[i];
  7676. if (boundBuffer != instancesBuffer) {
  7677. boundBuffer = instancesBuffer;
  7678. this.bindArrayBuffer(instancesBuffer);
  7679. }
  7680. var offsetLocation = this._currentInstanceLocations[i];
  7681. this._gl.vertexAttribDivisor(offsetLocation, 0);
  7682. }
  7683. this._currentInstanceBuffers.length = 0;
  7684. this._currentInstanceLocations.length = 0;
  7685. };
  7686. Engine.prototype.releaseVertexArrayObject = function (vao) {
  7687. this._gl.deleteVertexArray(vao);
  7688. };
  7689. Engine.prototype._releaseBuffer = function (buffer) {
  7690. buffer.references--;
  7691. if (buffer.references === 0) {
  7692. this._gl.deleteBuffer(buffer);
  7693. return true;
  7694. }
  7695. return false;
  7696. };
  7697. Engine.prototype.createInstancesBuffer = function (capacity) {
  7698. var buffer = this._gl.createBuffer();
  7699. buffer.capacity = capacity;
  7700. this.bindArrayBuffer(buffer);
  7701. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  7702. return buffer;
  7703. };
  7704. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  7705. this._gl.deleteBuffer(buffer);
  7706. };
  7707. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  7708. this.bindArrayBuffer(instancesBuffer);
  7709. if (data) {
  7710. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  7711. }
  7712. if (offsetLocations[0].index !== undefined) {
  7713. var stride = 0;
  7714. for (var i = 0; i < offsetLocations.length; i++) {
  7715. var ai = offsetLocations[i];
  7716. stride += ai.attributeSize * 4;
  7717. }
  7718. for (var i = 0; i < offsetLocations.length; i++) {
  7719. var ai = offsetLocations[i];
  7720. if (!this._vertexAttribArraysEnabled[ai.index]) {
  7721. this._gl.enableVertexAttribArray(ai.index);
  7722. this._vertexAttribArraysEnabled[ai.index] = true;
  7723. }
  7724. this.vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  7725. this._gl.vertexAttribDivisor(ai.index, 1);
  7726. this._currentInstanceLocations.push(ai.index);
  7727. this._currentInstanceBuffers.push(instancesBuffer);
  7728. }
  7729. }
  7730. else {
  7731. for (var index = 0; index < 4; index++) {
  7732. var offsetLocation = offsetLocations[index];
  7733. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  7734. this._gl.enableVertexAttribArray(offsetLocation);
  7735. this._vertexAttribArraysEnabled[offsetLocation] = true;
  7736. }
  7737. this.vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  7738. this._gl.vertexAttribDivisor(offsetLocation, 1);
  7739. this._currentInstanceLocations.push(offsetLocation);
  7740. this._currentInstanceBuffers.push(instancesBuffer);
  7741. }
  7742. }
  7743. };
  7744. Engine.prototype.applyStates = function () {
  7745. this._depthCullingState.apply(this._gl);
  7746. this._stencilState.apply(this._gl);
  7747. this._alphaState.apply(this._gl);
  7748. };
  7749. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  7750. // Apply states
  7751. this.applyStates();
  7752. this._drawCalls.addCount(1, false);
  7753. // Render
  7754. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  7755. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  7756. if (instancesCount) {
  7757. this._gl.drawElementsInstanced(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult, instancesCount);
  7758. return;
  7759. }
  7760. this._gl.drawElements(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult);
  7761. };
  7762. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  7763. // Apply states
  7764. this.applyStates();
  7765. this._drawCalls.addCount(1, false);
  7766. if (instancesCount) {
  7767. this._gl.drawArraysInstanced(this._gl.POINTS, verticesStart, verticesCount, instancesCount);
  7768. return;
  7769. }
  7770. this._gl.drawArrays(this._gl.POINTS, verticesStart, verticesCount);
  7771. };
  7772. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  7773. // Apply states
  7774. this.applyStates();
  7775. this._drawCalls.addCount(1, false);
  7776. if (instancesCount) {
  7777. this._gl.drawArraysInstanced(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount, instancesCount);
  7778. return;
  7779. }
  7780. this._gl.drawArrays(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount);
  7781. };
  7782. // Shaders
  7783. Engine.prototype._releaseEffect = function (effect) {
  7784. if (this._compiledEffects[effect._key]) {
  7785. delete this._compiledEffects[effect._key];
  7786. if (effect.getProgram()) {
  7787. this._gl.deleteProgram(effect.getProgram());
  7788. }
  7789. }
  7790. };
  7791. Engine.prototype.createEffect = function (baseName, attributesNames, uniformsNames, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  7792. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  7793. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  7794. var name = vertex + "+" + fragment + "@" + defines;
  7795. if (this._compiledEffects[name]) {
  7796. return this._compiledEffects[name];
  7797. }
  7798. var effect = new BABYLON.Effect(baseName, attributesNames, uniformsNames, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  7799. effect._key = name;
  7800. this._compiledEffects[name] = effect;
  7801. return effect;
  7802. };
  7803. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  7804. if (uniformsNames === void 0) { uniformsNames = []; }
  7805. if (samplers === void 0) { samplers = []; }
  7806. if (defines === void 0) { defines = ""; }
  7807. return this.createEffect({
  7808. vertex: "particles",
  7809. fragmentElement: fragmentName
  7810. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  7811. };
  7812. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context) {
  7813. context = context || this._gl;
  7814. var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n" : "";
  7815. var vertexShader = compileShader(context, vertexCode, "vertex", defines, shaderVersion);
  7816. var fragmentShader = compileShader(context, fragmentCode, "fragment", defines, shaderVersion);
  7817. var shaderProgram = context.createProgram();
  7818. context.attachShader(shaderProgram, vertexShader);
  7819. context.attachShader(shaderProgram, fragmentShader);
  7820. context.linkProgram(shaderProgram);
  7821. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  7822. if (!linked) {
  7823. var error = context.getProgramInfoLog(shaderProgram);
  7824. if (error) {
  7825. throw new Error(error);
  7826. }
  7827. }
  7828. context.deleteShader(vertexShader);
  7829. context.deleteShader(fragmentShader);
  7830. return shaderProgram;
  7831. };
  7832. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  7833. var results = [];
  7834. for (var index = 0; index < uniformsNames.length; index++) {
  7835. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  7836. }
  7837. return results;
  7838. };
  7839. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  7840. var results = [];
  7841. for (var index = 0; index < attributesNames.length; index++) {
  7842. try {
  7843. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  7844. }
  7845. catch (e) {
  7846. results.push(-1);
  7847. }
  7848. }
  7849. return results;
  7850. };
  7851. Engine.prototype.enableEffect = function (effect) {
  7852. // Use program
  7853. this.setProgram(effect.getProgram());
  7854. this._currentEffect = effect;
  7855. if (effect.onBind) {
  7856. effect.onBind(effect);
  7857. }
  7858. };
  7859. Engine.prototype.setIntArray = function (uniform, array) {
  7860. if (!uniform)
  7861. return;
  7862. this._gl.uniform1iv(uniform, array);
  7863. };
  7864. Engine.prototype.setIntArray2 = function (uniform, array) {
  7865. if (!uniform || array.length % 2 !== 0)
  7866. return;
  7867. this._gl.uniform2iv(uniform, array);
  7868. };
  7869. Engine.prototype.setIntArray3 = function (uniform, array) {
  7870. if (!uniform || array.length % 3 !== 0)
  7871. return;
  7872. this._gl.uniform3iv(uniform, array);
  7873. };
  7874. Engine.prototype.setIntArray4 = function (uniform, array) {
  7875. if (!uniform || array.length % 4 !== 0)
  7876. return;
  7877. this._gl.uniform4iv(uniform, array);
  7878. };
  7879. Engine.prototype.setFloatArray = function (uniform, array) {
  7880. if (!uniform)
  7881. return;
  7882. this._gl.uniform1fv(uniform, array);
  7883. };
  7884. Engine.prototype.setFloatArray2 = function (uniform, array) {
  7885. if (!uniform || array.length % 2 !== 0)
  7886. return;
  7887. this._gl.uniform2fv(uniform, array);
  7888. };
  7889. Engine.prototype.setFloatArray3 = function (uniform, array) {
  7890. if (!uniform || array.length % 3 !== 0)
  7891. return;
  7892. this._gl.uniform3fv(uniform, array);
  7893. };
  7894. Engine.prototype.setFloatArray4 = function (uniform, array) {
  7895. if (!uniform || array.length % 4 !== 0)
  7896. return;
  7897. this._gl.uniform4fv(uniform, array);
  7898. };
  7899. Engine.prototype.setArray = function (uniform, array) {
  7900. if (!uniform)
  7901. return;
  7902. this._gl.uniform1fv(uniform, array);
  7903. };
  7904. Engine.prototype.setArray2 = function (uniform, array) {
  7905. if (!uniform || array.length % 2 !== 0)
  7906. return;
  7907. this._gl.uniform2fv(uniform, array);
  7908. };
  7909. Engine.prototype.setArray3 = function (uniform, array) {
  7910. if (!uniform || array.length % 3 !== 0)
  7911. return;
  7912. this._gl.uniform3fv(uniform, array);
  7913. };
  7914. Engine.prototype.setArray4 = function (uniform, array) {
  7915. if (!uniform || array.length % 4 !== 0)
  7916. return;
  7917. this._gl.uniform4fv(uniform, array);
  7918. };
  7919. Engine.prototype.setMatrices = function (uniform, matrices) {
  7920. if (!uniform)
  7921. return;
  7922. this._gl.uniformMatrix4fv(uniform, false, matrices);
  7923. };
  7924. Engine.prototype.setMatrix = function (uniform, matrix) {
  7925. if (!uniform)
  7926. return;
  7927. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  7928. };
  7929. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  7930. if (!uniform)
  7931. return;
  7932. this._gl.uniformMatrix3fv(uniform, false, matrix);
  7933. };
  7934. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  7935. if (!uniform)
  7936. return;
  7937. this._gl.uniformMatrix2fv(uniform, false, matrix);
  7938. };
  7939. Engine.prototype.setFloat = function (uniform, value) {
  7940. if (!uniform)
  7941. return;
  7942. this._gl.uniform1f(uniform, value);
  7943. };
  7944. Engine.prototype.setFloat2 = function (uniform, x, y) {
  7945. if (!uniform)
  7946. return;
  7947. this._gl.uniform2f(uniform, x, y);
  7948. };
  7949. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  7950. if (!uniform)
  7951. return;
  7952. this._gl.uniform3f(uniform, x, y, z);
  7953. };
  7954. Engine.prototype.setBool = function (uniform, bool) {
  7955. if (!uniform)
  7956. return;
  7957. this._gl.uniform1i(uniform, bool);
  7958. };
  7959. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  7960. if (!uniform)
  7961. return;
  7962. this._gl.uniform4f(uniform, x, y, z, w);
  7963. };
  7964. Engine.prototype.setColor3 = function (uniform, color3) {
  7965. if (!uniform)
  7966. return;
  7967. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  7968. };
  7969. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  7970. if (!uniform)
  7971. return;
  7972. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  7973. };
  7974. // States
  7975. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  7976. if (zOffset === void 0) { zOffset = 0; }
  7977. if (reverseSide === void 0) { reverseSide = false; }
  7978. // Culling
  7979. var showSide = reverseSide ? this._gl.FRONT : this._gl.BACK;
  7980. var hideSide = reverseSide ? this._gl.BACK : this._gl.FRONT;
  7981. var cullFace = this.cullBackFaces ? showSide : hideSide;
  7982. if (this._depthCullingState.cull !== culling || force || this._depthCullingState.cullFace !== cullFace) {
  7983. if (culling) {
  7984. this._depthCullingState.cullFace = cullFace;
  7985. this._depthCullingState.cull = true;
  7986. }
  7987. else {
  7988. this._depthCullingState.cull = false;
  7989. }
  7990. }
  7991. // Z offset
  7992. this._depthCullingState.zOffset = zOffset;
  7993. };
  7994. Engine.prototype.setDepthBuffer = function (enable) {
  7995. this._depthCullingState.depthTest = enable;
  7996. };
  7997. Engine.prototype.getDepthWrite = function () {
  7998. return this._depthCullingState.depthMask;
  7999. };
  8000. Engine.prototype.setDepthWrite = function (enable) {
  8001. this._depthCullingState.depthMask = enable;
  8002. };
  8003. Engine.prototype.setColorWrite = function (enable) {
  8004. this._gl.colorMask(enable, enable, enable, enable);
  8005. };
  8006. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  8007. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  8008. if (this._alphaMode === mode) {
  8009. return;
  8010. }
  8011. switch (mode) {
  8012. case Engine.ALPHA_DISABLE:
  8013. this._alphaState.alphaBlend = false;
  8014. break;
  8015. case Engine.ALPHA_PREMULTIPLIED:
  8016. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  8017. this._alphaState.alphaBlend = true;
  8018. break;
  8019. case Engine.ALPHA_COMBINE:
  8020. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  8021. this._alphaState.alphaBlend = true;
  8022. break;
  8023. case Engine.ALPHA_ONEONE:
  8024. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  8025. this._alphaState.alphaBlend = true;
  8026. break;
  8027. case Engine.ALPHA_ADD:
  8028. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  8029. this._alphaState.alphaBlend = true;
  8030. break;
  8031. case Engine.ALPHA_SUBTRACT:
  8032. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  8033. this._alphaState.alphaBlend = true;
  8034. break;
  8035. case Engine.ALPHA_MULTIPLY:
  8036. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  8037. this._alphaState.alphaBlend = true;
  8038. break;
  8039. case Engine.ALPHA_MAXIMIZED:
  8040. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  8041. this._alphaState.alphaBlend = true;
  8042. break;
  8043. }
  8044. if (!noDepthWriteChange) {
  8045. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  8046. }
  8047. this._alphaMode = mode;
  8048. };
  8049. Engine.prototype.getAlphaMode = function () {
  8050. return this._alphaMode;
  8051. };
  8052. Engine.prototype.setAlphaTesting = function (enable) {
  8053. this._alphaTest = enable;
  8054. };
  8055. Engine.prototype.getAlphaTesting = function () {
  8056. return this._alphaTest;
  8057. };
  8058. // Textures
  8059. Engine.prototype.wipeCaches = function () {
  8060. this.resetTextureCache();
  8061. this._currentEffect = null;
  8062. this._stencilState.reset();
  8063. this._depthCullingState.reset();
  8064. this.setDepthFunctionToLessOrEqual();
  8065. this._alphaState.reset();
  8066. this._cachedVertexBuffers = null;
  8067. this._cachedIndexBuffer = null;
  8068. this._cachedEffectForVertexBuffers = null;
  8069. this._unBindVertexArrayObject();
  8070. this.bindIndexBuffer(null);
  8071. this.bindArrayBuffer(null);
  8072. };
  8073. /**
  8074. * Set the compressed texture format to use, based on the formats you have, and the formats
  8075. * supported by the hardware / browser.
  8076. *
  8077. * Khronos Texture Container (.ktx) files are used to support this. This format has the
  8078. * advantage of being specifically designed for OpenGL. Header elements directly correspond
  8079. * to API arguments needed to compressed textures. This puts the burden on the container
  8080. * generator to house the arcane code for determining these for current & future formats.
  8081. *
  8082. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  8083. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  8084. *
  8085. * Note: The result of this call is not taken into account when a texture is base64.
  8086. *
  8087. * @param {Array<string>} formatsAvailable- The list of those format families you have created
  8088. * on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.)
  8089. *
  8090. * Current families are astc, dxt, pvrtc, etc2, atc, & etc1.
  8091. * @returns The extension selected.
  8092. */
  8093. Engine.prototype.setTextureFormatToUse = function (formatsAvailable) {
  8094. for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
  8095. for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
  8096. if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
  8097. return this._textureFormatInUse = this._texturesSupported[i];
  8098. }
  8099. }
  8100. }
  8101. // actively set format to nothing, to allow this to be called more than once
  8102. // and possibly fail the 2nd time
  8103. return this._textureFormatInUse = null;
  8104. };
  8105. Engine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack) {
  8106. var _this = this;
  8107. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  8108. if (onLoad === void 0) { onLoad = null; }
  8109. if (onError === void 0) { onError = null; }
  8110. if (buffer === void 0) { buffer = null; }
  8111. var texture = fallBack ? fallBack : this._gl.createTexture();
  8112. var extension;
  8113. var isKTX = false;
  8114. var fromData = false;
  8115. var url = String(urlArg);
  8116. if (url.substr(0, 5) === "data:") {
  8117. fromData = true;
  8118. }
  8119. if (!fromData) {
  8120. var lastDot = url.lastIndexOf('.');
  8121. extension = url.substring(lastDot).toLowerCase();
  8122. if (this._textureFormatInUse && !fromData && !fallBack) {
  8123. extension = this._textureFormatInUse;
  8124. url = url.substring(0, lastDot) + this._textureFormatInUse;
  8125. isKTX = true;
  8126. }
  8127. }
  8128. else {
  8129. var oldUrl = url;
  8130. fromData = oldUrl.split(':');
  8131. url = oldUrl;
  8132. extension = fromData[1].substr(fromData[1].length - 4, 4).toLowerCase();
  8133. }
  8134. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  8135. var isTGA = (extension === ".tga");
  8136. scene._addPendingData(texture);
  8137. texture.url = url;
  8138. texture.noMipmap = noMipmap;
  8139. texture.references = 1;
  8140. texture.samplingMode = samplingMode;
  8141. texture.onLoadedCallbacks = [];
  8142. if (onLoad) {
  8143. texture.onLoadedCallbacks.push(onLoad);
  8144. }
  8145. if (!fallBack)
  8146. this._loadedTexturesCache.push(texture);
  8147. var onerror = function () {
  8148. scene._removePendingData(texture);
  8149. // fallback for when compressed file not found to try again. For instance, etc1 does not have an alpha capable type
  8150. if (isKTX) {
  8151. _this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, texture);
  8152. }
  8153. else if (onError) {
  8154. onError();
  8155. }
  8156. };
  8157. var callback;
  8158. if (isKTX || isTGA || isDDS) {
  8159. if (isKTX) {
  8160. callback = function (data) {
  8161. var ktx = new BABYLON.Internals.KhronosTextureContainer(data, 1);
  8162. prepareWebGLTexture(texture, _this._gl, scene, ktx.pixelWidth, ktx.pixelHeight, invertY, false, true, function () {
  8163. ktx.uploadLevels(_this._gl, !noMipmap);
  8164. }, samplingMode);
  8165. };
  8166. }
  8167. else if (isTGA) {
  8168. callback = function (arrayBuffer) {
  8169. var data = new Uint8Array(arrayBuffer);
  8170. var header = BABYLON.Internals.TGATools.GetTGAHeader(data);
  8171. prepareWebGLTexture(texture, _this._gl, scene, header.width, header.height, invertY, noMipmap, false, function () {
  8172. BABYLON.Internals.TGATools.UploadContent(_this._gl, data);
  8173. }, samplingMode);
  8174. };
  8175. }
  8176. else if (isDDS) {
  8177. callback = function (data) {
  8178. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  8179. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  8180. prepareWebGLTexture(texture, _this._gl, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  8181. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 1);
  8182. }, samplingMode);
  8183. };
  8184. }
  8185. if (!(fromData instanceof Array))
  8186. BABYLON.Tools.LoadFile(url, function (data) {
  8187. callback(data);
  8188. }, null, scene.database, true, onerror);
  8189. else
  8190. callback(buffer);
  8191. }
  8192. else {
  8193. var onload = function (img) {
  8194. prepareWebGLTexture(texture, _this._gl, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight) {
  8195. var isPot = (img.width === potWidth && img.height === potHeight);
  8196. if (!isPot) {
  8197. _this._prepareWorkingCanvas();
  8198. _this._workingCanvas.width = potWidth;
  8199. _this._workingCanvas.height = potHeight;
  8200. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  8201. _this._workingContext.imageSmoothingEnabled = false;
  8202. _this._workingContext.mozImageSmoothingEnabled = false;
  8203. _this._workingContext.oImageSmoothingEnabled = false;
  8204. _this._workingContext.webkitImageSmoothingEnabled = false;
  8205. _this._workingContext.msImageSmoothingEnabled = false;
  8206. }
  8207. _this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  8208. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  8209. _this._workingContext.imageSmoothingEnabled = true;
  8210. _this._workingContext.mozImageSmoothingEnabled = true;
  8211. _this._workingContext.oImageSmoothingEnabled = true;
  8212. _this._workingContext.webkitImageSmoothingEnabled = true;
  8213. _this._workingContext.msImageSmoothingEnabled = true;
  8214. }
  8215. }
  8216. _this._gl.texImage2D(_this._gl.TEXTURE_2D, 0, _this._gl.RGBA, _this._gl.RGBA, _this._gl.UNSIGNED_BYTE, isPot ? img : _this._workingCanvas);
  8217. }, samplingMode);
  8218. };
  8219. if (!(fromData instanceof Array))
  8220. BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  8221. else
  8222. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene.database);
  8223. }
  8224. return texture;
  8225. };
  8226. Engine.prototype._getInternalFormat = function (format) {
  8227. var internalFormat = this._gl.RGBA;
  8228. switch (format) {
  8229. case Engine.TEXTUREFORMAT_ALPHA:
  8230. internalFormat = this._gl.ALPHA;
  8231. break;
  8232. case Engine.TEXTUREFORMAT_LUMINANCE:
  8233. internalFormat = this._gl.LUMINANCE;
  8234. break;
  8235. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  8236. internalFormat = this._gl.LUMINANCE_ALPHA;
  8237. break;
  8238. case Engine.TEXTUREFORMAT_RGB:
  8239. internalFormat = this._gl.RGB;
  8240. break;
  8241. case Engine.TEXTUREFORMAT_RGBA:
  8242. internalFormat = this._gl.RGBA;
  8243. break;
  8244. }
  8245. return internalFormat;
  8246. };
  8247. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression) {
  8248. if (compression === void 0) { compression = null; }
  8249. var internalFormat = this._getInternalFormat(format);
  8250. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  8251. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  8252. if (texture._width % 4 !== 0) {
  8253. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  8254. }
  8255. if (compression) {
  8256. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture._width, texture._height, 0, data);
  8257. }
  8258. else {
  8259. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, texture._width, texture._height, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  8260. }
  8261. if (texture.generateMipMaps) {
  8262. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  8263. }
  8264. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  8265. this.resetTextureCache();
  8266. texture.isReady = true;
  8267. };
  8268. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression) {
  8269. if (compression === void 0) { compression = null; }
  8270. var texture = this._gl.createTexture();
  8271. texture._baseWidth = width;
  8272. texture._baseHeight = height;
  8273. texture._width = width;
  8274. texture._height = height;
  8275. texture.references = 1;
  8276. this.updateRawTexture(texture, data, format, invertY, compression);
  8277. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  8278. // Filters
  8279. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  8280. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  8281. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  8282. if (generateMipMaps) {
  8283. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  8284. }
  8285. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  8286. texture.samplingMode = samplingMode;
  8287. this._loadedTexturesCache.push(texture);
  8288. return texture;
  8289. };
  8290. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  8291. var texture = this._gl.createTexture();
  8292. texture._baseWidth = width;
  8293. texture._baseHeight = height;
  8294. if (generateMipMaps) {
  8295. width = BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize);
  8296. height = BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize);
  8297. }
  8298. this.resetTextureCache();
  8299. texture._width = width;
  8300. texture._height = height;
  8301. texture.isReady = false;
  8302. texture.generateMipMaps = generateMipMaps;
  8303. texture.references = 1;
  8304. texture.samplingMode = samplingMode;
  8305. this.updateTextureSamplingMode(samplingMode, texture);
  8306. this._loadedTexturesCache.push(texture);
  8307. return texture;
  8308. };
  8309. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  8310. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  8311. if (texture.isCube) {
  8312. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture);
  8313. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  8314. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  8315. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  8316. }
  8317. else {
  8318. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  8319. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  8320. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  8321. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  8322. }
  8323. texture.samplingMode = samplingMode;
  8324. };
  8325. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha) {
  8326. if (premulAlpha === void 0) { premulAlpha = false; }
  8327. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  8328. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  8329. if (premulAlpha) {
  8330. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  8331. }
  8332. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, canvas);
  8333. if (texture.generateMipMaps) {
  8334. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  8335. }
  8336. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  8337. if (premulAlpha) {
  8338. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  8339. }
  8340. this.resetTextureCache();
  8341. texture.isReady = true;
  8342. };
  8343. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  8344. if (texture._isDisabled) {
  8345. return;
  8346. }
  8347. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  8348. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  8349. try {
  8350. // Testing video texture support
  8351. if (this._videoTextureSupported === undefined) {
  8352. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  8353. if (this._gl.getError() !== 0) {
  8354. this._videoTextureSupported = false;
  8355. }
  8356. else {
  8357. this._videoTextureSupported = true;
  8358. }
  8359. }
  8360. // Copy video through the current working canvas if video texture is not supported
  8361. if (!this._videoTextureSupported) {
  8362. if (!texture._workingCanvas) {
  8363. texture._workingCanvas = document.createElement("canvas");
  8364. texture._workingContext = texture._workingCanvas.getContext("2d");
  8365. texture._workingCanvas.width = texture._width;
  8366. texture._workingCanvas.height = texture._height;
  8367. }
  8368. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture._width, texture._height);
  8369. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  8370. }
  8371. else {
  8372. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  8373. }
  8374. if (texture.generateMipMaps) {
  8375. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  8376. }
  8377. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  8378. this.resetTextureCache();
  8379. texture.isReady = true;
  8380. }
  8381. catch (ex) {
  8382. // Something unexpected
  8383. // Let's disable the texture
  8384. texture._isDisabled = true;
  8385. }
  8386. };
  8387. Engine.prototype.createRenderTargetTexture = function (size, options) {
  8388. // old version had a "generateMipMaps" arg instead of options.
  8389. // if options.generateMipMaps is undefined, consider that options itself if the generateMipmaps value
  8390. // in the same way, generateDepthBuffer is defaulted to true
  8391. var generateMipMaps = false;
  8392. var generateDepthBuffer = true;
  8393. var generateStencilBuffer = false;
  8394. var type = Engine.TEXTURETYPE_UNSIGNED_INT;
  8395. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  8396. if (options !== undefined) {
  8397. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipMaps;
  8398. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  8399. generateStencilBuffer = generateDepthBuffer && options.generateStencilBuffer;
  8400. type = options.type === undefined ? type : options.type;
  8401. if (options.samplingMode !== undefined) {
  8402. samplingMode = options.samplingMode;
  8403. }
  8404. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  8405. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  8406. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  8407. }
  8408. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  8409. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  8410. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  8411. }
  8412. }
  8413. var gl = this._gl;
  8414. var texture = gl.createTexture();
  8415. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  8416. var width = size.width || size;
  8417. var height = size.height || size;
  8418. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  8419. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  8420. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  8421. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  8422. }
  8423. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  8424. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  8425. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  8426. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  8427. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  8428. var depthStencilBuffer;
  8429. // Create the depth/stencil buffer
  8430. if (generateStencilBuffer) {
  8431. depthStencilBuffer = gl.createRenderbuffer();
  8432. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  8433. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  8434. }
  8435. else if (generateDepthBuffer) {
  8436. depthStencilBuffer = gl.createRenderbuffer();
  8437. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  8438. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  8439. }
  8440. // Create the framebuffer
  8441. var framebuffer = gl.createFramebuffer();
  8442. this.bindUnboundFramebuffer(framebuffer);
  8443. // Manage attachments
  8444. if (generateStencilBuffer) {
  8445. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  8446. }
  8447. else if (generateDepthBuffer) {
  8448. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  8449. }
  8450. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  8451. if (generateMipMaps) {
  8452. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  8453. }
  8454. // Unbind
  8455. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  8456. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  8457. this.bindUnboundFramebuffer(null);
  8458. texture._framebuffer = framebuffer;
  8459. if (generateDepthBuffer) {
  8460. texture._depthBuffer = depthStencilBuffer;
  8461. }
  8462. texture._baseWidth = width;
  8463. texture._baseHeight = height;
  8464. texture._width = width;
  8465. texture._height = height;
  8466. texture.isReady = true;
  8467. texture.generateMipMaps = generateMipMaps;
  8468. texture.references = 1;
  8469. texture.samplingMode = samplingMode;
  8470. texture.type = type;
  8471. this.resetTextureCache();
  8472. this._loadedTexturesCache.push(texture);
  8473. return texture;
  8474. };
  8475. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  8476. var gl = this._gl;
  8477. var texture = gl.createTexture();
  8478. var generateMipMaps = true;
  8479. var generateDepthBuffer = true;
  8480. var generateStencilBuffer = false;
  8481. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  8482. if (options !== undefined) {
  8483. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipMaps;
  8484. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  8485. generateStencilBuffer = generateDepthBuffer && options.generateStencilBuffer;
  8486. if (options.samplingMode !== undefined) {
  8487. samplingMode = options.samplingMode;
  8488. }
  8489. }
  8490. texture.isCube = true;
  8491. texture.references = 1;
  8492. texture.generateMipMaps = generateMipMaps;
  8493. texture.references = 1;
  8494. texture.samplingMode = samplingMode;
  8495. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  8496. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  8497. for (var face = 0; face < 6; face++) {
  8498. gl.texImage2D((gl.TEXTURE_CUBE_MAP_POSITIVE_X + face), 0, gl.RGBA, size, size, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
  8499. }
  8500. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  8501. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  8502. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  8503. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  8504. // Create the depth buffer
  8505. var depthStencilBuffer;
  8506. // Create the depth/stencil buffer
  8507. if (generateStencilBuffer) {
  8508. depthStencilBuffer = gl.createRenderbuffer();
  8509. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  8510. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, size, size);
  8511. }
  8512. else if (generateDepthBuffer) {
  8513. depthStencilBuffer = gl.createRenderbuffer();
  8514. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  8515. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, size, size);
  8516. }
  8517. // Create the framebuffer
  8518. var framebuffer = gl.createFramebuffer();
  8519. this.bindUnboundFramebuffer(framebuffer);
  8520. // Manage attachments
  8521. if (generateStencilBuffer) {
  8522. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  8523. }
  8524. else if (generateDepthBuffer) {
  8525. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  8526. }
  8527. // Mipmaps
  8528. if (texture.generateMipMaps) {
  8529. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  8530. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  8531. }
  8532. // Unbind
  8533. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  8534. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  8535. this.bindUnboundFramebuffer(null);
  8536. texture._framebuffer = framebuffer;
  8537. if (generateDepthBuffer) {
  8538. texture._depthBuffer = depthStencilBuffer;
  8539. }
  8540. texture._width = size;
  8541. texture._height = size;
  8542. texture.isReady = true;
  8543. this.resetTextureCache();
  8544. this._loadedTexturesCache.push(texture);
  8545. return texture;
  8546. };
  8547. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError) {
  8548. var _this = this;
  8549. if (onLoad === void 0) { onLoad = null; }
  8550. if (onError === void 0) { onError = null; }
  8551. var gl = this._gl;
  8552. var texture = gl.createTexture();
  8553. texture.isCube = true;
  8554. texture.url = rootUrl;
  8555. texture.references = 1;
  8556. texture.onLoadedCallbacks = [];
  8557. var isKTX = false;
  8558. var lastDot = rootUrl.lastIndexOf('.');
  8559. var extension = rootUrl.substring(lastDot).toLowerCase();
  8560. if (this._textureFormatInUse) {
  8561. extension = this._textureFormatInUse;
  8562. rootUrl = rootUrl.substring(0, lastDot) + this._textureFormatInUse;
  8563. isKTX = true;
  8564. }
  8565. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  8566. if (isKTX) {
  8567. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  8568. var ktx = new BABYLON.Internals.KhronosTextureContainer(data, 6);
  8569. var loadMipmap = ktx.numberOfMipmapLevels > 1 && !noMipmap;
  8570. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  8571. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  8572. ktx.uploadLevels(_this._gl, !noMipmap);
  8573. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  8574. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  8575. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  8576. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  8577. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  8578. _this.resetTextureCache();
  8579. texture._width = ktx.pixelWidth;
  8580. texture._height = ktx.pixelHeight;
  8581. texture.isReady = true;
  8582. }, null, null, true, onError);
  8583. }
  8584. else if (isDDS) {
  8585. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  8586. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  8587. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  8588. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  8589. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  8590. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 6);
  8591. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  8592. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  8593. }
  8594. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  8595. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  8596. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  8597. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  8598. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  8599. _this.resetTextureCache();
  8600. texture._width = info.width;
  8601. texture._height = info.height;
  8602. texture.isReady = true;
  8603. }, null, null, true, onError);
  8604. }
  8605. else {
  8606. cascadeLoad(rootUrl, scene, function (imgs) {
  8607. var width = BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize);
  8608. var height = width;
  8609. _this._prepareWorkingCanvas();
  8610. _this._workingCanvas.width = width;
  8611. _this._workingCanvas.height = height;
  8612. var faces = [
  8613. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  8614. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  8615. ];
  8616. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  8617. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  8618. for (var index = 0; index < faces.length; index++) {
  8619. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  8620. gl.texImage2D(faces[index], 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, _this._workingCanvas);
  8621. }
  8622. if (!noMipmap) {
  8623. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  8624. }
  8625. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  8626. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  8627. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  8628. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  8629. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  8630. _this.resetTextureCache();
  8631. texture._width = width;
  8632. texture._height = height;
  8633. texture.isReady = true;
  8634. texture.onLoadedCallbacks.forEach(function (callback) {
  8635. callback();
  8636. });
  8637. if (onLoad) {
  8638. onLoad();
  8639. }
  8640. }, files, onError);
  8641. }
  8642. this._loadedTexturesCache.push(texture);
  8643. return texture;
  8644. };
  8645. Engine.prototype.updateTextureSize = function (texture, width, height) {
  8646. texture._width = width;
  8647. texture._height = height;
  8648. texture._size = width * height;
  8649. texture._baseWidth = width;
  8650. texture._baseHeight = height;
  8651. };
  8652. Engine.prototype.createRawCubeTexture = function (url, scene, size, format, type, noMipmap, callback, mipmmapGenerator) {
  8653. var _this = this;
  8654. var gl = this._gl;
  8655. var texture = gl.createTexture();
  8656. scene._addPendingData(texture);
  8657. texture.isCube = true;
  8658. texture.references = 1;
  8659. texture.url = url;
  8660. var textureType = gl.UNSIGNED_BYTE;
  8661. if (type === Engine.TEXTURETYPE_FLOAT) {
  8662. textureType = gl.FLOAT;
  8663. }
  8664. var internalFormat = this._getInternalFormat(format);
  8665. var needConversion = false;
  8666. if (internalFormat === gl.RGB) {
  8667. internalFormat = gl.RGBA;
  8668. needConversion = true;
  8669. }
  8670. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  8671. var width = size;
  8672. var height = width;
  8673. var isPot = (BABYLON.Tools.IsExponentOfTwo(width) && BABYLON.Tools.IsExponentOfTwo(height));
  8674. texture._width = width;
  8675. texture._height = height;
  8676. var onerror = function () {
  8677. scene._removePendingData(texture);
  8678. };
  8679. var internalCallback = function (data) {
  8680. var rgbeDataArrays = callback(data);
  8681. var facesIndex = [
  8682. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  8683. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  8684. ];
  8685. width = texture._width;
  8686. height = texture._height;
  8687. isPot = (BABYLON.Tools.IsExponentOfTwo(width) && BABYLON.Tools.IsExponentOfTwo(height));
  8688. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  8689. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  8690. if (mipmmapGenerator) {
  8691. var arrayTemp = [];
  8692. // Data are known to be in +X +Y +Z -X -Y -Z
  8693. // mipmmapGenerator data is expected to be order in +X -X +Y -Y +Z -Z
  8694. arrayTemp.push(rgbeDataArrays[0]); // +X
  8695. arrayTemp.push(rgbeDataArrays[3]); // -X
  8696. arrayTemp.push(rgbeDataArrays[1]); // +Y
  8697. arrayTemp.push(rgbeDataArrays[4]); // -Y
  8698. arrayTemp.push(rgbeDataArrays[2]); // +Z
  8699. arrayTemp.push(rgbeDataArrays[5]); // -Z
  8700. var mipData = mipmmapGenerator(arrayTemp);
  8701. // mipData is order in +X -X +Y -Y +Z -Z
  8702. var mipFaces = [0, 2, 4, 1, 3, 5];
  8703. for (var level = 0; level < mipData.length; level++) {
  8704. var mipSize = width >> level;
  8705. for (var mipIndex in mipFaces) {
  8706. var mipFaceData = mipData[level][mipFaces[mipIndex]];
  8707. if (needConversion) {
  8708. mipFaceData = _this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
  8709. }
  8710. gl.texImage2D(facesIndex[mipIndex], level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);
  8711. }
  8712. }
  8713. }
  8714. else {
  8715. // Data are known to be in +X +Y +Z -X -Y -Z
  8716. for (var index = 0; index < facesIndex.length; index++) {
  8717. var faceData = rgbeDataArrays[index];
  8718. if (needConversion) {
  8719. faceData = _this._convertRGBtoRGBATextureData(faceData, width, height, type);
  8720. }
  8721. gl.texImage2D(facesIndex[index], 0, internalSizedFomat, width, height, 0, internalFormat, textureType, faceData);
  8722. }
  8723. if (!noMipmap && isPot) {
  8724. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  8725. }
  8726. else {
  8727. noMipmap = true;
  8728. }
  8729. }
  8730. if (textureType === gl.FLOAT && !_this._caps.textureFloatLinearFiltering) {
  8731. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  8732. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  8733. }
  8734. else if (textureType === Engine.HALF_FLOAT_OES && !_this._caps.textureHalfFloatLinearFiltering) {
  8735. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  8736. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  8737. }
  8738. else {
  8739. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  8740. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  8741. }
  8742. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  8743. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  8744. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  8745. texture.isReady = true;
  8746. _this.resetTextureCache();
  8747. scene._removePendingData(texture);
  8748. };
  8749. BABYLON.Tools.LoadFile(url, function (data) {
  8750. internalCallback(data);
  8751. }, onerror, scene.database, true);
  8752. return texture;
  8753. };
  8754. ;
  8755. Engine.prototype._convertRGBtoRGBATextureData = function (rgbData, width, height, textureType) {
  8756. // Create new RGBA data container.
  8757. var rgbaData;
  8758. if (textureType === Engine.TEXTURETYPE_FLOAT) {
  8759. rgbaData = new Float32Array(width * height * 4);
  8760. }
  8761. else {
  8762. rgbaData = new Uint32Array(width * height * 4);
  8763. }
  8764. // Convert each pixel.
  8765. for (var x = 0; x < width; x++) {
  8766. for (var y = 0; y < height; y++) {
  8767. var index = (y * width + x) * 3;
  8768. var newIndex = (y * width + x) * 4;
  8769. // Map Old Value to new value.
  8770. rgbaData[newIndex + 0] = rgbData[index + 0];
  8771. rgbaData[newIndex + 1] = rgbData[index + 1];
  8772. rgbaData[newIndex + 2] = rgbData[index + 2];
  8773. // Add fully opaque alpha channel.
  8774. rgbaData[newIndex + 3] = 1;
  8775. }
  8776. }
  8777. return rgbaData;
  8778. };
  8779. Engine.prototype._releaseTexture = function (texture) {
  8780. var gl = this._gl;
  8781. if (texture._framebuffer) {
  8782. gl.deleteFramebuffer(texture._framebuffer);
  8783. }
  8784. if (texture._depthBuffer) {
  8785. gl.deleteRenderbuffer(texture._depthBuffer);
  8786. }
  8787. gl.deleteTexture(texture);
  8788. // Unbind channels
  8789. this.unbindAllTextures();
  8790. var index = this._loadedTexturesCache.indexOf(texture);
  8791. if (index !== -1) {
  8792. this._loadedTexturesCache.splice(index, 1);
  8793. }
  8794. };
  8795. Engine.prototype.setProgram = function (program) {
  8796. if (this._currentProgram !== program) {
  8797. this._gl.useProgram(program);
  8798. this._currentProgram = program;
  8799. }
  8800. };
  8801. Engine.prototype.bindSamplers = function (effect) {
  8802. this.setProgram(effect.getProgram());
  8803. var samplers = effect.getSamplers();
  8804. for (var index = 0; index < samplers.length; index++) {
  8805. var uniform = effect.getUniform(samplers[index]);
  8806. this._gl.uniform1i(uniform, index);
  8807. }
  8808. this._currentEffect = null;
  8809. };
  8810. Engine.prototype.activateTexture = function (texture) {
  8811. if (this._activeTexture !== texture) {
  8812. this._gl.activeTexture(texture);
  8813. this._activeTexture = texture;
  8814. }
  8815. };
  8816. Engine.prototype._bindTextureDirectly = function (target, texture) {
  8817. if (this._activeTexturesCache[this._activeTexture] !== texture) {
  8818. this._gl.bindTexture(target, texture);
  8819. this._activeTexturesCache[this._activeTexture] = texture;
  8820. }
  8821. };
  8822. Engine.prototype._bindTexture = function (channel, texture) {
  8823. if (channel < 0) {
  8824. return;
  8825. }
  8826. this.activateTexture(this._gl.TEXTURE0 + channel);
  8827. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  8828. };
  8829. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  8830. this._bindTexture(channel, postProcess._textures.data[postProcess._currentRenderTextureInd]);
  8831. };
  8832. Engine.prototype.unbindAllTextures = function () {
  8833. for (var channel = 0; channel < this._caps.maxTexturesImageUnits; channel++) {
  8834. this.activateTexture(this._gl["TEXTURE" + channel]);
  8835. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  8836. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  8837. }
  8838. };
  8839. Engine.prototype.setTexture = function (channel, uniform, texture) {
  8840. if (channel < 0) {
  8841. return;
  8842. }
  8843. this._gl.uniform1i(uniform, channel);
  8844. this._setTexture(channel, texture);
  8845. };
  8846. Engine.prototype._setTexture = function (channel, texture) {
  8847. // Not ready?
  8848. if (!texture || !texture.isReady()) {
  8849. if (this._activeTexturesCache[channel] != null) {
  8850. this.activateTexture(this._gl["TEXTURE" + channel]);
  8851. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  8852. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  8853. }
  8854. return;
  8855. }
  8856. // Video
  8857. var alreadyActivated = false;
  8858. if (texture instanceof BABYLON.VideoTexture) {
  8859. this.activateTexture(this._gl["TEXTURE" + channel]);
  8860. alreadyActivated = true;
  8861. texture.update();
  8862. }
  8863. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  8864. texture.delayLoad();
  8865. return;
  8866. }
  8867. var internalTexture = texture.getInternalTexture();
  8868. if (this._activeTexturesCache[channel] === internalTexture) {
  8869. return;
  8870. }
  8871. if (!alreadyActivated) {
  8872. this.activateTexture(this._gl["TEXTURE" + channel]);
  8873. }
  8874. if (internalTexture.isCube) {
  8875. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture);
  8876. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  8877. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  8878. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  8879. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  8880. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  8881. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  8882. }
  8883. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  8884. }
  8885. else {
  8886. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture);
  8887. if (internalTexture._cachedWrapU !== texture.wrapU) {
  8888. internalTexture._cachedWrapU = texture.wrapU;
  8889. switch (texture.wrapU) {
  8890. case BABYLON.Texture.WRAP_ADDRESSMODE:
  8891. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  8892. break;
  8893. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  8894. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  8895. break;
  8896. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  8897. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  8898. break;
  8899. }
  8900. }
  8901. if (internalTexture._cachedWrapV !== texture.wrapV) {
  8902. internalTexture._cachedWrapV = texture.wrapV;
  8903. switch (texture.wrapV) {
  8904. case BABYLON.Texture.WRAP_ADDRESSMODE:
  8905. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  8906. break;
  8907. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  8908. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  8909. break;
  8910. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  8911. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  8912. break;
  8913. }
  8914. }
  8915. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  8916. }
  8917. };
  8918. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  8919. if (channel < 0) {
  8920. return;
  8921. }
  8922. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  8923. this._textureUnits = new Int32Array(textures.length);
  8924. }
  8925. for (var i = 0; i < textures.length; i++) {
  8926. this._textureUnits[i] = channel + i;
  8927. }
  8928. this._gl.uniform1iv(uniform, this._textureUnits);
  8929. for (var index = 0; index < textures.length; index++) {
  8930. this._setTexture(channel + index, textures[index]);
  8931. }
  8932. };
  8933. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  8934. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  8935. var value = texture.anisotropicFilteringLevel;
  8936. if (texture.getInternalTexture().samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  8937. value = 1;
  8938. }
  8939. if (anisotropicFilterExtension && texture._cachedAnisotropicFilteringLevel !== value) {
  8940. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
  8941. texture._cachedAnisotropicFilteringLevel = value;
  8942. }
  8943. };
  8944. Engine.prototype.readPixels = function (x, y, width, height) {
  8945. var data = new Uint8Array(height * width * 4);
  8946. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  8947. return data;
  8948. };
  8949. /**
  8950. * Add an externaly attached data from its key.
  8951. * This method call will fail and return false, if such key already exists.
  8952. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  8953. * @param key the unique key that identifies the data
  8954. * @param data the data object to associate to the key for this Engine instance
  8955. * @return true if no such key were already present and the data was added successfully, false otherwise
  8956. */
  8957. Engine.prototype.addExternalData = function (key, data) {
  8958. return this._externalData.add(key, data);
  8959. };
  8960. /**
  8961. * Get an externaly attached data from its key
  8962. * @param key the unique key that identifies the data
  8963. * @return the associated data, if present (can be null), or undefined if not present
  8964. */
  8965. Engine.prototype.getExternalData = function (key) {
  8966. return this._externalData.get(key);
  8967. };
  8968. /**
  8969. * Get an externaly attached data from its key, create it using a factory if it's not already present
  8970. * @param key the unique key that identifies the data
  8971. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  8972. * @return the associated data, can be null if the factory returned null.
  8973. */
  8974. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  8975. return this._externalData.getOrAddWithFactory(key, factory);
  8976. };
  8977. /**
  8978. * Remove an externaly attached data from the Engine instance
  8979. * @param key the unique key that identifies the data
  8980. * @return true if the data was successfully removed, false if it doesn't exist
  8981. */
  8982. Engine.prototype.removeExternalData = function (key) {
  8983. return this._externalData.remove(key);
  8984. };
  8985. Engine.prototype.releaseInternalTexture = function (texture) {
  8986. if (!texture) {
  8987. return;
  8988. }
  8989. texture.references--;
  8990. // Final reference ?
  8991. if (texture.references === 0) {
  8992. var texturesCache = this.getLoadedTexturesCache();
  8993. var index = texturesCache.indexOf(texture);
  8994. if (index > -1) {
  8995. texturesCache.splice(index, 1);
  8996. }
  8997. this._releaseTexture(texture);
  8998. }
  8999. };
  9000. Engine.prototype.unbindAllAttributes = function () {
  9001. if (this._mustWipeVertexAttributes) {
  9002. this._mustWipeVertexAttributes = false;
  9003. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  9004. this._gl.disableVertexAttribArray(i);
  9005. this._vertexAttribArraysEnabled[i] = false;
  9006. this._currentBufferPointers[i] = null;
  9007. }
  9008. return;
  9009. }
  9010. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  9011. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  9012. continue;
  9013. }
  9014. this._gl.disableVertexAttribArray(i);
  9015. this._vertexAttribArraysEnabled[i] = false;
  9016. this._currentBufferPointers[i] = null;
  9017. }
  9018. };
  9019. // Dispose
  9020. Engine.prototype.dispose = function () {
  9021. this.hideLoadingUI();
  9022. this.stopRenderLoop();
  9023. // Release scenes
  9024. while (this.scenes.length) {
  9025. this.scenes[0].dispose();
  9026. }
  9027. // Release audio engine
  9028. Engine.audioEngine.dispose();
  9029. // Release effects
  9030. for (var name in this._compiledEffects) {
  9031. this._gl.deleteProgram(this._compiledEffects[name]._program);
  9032. }
  9033. // Unbind
  9034. this.unbindAllAttributes();
  9035. this._gl = null;
  9036. //WebVR
  9037. this.disableVR();
  9038. // Events
  9039. window.removeEventListener("blur", this._onBlur);
  9040. window.removeEventListener("focus", this._onFocus);
  9041. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  9042. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  9043. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  9044. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  9045. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  9046. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  9047. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  9048. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  9049. };
  9050. // Loading screen
  9051. Engine.prototype.displayLoadingUI = function () {
  9052. this._loadingScreen.displayLoadingUI();
  9053. };
  9054. Engine.prototype.hideLoadingUI = function () {
  9055. this._loadingScreen.hideLoadingUI();
  9056. };
  9057. Object.defineProperty(Engine.prototype, "loadingScreen", {
  9058. get: function () {
  9059. return this._loadingScreen;
  9060. },
  9061. set: function (loadingScreen) {
  9062. this._loadingScreen = loadingScreen;
  9063. },
  9064. enumerable: true,
  9065. configurable: true
  9066. });
  9067. Object.defineProperty(Engine.prototype, "loadingUIText", {
  9068. set: function (text) {
  9069. this._loadingScreen.loadingUIText = text;
  9070. },
  9071. enumerable: true,
  9072. configurable: true
  9073. });
  9074. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  9075. set: function (color) {
  9076. this._loadingScreen.loadingUIBackgroundColor = color;
  9077. },
  9078. enumerable: true,
  9079. configurable: true
  9080. });
  9081. Engine.prototype.attachContextLostEvent = function (callback) {
  9082. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  9083. };
  9084. Engine.prototype.attachContextRestoredEvent = function (callback) {
  9085. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  9086. };
  9087. Engine.prototype.getVertexShaderSource = function (program) {
  9088. var shaders = this._gl.getAttachedShaders(program);
  9089. return this._gl.getShaderSource(shaders[0]);
  9090. };
  9091. Engine.prototype.getFragmentShaderSource = function (program) {
  9092. var shaders = this._gl.getAttachedShaders(program);
  9093. return this._gl.getShaderSource(shaders[1]);
  9094. };
  9095. // FPS
  9096. Engine.prototype.getFps = function () {
  9097. return this.fps;
  9098. };
  9099. Engine.prototype.getDeltaTime = function () {
  9100. return this.deltaTime;
  9101. };
  9102. Engine.prototype._measureFps = function () {
  9103. this.previousFramesDuration.push(BABYLON.Tools.Now);
  9104. var length = this.previousFramesDuration.length;
  9105. if (length >= 2) {
  9106. this.deltaTime = this.previousFramesDuration[length - 1] - this.previousFramesDuration[length - 2];
  9107. }
  9108. if (length >= this.fpsRange) {
  9109. if (length > this.fpsRange) {
  9110. this.previousFramesDuration.splice(0, 1);
  9111. length = this.previousFramesDuration.length;
  9112. }
  9113. var sum = 0;
  9114. for (var id = 0; id < length - 1; id++) {
  9115. sum += this.previousFramesDuration[id + 1] - this.previousFramesDuration[id];
  9116. }
  9117. this.fps = 1000.0 / (sum / (length - 1));
  9118. }
  9119. };
  9120. Engine.prototype._canRenderToFloatFramebuffer = function () {
  9121. if (this._webGLVersion > 1) {
  9122. return this._caps.colorBufferFloat;
  9123. }
  9124. return this._canRenderToFramebuffer(BABYLON.Engine.TEXTURETYPE_FLOAT);
  9125. };
  9126. Engine.prototype._canRenderToHalfFloatFramebuffer = function () {
  9127. if (this._webGLVersion > 1) {
  9128. return this._caps.colorBufferFloat;
  9129. }
  9130. return this._canRenderToFramebuffer(BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  9131. };
  9132. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  9133. Engine.prototype._canRenderToFramebuffer = function (type) {
  9134. var gl = this._gl;
  9135. //clear existing errors
  9136. while (gl.getError() !== gl.NO_ERROR) { }
  9137. var successful = true;
  9138. var texture = gl.createTexture();
  9139. gl.bindTexture(gl.TEXTURE_2D, texture);
  9140. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  9141. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  9142. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  9143. var fb = gl.createFramebuffer();
  9144. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  9145. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  9146. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  9147. successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
  9148. successful = successful && (gl.getError() === gl.NO_ERROR);
  9149. //try render by clearing frame buffer's color buffer
  9150. if (successful) {
  9151. gl.clear(gl.COLOR_BUFFER_BIT);
  9152. successful = successful && (gl.getError() === gl.NO_ERROR);
  9153. }
  9154. //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
  9155. if (successful) {
  9156. //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
  9157. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  9158. var readFormat = gl.RGBA;
  9159. var readType = gl.UNSIGNED_BYTE;
  9160. var buffer = new Uint8Array(4);
  9161. gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
  9162. successful = successful && (gl.getError() === gl.NO_ERROR);
  9163. }
  9164. //clean up
  9165. gl.deleteTexture(texture);
  9166. gl.deleteFramebuffer(fb);
  9167. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  9168. //clear accumulated errors
  9169. while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
  9170. return successful;
  9171. };
  9172. Engine.prototype._getWebGLTextureType = function (type) {
  9173. if (type === Engine.TEXTURETYPE_FLOAT) {
  9174. return this._gl.FLOAT;
  9175. }
  9176. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  9177. // Add Half Float Constant.
  9178. return Engine.HALF_FLOAT_OES;
  9179. }
  9180. return this._gl.UNSIGNED_BYTE;
  9181. };
  9182. ;
  9183. Engine.prototype._getRGBABufferInternalSizedFormat = function (type) {
  9184. if (this._webGLVersion === 1) {
  9185. return this._gl.RGBA;
  9186. }
  9187. if (type === Engine.TEXTURETYPE_FLOAT) {
  9188. return Engine.RGBA32F;
  9189. }
  9190. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  9191. return Engine.RGBA16F;
  9192. }
  9193. return this._gl.RGBA;
  9194. };
  9195. ;
  9196. // Statics
  9197. Engine.isSupported = function () {
  9198. try {
  9199. // Avoid creating an unsized context for CocoonJS, since size determined on first creation. Is not resizable
  9200. if (navigator.isCocoonJS) {
  9201. return true;
  9202. }
  9203. var tempcanvas = document.createElement("canvas");
  9204. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  9205. return gl != null && !!window.WebGLRenderingContext;
  9206. }
  9207. catch (e) {
  9208. return false;
  9209. }
  9210. };
  9211. return Engine;
  9212. }());
  9213. // Const statics
  9214. Engine._ALPHA_DISABLE = 0;
  9215. Engine._ALPHA_ADD = 1;
  9216. Engine._ALPHA_COMBINE = 2;
  9217. Engine._ALPHA_SUBTRACT = 3;
  9218. Engine._ALPHA_MULTIPLY = 4;
  9219. Engine._ALPHA_MAXIMIZED = 5;
  9220. Engine._ALPHA_ONEONE = 6;
  9221. Engine._ALPHA_PREMULTIPLIED = 7;
  9222. Engine._DELAYLOADSTATE_NONE = 0;
  9223. Engine._DELAYLOADSTATE_LOADED = 1;
  9224. Engine._DELAYLOADSTATE_LOADING = 2;
  9225. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  9226. Engine._TEXTUREFORMAT_ALPHA = 0;
  9227. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  9228. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  9229. Engine._TEXTUREFORMAT_RGB = 4;
  9230. Engine._TEXTUREFORMAT_RGBA = 5;
  9231. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  9232. Engine._TEXTURETYPE_FLOAT = 1;
  9233. Engine._TEXTURETYPE_HALF_FLOAT = 2;
  9234. // Depht or Stencil test Constants.
  9235. Engine._NEVER = 0x0200; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn.
  9236. 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.
  9237. 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.
  9238. 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.
  9239. 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.
  9240. 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.
  9241. 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.
  9242. 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.
  9243. Engine.HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).
  9244. Engine.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.
  9245. Engine.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
  9246. // Stencil Actions Constants.
  9247. Engine._KEEP = 0x1E00;
  9248. Engine._REPLACE = 0x1E01;
  9249. Engine._INCR = 0x1E02;
  9250. Engine._DECR = 0x1E03;
  9251. Engine._INVERT = 0x150A;
  9252. Engine._INCR_WRAP = 0x8507;
  9253. Engine._DECR_WRAP = 0x8508;
  9254. // Updatable statics so stick with vars here
  9255. Engine.CollisionsEpsilon = 0.001;
  9256. Engine.CodeRepository = "src/";
  9257. Engine.ShadersRepository = "src/Shaders/";
  9258. BABYLON.Engine = Engine;
  9259. })(BABYLON || (BABYLON = {}));
  9260. //# sourceMappingURL=babylon.engine.js.map
  9261. var BABYLON;
  9262. (function (BABYLON) {
  9263. /**
  9264. * Node is the basic class for all scene objects (Mesh, Light Camera).
  9265. */
  9266. var Node = (function () {
  9267. /**
  9268. * @constructor
  9269. * @param {string} name - the name and id to be given to this node
  9270. * @param {BABYLON.Scene} the scene this node will be added to
  9271. */
  9272. function Node(name, scene) {
  9273. this.state = "";
  9274. this.metadata = null;
  9275. this.doNotSerialize = false;
  9276. this.animations = new Array();
  9277. this._ranges = {};
  9278. this._childrenFlag = -1;
  9279. this._isEnabled = true;
  9280. this._isReady = true;
  9281. this._currentRenderId = -1;
  9282. this._parentRenderId = -1;
  9283. /**
  9284. * An event triggered when the mesh is disposed.
  9285. * @type {BABYLON.Observable}
  9286. */
  9287. this.onDisposeObservable = new BABYLON.Observable();
  9288. this.name = name;
  9289. this.id = name;
  9290. this._scene = scene;
  9291. this._initCache();
  9292. }
  9293. Object.defineProperty(Node.prototype, "parent", {
  9294. get: function () {
  9295. return this._parentNode;
  9296. },
  9297. set: function (parent) {
  9298. if (this._parentNode === parent) {
  9299. return;
  9300. }
  9301. if (this._parentNode) {
  9302. var index = this._parentNode._children.indexOf(this);
  9303. if (index !== -1) {
  9304. this._parentNode._children.splice(index, 1);
  9305. }
  9306. }
  9307. this._parentNode = parent;
  9308. if (this._parentNode) {
  9309. if (!this._parentNode._children) {
  9310. this._parentNode._children = new Array();
  9311. }
  9312. this._parentNode._children.push(this);
  9313. }
  9314. },
  9315. enumerable: true,
  9316. configurable: true
  9317. });
  9318. Node.prototype.getClassName = function () {
  9319. return "Node";
  9320. };
  9321. Object.defineProperty(Node.prototype, "onDispose", {
  9322. set: function (callback) {
  9323. if (this._onDisposeObserver) {
  9324. this.onDisposeObservable.remove(this._onDisposeObserver);
  9325. }
  9326. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  9327. },
  9328. enumerable: true,
  9329. configurable: true
  9330. });
  9331. Node.prototype.getScene = function () {
  9332. return this._scene;
  9333. };
  9334. Node.prototype.getEngine = function () {
  9335. return this._scene.getEngine();
  9336. };
  9337. // override it in derived class
  9338. Node.prototype.getWorldMatrix = function () {
  9339. return BABYLON.Matrix.Identity();
  9340. };
  9341. // override it in derived class if you add new variables to the cache
  9342. // and call the parent class method
  9343. Node.prototype._initCache = function () {
  9344. this._cache = {};
  9345. this._cache.parent = undefined;
  9346. };
  9347. Node.prototype.updateCache = function (force) {
  9348. if (!force && this.isSynchronized())
  9349. return;
  9350. this._cache.parent = this.parent;
  9351. this._updateCache();
  9352. };
  9353. // override it in derived class if you add new variables to the cache
  9354. // and call the parent class method if !ignoreParentClass
  9355. Node.prototype._updateCache = function (ignoreParentClass) {
  9356. };
  9357. // override it in derived class if you add new variables to the cache
  9358. Node.prototype._isSynchronized = function () {
  9359. return true;
  9360. };
  9361. Node.prototype._markSyncedWithParent = function () {
  9362. this._parentRenderId = this.parent._currentRenderId;
  9363. };
  9364. Node.prototype.isSynchronizedWithParent = function () {
  9365. if (!this.parent) {
  9366. return true;
  9367. }
  9368. if (this._parentRenderId !== this.parent._currentRenderId) {
  9369. return false;
  9370. }
  9371. return this.parent.isSynchronized();
  9372. };
  9373. Node.prototype.isSynchronized = function (updateCache) {
  9374. var check = this.hasNewParent();
  9375. check = check || !this.isSynchronizedWithParent();
  9376. check = check || !this._isSynchronized();
  9377. if (updateCache)
  9378. this.updateCache(true);
  9379. return !check;
  9380. };
  9381. Node.prototype.hasNewParent = function (update) {
  9382. if (this._cache.parent === this.parent)
  9383. return false;
  9384. if (update)
  9385. this._cache.parent = this.parent;
  9386. return true;
  9387. };
  9388. /**
  9389. * Is this node ready to be used/rendered
  9390. * @return {boolean} is it ready
  9391. */
  9392. Node.prototype.isReady = function () {
  9393. return this._isReady;
  9394. };
  9395. /**
  9396. * Is this node enabled.
  9397. * If the node has a parent and is enabled, the parent will be inspected as well.
  9398. * @return {boolean} whether this node (and its parent) is enabled.
  9399. * @see setEnabled
  9400. */
  9401. Node.prototype.isEnabled = function () {
  9402. if (!this._isEnabled) {
  9403. return false;
  9404. }
  9405. if (this.parent) {
  9406. return this.parent.isEnabled();
  9407. }
  9408. return true;
  9409. };
  9410. /**
  9411. * Set the enabled state of this node.
  9412. * @param {boolean} value - the new enabled state
  9413. * @see isEnabled
  9414. */
  9415. Node.prototype.setEnabled = function (value) {
  9416. this._isEnabled = value;
  9417. };
  9418. /**
  9419. * Is this node a descendant of the given node.
  9420. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined.
  9421. * @param {BABYLON.Node} ancestor - The parent node to inspect
  9422. * @see parent
  9423. */
  9424. Node.prototype.isDescendantOf = function (ancestor) {
  9425. if (this.parent) {
  9426. if (this.parent === ancestor) {
  9427. return true;
  9428. }
  9429. return this.parent.isDescendantOf(ancestor);
  9430. }
  9431. return false;
  9432. };
  9433. /**
  9434. * Evaluate the list of children and determine if they should be considered as descendants considering the given criterias
  9435. * @param {BABYLON.Node[]} results the result array containing the nodes matching the given criterias
  9436. * @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.
  9437. * @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.
  9438. */
  9439. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  9440. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  9441. if (!this._children) {
  9442. return;
  9443. }
  9444. for (var index = 0; index < this._children.length; index++) {
  9445. var item = this._children[index];
  9446. if (!predicate || predicate(item)) {
  9447. results.push(item);
  9448. }
  9449. if (!directDescendantsOnly) {
  9450. item._getDescendants(results, false, predicate);
  9451. }
  9452. }
  9453. };
  9454. /**
  9455. * Will return all nodes that have this node as ascendant.
  9456. * @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.
  9457. * @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.
  9458. * @return {BABYLON.Node[]} all children nodes of all types.
  9459. */
  9460. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  9461. var results = [];
  9462. this._getDescendants(results, directDescendantsOnly, predicate);
  9463. return results;
  9464. };
  9465. /**
  9466. * @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.
  9467. * @Deprecated, legacy support.
  9468. * use getDecendants instead.
  9469. */
  9470. Node.prototype.getChildren = function (predicate) {
  9471. return this.getDescendants(true, predicate);
  9472. };
  9473. /**
  9474. * Get all child-meshes of this node.
  9475. */
  9476. Node.prototype.getChildMeshes = function (directDecendantsOnly, predicate) {
  9477. var results = [];
  9478. this._getDescendants(results, directDecendantsOnly, function (node) {
  9479. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  9480. });
  9481. return results;
  9482. };
  9483. Node.prototype._setReady = function (state) {
  9484. if (state === this._isReady) {
  9485. return;
  9486. }
  9487. if (!state) {
  9488. this._isReady = false;
  9489. return;
  9490. }
  9491. this._isReady = true;
  9492. if (this.onReady) {
  9493. this.onReady(this);
  9494. }
  9495. };
  9496. Node.prototype.getAnimationByName = function (name) {
  9497. for (var i = 0; i < this.animations.length; i++) {
  9498. var animation = this.animations[i];
  9499. if (animation.name === name) {
  9500. return animation;
  9501. }
  9502. }
  9503. return null;
  9504. };
  9505. Node.prototype.createAnimationRange = function (name, from, to) {
  9506. // check name not already in use
  9507. if (!this._ranges[name]) {
  9508. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  9509. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  9510. if (this.animations[i]) {
  9511. this.animations[i].createRange(name, from, to);
  9512. }
  9513. }
  9514. }
  9515. };
  9516. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  9517. if (deleteFrames === void 0) { deleteFrames = true; }
  9518. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  9519. if (this.animations[i]) {
  9520. this.animations[i].deleteRange(name, deleteFrames);
  9521. }
  9522. }
  9523. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  9524. };
  9525. Node.prototype.getAnimationRange = function (name) {
  9526. return this._ranges[name];
  9527. };
  9528. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  9529. var range = this.getAnimationRange(name);
  9530. if (!range) {
  9531. return null;
  9532. }
  9533. this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  9534. };
  9535. Node.prototype.serializeAnimationRanges = function () {
  9536. var serializationRanges = [];
  9537. for (var name in this._ranges) {
  9538. var range = {};
  9539. range.name = name;
  9540. range.from = this._ranges[name].from;
  9541. range.to = this._ranges[name].to;
  9542. serializationRanges.push(range);
  9543. }
  9544. return serializationRanges;
  9545. };
  9546. Node.prototype.dispose = function () {
  9547. this.parent = null;
  9548. // Callback
  9549. this.onDisposeObservable.notifyObservers(this);
  9550. this.onDisposeObservable.clear();
  9551. };
  9552. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  9553. if (parsedNode.ranges) {
  9554. for (var index = 0; index < parsedNode.ranges.length; index++) {
  9555. var data = parsedNode.ranges[index];
  9556. node.createAnimationRange(data.name, data.from, data.to);
  9557. }
  9558. }
  9559. };
  9560. return Node;
  9561. }());
  9562. __decorate([
  9563. BABYLON.serialize()
  9564. ], Node.prototype, "name", void 0);
  9565. __decorate([
  9566. BABYLON.serialize()
  9567. ], Node.prototype, "id", void 0);
  9568. __decorate([
  9569. BABYLON.serialize()
  9570. ], Node.prototype, "uniqueId", void 0);
  9571. __decorate([
  9572. BABYLON.serialize()
  9573. ], Node.prototype, "state", void 0);
  9574. __decorate([
  9575. BABYLON.serialize()
  9576. ], Node.prototype, "metadata", void 0);
  9577. BABYLON.Node = Node;
  9578. })(BABYLON || (BABYLON = {}));
  9579. //# sourceMappingURL=babylon.node.js.map
  9580. var BABYLON;
  9581. (function (BABYLON) {
  9582. var FilesInput = (function () {
  9583. /// Register to core BabylonJS object: engine, scene, rendering canvas, callback function when the scene will be loaded,
  9584. /// loading progress callback and optionnal addionnal logic to call in the rendering loop
  9585. function FilesInput(p_engine, p_scene, p_canvas, p_sceneLoadedCallback, p_progressCallback, p_additionnalRenderLoopLogicCallback, p_textureLoadingCallback, p_startingProcessingFilesCallback) {
  9586. this._engine = p_engine;
  9587. this._canvas = p_canvas;
  9588. this._currentScene = p_scene;
  9589. this._sceneLoadedCallback = p_sceneLoadedCallback;
  9590. this._progressCallback = p_progressCallback;
  9591. this._additionnalRenderLoopLogicCallback = p_additionnalRenderLoopLogicCallback;
  9592. this._textureLoadingCallback = p_textureLoadingCallback;
  9593. this._startingProcessingFilesCallback = p_startingProcessingFilesCallback;
  9594. }
  9595. FilesInput.prototype.monitorElementForDragNDrop = function (p_elementToMonitor) {
  9596. var _this = this;
  9597. if (p_elementToMonitor) {
  9598. this._elementToMonitor = p_elementToMonitor;
  9599. this._elementToMonitor.addEventListener("dragenter", function (e) { _this.drag(e); }, false);
  9600. this._elementToMonitor.addEventListener("dragover", function (e) { _this.drag(e); }, false);
  9601. this._elementToMonitor.addEventListener("drop", function (e) { _this.drop(e); }, false);
  9602. }
  9603. };
  9604. FilesInput.prototype.renderFunction = function () {
  9605. if (this._additionnalRenderLoopLogicCallback) {
  9606. this._additionnalRenderLoopLogicCallback();
  9607. }
  9608. if (this._currentScene) {
  9609. if (this._textureLoadingCallback) {
  9610. var remaining = this._currentScene.getWaitingItemsCount();
  9611. if (remaining > 0) {
  9612. this._textureLoadingCallback(remaining);
  9613. }
  9614. }
  9615. this._currentScene.render();
  9616. }
  9617. };
  9618. FilesInput.prototype.drag = function (e) {
  9619. e.stopPropagation();
  9620. e.preventDefault();
  9621. };
  9622. FilesInput.prototype.drop = function (eventDrop) {
  9623. eventDrop.stopPropagation();
  9624. eventDrop.preventDefault();
  9625. this.loadFiles(eventDrop);
  9626. };
  9627. FilesInput.prototype.loadFiles = function (event) {
  9628. if (this._startingProcessingFilesCallback)
  9629. this._startingProcessingFilesCallback();
  9630. // Handling data transfer via drag'n'drop
  9631. if (event && event.dataTransfer && event.dataTransfer.files) {
  9632. this._filesToLoad = event.dataTransfer.files;
  9633. }
  9634. // Handling files from input files
  9635. if (event && event.target && event.target.files) {
  9636. this._filesToLoad = event.target.files;
  9637. }
  9638. if (this._filesToLoad && this._filesToLoad.length > 0) {
  9639. for (var i = 0; i < this._filesToLoad.length; i++) {
  9640. var name_1 = this._filesToLoad[i].name.toLowerCase();
  9641. var extension = name_1.split('.').pop();
  9642. var type = this._filesToLoad[i].type;
  9643. if (extension === "jpg" || extension === "png" || extension === "bmp" || extension === "jpeg" ||
  9644. type === "image/jpeg" || type === "image/png" || type === "image/bmp") {
  9645. FilesInput.FilesTextures[name_1] = this._filesToLoad[i];
  9646. }
  9647. else {
  9648. if ((extension === "babylon" || extension === "stl" || extension === "obj")
  9649. && name_1.indexOf(".binary.babylon") === -1 && name_1.indexOf(".incremental.babylon") === -1) {
  9650. this._sceneFileToLoad = this._filesToLoad[i];
  9651. }
  9652. else {
  9653. FilesInput.FilesToLoad[name_1] = this._filesToLoad[i];
  9654. }
  9655. }
  9656. }
  9657. this.reload();
  9658. }
  9659. };
  9660. FilesInput.prototype.reload = function () {
  9661. var _this = this;
  9662. var that = this;
  9663. // If a ".babylon" file has been provided
  9664. if (this._sceneFileToLoad) {
  9665. if (this._currentScene) {
  9666. if (BABYLON.Tools.errorsCount > 0) {
  9667. BABYLON.Tools.ClearLogCache();
  9668. BABYLON.Tools.Log("Babylon.js engine (v" + BABYLON.Engine.Version + ") launched");
  9669. }
  9670. this._engine.stopRenderLoop();
  9671. this._currentScene.dispose();
  9672. }
  9673. BABYLON.SceneLoader.Load("file:", this._sceneFileToLoad, this._engine, function (newScene) {
  9674. that._currentScene = newScene;
  9675. // Wait for textures and shaders to be ready
  9676. that._currentScene.executeWhenReady(function () {
  9677. // Attach camera to canvas inputs
  9678. if (!that._currentScene.activeCamera || that._currentScene.lights.length === 0) {
  9679. that._currentScene.createDefaultCameraOrLight();
  9680. }
  9681. that._currentScene.activeCamera.attachControl(that._canvas);
  9682. if (that._sceneLoadedCallback) {
  9683. that._sceneLoadedCallback(_this._sceneFileToLoad, that._currentScene);
  9684. }
  9685. that._engine.runRenderLoop(function () { that.renderFunction(); });
  9686. });
  9687. }, function (progress) {
  9688. if (_this._progressCallback) {
  9689. _this._progressCallback(progress);
  9690. }
  9691. });
  9692. }
  9693. else {
  9694. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  9695. }
  9696. };
  9697. return FilesInput;
  9698. }());
  9699. FilesInput.FilesTextures = new Array();
  9700. FilesInput.FilesToLoad = new Array();
  9701. BABYLON.FilesInput = FilesInput;
  9702. })(BABYLON || (BABYLON = {}));
  9703. //# sourceMappingURL=babylon.filesInput.js.map
  9704. var BABYLON;
  9705. (function (BABYLON) {
  9706. var IntersectionInfo = (function () {
  9707. function IntersectionInfo(bu, bv, distance) {
  9708. this.bu = bu;
  9709. this.bv = bv;
  9710. this.distance = distance;
  9711. this.faceId = 0;
  9712. this.subMeshId = 0;
  9713. }
  9714. return IntersectionInfo;
  9715. }());
  9716. BABYLON.IntersectionInfo = IntersectionInfo;
  9717. var PickingInfo = (function () {
  9718. function PickingInfo() {
  9719. this.hit = false;
  9720. this.distance = 0;
  9721. this.pickedPoint = null;
  9722. this.pickedMesh = null;
  9723. this.bu = 0;
  9724. this.bv = 0;
  9725. this.faceId = -1;
  9726. this.subMeshId = 0;
  9727. this.pickedSprite = null;
  9728. }
  9729. // Methods
  9730. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  9731. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  9732. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  9733. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  9734. return null;
  9735. }
  9736. var indices = this.pickedMesh.getIndices();
  9737. var result;
  9738. if (useVerticesNormals) {
  9739. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  9740. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  9741. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  9742. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  9743. normal0 = normal0.scale(this.bu);
  9744. normal1 = normal1.scale(this.bv);
  9745. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  9746. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  9747. }
  9748. else {
  9749. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  9750. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  9751. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  9752. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  9753. var p1p2 = vertex1.subtract(vertex2);
  9754. var p3p2 = vertex3.subtract(vertex2);
  9755. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  9756. }
  9757. if (useWorldCoordinates) {
  9758. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  9759. }
  9760. return BABYLON.Vector3.Normalize(result);
  9761. };
  9762. PickingInfo.prototype.getTextureCoordinates = function () {
  9763. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  9764. return null;
  9765. }
  9766. var indices = this.pickedMesh.getIndices();
  9767. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  9768. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  9769. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  9770. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  9771. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  9772. uv1 = uv1.scale(this.bu);
  9773. uv2 = uv2.scale(this.bv);
  9774. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  9775. };
  9776. return PickingInfo;
  9777. }());
  9778. BABYLON.PickingInfo = PickingInfo;
  9779. })(BABYLON || (BABYLON = {}));
  9780. //# sourceMappingURL=babylon.pickingInfo.js.map
  9781. var BABYLON;
  9782. (function (BABYLON) {
  9783. var BoundingSphere = (function () {
  9784. function BoundingSphere(minimum, maximum) {
  9785. this.minimum = minimum;
  9786. this.maximum = maximum;
  9787. this._tempRadiusVector = BABYLON.Vector3.Zero();
  9788. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  9789. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  9790. this.radius = distance * 0.5;
  9791. this.centerWorld = BABYLON.Vector3.Zero();
  9792. this._update(BABYLON.Matrix.Identity());
  9793. }
  9794. // Methods
  9795. BoundingSphere.prototype._update = function (world) {
  9796. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  9797. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  9798. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  9799. };
  9800. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  9801. for (var i = 0; i < 6; i++) {
  9802. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  9803. return false;
  9804. }
  9805. return true;
  9806. };
  9807. BoundingSphere.prototype.intersectsPoint = function (point) {
  9808. var x = this.centerWorld.x - point.x;
  9809. var y = this.centerWorld.y - point.y;
  9810. var z = this.centerWorld.z - point.z;
  9811. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  9812. if (Math.abs(this.radiusWorld - distance) < BABYLON.Epsilon)
  9813. return false;
  9814. return true;
  9815. };
  9816. // Statics
  9817. BoundingSphere.Intersects = function (sphere0, sphere1) {
  9818. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  9819. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  9820. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  9821. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  9822. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  9823. return false;
  9824. return true;
  9825. };
  9826. return BoundingSphere;
  9827. }());
  9828. BABYLON.BoundingSphere = BoundingSphere;
  9829. })(BABYLON || (BABYLON = {}));
  9830. //# sourceMappingURL=babylon.boundingSphere.js.map
  9831. var BABYLON;
  9832. (function (BABYLON) {
  9833. var BoundingBox = (function () {
  9834. function BoundingBox(minimum, maximum) {
  9835. this.minimum = minimum;
  9836. this.maximum = maximum;
  9837. this.vectors = new Array();
  9838. this.vectorsWorld = new Array();
  9839. // Bounding vectors
  9840. this.vectors.push(this.minimum.clone());
  9841. this.vectors.push(this.maximum.clone());
  9842. this.vectors.push(this.minimum.clone());
  9843. this.vectors[2].x = this.maximum.x;
  9844. this.vectors.push(this.minimum.clone());
  9845. this.vectors[3].y = this.maximum.y;
  9846. this.vectors.push(this.minimum.clone());
  9847. this.vectors[4].z = this.maximum.z;
  9848. this.vectors.push(this.maximum.clone());
  9849. this.vectors[5].z = this.minimum.z;
  9850. this.vectors.push(this.maximum.clone());
  9851. this.vectors[6].x = this.minimum.x;
  9852. this.vectors.push(this.maximum.clone());
  9853. this.vectors[7].y = this.minimum.y;
  9854. // OBB
  9855. this.center = this.maximum.add(this.minimum).scale(0.5);
  9856. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  9857. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  9858. // World
  9859. for (var index = 0; index < this.vectors.length; index++) {
  9860. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  9861. }
  9862. this.minimumWorld = BABYLON.Vector3.Zero();
  9863. this.maximumWorld = BABYLON.Vector3.Zero();
  9864. this._update(BABYLON.Matrix.Identity());
  9865. }
  9866. // Methods
  9867. BoundingBox.prototype.getWorldMatrix = function () {
  9868. return this._worldMatrix;
  9869. };
  9870. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  9871. this._worldMatrix.copyFrom(matrix);
  9872. return this;
  9873. };
  9874. BoundingBox.prototype._update = function (world) {
  9875. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  9876. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  9877. for (var index = 0; index < this.vectors.length; index++) {
  9878. var v = this.vectorsWorld[index];
  9879. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  9880. if (v.x < this.minimumWorld.x)
  9881. this.minimumWorld.x = v.x;
  9882. if (v.y < this.minimumWorld.y)
  9883. this.minimumWorld.y = v.y;
  9884. if (v.z < this.minimumWorld.z)
  9885. this.minimumWorld.z = v.z;
  9886. if (v.x > this.maximumWorld.x)
  9887. this.maximumWorld.x = v.x;
  9888. if (v.y > this.maximumWorld.y)
  9889. this.maximumWorld.y = v.y;
  9890. if (v.z > this.maximumWorld.z)
  9891. this.maximumWorld.z = v.z;
  9892. }
  9893. // OBB
  9894. this.maximumWorld.addToRef(this.minimumWorld, this.center);
  9895. this.center.scaleInPlace(0.5);
  9896. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  9897. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  9898. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  9899. this._worldMatrix = world;
  9900. };
  9901. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  9902. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  9903. };
  9904. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  9905. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  9906. };
  9907. BoundingBox.prototype.intersectsPoint = function (point) {
  9908. var delta = -BABYLON.Epsilon;
  9909. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  9910. return false;
  9911. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  9912. return false;
  9913. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  9914. return false;
  9915. return true;
  9916. };
  9917. BoundingBox.prototype.intersectsSphere = function (sphere) {
  9918. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  9919. };
  9920. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  9921. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  9922. return false;
  9923. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  9924. return false;
  9925. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  9926. return false;
  9927. return true;
  9928. };
  9929. // Statics
  9930. BoundingBox.Intersects = function (box0, box1) {
  9931. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  9932. return false;
  9933. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  9934. return false;
  9935. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  9936. return false;
  9937. return true;
  9938. };
  9939. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  9940. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  9941. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  9942. return (num <= (sphereRadius * sphereRadius));
  9943. };
  9944. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  9945. for (var p = 0; p < 6; p++) {
  9946. for (var i = 0; i < 8; i++) {
  9947. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  9948. return false;
  9949. }
  9950. }
  9951. }
  9952. return true;
  9953. };
  9954. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  9955. for (var p = 0; p < 6; p++) {
  9956. var inCount = 8;
  9957. for (var i = 0; i < 8; i++) {
  9958. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  9959. --inCount;
  9960. }
  9961. else {
  9962. break;
  9963. }
  9964. }
  9965. if (inCount === 0)
  9966. return false;
  9967. }
  9968. return true;
  9969. };
  9970. return BoundingBox;
  9971. }());
  9972. BABYLON.BoundingBox = BoundingBox;
  9973. })(BABYLON || (BABYLON = {}));
  9974. //# sourceMappingURL=babylon.boundingBox.js.map
  9975. var BABYLON;
  9976. (function (BABYLON) {
  9977. var computeBoxExtents = function (axis, box) {
  9978. var p = BABYLON.Vector3.Dot(box.center, axis);
  9979. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  9980. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  9981. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  9982. var r = r0 + r1 + r2;
  9983. return {
  9984. min: p - r,
  9985. max: p + r
  9986. };
  9987. };
  9988. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  9989. var axisOverlap = function (axis, box0, box1) {
  9990. var result0 = computeBoxExtents(axis, box0);
  9991. var result1 = computeBoxExtents(axis, box1);
  9992. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  9993. };
  9994. var BoundingInfo = (function () {
  9995. function BoundingInfo(minimum, maximum) {
  9996. this.minimum = minimum;
  9997. this.maximum = maximum;
  9998. this._isLocked = false;
  9999. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  10000. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  10001. }
  10002. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  10003. get: function () {
  10004. return this._isLocked;
  10005. },
  10006. set: function (value) {
  10007. this._isLocked = value;
  10008. },
  10009. enumerable: true,
  10010. configurable: true
  10011. });
  10012. // Methods
  10013. BoundingInfo.prototype.update = function (world) {
  10014. if (this._isLocked) {
  10015. return;
  10016. }
  10017. this.boundingBox._update(world);
  10018. this.boundingSphere._update(world);
  10019. };
  10020. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  10021. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  10022. return false;
  10023. return this.boundingBox.isInFrustum(frustumPlanes);
  10024. };
  10025. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  10026. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  10027. };
  10028. BoundingInfo.prototype._checkCollision = function (collider) {
  10029. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  10030. };
  10031. BoundingInfo.prototype.intersectsPoint = function (point) {
  10032. if (!this.boundingSphere.centerWorld) {
  10033. return false;
  10034. }
  10035. if (!this.boundingSphere.intersectsPoint(point)) {
  10036. return false;
  10037. }
  10038. if (!this.boundingBox.intersectsPoint(point)) {
  10039. return false;
  10040. }
  10041. return true;
  10042. };
  10043. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  10044. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  10045. return false;
  10046. }
  10047. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  10048. return false;
  10049. }
  10050. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  10051. return false;
  10052. }
  10053. if (!precise) {
  10054. return true;
  10055. }
  10056. var box0 = this.boundingBox;
  10057. var box1 = boundingInfo.boundingBox;
  10058. if (!axisOverlap(box0.directions[0], box0, box1))
  10059. return false;
  10060. if (!axisOverlap(box0.directions[1], box0, box1))
  10061. return false;
  10062. if (!axisOverlap(box0.directions[2], box0, box1))
  10063. return false;
  10064. if (!axisOverlap(box1.directions[0], box0, box1))
  10065. return false;
  10066. if (!axisOverlap(box1.directions[1], box0, box1))
  10067. return false;
  10068. if (!axisOverlap(box1.directions[2], box0, box1))
  10069. return false;
  10070. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  10071. return false;
  10072. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  10073. return false;
  10074. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  10075. return false;
  10076. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  10077. return false;
  10078. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  10079. return false;
  10080. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  10081. return false;
  10082. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  10083. return false;
  10084. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  10085. return false;
  10086. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  10087. return false;
  10088. return true;
  10089. };
  10090. return BoundingInfo;
  10091. }());
  10092. BABYLON.BoundingInfo = BoundingInfo;
  10093. })(BABYLON || (BABYLON = {}));
  10094. //# sourceMappingURL=babylon.boundingInfo.js.map
  10095. var BABYLON;
  10096. (function (BABYLON) {
  10097. var Ray = (function () {
  10098. function Ray(origin, direction, length) {
  10099. if (length === void 0) { length = Number.MAX_VALUE; }
  10100. this.origin = origin;
  10101. this.direction = direction;
  10102. this.length = length;
  10103. }
  10104. // Methods
  10105. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  10106. var d = 0.0;
  10107. var maxValue = Number.MAX_VALUE;
  10108. var inv;
  10109. var min;
  10110. var max;
  10111. var temp;
  10112. if (Math.abs(this.direction.x) < 0.0000001) {
  10113. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  10114. return false;
  10115. }
  10116. }
  10117. else {
  10118. inv = 1.0 / this.direction.x;
  10119. min = (minimum.x - this.origin.x) * inv;
  10120. max = (maximum.x - this.origin.x) * inv;
  10121. if (max === -Infinity) {
  10122. max = Infinity;
  10123. }
  10124. if (min > max) {
  10125. temp = min;
  10126. min = max;
  10127. max = temp;
  10128. }
  10129. d = Math.max(min, d);
  10130. maxValue = Math.min(max, maxValue);
  10131. if (d > maxValue) {
  10132. return false;
  10133. }
  10134. }
  10135. if (Math.abs(this.direction.y) < 0.0000001) {
  10136. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  10137. return false;
  10138. }
  10139. }
  10140. else {
  10141. inv = 1.0 / this.direction.y;
  10142. min = (minimum.y - this.origin.y) * inv;
  10143. max = (maximum.y - this.origin.y) * inv;
  10144. if (max === -Infinity) {
  10145. max = Infinity;
  10146. }
  10147. if (min > max) {
  10148. temp = min;
  10149. min = max;
  10150. max = temp;
  10151. }
  10152. d = Math.max(min, d);
  10153. maxValue = Math.min(max, maxValue);
  10154. if (d > maxValue) {
  10155. return false;
  10156. }
  10157. }
  10158. if (Math.abs(this.direction.z) < 0.0000001) {
  10159. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  10160. return false;
  10161. }
  10162. }
  10163. else {
  10164. inv = 1.0 / this.direction.z;
  10165. min = (minimum.z - this.origin.z) * inv;
  10166. max = (maximum.z - this.origin.z) * inv;
  10167. if (max === -Infinity) {
  10168. max = Infinity;
  10169. }
  10170. if (min > max) {
  10171. temp = min;
  10172. min = max;
  10173. max = temp;
  10174. }
  10175. d = Math.max(min, d);
  10176. maxValue = Math.min(max, maxValue);
  10177. if (d > maxValue) {
  10178. return false;
  10179. }
  10180. }
  10181. return true;
  10182. };
  10183. Ray.prototype.intersectsBox = function (box) {
  10184. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  10185. };
  10186. Ray.prototype.intersectsSphere = function (sphere) {
  10187. var x = sphere.center.x - this.origin.x;
  10188. var y = sphere.center.y - this.origin.y;
  10189. var z = sphere.center.z - this.origin.z;
  10190. var pyth = (x * x) + (y * y) + (z * z);
  10191. var rr = sphere.radius * sphere.radius;
  10192. if (pyth <= rr) {
  10193. return true;
  10194. }
  10195. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  10196. if (dot < 0.0) {
  10197. return false;
  10198. }
  10199. var temp = pyth - (dot * dot);
  10200. return temp <= rr;
  10201. };
  10202. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  10203. if (!this._edge1) {
  10204. this._edge1 = BABYLON.Vector3.Zero();
  10205. this._edge2 = BABYLON.Vector3.Zero();
  10206. this._pvec = BABYLON.Vector3.Zero();
  10207. this._tvec = BABYLON.Vector3.Zero();
  10208. this._qvec = BABYLON.Vector3.Zero();
  10209. }
  10210. vertex1.subtractToRef(vertex0, this._edge1);
  10211. vertex2.subtractToRef(vertex0, this._edge2);
  10212. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  10213. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  10214. if (det === 0) {
  10215. return null;
  10216. }
  10217. var invdet = 1 / det;
  10218. this.origin.subtractToRef(vertex0, this._tvec);
  10219. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  10220. if (bu < 0 || bu > 1.0) {
  10221. return null;
  10222. }
  10223. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  10224. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  10225. if (bv < 0 || bu + bv > 1.0) {
  10226. return null;
  10227. }
  10228. //check if the distance is longer than the predefined length.
  10229. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  10230. if (distance > this.length) {
  10231. return null;
  10232. }
  10233. return new BABYLON.IntersectionInfo(bu, bv, distance);
  10234. };
  10235. Ray.prototype.intersectsPlane = function (plane) {
  10236. var distance;
  10237. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  10238. if (Math.abs(result1) < 9.99999997475243E-07) {
  10239. return null;
  10240. }
  10241. else {
  10242. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  10243. distance = (-plane.d - result2) / result1;
  10244. if (distance < 0.0) {
  10245. if (distance < -9.99999997475243E-07) {
  10246. return null;
  10247. }
  10248. else {
  10249. return 0;
  10250. }
  10251. }
  10252. return distance;
  10253. }
  10254. };
  10255. Ray.prototype.intersectsMesh = function (mesh, fastCheck) {
  10256. var tm = BABYLON.Tmp.Matrix[0];
  10257. mesh.getWorldMatrix().invertToRef(tm);
  10258. if (this._tmpRay) {
  10259. Ray.TransformToRef(this, tm, this._tmpRay);
  10260. }
  10261. else {
  10262. this._tmpRay = Ray.Transform(this, tm);
  10263. }
  10264. return mesh.intersects(this._tmpRay, fastCheck);
  10265. };
  10266. Ray.prototype.intersectsMeshes = function (meshes, fastCheck, results) {
  10267. if (results) {
  10268. results.length = 0;
  10269. }
  10270. else {
  10271. results = [];
  10272. }
  10273. for (var i = 0; i < meshes.length; i++) {
  10274. var pickInfo = this.intersectsMesh(meshes[i], fastCheck);
  10275. if (pickInfo.hit) {
  10276. results.push(pickInfo);
  10277. }
  10278. }
  10279. results.sort(this._comparePickingInfo);
  10280. return results;
  10281. };
  10282. Ray.prototype._comparePickingInfo = function (pickingInfoA, pickingInfoB) {
  10283. if (pickingInfoA.distance < pickingInfoB.distance) {
  10284. return -1;
  10285. }
  10286. else if (pickingInfoA.distance > pickingInfoB.distance) {
  10287. return 1;
  10288. }
  10289. else {
  10290. return 0;
  10291. }
  10292. };
  10293. /**
  10294. * @Deprecated. Use new RayHelper.show() instead.
  10295. * */
  10296. Ray.prototype.show = function (scene, color) {
  10297. console.warn('Ray.show() has been deprecated. Use new RayHelper.show() instead.');
  10298. if (!this._rayHelper) {
  10299. this._rayHelper = new BABYLON.RayHelper(this);
  10300. }
  10301. this._rayHelper.show(scene, color);
  10302. };
  10303. /**
  10304. * @Deprecated. Use new RayHelper.hide() instead.
  10305. * */
  10306. Ray.prototype.hide = function () {
  10307. console.warn('Ray.hide() has been deprecated. Use new RayHelper.hide() instead.');
  10308. if (this._rayHelper) {
  10309. this._rayHelper.hide();
  10310. this._rayHelper = null;
  10311. }
  10312. };
  10313. /**
  10314. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  10315. * @param sega the first point of the segment to test the intersection against
  10316. * @param segb the second point of the segment to test the intersection against
  10317. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  10318. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  10319. */
  10320. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  10321. var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
  10322. var u = segb.subtract(sega);
  10323. var v = rsegb.subtract(this.origin);
  10324. var w = sega.subtract(this.origin);
  10325. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  10326. var b = BABYLON.Vector3.Dot(u, v);
  10327. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  10328. var d = BABYLON.Vector3.Dot(u, w);
  10329. var e = BABYLON.Vector3.Dot(v, w);
  10330. var D = a * c - b * b; // always >= 0
  10331. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  10332. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  10333. // compute the line parameters of the two closest points
  10334. if (D < Ray.smallnum) {
  10335. sN = 0.0; // force using point P0 on segment S1
  10336. sD = 1.0; // to prevent possible division by 0.0 later
  10337. tN = e;
  10338. tD = c;
  10339. }
  10340. else {
  10341. sN = (b * e - c * d);
  10342. tN = (a * e - b * d);
  10343. if (sN < 0.0) {
  10344. sN = 0.0;
  10345. tN = e;
  10346. tD = c;
  10347. }
  10348. else if (sN > sD) {
  10349. sN = sD;
  10350. tN = e + b;
  10351. tD = c;
  10352. }
  10353. }
  10354. if (tN < 0.0) {
  10355. tN = 0.0;
  10356. // recompute sc for this edge
  10357. if (-d < 0.0) {
  10358. sN = 0.0;
  10359. }
  10360. else if (-d > a)
  10361. sN = sD;
  10362. else {
  10363. sN = -d;
  10364. sD = a;
  10365. }
  10366. }
  10367. else if (tN > tD) {
  10368. tN = tD;
  10369. // recompute sc for this edge
  10370. if ((-d + b) < 0.0) {
  10371. sN = 0;
  10372. }
  10373. else if ((-d + b) > a) {
  10374. sN = sD;
  10375. }
  10376. else {
  10377. sN = (-d + b);
  10378. sD = a;
  10379. }
  10380. }
  10381. // finally do the division to get sc and tc
  10382. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  10383. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  10384. // get the difference of the two closest points
  10385. var qtc = v.multiplyByFloats(tc, tc, tc);
  10386. var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)
  10387. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  10388. if (isIntersected) {
  10389. return qtc.length();
  10390. }
  10391. return -1;
  10392. };
  10393. // Statics
  10394. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  10395. var start = BABYLON.Vector3.Unproject(new BABYLON.Vector3(x, y, 0), viewportWidth, viewportHeight, world, view, projection);
  10396. var end = BABYLON.Vector3.Unproject(new BABYLON.Vector3(x, y, 1), viewportWidth, viewportHeight, world, view, projection);
  10397. var direction = end.subtract(start);
  10398. direction.normalize();
  10399. return new Ray(start, direction);
  10400. };
  10401. /**
  10402. * 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
  10403. * transformed to the given world matrix.
  10404. * @param origin The origin point
  10405. * @param end The end point
  10406. * @param world a matrix to transform the ray to. Default is the identity matrix.
  10407. */
  10408. Ray.CreateNewFromTo = function (origin, end, world) {
  10409. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  10410. var direction = end.subtract(origin);
  10411. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  10412. direction.normalize();
  10413. return Ray.Transform(new Ray(origin, direction, length), world);
  10414. };
  10415. Ray.Transform = function (ray, matrix) {
  10416. var newOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, matrix);
  10417. var newDirection = BABYLON.Vector3.TransformNormal(ray.direction, matrix);
  10418. newDirection.normalize();
  10419. return new Ray(newOrigin, newDirection, ray.length);
  10420. };
  10421. Ray.TransformToRef = function (ray, matrix, result) {
  10422. BABYLON.Vector3.TransformCoordinatesToRef(ray.origin, matrix, result.origin);
  10423. BABYLON.Vector3.TransformNormalToRef(ray.direction, matrix, result.direction);
  10424. ray.direction.normalize();
  10425. };
  10426. return Ray;
  10427. }());
  10428. Ray.smallnum = 0.00000001;
  10429. Ray.rayl = 10e8;
  10430. BABYLON.Ray = Ray;
  10431. })(BABYLON || (BABYLON = {}));
  10432. //# sourceMappingURL=babylon.ray.js.map
  10433. var BABYLON;
  10434. (function (BABYLON) {
  10435. var RayHelper = (function () {
  10436. function RayHelper(ray) {
  10437. this.ray = ray;
  10438. }
  10439. RayHelper.prototype.show = function (scene, color) {
  10440. if (!this._renderFunction) {
  10441. var ray = this.ray;
  10442. this._renderFunction = this._render.bind(this);
  10443. this._scene = scene;
  10444. this._renderPoints = [ray.origin, ray.origin.add(ray.direction.scale(ray.length))];
  10445. this._renderLine = BABYLON.Mesh.CreateLines("ray", this._renderPoints, scene, true);
  10446. this._scene.registerBeforeRender(this._renderFunction);
  10447. }
  10448. if (color) {
  10449. this._renderLine.color.copyFrom(color);
  10450. }
  10451. };
  10452. RayHelper.prototype.hide = function () {
  10453. if (this._renderFunction) {
  10454. this._scene.unregisterBeforeRender(this._renderFunction);
  10455. this._scene = null;
  10456. this._renderFunction = null;
  10457. this._renderLine.dispose();
  10458. this._renderLine = null;
  10459. this._renderPoints = null;
  10460. }
  10461. };
  10462. RayHelper.prototype._render = function () {
  10463. var ray = this.ray;
  10464. var point = this._renderPoints[1];
  10465. var len = Math.min(ray.length, 1000000);
  10466. point.copyFrom(ray.direction);
  10467. point.scaleInPlace(len);
  10468. point.addInPlace(ray.origin);
  10469. BABYLON.Mesh.CreateLines("ray", this._renderPoints, this._scene, true, this._renderLine);
  10470. };
  10471. RayHelper.prototype.attachToMesh = function (mesh, meshSpaceDirection, meshSpaceOrigin, length) {
  10472. this._attachedToMesh = mesh;
  10473. var ray = this.ray;
  10474. if (!ray.direction) {
  10475. ray.direction = BABYLON.Vector3.Zero();
  10476. }
  10477. if (!ray.origin) {
  10478. ray.origin = BABYLON.Vector3.Zero();
  10479. }
  10480. if (length) {
  10481. ray.length = length;
  10482. }
  10483. if (!meshSpaceOrigin) {
  10484. meshSpaceOrigin = BABYLON.Vector3.Zero();
  10485. }
  10486. if (!meshSpaceDirection) {
  10487. // -1 so that this will work with Mesh.lookAt
  10488. meshSpaceDirection = new BABYLON.Vector3(0, 0, -1);
  10489. }
  10490. if (!this._meshSpaceDirection) {
  10491. this._meshSpaceDirection = meshSpaceDirection.clone();
  10492. this._meshSpaceOrigin = meshSpaceOrigin.clone();
  10493. }
  10494. else {
  10495. this._meshSpaceDirection.copyFrom(meshSpaceDirection);
  10496. this._meshSpaceOrigin.copyFrom(meshSpaceOrigin);
  10497. }
  10498. if (!this._updateToMeshFunction) {
  10499. this._updateToMeshFunction = this._updateToMesh.bind(this);
  10500. this._attachedToMesh.getScene().registerBeforeRender(this._updateToMeshFunction);
  10501. }
  10502. this._updateToMesh();
  10503. };
  10504. RayHelper.prototype.detachFromMesh = function () {
  10505. if (this._attachedToMesh) {
  10506. this._attachedToMesh.getScene().unregisterBeforeRender(this._updateToMeshFunction);
  10507. this._attachedToMesh = null;
  10508. this._updateToMeshFunction = null;
  10509. }
  10510. };
  10511. RayHelper.prototype._updateToMesh = function () {
  10512. var ray = this.ray;
  10513. if (this._attachedToMesh._isDisposed) {
  10514. this.detachFromMesh();
  10515. return;
  10516. }
  10517. this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection, ray.direction);
  10518. BABYLON.Vector3.TransformCoordinatesToRef(this._meshSpaceOrigin, this._attachedToMesh.getWorldMatrix(), ray.origin);
  10519. };
  10520. RayHelper.prototype.dispose = function () {
  10521. this.hide();
  10522. this.detachFromMesh();
  10523. this.ray = null;
  10524. };
  10525. return RayHelper;
  10526. }());
  10527. BABYLON.RayHelper = RayHelper;
  10528. })(BABYLON || (BABYLON = {}));
  10529. //# sourceMappingURL=babylon.rayHelper.js.map
  10530. var BABYLON;
  10531. (function (BABYLON) {
  10532. var AbstractMesh = (function (_super) {
  10533. __extends(AbstractMesh, _super);
  10534. // Constructor
  10535. function AbstractMesh(name, scene) {
  10536. var _this = _super.call(this, name, scene) || this;
  10537. // Events
  10538. /**
  10539. * An event triggered when this mesh collides with another one
  10540. * @type {BABYLON.Observable}
  10541. */
  10542. _this.onCollideObservable = new BABYLON.Observable();
  10543. /**
  10544. * An event triggered when the collision's position changes
  10545. * @type {BABYLON.Observable}
  10546. */
  10547. _this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  10548. /**
  10549. * An event triggered after the world matrix is updated
  10550. * @type {BABYLON.Observable}
  10551. */
  10552. _this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  10553. // Properties
  10554. _this.definedFacingForward = true; // orientation for POV movement & rotation
  10555. _this.position = new BABYLON.Vector3(0, 0, 0);
  10556. _this._rotation = new BABYLON.Vector3(0, 0, 0);
  10557. _this._scaling = new BABYLON.Vector3(1, 1, 1);
  10558. _this.billboardMode = AbstractMesh.BILLBOARDMODE_NONE;
  10559. _this.visibility = 1.0;
  10560. _this.alphaIndex = Number.MAX_VALUE;
  10561. _this.infiniteDistance = false;
  10562. _this.isVisible = true;
  10563. _this.isPickable = true;
  10564. _this.showBoundingBox = false;
  10565. _this.showSubMeshesBoundingBox = false;
  10566. _this.isBlocker = false;
  10567. _this.renderingGroupId = 0;
  10568. _this.receiveShadows = false;
  10569. _this.renderOutline = false;
  10570. _this.outlineColor = BABYLON.Color3.Red();
  10571. _this.outlineWidth = 0.02;
  10572. _this.renderOverlay = false;
  10573. _this.overlayColor = BABYLON.Color3.Red();
  10574. _this.overlayAlpha = 0.5;
  10575. _this.hasVertexAlpha = false;
  10576. _this.useVertexColors = true;
  10577. _this.applyFog = true;
  10578. _this.computeBonesUsingShaders = true;
  10579. _this.scalingDeterminant = 1;
  10580. _this.numBoneInfluencers = 4;
  10581. _this.useOctreeForRenderingSelection = true;
  10582. _this.useOctreeForPicking = true;
  10583. _this.useOctreeForCollisions = true;
  10584. _this.layerMask = 0x0FFFFFFF;
  10585. _this.alwaysSelectAsActiveMesh = false;
  10586. // Collisions
  10587. _this._checkCollisions = false;
  10588. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  10589. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  10590. _this._collider = new BABYLON.Collider();
  10591. _this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  10592. _this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  10593. _this._newPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  10594. // Edges
  10595. _this.edgesWidth = 1;
  10596. _this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  10597. // Cache
  10598. _this._localWorld = BABYLON.Matrix.Zero();
  10599. _this._worldMatrix = BABYLON.Matrix.Zero();
  10600. _this._rotateYByPI = BABYLON.Matrix.RotationY(Math.PI);
  10601. _this._absolutePosition = BABYLON.Vector3.Zero();
  10602. _this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  10603. _this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  10604. _this._isDirty = false;
  10605. _this._pivotMatrix = BABYLON.Matrix.Identity();
  10606. _this._isDisposed = false;
  10607. _this._renderId = 0;
  10608. _this._intersectionsInProgress = new Array();
  10609. _this._isWorldMatrixFrozen = false;
  10610. _this._unIndexed = false;
  10611. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  10612. if (collidedMesh === void 0) { collidedMesh = null; }
  10613. //TODO move this to the collision coordinator!
  10614. if (_this.getScene().workerCollisions)
  10615. newPosition.multiplyInPlace(_this._collider.radius);
  10616. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  10617. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  10618. _this.position.addInPlace(_this._diffPositionForCollisions);
  10619. }
  10620. if (collidedMesh) {
  10621. _this.onCollideObservable.notifyObservers(collidedMesh);
  10622. }
  10623. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  10624. };
  10625. scene.addMesh(_this);
  10626. return _this;
  10627. }
  10628. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  10629. get: function () {
  10630. return AbstractMesh._BILLBOARDMODE_NONE;
  10631. },
  10632. enumerable: true,
  10633. configurable: true
  10634. });
  10635. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  10636. get: function () {
  10637. return AbstractMesh._BILLBOARDMODE_X;
  10638. },
  10639. enumerable: true,
  10640. configurable: true
  10641. });
  10642. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  10643. get: function () {
  10644. return AbstractMesh._BILLBOARDMODE_Y;
  10645. },
  10646. enumerable: true,
  10647. configurable: true
  10648. });
  10649. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  10650. get: function () {
  10651. return AbstractMesh._BILLBOARDMODE_Z;
  10652. },
  10653. enumerable: true,
  10654. configurable: true
  10655. });
  10656. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  10657. get: function () {
  10658. return AbstractMesh._BILLBOARDMODE_ALL;
  10659. },
  10660. enumerable: true,
  10661. configurable: true
  10662. });
  10663. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  10664. set: function (callback) {
  10665. if (this._onCollideObserver) {
  10666. this.onCollideObservable.remove(this._onCollideObserver);
  10667. }
  10668. this._onCollideObserver = this.onCollideObservable.add(callback);
  10669. },
  10670. enumerable: true,
  10671. configurable: true
  10672. });
  10673. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  10674. set: function (callback) {
  10675. if (this._onCollisionPositionChangeObserver) {
  10676. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  10677. }
  10678. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  10679. },
  10680. enumerable: true,
  10681. configurable: true
  10682. });
  10683. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  10684. get: function () {
  10685. return this._skeleton;
  10686. },
  10687. set: function (value) {
  10688. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  10689. this._skeleton._unregisterMeshWithPoseMatrix(this);
  10690. }
  10691. if (value && value.needInitialSkinMatrix) {
  10692. value._registerMeshWithPoseMatrix(this);
  10693. }
  10694. this._skeleton = value;
  10695. if (!this._skeleton) {
  10696. this._bonesTransformMatrices = null;
  10697. }
  10698. },
  10699. enumerable: true,
  10700. configurable: true
  10701. });
  10702. AbstractMesh.prototype.getClassName = function () {
  10703. return "AbstractMesh";
  10704. };
  10705. /**
  10706. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  10707. */
  10708. AbstractMesh.prototype.toString = function (fullDetails) {
  10709. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  10710. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  10711. if (this._skeleton) {
  10712. ret += ", skeleton: " + this._skeleton.name;
  10713. }
  10714. if (fullDetails) {
  10715. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  10716. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  10717. }
  10718. return ret;
  10719. };
  10720. Object.defineProperty(AbstractMesh.prototype, "rotation", {
  10721. /**
  10722. * Getting the rotation object.
  10723. * If rotation quaternion is set, this vector will (almost always) be the Zero vector!
  10724. */
  10725. get: function () {
  10726. return this._rotation;
  10727. },
  10728. set: function (newRotation) {
  10729. this._rotation = newRotation;
  10730. },
  10731. enumerable: true,
  10732. configurable: true
  10733. });
  10734. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  10735. get: function () {
  10736. return this._scaling;
  10737. },
  10738. set: function (newScaling) {
  10739. this._scaling = newScaling;
  10740. if (this.physicsImpostor) {
  10741. this.physicsImpostor.forceUpdate();
  10742. }
  10743. },
  10744. enumerable: true,
  10745. configurable: true
  10746. });
  10747. Object.defineProperty(AbstractMesh.prototype, "rotationQuaternion", {
  10748. get: function () {
  10749. return this._rotationQuaternion;
  10750. },
  10751. set: function (quaternion) {
  10752. this._rotationQuaternion = quaternion;
  10753. //reset the rotation vector.
  10754. if (quaternion && this.rotation.length()) {
  10755. this.rotation.copyFromFloats(0, 0, 0);
  10756. }
  10757. },
  10758. enumerable: true,
  10759. configurable: true
  10760. });
  10761. // Methods
  10762. AbstractMesh.prototype.updatePoseMatrix = function (matrix) {
  10763. this._poseMatrix.copyFrom(matrix);
  10764. };
  10765. AbstractMesh.prototype.getPoseMatrix = function () {
  10766. return this._poseMatrix;
  10767. };
  10768. AbstractMesh.prototype.disableEdgesRendering = function () {
  10769. if (this._edgesRenderer !== undefined) {
  10770. this._edgesRenderer.dispose();
  10771. this._edgesRenderer = undefined;
  10772. }
  10773. };
  10774. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  10775. if (epsilon === void 0) { epsilon = 0.95; }
  10776. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  10777. this.disableEdgesRendering();
  10778. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  10779. };
  10780. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  10781. get: function () {
  10782. return false;
  10783. },
  10784. enumerable: true,
  10785. configurable: true
  10786. });
  10787. AbstractMesh.prototype.getLOD = function (camera) {
  10788. return this;
  10789. };
  10790. AbstractMesh.prototype.getTotalVertices = function () {
  10791. return 0;
  10792. };
  10793. AbstractMesh.prototype.getIndices = function () {
  10794. return null;
  10795. };
  10796. AbstractMesh.prototype.getVerticesData = function (kind) {
  10797. return null;
  10798. };
  10799. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  10800. return false;
  10801. };
  10802. AbstractMesh.prototype.getBoundingInfo = function () {
  10803. if (this._masterMesh) {
  10804. return this._masterMesh.getBoundingInfo();
  10805. }
  10806. if (!this._boundingInfo) {
  10807. this._updateBoundingInfo();
  10808. }
  10809. return this._boundingInfo;
  10810. };
  10811. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  10812. this._boundingInfo = boundingInfo;
  10813. };
  10814. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  10815. get: function () {
  10816. return this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind);
  10817. },
  10818. enumerable: true,
  10819. configurable: true
  10820. });
  10821. AbstractMesh.prototype._preActivate = function () {
  10822. };
  10823. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  10824. };
  10825. AbstractMesh.prototype._activate = function (renderId) {
  10826. this._renderId = renderId;
  10827. };
  10828. AbstractMesh.prototype.getWorldMatrix = function () {
  10829. if (this._masterMesh) {
  10830. return this._masterMesh.getWorldMatrix();
  10831. }
  10832. if (this._currentRenderId !== this.getScene().getRenderId()) {
  10833. this.computeWorldMatrix();
  10834. }
  10835. return this._worldMatrix;
  10836. };
  10837. Object.defineProperty(AbstractMesh.prototype, "worldMatrixFromCache", {
  10838. get: function () {
  10839. return this._worldMatrix;
  10840. },
  10841. enumerable: true,
  10842. configurable: true
  10843. });
  10844. Object.defineProperty(AbstractMesh.prototype, "absolutePosition", {
  10845. get: function () {
  10846. return this._absolutePosition;
  10847. },
  10848. enumerable: true,
  10849. configurable: true
  10850. });
  10851. AbstractMesh.prototype.freezeWorldMatrix = function () {
  10852. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  10853. this.computeWorldMatrix(true);
  10854. this._isWorldMatrixFrozen = true;
  10855. };
  10856. AbstractMesh.prototype.unfreezeWorldMatrix = function () {
  10857. this._isWorldMatrixFrozen = false;
  10858. this.computeWorldMatrix(true);
  10859. };
  10860. Object.defineProperty(AbstractMesh.prototype, "isWorldMatrixFrozen", {
  10861. get: function () {
  10862. return this._isWorldMatrixFrozen;
  10863. },
  10864. enumerable: true,
  10865. configurable: true
  10866. });
  10867. AbstractMesh.prototype.rotate = function (axis, amount, space) {
  10868. axis.normalize();
  10869. if (!this.rotationQuaternion) {
  10870. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  10871. this.rotation = BABYLON.Vector3.Zero();
  10872. }
  10873. var rotationQuaternion;
  10874. if (!space || space === BABYLON.Space.LOCAL) {
  10875. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, AbstractMesh._rotationAxisCache);
  10876. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  10877. }
  10878. else {
  10879. if (this.parent) {
  10880. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  10881. invertParentWorldMatrix.invert();
  10882. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  10883. }
  10884. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, AbstractMesh._rotationAxisCache);
  10885. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  10886. }
  10887. };
  10888. AbstractMesh.prototype.translate = function (axis, distance, space) {
  10889. var displacementVector = axis.scale(distance);
  10890. if (!space || space === BABYLON.Space.LOCAL) {
  10891. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  10892. this.setPositionWithLocalVector(tempV3);
  10893. }
  10894. else {
  10895. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  10896. }
  10897. };
  10898. AbstractMesh.prototype.getAbsolutePosition = function () {
  10899. this.computeWorldMatrix();
  10900. return this._absolutePosition;
  10901. };
  10902. AbstractMesh.prototype.setAbsolutePosition = function (absolutePosition) {
  10903. if (!absolutePosition) {
  10904. return;
  10905. }
  10906. var absolutePositionX;
  10907. var absolutePositionY;
  10908. var absolutePositionZ;
  10909. if (absolutePosition.x === undefined) {
  10910. if (arguments.length < 3) {
  10911. return;
  10912. }
  10913. absolutePositionX = arguments[0];
  10914. absolutePositionY = arguments[1];
  10915. absolutePositionZ = arguments[2];
  10916. }
  10917. else {
  10918. absolutePositionX = absolutePosition.x;
  10919. absolutePositionY = absolutePosition.y;
  10920. absolutePositionZ = absolutePosition.z;
  10921. }
  10922. if (this.parent) {
  10923. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  10924. invertParentWorldMatrix.invert();
  10925. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  10926. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  10927. }
  10928. else {
  10929. this.position.x = absolutePositionX;
  10930. this.position.y = absolutePositionY;
  10931. this.position.z = absolutePositionZ;
  10932. }
  10933. };
  10934. // ================================== Point of View Movement =================================
  10935. /**
  10936. * Perform relative position change from the point of view of behind the front of the mesh.
  10937. * This is performed taking into account the meshes current rotation, so you do not have to care.
  10938. * Supports definition of mesh facing forward or backward.
  10939. * @param {number} amountRight
  10940. * @param {number} amountUp
  10941. * @param {number} amountForward
  10942. */
  10943. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  10944. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  10945. };
  10946. /**
  10947. * Calculate relative position change from the point of view of behind the front of the mesh.
  10948. * This is performed taking into account the meshes current rotation, so you do not have to care.
  10949. * Supports definition of mesh facing forward or backward.
  10950. * @param {number} amountRight
  10951. * @param {number} amountUp
  10952. * @param {number} amountForward
  10953. */
  10954. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  10955. var rotMatrix = new BABYLON.Matrix();
  10956. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  10957. rotQuaternion.toRotationMatrix(rotMatrix);
  10958. var translationDelta = BABYLON.Vector3.Zero();
  10959. var defForwardMult = this.definedFacingForward ? -1 : 1;
  10960. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  10961. return translationDelta;
  10962. };
  10963. // ================================== Point of View Rotation =================================
  10964. /**
  10965. * Perform relative rotation change from the point of view of behind the front of the mesh.
  10966. * Supports definition of mesh facing forward or backward.
  10967. * @param {number} flipBack
  10968. * @param {number} twirlClockwise
  10969. * @param {number} tiltRight
  10970. */
  10971. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  10972. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  10973. };
  10974. /**
  10975. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  10976. * Supports definition of mesh facing forward or backward.
  10977. * @param {number} flipBack
  10978. * @param {number} twirlClockwise
  10979. * @param {number} tiltRight
  10980. */
  10981. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  10982. var defForwardMult = this.definedFacingForward ? 1 : -1;
  10983. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  10984. };
  10985. AbstractMesh.prototype.setPivotMatrix = function (matrix) {
  10986. this._pivotMatrix = matrix;
  10987. this._cache.pivotMatrixUpdated = true;
  10988. };
  10989. AbstractMesh.prototype.getPivotMatrix = function () {
  10990. return this._pivotMatrix;
  10991. };
  10992. AbstractMesh.prototype._isSynchronized = function () {
  10993. if (this._isDirty) {
  10994. return false;
  10995. }
  10996. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE)
  10997. return false;
  10998. if (this._cache.pivotMatrixUpdated) {
  10999. return false;
  11000. }
  11001. if (this.infiniteDistance) {
  11002. return false;
  11003. }
  11004. if (!this._cache.position.equals(this.position))
  11005. return false;
  11006. if (this.rotationQuaternion) {
  11007. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  11008. return false;
  11009. }
  11010. if (!this._cache.rotation.equals(this.rotation))
  11011. return false;
  11012. if (!this._cache.scaling.equals(this.scaling))
  11013. return false;
  11014. return true;
  11015. };
  11016. AbstractMesh.prototype._initCache = function () {
  11017. _super.prototype._initCache.call(this);
  11018. this._cache.localMatrixUpdated = false;
  11019. this._cache.position = BABYLON.Vector3.Zero();
  11020. this._cache.scaling = BABYLON.Vector3.Zero();
  11021. this._cache.rotation = BABYLON.Vector3.Zero();
  11022. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  11023. this._cache.billboardMode = -1;
  11024. };
  11025. AbstractMesh.prototype.markAsDirty = function (property) {
  11026. if (property === "rotation") {
  11027. this.rotationQuaternion = null;
  11028. }
  11029. this._currentRenderId = Number.MAX_VALUE;
  11030. this._isDirty = true;
  11031. };
  11032. AbstractMesh.prototype._updateBoundingInfo = function () {
  11033. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  11034. this._boundingInfo.update(this.worldMatrixFromCache);
  11035. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  11036. };
  11037. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  11038. if (!this.subMeshes) {
  11039. return;
  11040. }
  11041. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  11042. var subMesh = this.subMeshes[subIndex];
  11043. if (!subMesh.IsGlobal) {
  11044. subMesh.updateBoundingInfo(matrix);
  11045. }
  11046. }
  11047. };
  11048. AbstractMesh.prototype.computeWorldMatrix = function (force) {
  11049. if (this._isWorldMatrixFrozen) {
  11050. return this._worldMatrix;
  11051. }
  11052. if (!force && (this._currentRenderId === this.getScene().getRenderId() || this.isSynchronized(true))) {
  11053. this._currentRenderId = this.getScene().getRenderId();
  11054. return this._worldMatrix;
  11055. }
  11056. this._cache.position.copyFrom(this.position);
  11057. this._cache.scaling.copyFrom(this.scaling);
  11058. this._cache.pivotMatrixUpdated = false;
  11059. this._cache.billboardMode = this.billboardMode;
  11060. this._currentRenderId = this.getScene().getRenderId();
  11061. this._isDirty = false;
  11062. // Scaling
  11063. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  11064. // Rotation
  11065. //rotate, if quaternion is set and rotation was used
  11066. if (this.rotationQuaternion) {
  11067. var len = this.rotation.length();
  11068. if (len) {
  11069. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  11070. this.rotation.copyFromFloats(0, 0, 0);
  11071. }
  11072. }
  11073. if (this.rotationQuaternion) {
  11074. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  11075. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  11076. }
  11077. else {
  11078. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  11079. this._cache.rotation.copyFrom(this.rotation);
  11080. }
  11081. // Translation
  11082. if (this.infiniteDistance && !this.parent) {
  11083. var camera = this.getScene().activeCamera;
  11084. if (camera) {
  11085. var cameraWorldMatrix = camera.getWorldMatrix();
  11086. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  11087. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  11088. }
  11089. }
  11090. else {
  11091. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  11092. }
  11093. // Composing transformations
  11094. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  11095. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  11096. // Billboarding
  11097. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE && this.getScene().activeCamera) {
  11098. BABYLON.Tmp.Vector3[0].copyFrom(this.position);
  11099. var localPosition = BABYLON.Tmp.Vector3[0];
  11100. if (this.parent && this.parent.getWorldMatrix) {
  11101. this._markSyncedWithParent();
  11102. var parentMatrix;
  11103. if (this._meshToBoneReferal) {
  11104. this.parent.getWorldMatrix().multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  11105. parentMatrix = BABYLON.Tmp.Matrix[6];
  11106. }
  11107. else {
  11108. parentMatrix = this.parent.getWorldMatrix();
  11109. }
  11110. BABYLON.Vector3.TransformNormalToRef(localPosition, parentMatrix, BABYLON.Tmp.Vector3[1]);
  11111. localPosition = BABYLON.Tmp.Vector3[1];
  11112. }
  11113. var zero = this.getScene().activeCamera.globalPosition.clone();
  11114. if (this.parent && this.parent.position) {
  11115. localPosition.addInPlace(this.parent.position);
  11116. BABYLON.Matrix.TranslationToRef(localPosition.x, localPosition.y, localPosition.z, BABYLON.Tmp.Matrix[2]);
  11117. }
  11118. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_ALL) !== AbstractMesh.BILLBOARDMODE_ALL) {
  11119. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_X)
  11120. zero.x = localPosition.x + BABYLON.Epsilon;
  11121. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_Y)
  11122. zero.y = localPosition.y + BABYLON.Epsilon;
  11123. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_Z)
  11124. zero.z = localPosition.z + BABYLON.Epsilon;
  11125. }
  11126. BABYLON.Matrix.LookAtLHToRef(localPosition, zero, BABYLON.Vector3.Up(), BABYLON.Tmp.Matrix[3]);
  11127. BABYLON.Tmp.Matrix[3].m[12] = BABYLON.Tmp.Matrix[3].m[13] = BABYLON.Tmp.Matrix[3].m[14] = 0;
  11128. BABYLON.Tmp.Matrix[3].invert();
  11129. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[3], this._localWorld);
  11130. this._rotateYByPI.multiplyToRef(this._localWorld, BABYLON.Tmp.Matrix[5]);
  11131. }
  11132. // Local world
  11133. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  11134. // Parent
  11135. if (this.parent && this.parent.getWorldMatrix && this.billboardMode === AbstractMesh.BILLBOARDMODE_NONE) {
  11136. this._markSyncedWithParent();
  11137. if (this._meshToBoneReferal) {
  11138. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  11139. BABYLON.Tmp.Matrix[6].multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), this._worldMatrix);
  11140. }
  11141. else {
  11142. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  11143. }
  11144. }
  11145. else {
  11146. this._worldMatrix.copyFrom(this._localWorld);
  11147. }
  11148. // Bounding info
  11149. this._updateBoundingInfo();
  11150. // Absolute position
  11151. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  11152. // Callbacks
  11153. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  11154. if (!this._poseMatrix) {
  11155. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  11156. }
  11157. return this._worldMatrix;
  11158. };
  11159. /**
  11160. * If you'd like to be callbacked after the mesh position, rotation or scaling has been updated
  11161. * @param func: callback function to add
  11162. */
  11163. AbstractMesh.prototype.registerAfterWorldMatrixUpdate = function (func) {
  11164. this.onAfterWorldMatrixUpdateObservable.add(func);
  11165. };
  11166. AbstractMesh.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  11167. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  11168. };
  11169. AbstractMesh.prototype.setPositionWithLocalVector = function (vector3) {
  11170. this.computeWorldMatrix();
  11171. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  11172. };
  11173. AbstractMesh.prototype.getPositionExpressedInLocalSpace = function () {
  11174. this.computeWorldMatrix();
  11175. var invLocalWorldMatrix = this._localWorld.clone();
  11176. invLocalWorldMatrix.invert();
  11177. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  11178. };
  11179. AbstractMesh.prototype.locallyTranslate = function (vector3) {
  11180. this.computeWorldMatrix(true);
  11181. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  11182. };
  11183. AbstractMesh.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  11184. /// <summary>Orients a mesh towards a target point. Mesh must be drawn facing user.</summary>
  11185. /// <param name="targetPoint" type="Vector3">The position (must be in same space as current mesh) to look at</param>
  11186. /// <param name="yawCor" type="Number">optional yaw (y-axis) correction in radians</param>
  11187. /// <param name="pitchCor" type="Number">optional pitch (x-axis) correction in radians</param>
  11188. /// <param name="rollCor" type="Number">optional roll (z-axis) correction in radians</param>
  11189. /// <returns>Mesh oriented towards targetMesh</returns>
  11190. if (yawCor === void 0) { yawCor = 0; }
  11191. if (pitchCor === void 0) { pitchCor = 0; }
  11192. if (rollCor === void 0) { rollCor = 0; }
  11193. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  11194. var dv = AbstractMesh._lookAtVectorCache;
  11195. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  11196. targetPoint.subtractToRef(pos, dv);
  11197. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  11198. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  11199. var pitch = Math.atan2(dv.y, len);
  11200. this.rotationQuaternion = this.rotationQuaternion || new BABYLON.Quaternion();
  11201. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  11202. };
  11203. AbstractMesh.prototype.attachToBone = function (bone, affectedMesh) {
  11204. this._meshToBoneReferal = affectedMesh;
  11205. this.parent = bone;
  11206. if (bone.getWorldMatrix().determinant() < 0) {
  11207. this.scalingDeterminant *= -1;
  11208. }
  11209. };
  11210. AbstractMesh.prototype.detachFromBone = function () {
  11211. if (this.parent.getWorldMatrix().determinant() < 0) {
  11212. this.scalingDeterminant *= -1;
  11213. }
  11214. this._meshToBoneReferal = null;
  11215. this.parent = null;
  11216. };
  11217. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  11218. return this._boundingInfo.isInFrustum(frustumPlanes);
  11219. };
  11220. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  11221. return this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  11222. ;
  11223. };
  11224. AbstractMesh.prototype.intersectsMesh = function (mesh, precise) {
  11225. if (!this._boundingInfo || !mesh._boundingInfo) {
  11226. return false;
  11227. }
  11228. return this._boundingInfo.intersects(mesh._boundingInfo, precise);
  11229. };
  11230. AbstractMesh.prototype.intersectsPoint = function (point) {
  11231. if (!this._boundingInfo) {
  11232. return false;
  11233. }
  11234. return this._boundingInfo.intersectsPoint(point);
  11235. };
  11236. // Physics
  11237. /**
  11238. * @Deprecated. Use new PhysicsImpostor instead.
  11239. * */
  11240. AbstractMesh.prototype.setPhysicsState = function (impostor, options) {
  11241. //legacy support
  11242. if (impostor.impostor) {
  11243. options = impostor;
  11244. impostor = impostor.impostor;
  11245. }
  11246. this.physicsImpostor = new BABYLON.PhysicsImpostor(this, impostor, options, this.getScene());
  11247. return this.physicsImpostor.physicsBody;
  11248. };
  11249. AbstractMesh.prototype.getPhysicsImpostor = function () {
  11250. return this.physicsImpostor;
  11251. };
  11252. /**
  11253. * @Deprecated. Use getPhysicsImpostor().getParam("mass");
  11254. */
  11255. AbstractMesh.prototype.getPhysicsMass = function () {
  11256. return this.physicsImpostor.getParam("mass");
  11257. };
  11258. /**
  11259. * @Deprecated. Use getPhysicsImpostor().getParam("friction");
  11260. */
  11261. AbstractMesh.prototype.getPhysicsFriction = function () {
  11262. return this.physicsImpostor.getParam("friction");
  11263. };
  11264. /**
  11265. * @Deprecated. Use getPhysicsImpostor().getParam("restitution");
  11266. */
  11267. AbstractMesh.prototype.getPhysicsRestitution = function () {
  11268. return this.physicsImpostor.getParam("restitution");
  11269. };
  11270. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  11271. if (!camera) {
  11272. camera = this.getScene().activeCamera;
  11273. }
  11274. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  11275. };
  11276. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  11277. if (!camera) {
  11278. camera = this.getScene().activeCamera;
  11279. }
  11280. return this.absolutePosition.subtract(camera.position).length();
  11281. };
  11282. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  11283. if (!this.physicsImpostor) {
  11284. return;
  11285. }
  11286. this.physicsImpostor.applyImpulse(force, contactPoint);
  11287. };
  11288. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  11289. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  11290. return;
  11291. }
  11292. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  11293. mainPivot: pivot1,
  11294. connectedPivot: pivot2,
  11295. nativeParams: options
  11296. });
  11297. };
  11298. /**
  11299. * @Deprecated
  11300. */
  11301. AbstractMesh.prototype.updatePhysicsBodyPosition = function () {
  11302. BABYLON.Tools.Warn("updatePhysicsBodyPosition() is deprecated, please use updatePhysicsBody()");
  11303. this.updatePhysicsBody();
  11304. };
  11305. /**
  11306. * @Deprecated
  11307. * Calling this function is not needed anymore.
  11308. * The physics engine takes care of transofmration automatically.
  11309. */
  11310. AbstractMesh.prototype.updatePhysicsBody = function () {
  11311. //Unneeded
  11312. };
  11313. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  11314. // Collisions
  11315. get: function () {
  11316. return this._checkCollisions;
  11317. },
  11318. set: function (collisionEnabled) {
  11319. this._checkCollisions = collisionEnabled;
  11320. if (this.getScene().workerCollisions) {
  11321. this.getScene().collisionCoordinator.onMeshUpdated(this);
  11322. }
  11323. },
  11324. enumerable: true,
  11325. configurable: true
  11326. });
  11327. AbstractMesh.prototype.moveWithCollisions = function (velocity) {
  11328. var globalPosition = this.getAbsolutePosition();
  11329. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPositionForCollisions);
  11330. this._oldPositionForCollisions.addInPlace(this.ellipsoidOffset);
  11331. this._collider.radius = this.ellipsoid;
  11332. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, velocity, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  11333. };
  11334. // Submeshes octree
  11335. /**
  11336. * This function will create an octree to help select the right submeshes for rendering, picking and collisions
  11337. * Please note that you must have a decent number of submeshes to get performance improvements when using octree
  11338. */
  11339. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  11340. if (maxCapacity === void 0) { maxCapacity = 64; }
  11341. if (maxDepth === void 0) { maxDepth = 2; }
  11342. if (!this._submeshesOctree) {
  11343. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  11344. }
  11345. this.computeWorldMatrix(true);
  11346. // Update octree
  11347. var bbox = this.getBoundingInfo().boundingBox;
  11348. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  11349. return this._submeshesOctree;
  11350. };
  11351. // Collisions
  11352. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  11353. this._generatePointsArray();
  11354. // Transformation
  11355. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  11356. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  11357. subMesh._lastColliderWorldVertices = [];
  11358. subMesh._trianglePlanes = [];
  11359. var start = subMesh.verticesStart;
  11360. var end = (subMesh.verticesStart + subMesh.verticesCount);
  11361. for (var i = start; i < end; i++) {
  11362. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  11363. }
  11364. }
  11365. // Collide
  11366. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  11367. if (collider.collisionFound) {
  11368. collider.collidedMesh = this;
  11369. }
  11370. };
  11371. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  11372. var subMeshes;
  11373. var len;
  11374. // Octrees
  11375. if (this._submeshesOctree && this.useOctreeForCollisions) {
  11376. var radius = collider.velocityWorldLength + Math.max(collider.radius.x, collider.radius.y, collider.radius.z);
  11377. var intersections = this._submeshesOctree.intersects(collider.basePointWorld, radius);
  11378. len = intersections.length;
  11379. subMeshes = intersections.data;
  11380. }
  11381. else {
  11382. subMeshes = this.subMeshes;
  11383. len = subMeshes.length;
  11384. }
  11385. for (var index = 0; index < len; index++) {
  11386. var subMesh = subMeshes[index];
  11387. // Bounding test
  11388. if (len > 1 && !subMesh._checkCollision(collider))
  11389. continue;
  11390. this._collideForSubMesh(subMesh, transformMatrix, collider);
  11391. }
  11392. };
  11393. AbstractMesh.prototype._checkCollision = function (collider) {
  11394. // Bounding box test
  11395. if (!this._boundingInfo._checkCollision(collider))
  11396. return;
  11397. // Transformation matrix
  11398. BABYLON.Matrix.ScalingToRef(1.0 / collider.radius.x, 1.0 / collider.radius.y, 1.0 / collider.radius.z, this._collisionsScalingMatrix);
  11399. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  11400. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  11401. };
  11402. // Picking
  11403. AbstractMesh.prototype._generatePointsArray = function () {
  11404. return false;
  11405. };
  11406. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  11407. var pickingInfo = new BABYLON.PickingInfo();
  11408. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  11409. return pickingInfo;
  11410. }
  11411. if (!this._generatePointsArray()) {
  11412. return pickingInfo;
  11413. }
  11414. var intersectInfo = null;
  11415. // Octrees
  11416. var subMeshes;
  11417. var len;
  11418. if (this._submeshesOctree && this.useOctreeForPicking) {
  11419. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  11420. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  11421. len = intersections.length;
  11422. subMeshes = intersections.data;
  11423. }
  11424. else {
  11425. subMeshes = this.subMeshes;
  11426. len = subMeshes.length;
  11427. }
  11428. for (var index = 0; index < len; index++) {
  11429. var subMesh = subMeshes[index];
  11430. // Bounding test
  11431. if (len > 1 && !subMesh.canIntersects(ray))
  11432. continue;
  11433. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  11434. if (currentIntersectInfo) {
  11435. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  11436. intersectInfo = currentIntersectInfo;
  11437. intersectInfo.subMeshId = index;
  11438. if (fastCheck) {
  11439. break;
  11440. }
  11441. }
  11442. }
  11443. }
  11444. if (intersectInfo) {
  11445. // Get picked point
  11446. var world = this.getWorldMatrix();
  11447. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  11448. var direction = ray.direction.clone();
  11449. direction = direction.scale(intersectInfo.distance);
  11450. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  11451. var pickedPoint = worldOrigin.add(worldDirection);
  11452. // Return result
  11453. pickingInfo.hit = true;
  11454. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  11455. pickingInfo.pickedPoint = pickedPoint;
  11456. pickingInfo.pickedMesh = this;
  11457. pickingInfo.bu = intersectInfo.bu;
  11458. pickingInfo.bv = intersectInfo.bv;
  11459. pickingInfo.faceId = intersectInfo.faceId;
  11460. pickingInfo.subMeshId = intersectInfo.subMeshId;
  11461. return pickingInfo;
  11462. }
  11463. return pickingInfo;
  11464. };
  11465. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  11466. return null;
  11467. };
  11468. AbstractMesh.prototype.releaseSubMeshes = function () {
  11469. if (this.subMeshes) {
  11470. while (this.subMeshes.length) {
  11471. this.subMeshes[0].dispose();
  11472. }
  11473. }
  11474. else {
  11475. this.subMeshes = new Array();
  11476. }
  11477. };
  11478. AbstractMesh.prototype.dispose = function (doNotRecurse) {
  11479. var _this = this;
  11480. var index;
  11481. // Action manager
  11482. if (this.actionManager) {
  11483. this.actionManager.dispose();
  11484. this.actionManager = null;
  11485. }
  11486. // Skeleton
  11487. this.skeleton = null;
  11488. // Animations
  11489. this.getScene().stopAnimation(this);
  11490. // Physics
  11491. if (this.physicsImpostor) {
  11492. this.physicsImpostor.dispose();
  11493. }
  11494. // Intersections in progress
  11495. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  11496. var other = this._intersectionsInProgress[index];
  11497. var pos = other._intersectionsInProgress.indexOf(this);
  11498. other._intersectionsInProgress.splice(pos, 1);
  11499. }
  11500. this._intersectionsInProgress = [];
  11501. // Lights
  11502. var lights = this.getScene().lights;
  11503. lights.forEach(function (light) {
  11504. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  11505. if (meshIndex !== -1) {
  11506. light.includedOnlyMeshes.splice(meshIndex, 1);
  11507. }
  11508. meshIndex = light.excludedMeshes.indexOf(_this);
  11509. if (meshIndex !== -1) {
  11510. light.excludedMeshes.splice(meshIndex, 1);
  11511. }
  11512. // Shadow generators
  11513. var generator = light.getShadowGenerator();
  11514. if (generator) {
  11515. meshIndex = generator.getShadowMap().renderList.indexOf(_this);
  11516. if (meshIndex !== -1) {
  11517. generator.getShadowMap().renderList.splice(meshIndex, 1);
  11518. }
  11519. }
  11520. });
  11521. // Edges
  11522. if (this._edgesRenderer) {
  11523. this._edgesRenderer.dispose();
  11524. this._edgesRenderer = null;
  11525. }
  11526. // SubMeshes
  11527. if (this.getClassName() !== "InstancedMesh") {
  11528. this.releaseSubMeshes();
  11529. }
  11530. // Engine
  11531. this.getScene().getEngine().wipeCaches();
  11532. // Remove from scene
  11533. this.getScene().removeMesh(this);
  11534. if (!doNotRecurse) {
  11535. // Particles
  11536. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  11537. if (this.getScene().particleSystems[index].emitter === this) {
  11538. this.getScene().particleSystems[index].dispose();
  11539. index--;
  11540. }
  11541. }
  11542. // Children
  11543. var objects = this.getDescendants(true);
  11544. for (index = 0; index < objects.length; index++) {
  11545. objects[index].dispose();
  11546. }
  11547. }
  11548. else {
  11549. var childMeshes = this.getChildMeshes(true);
  11550. for (index = 0; index < childMeshes.length; index++) {
  11551. var child = childMeshes[index];
  11552. child.parent = null;
  11553. child.computeWorldMatrix(true);
  11554. }
  11555. }
  11556. this.onAfterWorldMatrixUpdateObservable.clear();
  11557. this.onCollideObservable.clear();
  11558. this.onCollisionPositionChangeObservable.clear();
  11559. this._isDisposed = true;
  11560. _super.prototype.dispose.call(this);
  11561. };
  11562. AbstractMesh.prototype.getDirection = function (localAxis) {
  11563. var result = BABYLON.Vector3.Zero();
  11564. this.getDirectionToRef(localAxis, result);
  11565. return result;
  11566. };
  11567. AbstractMesh.prototype.getDirectionToRef = function (localAxis, result) {
  11568. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  11569. };
  11570. AbstractMesh.prototype.setPivotPoint = function (point, space) {
  11571. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  11572. if (this.getScene().getRenderId() == 0) {
  11573. this.computeWorldMatrix(true);
  11574. }
  11575. var wm = this.getWorldMatrix();
  11576. if (space == BABYLON.Space.WORLD) {
  11577. var tmat = BABYLON.Tmp.Matrix[0];
  11578. wm.invertToRef(tmat);
  11579. point = BABYLON.Vector3.TransformCoordinates(point, tmat);
  11580. }
  11581. BABYLON.Vector3.TransformCoordinatesToRef(point, wm, this.position);
  11582. this._pivotMatrix.m[12] = -point.x;
  11583. this._pivotMatrix.m[13] = -point.y;
  11584. this._pivotMatrix.m[14] = -point.z;
  11585. this._cache.pivotMatrixUpdated = true;
  11586. };
  11587. AbstractMesh.prototype.getPivotPoint = function () {
  11588. var point = BABYLON.Vector3.Zero();
  11589. this.getPivotPointToRef(point);
  11590. return point;
  11591. };
  11592. AbstractMesh.prototype.getPivotPointToRef = function (result) {
  11593. result.x = -this._pivotMatrix.m[12];
  11594. result.y = -this._pivotMatrix.m[13];
  11595. result.z = -this._pivotMatrix.m[14];
  11596. };
  11597. AbstractMesh.prototype.getAbsolutePivotPoint = function () {
  11598. var point = BABYLON.Vector3.Zero();
  11599. this.getAbsolutePivotPointToRef(point);
  11600. return point;
  11601. };
  11602. AbstractMesh.prototype.setParent = function (mesh, keepWorldPositionRotation) {
  11603. if (keepWorldPositionRotation === void 0) { keepWorldPositionRotation = false; }
  11604. var child = this;
  11605. var parent = mesh;
  11606. if (mesh == null) {
  11607. if (child.parent && keepWorldPositionRotation) {
  11608. var rotation = BABYLON.Tmp.Quaternion[0];
  11609. var position = BABYLON.Tmp.Vector3[0];
  11610. var scale = BABYLON.Tmp.Vector3[1];
  11611. child.getWorldMatrix().decompose(scale, rotation, position);
  11612. if (child.rotationQuaternion) {
  11613. child.rotationQuaternion.copyFrom(rotation);
  11614. }
  11615. else {
  11616. rotation.toEulerAnglesToRef(child.rotation);
  11617. }
  11618. child.position.x = position.x;
  11619. child.position.y = position.y;
  11620. child.position.z = position.z;
  11621. }
  11622. }
  11623. else {
  11624. if (keepWorldPositionRotation) {
  11625. var rotation = BABYLON.Tmp.Quaternion[0];
  11626. var position = BABYLON.Tmp.Vector3[0];
  11627. var scale = BABYLON.Tmp.Vector3[1];
  11628. var m1 = BABYLON.Tmp.Matrix[0];
  11629. var m2 = BABYLON.Tmp.Matrix[1];
  11630. parent.getWorldMatrix().decompose(scale, rotation, position);
  11631. rotation.toRotationMatrix(m1);
  11632. m2.setTranslation(position);
  11633. m2.multiplyToRef(m1, m1);
  11634. var invParentMatrix = BABYLON.Matrix.Invert(m1);
  11635. var m = child.getWorldMatrix().multiply(invParentMatrix);
  11636. m.decompose(scale, rotation, position);
  11637. if (child.rotationQuaternion) {
  11638. child.rotationQuaternion.copyFrom(rotation);
  11639. }
  11640. else {
  11641. rotation.toEulerAnglesToRef(child.rotation);
  11642. }
  11643. invParentMatrix = BABYLON.Matrix.Invert(parent.getWorldMatrix());
  11644. var m = child.getWorldMatrix().multiply(invParentMatrix);
  11645. m.decompose(scale, rotation, position);
  11646. child.position.x = position.x;
  11647. child.position.y = position.y;
  11648. child.position.z = position.z;
  11649. }
  11650. }
  11651. child.parent = parent;
  11652. };
  11653. AbstractMesh.prototype.addChild = function (mesh, keepWorldPositionRotation) {
  11654. if (keepWorldPositionRotation === void 0) { keepWorldPositionRotation = false; }
  11655. mesh.setParent(this, keepWorldPositionRotation);
  11656. };
  11657. AbstractMesh.prototype.removeChild = function (mesh, keepWorldPositionRotation) {
  11658. if (keepWorldPositionRotation === void 0) { keepWorldPositionRotation = false; }
  11659. mesh.setParent(null, keepWorldPositionRotation);
  11660. };
  11661. AbstractMesh.prototype.getAbsolutePivotPointToRef = function (result) {
  11662. result.x = this._pivotMatrix.m[12];
  11663. result.y = this._pivotMatrix.m[13];
  11664. result.z = this._pivotMatrix.m[14];
  11665. this.getPivotPointToRef(result);
  11666. BABYLON.Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
  11667. };
  11668. return AbstractMesh;
  11669. }(BABYLON.Node));
  11670. // Statics
  11671. AbstractMesh._BILLBOARDMODE_NONE = 0;
  11672. AbstractMesh._BILLBOARDMODE_X = 1;
  11673. AbstractMesh._BILLBOARDMODE_Y = 2;
  11674. AbstractMesh._BILLBOARDMODE_Z = 4;
  11675. AbstractMesh._BILLBOARDMODE_ALL = 7;
  11676. AbstractMesh._rotationAxisCache = new BABYLON.Quaternion();
  11677. AbstractMesh._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  11678. BABYLON.AbstractMesh = AbstractMesh;
  11679. })(BABYLON || (BABYLON = {}));
  11680. //# sourceMappingURL=babylon.abstractMesh.js.map
  11681. var BABYLON;
  11682. (function (BABYLON) {
  11683. var Light = (function (_super) {
  11684. __extends(Light, _super);
  11685. function Light(name, scene) {
  11686. var _this = _super.call(this, name, scene) || this;
  11687. _this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  11688. _this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  11689. _this.intensity = 1.0;
  11690. _this.range = Number.MAX_VALUE;
  11691. _this.includeOnlyWithLayerMask = 0;
  11692. _this.includedOnlyMeshes = new Array();
  11693. _this.excludedMeshes = new Array();
  11694. _this.excludeWithLayerMask = 0;
  11695. _this.lightmapMode = 0;
  11696. // PBR Properties.
  11697. _this.radius = 0.00001;
  11698. _this._excludedMeshesIds = new Array();
  11699. _this._includedOnlyMeshesIds = new Array();
  11700. scene.addLight(_this);
  11701. return _this;
  11702. }
  11703. Object.defineProperty(Light, "LIGHTMAP_DEFAULT", {
  11704. /**
  11705. * If every light affecting the material is in this lightmapMode,
  11706. * material.lightmapTexture adds or multiplies
  11707. * (depends on material.useLightmapAsShadowmap)
  11708. * after every other light calculations.
  11709. */
  11710. get: function () {
  11711. return Light._LIGHTMAP_DEFAULT;
  11712. },
  11713. enumerable: true,
  11714. configurable: true
  11715. });
  11716. Object.defineProperty(Light, "LIGHTMAP_SPECULAR", {
  11717. /**
  11718. * material.lightmapTexture as only diffuse lighting from this light
  11719. * adds pnly specular lighting from this light
  11720. * adds dynamic shadows
  11721. */
  11722. get: function () {
  11723. return Light._LIGHTMAP_SPECULAR;
  11724. },
  11725. enumerable: true,
  11726. configurable: true
  11727. });
  11728. Object.defineProperty(Light, "LIGHTMAP_SHADOWSONLY", {
  11729. /**
  11730. * material.lightmapTexture as only lighting
  11731. * no light calculation from this light
  11732. * only adds dynamic shadows from this light
  11733. */
  11734. get: function () {
  11735. return Light._LIGHTMAP_SHADOWSONLY;
  11736. },
  11737. enumerable: true,
  11738. configurable: true
  11739. });
  11740. Light.prototype.getClassName = function () {
  11741. return "Light";
  11742. };
  11743. /**
  11744. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  11745. */
  11746. Light.prototype.toString = function (fullDetails) {
  11747. var ret = "Name: " + this.name;
  11748. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  11749. if (this.animations) {
  11750. for (var i = 0; i < this.animations.length; i++) {
  11751. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  11752. }
  11753. }
  11754. if (fullDetails) {
  11755. }
  11756. return ret;
  11757. };
  11758. Light.prototype.getShadowGenerator = function () {
  11759. return this._shadowGenerator;
  11760. };
  11761. Light.prototype.getAbsolutePosition = function () {
  11762. return BABYLON.Vector3.Zero();
  11763. };
  11764. Light.prototype.transferToEffect = function (effect, uniformName0, uniformName1) {
  11765. };
  11766. Light.prototype._getWorldMatrix = function () {
  11767. return BABYLON.Matrix.Identity();
  11768. };
  11769. Light.prototype.canAffectMesh = function (mesh) {
  11770. if (!mesh) {
  11771. return true;
  11772. }
  11773. if (this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  11774. return false;
  11775. }
  11776. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  11777. return false;
  11778. }
  11779. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  11780. return false;
  11781. }
  11782. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  11783. return false;
  11784. }
  11785. return true;
  11786. };
  11787. Light.prototype.getWorldMatrix = function () {
  11788. this._currentRenderId = this.getScene().getRenderId();
  11789. var worldMatrix = this._getWorldMatrix();
  11790. if (this.parent && this.parent.getWorldMatrix) {
  11791. if (!this._parentedWorldMatrix) {
  11792. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  11793. }
  11794. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  11795. this._markSyncedWithParent();
  11796. return this._parentedWorldMatrix;
  11797. }
  11798. return worldMatrix;
  11799. };
  11800. Light.prototype.dispose = function () {
  11801. if (this._shadowGenerator) {
  11802. this._shadowGenerator.dispose();
  11803. this._shadowGenerator = null;
  11804. }
  11805. // Animations
  11806. this.getScene().stopAnimation(this);
  11807. // Remove from scene
  11808. this.getScene().removeLight(this);
  11809. _super.prototype.dispose.call(this);
  11810. };
  11811. Light.prototype.getTypeID = function () {
  11812. return 0;
  11813. };
  11814. Light.prototype.clone = function (name) {
  11815. return BABYLON.SerializationHelper.Clone(Light.GetConstructorFromName(this.getTypeID(), name, this.getScene()), this);
  11816. };
  11817. Light.prototype.serialize = function () {
  11818. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  11819. // Type
  11820. serializationObject.type = this.getTypeID();
  11821. // Parent
  11822. if (this.parent) {
  11823. serializationObject.parentId = this.parent.id;
  11824. }
  11825. // Inclusion / exclusions
  11826. if (this.excludedMeshes.length > 0) {
  11827. serializationObject.excludedMeshesIds = [];
  11828. this.excludedMeshes.forEach(function (mesh) {
  11829. serializationObject.excludedMeshesIds.push(mesh.id);
  11830. });
  11831. }
  11832. if (this.includedOnlyMeshes.length > 0) {
  11833. serializationObject.includedOnlyMeshesIds = [];
  11834. this.includedOnlyMeshes.forEach(function (mesh) {
  11835. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  11836. });
  11837. }
  11838. // Animations
  11839. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  11840. serializationObject.ranges = this.serializeAnimationRanges();
  11841. return serializationObject;
  11842. };
  11843. Light.GetConstructorFromName = function (type, name, scene) {
  11844. switch (type) {
  11845. case 0:
  11846. return function () { return new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), scene); };
  11847. case 1:
  11848. return function () { return new BABYLON.DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  11849. case 2:
  11850. return function () { return new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  11851. case 3:
  11852. return function () { return new BABYLON.HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  11853. }
  11854. };
  11855. Light.Parse = function (parsedLight, scene) {
  11856. var light = BABYLON.SerializationHelper.Parse(Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene), parsedLight, scene);
  11857. // Inclusion / exclusions
  11858. if (parsedLight.excludedMeshesIds) {
  11859. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  11860. }
  11861. if (parsedLight.includedOnlyMeshesIds) {
  11862. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  11863. }
  11864. // Parent
  11865. if (parsedLight.parentId) {
  11866. light._waitingParentId = parsedLight.parentId;
  11867. }
  11868. // Animations
  11869. if (parsedLight.animations) {
  11870. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  11871. var parsedAnimation = parsedLight.animations[animationIndex];
  11872. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  11873. }
  11874. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  11875. }
  11876. if (parsedLight.autoAnimate) {
  11877. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  11878. }
  11879. return light;
  11880. };
  11881. return Light;
  11882. }(BABYLON.Node));
  11883. //lightmapMode Consts
  11884. Light._LIGHTMAP_DEFAULT = 0;
  11885. Light._LIGHTMAP_SPECULAR = 1;
  11886. Light._LIGHTMAP_SHADOWSONLY = 2;
  11887. __decorate([
  11888. BABYLON.serializeAsColor3()
  11889. ], Light.prototype, "diffuse", void 0);
  11890. __decorate([
  11891. BABYLON.serializeAsColor3()
  11892. ], Light.prototype, "specular", void 0);
  11893. __decorate([
  11894. BABYLON.serialize()
  11895. ], Light.prototype, "intensity", void 0);
  11896. __decorate([
  11897. BABYLON.serialize()
  11898. ], Light.prototype, "range", void 0);
  11899. __decorate([
  11900. BABYLON.serialize()
  11901. ], Light.prototype, "includeOnlyWithLayerMask", void 0);
  11902. __decorate([
  11903. BABYLON.serialize()
  11904. ], Light.prototype, "excludeWithLayerMask", void 0);
  11905. __decorate([
  11906. BABYLON.serialize()
  11907. ], Light.prototype, "lightmapMode", void 0);
  11908. __decorate([
  11909. BABYLON.serialize()
  11910. ], Light.prototype, "radius", void 0);
  11911. BABYLON.Light = Light;
  11912. })(BABYLON || (BABYLON = {}));
  11913. //# sourceMappingURL=babylon.light.js.map
  11914. var BABYLON;
  11915. (function (BABYLON) {
  11916. var PointLight = (function (_super) {
  11917. __extends(PointLight, _super);
  11918. function PointLight(name, position, scene) {
  11919. var _this = _super.call(this, name, scene) || this;
  11920. _this.position = position;
  11921. return _this;
  11922. }
  11923. PointLight.prototype.getClassName = function () {
  11924. return "PointLight";
  11925. };
  11926. PointLight.prototype.getAbsolutePosition = function () {
  11927. return this.transformedPosition ? this.transformedPosition : this.position;
  11928. };
  11929. PointLight.prototype.computeTransformedPosition = function () {
  11930. if (this.parent && this.parent.getWorldMatrix) {
  11931. if (!this.transformedPosition) {
  11932. this.transformedPosition = BABYLON.Vector3.Zero();
  11933. }
  11934. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  11935. return true;
  11936. }
  11937. return false;
  11938. };
  11939. PointLight.prototype.transferToEffect = function (effect, positionUniformName) {
  11940. if (this.parent && this.parent.getWorldMatrix) {
  11941. this.computeTransformedPosition();
  11942. effect.setFloat4(positionUniformName, this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0);
  11943. return;
  11944. }
  11945. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, 0);
  11946. };
  11947. PointLight.prototype.needCube = function () {
  11948. return true;
  11949. };
  11950. PointLight.prototype.supportsVSM = function () {
  11951. return false;
  11952. };
  11953. PointLight.prototype.needRefreshPerFrame = function () {
  11954. return false;
  11955. };
  11956. PointLight.prototype.getShadowDirection = function (faceIndex) {
  11957. switch (faceIndex) {
  11958. case 0:
  11959. return new BABYLON.Vector3(1, 0, 0);
  11960. case 1:
  11961. return new BABYLON.Vector3(-1, 0, 0);
  11962. case 2:
  11963. return new BABYLON.Vector3(0, -1, 0);
  11964. case 3:
  11965. return new BABYLON.Vector3(0, 1, 0);
  11966. case 4:
  11967. return new BABYLON.Vector3(0, 0, 1);
  11968. case 5:
  11969. return new BABYLON.Vector3(0, 0, -1);
  11970. }
  11971. return BABYLON.Vector3.Zero();
  11972. };
  11973. PointLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  11974. var activeCamera = this.getScene().activeCamera;
  11975. BABYLON.Matrix.PerspectiveFovLHToRef(Math.PI / 2, 1.0, activeCamera.minZ, activeCamera.maxZ, matrix);
  11976. };
  11977. PointLight.prototype._getWorldMatrix = function () {
  11978. if (!this._worldMatrix) {
  11979. this._worldMatrix = BABYLON.Matrix.Identity();
  11980. }
  11981. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  11982. return this._worldMatrix;
  11983. };
  11984. PointLight.prototype.getTypeID = function () {
  11985. return 0;
  11986. };
  11987. return PointLight;
  11988. }(BABYLON.Light));
  11989. __decorate([
  11990. BABYLON.serializeAsVector3()
  11991. ], PointLight.prototype, "position", void 0);
  11992. BABYLON.PointLight = PointLight;
  11993. })(BABYLON || (BABYLON = {}));
  11994. //# sourceMappingURL=babylon.pointLight.js.map
  11995. var BABYLON;
  11996. (function (BABYLON) {
  11997. var SpotLight = (function (_super) {
  11998. __extends(SpotLight, _super);
  11999. function SpotLight(name, position, direction, angle, exponent, scene) {
  12000. var _this = _super.call(this, name, scene) || this;
  12001. _this.position = position;
  12002. _this.direction = direction;
  12003. _this.angle = angle;
  12004. _this.exponent = exponent;
  12005. return _this;
  12006. }
  12007. SpotLight.prototype.getClassName = function () {
  12008. return "SpotLight";
  12009. };
  12010. SpotLight.prototype.getAbsolutePosition = function () {
  12011. return this.transformedPosition ? this.transformedPosition : this.position;
  12012. };
  12013. SpotLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  12014. var activeCamera = this.getScene().activeCamera;
  12015. BABYLON.Matrix.PerspectiveFovLHToRef(this.angle, 1.0, activeCamera.minZ, activeCamera.maxZ, matrix);
  12016. };
  12017. SpotLight.prototype.needCube = function () {
  12018. return false;
  12019. };
  12020. SpotLight.prototype.supportsVSM = function () {
  12021. return true;
  12022. };
  12023. SpotLight.prototype.needRefreshPerFrame = function () {
  12024. return false;
  12025. };
  12026. SpotLight.prototype.getShadowDirection = function (faceIndex) {
  12027. return this.direction;
  12028. };
  12029. SpotLight.prototype.setDirectionToTarget = function (target) {
  12030. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  12031. return this.direction;
  12032. };
  12033. SpotLight.prototype.computeTransformedPosition = function () {
  12034. if (this.parent && this.parent.getWorldMatrix) {
  12035. if (!this.transformedPosition) {
  12036. this.transformedPosition = BABYLON.Vector3.Zero();
  12037. }
  12038. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  12039. return true;
  12040. }
  12041. return false;
  12042. };
  12043. SpotLight.prototype.transferToEffect = function (effect, positionUniformName, directionUniformName) {
  12044. var normalizeDirection;
  12045. if (this.parent && this.parent.getWorldMatrix) {
  12046. if (!this._transformedDirection) {
  12047. this._transformedDirection = BABYLON.Vector3.Zero();
  12048. }
  12049. this.computeTransformedPosition();
  12050. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  12051. effect.setFloat4(positionUniformName, this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent);
  12052. normalizeDirection = BABYLON.Vector3.Normalize(this._transformedDirection);
  12053. }
  12054. else {
  12055. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, this.exponent);
  12056. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  12057. }
  12058. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5));
  12059. };
  12060. SpotLight.prototype._getWorldMatrix = function () {
  12061. if (!this._worldMatrix) {
  12062. this._worldMatrix = BABYLON.Matrix.Identity();
  12063. }
  12064. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  12065. return this._worldMatrix;
  12066. };
  12067. SpotLight.prototype.getTypeID = function () {
  12068. return 2;
  12069. };
  12070. SpotLight.prototype.getRotation = function () {
  12071. this.direction.normalize();
  12072. var xaxis = BABYLON.Vector3.Cross(this.direction, BABYLON.Axis.Y);
  12073. var yaxis = BABYLON.Vector3.Cross(xaxis, this.direction);
  12074. return BABYLON.Vector3.RotationFromAxis(xaxis, yaxis, this.direction);
  12075. };
  12076. return SpotLight;
  12077. }(BABYLON.Light));
  12078. __decorate([
  12079. BABYLON.serializeAsVector3()
  12080. ], SpotLight.prototype, "position", void 0);
  12081. __decorate([
  12082. BABYLON.serializeAsVector3()
  12083. ], SpotLight.prototype, "direction", void 0);
  12084. __decorate([
  12085. BABYLON.serialize()
  12086. ], SpotLight.prototype, "angle", void 0);
  12087. __decorate([
  12088. BABYLON.serialize()
  12089. ], SpotLight.prototype, "exponent", void 0);
  12090. BABYLON.SpotLight = SpotLight;
  12091. })(BABYLON || (BABYLON = {}));
  12092. //# sourceMappingURL=babylon.spotLight.js.map
  12093. var BABYLON;
  12094. (function (BABYLON) {
  12095. var HemisphericLight = (function (_super) {
  12096. __extends(HemisphericLight, _super);
  12097. function HemisphericLight(name, direction, scene) {
  12098. var _this = _super.call(this, name, scene) || this;
  12099. _this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  12100. _this.direction = direction;
  12101. return _this;
  12102. }
  12103. HemisphericLight.prototype.getClassName = function () {
  12104. return "HemisphericLight";
  12105. };
  12106. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  12107. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  12108. return this.direction;
  12109. };
  12110. HemisphericLight.prototype.getShadowGenerator = function () {
  12111. return null;
  12112. };
  12113. HemisphericLight.prototype.transferToEffect = function (effect, directionUniformName, groundColorUniformName) {
  12114. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  12115. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0);
  12116. effect.setColor3(groundColorUniformName, this.groundColor.scale(this.intensity));
  12117. };
  12118. HemisphericLight.prototype._getWorldMatrix = function () {
  12119. if (!this._worldMatrix) {
  12120. this._worldMatrix = BABYLON.Matrix.Identity();
  12121. }
  12122. return this._worldMatrix;
  12123. };
  12124. HemisphericLight.prototype.getTypeID = function () {
  12125. return 3;
  12126. };
  12127. return HemisphericLight;
  12128. }(BABYLON.Light));
  12129. __decorate([
  12130. BABYLON.serializeAsColor3()
  12131. ], HemisphericLight.prototype, "groundColor", void 0);
  12132. __decorate([
  12133. BABYLON.serializeAsVector3()
  12134. ], HemisphericLight.prototype, "direction", void 0);
  12135. BABYLON.HemisphericLight = HemisphericLight;
  12136. })(BABYLON || (BABYLON = {}));
  12137. //# sourceMappingURL=babylon.hemisphericLight.js.map
  12138. var BABYLON;
  12139. (function (BABYLON) {
  12140. var DirectionalLight = (function (_super) {
  12141. __extends(DirectionalLight, _super);
  12142. function DirectionalLight(name, direction, scene) {
  12143. var _this = _super.call(this, name, scene) || this;
  12144. _this.shadowOrthoScale = 0.5;
  12145. _this.autoUpdateExtends = true;
  12146. // Cache
  12147. _this._orthoLeft = Number.MAX_VALUE;
  12148. _this._orthoRight = Number.MIN_VALUE;
  12149. _this._orthoTop = Number.MIN_VALUE;
  12150. _this._orthoBottom = Number.MAX_VALUE;
  12151. _this.position = direction.scale(-1);
  12152. _this.direction = direction;
  12153. return _this;
  12154. }
  12155. DirectionalLight.prototype.getClassName = function () {
  12156. return "DirectionalLight";
  12157. };
  12158. DirectionalLight.prototype.getAbsolutePosition = function () {
  12159. return this.transformedPosition ? this.transformedPosition : this.position;
  12160. };
  12161. DirectionalLight.prototype.setDirectionToTarget = function (target) {
  12162. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  12163. return this.direction;
  12164. };
  12165. DirectionalLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  12166. var activeCamera = this.getScene().activeCamera;
  12167. // Check extends
  12168. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  12169. var tempVector3 = BABYLON.Vector3.Zero();
  12170. this._orthoLeft = Number.MAX_VALUE;
  12171. this._orthoRight = Number.MIN_VALUE;
  12172. this._orthoTop = Number.MIN_VALUE;
  12173. this._orthoBottom = Number.MAX_VALUE;
  12174. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  12175. var mesh = renderList[meshIndex];
  12176. if (!mesh) {
  12177. continue;
  12178. }
  12179. var boundingInfo = mesh.getBoundingInfo();
  12180. if (!boundingInfo) {
  12181. continue;
  12182. }
  12183. var boundingBox = boundingInfo.boundingBox;
  12184. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  12185. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  12186. if (tempVector3.x < this._orthoLeft)
  12187. this._orthoLeft = tempVector3.x;
  12188. if (tempVector3.y < this._orthoBottom)
  12189. this._orthoBottom = tempVector3.y;
  12190. if (tempVector3.x > this._orthoRight)
  12191. this._orthoRight = tempVector3.x;
  12192. if (tempVector3.y > this._orthoTop)
  12193. this._orthoTop = tempVector3.y;
  12194. }
  12195. }
  12196. }
  12197. var xOffset = this._orthoRight - this._orthoLeft;
  12198. var yOffset = this._orthoTop - this._orthoBottom;
  12199. 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);
  12200. };
  12201. DirectionalLight.prototype.supportsVSM = function () {
  12202. return true;
  12203. };
  12204. DirectionalLight.prototype.needRefreshPerFrame = function () {
  12205. return true;
  12206. };
  12207. DirectionalLight.prototype.needCube = function () {
  12208. return false;
  12209. };
  12210. DirectionalLight.prototype.getShadowDirection = function (faceIndex) {
  12211. return this.direction;
  12212. };
  12213. DirectionalLight.prototype.computeTransformedPosition = function () {
  12214. if (this.parent && this.parent.getWorldMatrix) {
  12215. if (!this.transformedPosition) {
  12216. this.transformedPosition = BABYLON.Vector3.Zero();
  12217. }
  12218. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  12219. return true;
  12220. }
  12221. return false;
  12222. };
  12223. DirectionalLight.prototype.transferToEffect = function (effect, directionUniformName) {
  12224. if (this.parent && this.parent.getWorldMatrix) {
  12225. if (!this._transformedDirection) {
  12226. this._transformedDirection = BABYLON.Vector3.Zero();
  12227. }
  12228. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  12229. effect.setFloat4(directionUniformName, this._transformedDirection.x, this._transformedDirection.y, this._transformedDirection.z, 1);
  12230. return;
  12231. }
  12232. effect.setFloat4(directionUniformName, this.direction.x, this.direction.y, this.direction.z, 1);
  12233. };
  12234. DirectionalLight.prototype._getWorldMatrix = function () {
  12235. if (!this._worldMatrix) {
  12236. this._worldMatrix = BABYLON.Matrix.Identity();
  12237. }
  12238. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  12239. return this._worldMatrix;
  12240. };
  12241. DirectionalLight.prototype.getTypeID = function () {
  12242. return 1;
  12243. };
  12244. return DirectionalLight;
  12245. }(BABYLON.Light));
  12246. __decorate([
  12247. BABYLON.serializeAsVector3()
  12248. ], DirectionalLight.prototype, "position", void 0);
  12249. __decorate([
  12250. BABYLON.serializeAsVector3()
  12251. ], DirectionalLight.prototype, "direction", void 0);
  12252. __decorate([
  12253. BABYLON.serialize()
  12254. ], DirectionalLight.prototype, "shadowOrthoScale", void 0);
  12255. __decorate([
  12256. BABYLON.serialize()
  12257. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  12258. BABYLON.DirectionalLight = DirectionalLight;
  12259. })(BABYLON || (BABYLON = {}));
  12260. //# sourceMappingURL=babylon.directionalLight.js.map
  12261. var BABYLON;
  12262. (function (BABYLON) {
  12263. var ShadowGenerator = (function () {
  12264. function ShadowGenerator(mapSize, light) {
  12265. var _this = this;
  12266. // Members
  12267. this._filter = ShadowGenerator.FILTER_NONE;
  12268. this.blurScale = 2;
  12269. this._blurBoxOffset = 0;
  12270. this._bias = 0.00005;
  12271. this._lightDirection = BABYLON.Vector3.Zero();
  12272. this.forceBackFacesOnly = false;
  12273. this._darkness = 0;
  12274. this._transparencyShadow = false;
  12275. this._viewMatrix = BABYLON.Matrix.Zero();
  12276. this._projectionMatrix = BABYLON.Matrix.Zero();
  12277. this._transformMatrix = BABYLON.Matrix.Zero();
  12278. this._worldViewProjection = BABYLON.Matrix.Zero();
  12279. this._currentFaceIndex = 0;
  12280. this._currentFaceIndexCache = 0;
  12281. this._useFullFloat = true;
  12282. this._light = light;
  12283. this._scene = light.getScene();
  12284. this._mapSize = mapSize;
  12285. light._shadowGenerator = this;
  12286. // Texture type fallback from float to int if not supported.
  12287. var textureType;
  12288. var caps = this._scene.getEngine().getCaps();
  12289. if (caps.textureFloat && caps.textureFloatLinearFiltering && caps.textureFloatRender) {
  12290. this._useFullFloat = true;
  12291. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  12292. }
  12293. else {
  12294. this._useFullFloat = false;
  12295. textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  12296. }
  12297. // Render target
  12298. this._shadowMap = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, this._scene, false, true, textureType, light.needCube());
  12299. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  12300. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  12301. this._shadowMap.anisotropicFilteringLevel = 1;
  12302. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  12303. this._shadowMap.renderParticles = false;
  12304. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  12305. _this._currentFaceIndex = faceIndex;
  12306. });
  12307. this._shadowMap.onAfterUnbindObservable.add(function () {
  12308. if (!_this.useBlurVarianceShadowMap) {
  12309. return;
  12310. }
  12311. if (!_this._shadowMap2) {
  12312. _this._shadowMap2 = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, _this._scene, false, true, textureType);
  12313. _this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  12314. _this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  12315. _this._shadowMap2.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  12316. _this._downSamplePostprocess = new BABYLON.PassPostProcess("downScale", 1.0 / _this.blurScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, _this._scene.getEngine());
  12317. _this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  12318. effect.setTexture("textureSampler", _this._shadowMap);
  12319. });
  12320. _this.blurBoxOffset = 1;
  12321. }
  12322. _this._scene.postProcessManager.directRender([_this._downSamplePostprocess, _this._boxBlurPostprocess], _this._shadowMap2.getInternalTexture());
  12323. });
  12324. // Custom render function
  12325. var renderSubMesh = function (subMesh) {
  12326. var mesh = subMesh.getRenderingMesh();
  12327. var scene = _this._scene;
  12328. var engine = scene.getEngine();
  12329. // Culling
  12330. engine.setState(subMesh.getMaterial().backFaceCulling);
  12331. // Managing instances
  12332. var batch = mesh._getInstancesRenderList(subMesh._id);
  12333. if (batch.mustReturn) {
  12334. return;
  12335. }
  12336. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  12337. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  12338. engine.enableEffect(_this._effect);
  12339. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  12340. var material = subMesh.getMaterial();
  12341. _this._effect.setMatrix("viewProjection", _this.getTransformMatrix());
  12342. _this._effect.setVector3("lightPosition", _this.getLight().position);
  12343. if (_this.getLight().needCube()) {
  12344. _this._effect.setFloat2("depthValues", scene.activeCamera.minZ, scene.activeCamera.maxZ);
  12345. }
  12346. // Alpha test
  12347. if (material && material.needAlphaTesting()) {
  12348. var alphaTexture = material.getAlphaTestTexture();
  12349. _this._effect.setTexture("diffuseSampler", alphaTexture);
  12350. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  12351. }
  12352. // Bones
  12353. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  12354. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  12355. }
  12356. if (_this.forceBackFacesOnly) {
  12357. engine.setState(true, 0, false, true);
  12358. }
  12359. // Draw
  12360. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  12361. if (_this.forceBackFacesOnly) {
  12362. engine.setState(true, 0, false, false);
  12363. }
  12364. }
  12365. else {
  12366. // Need to reset refresh rate of the shadowMap
  12367. _this._shadowMap.resetRefreshCounter();
  12368. }
  12369. };
  12370. this._shadowMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  12371. var index;
  12372. for (index = 0; index < opaqueSubMeshes.length; index++) {
  12373. renderSubMesh(opaqueSubMeshes.data[index]);
  12374. }
  12375. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  12376. renderSubMesh(alphaTestSubMeshes.data[index]);
  12377. }
  12378. if (_this._transparencyShadow) {
  12379. for (index = 0; index < transparentSubMeshes.length; index++) {
  12380. renderSubMesh(transparentSubMeshes.data[index]);
  12381. }
  12382. }
  12383. };
  12384. this._shadowMap.onClearObservable.add(function (engine) {
  12385. if (_this.useBlurVarianceShadowMap || _this.useVarianceShadowMap) {
  12386. engine.clear(new BABYLON.Color4(0, 0, 0, 0), true, true, true);
  12387. }
  12388. else {
  12389. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  12390. }
  12391. });
  12392. }
  12393. Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
  12394. // Static
  12395. get: function () {
  12396. return ShadowGenerator._FILTER_NONE;
  12397. },
  12398. enumerable: true,
  12399. configurable: true
  12400. });
  12401. Object.defineProperty(ShadowGenerator, "FILTER_VARIANCESHADOWMAP", {
  12402. get: function () {
  12403. return ShadowGenerator._FILTER_VARIANCESHADOWMAP;
  12404. },
  12405. enumerable: true,
  12406. configurable: true
  12407. });
  12408. Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
  12409. get: function () {
  12410. return ShadowGenerator._FILTER_POISSONSAMPLING;
  12411. },
  12412. enumerable: true,
  12413. configurable: true
  12414. });
  12415. Object.defineProperty(ShadowGenerator, "FILTER_BLURVARIANCESHADOWMAP", {
  12416. get: function () {
  12417. return ShadowGenerator._FILTER_BLURVARIANCESHADOWMAP;
  12418. },
  12419. enumerable: true,
  12420. configurable: true
  12421. });
  12422. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  12423. get: function () {
  12424. return this._bias;
  12425. },
  12426. set: function (bias) {
  12427. this._bias = bias;
  12428. },
  12429. enumerable: true,
  12430. configurable: true
  12431. });
  12432. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  12433. get: function () {
  12434. return this._blurBoxOffset;
  12435. },
  12436. set: function (value) {
  12437. var _this = this;
  12438. if (this._blurBoxOffset === value) {
  12439. return;
  12440. }
  12441. this._blurBoxOffset = value;
  12442. if (this._boxBlurPostprocess) {
  12443. this._boxBlurPostprocess.dispose();
  12444. }
  12445. 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);
  12446. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  12447. effect.setFloat2("screenSize", _this._mapSize / _this.blurScale, _this._mapSize / _this.blurScale);
  12448. });
  12449. },
  12450. enumerable: true,
  12451. configurable: true
  12452. });
  12453. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  12454. get: function () {
  12455. return this._filter;
  12456. },
  12457. set: function (value) {
  12458. if (this._filter === value) {
  12459. return;
  12460. }
  12461. this._filter = value;
  12462. if (this.useVarianceShadowMap || this.useBlurVarianceShadowMap || this.usePoissonSampling) {
  12463. this._shadowMap.anisotropicFilteringLevel = 16;
  12464. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  12465. }
  12466. else {
  12467. this._shadowMap.anisotropicFilteringLevel = 1;
  12468. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  12469. }
  12470. },
  12471. enumerable: true,
  12472. configurable: true
  12473. });
  12474. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  12475. get: function () {
  12476. return this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP && this._light.supportsVSM();
  12477. },
  12478. set: function (value) {
  12479. this.filter = (value ? ShadowGenerator.FILTER_VARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  12480. },
  12481. enumerable: true,
  12482. configurable: true
  12483. });
  12484. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  12485. get: function () {
  12486. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING ||
  12487. (!this._light.supportsVSM() && (this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP ||
  12488. this.filter === ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP));
  12489. },
  12490. set: function (value) {
  12491. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  12492. },
  12493. enumerable: true,
  12494. configurable: true
  12495. });
  12496. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  12497. get: function () {
  12498. return this.filter === ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP && this._light.supportsVSM();
  12499. },
  12500. set: function (value) {
  12501. this.filter = (value ? ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  12502. },
  12503. enumerable: true,
  12504. configurable: true
  12505. });
  12506. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  12507. var defines = [];
  12508. if (this._useFullFloat) {
  12509. defines.push("#define FULLFLOAT");
  12510. }
  12511. if (this.useVarianceShadowMap || this.useBlurVarianceShadowMap) {
  12512. defines.push("#define VSM");
  12513. }
  12514. if (this.getLight().needCube()) {
  12515. defines.push("#define CUBEMAP");
  12516. }
  12517. var attribs = [BABYLON.VertexBuffer.PositionKind];
  12518. var mesh = subMesh.getMesh();
  12519. var material = subMesh.getMaterial();
  12520. // Alpha test
  12521. if (material && material.needAlphaTesting()) {
  12522. defines.push("#define ALPHATEST");
  12523. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  12524. attribs.push(BABYLON.VertexBuffer.UVKind);
  12525. defines.push("#define UV1");
  12526. }
  12527. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  12528. var alphaTexture = material.getAlphaTestTexture();
  12529. if (alphaTexture.coordinatesIndex === 1) {
  12530. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  12531. defines.push("#define UV2");
  12532. }
  12533. }
  12534. }
  12535. // Bones
  12536. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  12537. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  12538. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  12539. if (mesh.numBoneInfluencers > 4) {
  12540. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  12541. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  12542. }
  12543. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  12544. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  12545. }
  12546. else {
  12547. defines.push("#define NUM_BONE_INFLUENCERS 0");
  12548. }
  12549. // Instances
  12550. if (useInstances) {
  12551. defines.push("#define INSTANCES");
  12552. attribs.push("world0");
  12553. attribs.push("world1");
  12554. attribs.push("world2");
  12555. attribs.push("world3");
  12556. }
  12557. // Get correct effect
  12558. var join = defines.join("\n");
  12559. if (this._cachedDefines !== join) {
  12560. this._cachedDefines = join;
  12561. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightPosition", "depthValues"], ["diffuseSampler"], join);
  12562. }
  12563. return this._effect.isReady();
  12564. };
  12565. ShadowGenerator.prototype.getShadowMap = function () {
  12566. return this._shadowMap;
  12567. };
  12568. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  12569. if (this._shadowMap2) {
  12570. return this._shadowMap2;
  12571. }
  12572. return this._shadowMap;
  12573. };
  12574. ShadowGenerator.prototype.getLight = function () {
  12575. return this._light;
  12576. };
  12577. // Methods
  12578. ShadowGenerator.prototype.getTransformMatrix = function () {
  12579. var scene = this._scene;
  12580. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  12581. return this._transformMatrix;
  12582. }
  12583. this._currentRenderID = scene.getRenderId();
  12584. this._currentFaceIndexCache = this._currentFaceIndex;
  12585. var lightPosition = this._light.position;
  12586. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  12587. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  12588. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  12589. }
  12590. if (this._light.computeTransformedPosition()) {
  12591. lightPosition = this._light.transformedPosition;
  12592. }
  12593. if (this._light.needRefreshPerFrame() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  12594. this._cachedPosition = lightPosition.clone();
  12595. this._cachedDirection = this._lightDirection.clone();
  12596. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  12597. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, this.getShadowMap().renderList);
  12598. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  12599. }
  12600. return this._transformMatrix;
  12601. };
  12602. ShadowGenerator.prototype.getDarkness = function () {
  12603. return this._darkness;
  12604. };
  12605. ShadowGenerator.prototype.setDarkness = function (darkness) {
  12606. if (darkness >= 1.0)
  12607. this._darkness = 1.0;
  12608. else if (darkness <= 0.0)
  12609. this._darkness = 0.0;
  12610. else
  12611. this._darkness = darkness;
  12612. };
  12613. ShadowGenerator.prototype.setTransparencyShadow = function (hasShadow) {
  12614. this._transparencyShadow = hasShadow;
  12615. };
  12616. ShadowGenerator.prototype._packHalf = function (depth) {
  12617. var scale = depth * 255.0;
  12618. var fract = scale - Math.floor(scale);
  12619. return new BABYLON.Vector2(depth - fract / 255.0, fract);
  12620. };
  12621. ShadowGenerator.prototype.dispose = function () {
  12622. this._shadowMap.dispose();
  12623. if (this._shadowMap2) {
  12624. this._shadowMap2.dispose();
  12625. }
  12626. if (this._downSamplePostprocess) {
  12627. this._downSamplePostprocess.dispose();
  12628. }
  12629. if (this._boxBlurPostprocess) {
  12630. this._boxBlurPostprocess.dispose();
  12631. }
  12632. this._light._shadowGenerator = null;
  12633. };
  12634. ShadowGenerator.prototype.serialize = function () {
  12635. var serializationObject = {};
  12636. serializationObject.lightId = this._light.id;
  12637. serializationObject.mapSize = this.getShadowMap().getRenderSize();
  12638. serializationObject.useVarianceShadowMap = this.useVarianceShadowMap;
  12639. serializationObject.usePoissonSampling = this.usePoissonSampling;
  12640. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  12641. serializationObject.renderList = [];
  12642. for (var meshIndex = 0; meshIndex < this.getShadowMap().renderList.length; meshIndex++) {
  12643. var mesh = this.getShadowMap().renderList[meshIndex];
  12644. serializationObject.renderList.push(mesh.id);
  12645. }
  12646. return serializationObject;
  12647. };
  12648. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  12649. //casting to point light, as light is missing the position attr and typescript complains.
  12650. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  12651. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  12652. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  12653. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  12654. meshes.forEach(function (mesh) {
  12655. shadowGenerator.getShadowMap().renderList.push(mesh);
  12656. });
  12657. }
  12658. if (parsedShadowGenerator.usePoissonSampling) {
  12659. shadowGenerator.usePoissonSampling = true;
  12660. }
  12661. else if (parsedShadowGenerator.useVarianceShadowMap) {
  12662. shadowGenerator.useVarianceShadowMap = true;
  12663. }
  12664. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  12665. shadowGenerator.useBlurVarianceShadowMap = true;
  12666. if (parsedShadowGenerator.blurScale) {
  12667. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  12668. }
  12669. if (parsedShadowGenerator.blurBoxOffset) {
  12670. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  12671. }
  12672. }
  12673. if (parsedShadowGenerator.bias !== undefined) {
  12674. shadowGenerator.bias = parsedShadowGenerator.bias;
  12675. }
  12676. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  12677. return shadowGenerator;
  12678. };
  12679. return ShadowGenerator;
  12680. }());
  12681. ShadowGenerator._FILTER_NONE = 0;
  12682. ShadowGenerator._FILTER_VARIANCESHADOWMAP = 1;
  12683. ShadowGenerator._FILTER_POISSONSAMPLING = 2;
  12684. ShadowGenerator._FILTER_BLURVARIANCESHADOWMAP = 3;
  12685. BABYLON.ShadowGenerator = ShadowGenerator;
  12686. })(BABYLON || (BABYLON = {}));
  12687. //# sourceMappingURL=babylon.shadowGenerator.js.map
  12688. var BABYLON;
  12689. (function (BABYLON) {
  12690. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  12691. if (boxMin.x > sphereCenter.x + sphereRadius)
  12692. return false;
  12693. if (sphereCenter.x - sphereRadius > boxMax.x)
  12694. return false;
  12695. if (boxMin.y > sphereCenter.y + sphereRadius)
  12696. return false;
  12697. if (sphereCenter.y - sphereRadius > boxMax.y)
  12698. return false;
  12699. if (boxMin.z > sphereCenter.z + sphereRadius)
  12700. return false;
  12701. if (sphereCenter.z - sphereRadius > boxMax.z)
  12702. return false;
  12703. return true;
  12704. };
  12705. var getLowestRoot = (function () {
  12706. var result = { root: 0, found: false };
  12707. return function (a, b, c, maxR) {
  12708. result.root = 0;
  12709. result.found = false;
  12710. var determinant = b * b - 4.0 * a * c;
  12711. if (determinant < 0)
  12712. return result;
  12713. var sqrtD = Math.sqrt(determinant);
  12714. var r1 = (-b - sqrtD) / (2.0 * a);
  12715. var r2 = (-b + sqrtD) / (2.0 * a);
  12716. if (r1 > r2) {
  12717. var temp = r2;
  12718. r2 = r1;
  12719. r1 = temp;
  12720. }
  12721. if (r1 > 0 && r1 < maxR) {
  12722. result.root = r1;
  12723. result.found = true;
  12724. return result;
  12725. }
  12726. if (r2 > 0 && r2 < maxR) {
  12727. result.root = r2;
  12728. result.found = true;
  12729. return result;
  12730. }
  12731. return result;
  12732. };
  12733. })();
  12734. var Collider = (function () {
  12735. function Collider() {
  12736. this.radius = new BABYLON.Vector3(1, 1, 1);
  12737. this.retry = 0;
  12738. this.basePointWorld = BABYLON.Vector3.Zero();
  12739. this.velocityWorld = BABYLON.Vector3.Zero();
  12740. this.normalizedVelocity = BABYLON.Vector3.Zero();
  12741. this._collisionPoint = BABYLON.Vector3.Zero();
  12742. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  12743. this._tempVector = BABYLON.Vector3.Zero();
  12744. this._tempVector2 = BABYLON.Vector3.Zero();
  12745. this._tempVector3 = BABYLON.Vector3.Zero();
  12746. this._tempVector4 = BABYLON.Vector3.Zero();
  12747. this._edge = BABYLON.Vector3.Zero();
  12748. this._baseToVertex = BABYLON.Vector3.Zero();
  12749. this._destinationPoint = BABYLON.Vector3.Zero();
  12750. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  12751. this._displacementVector = BABYLON.Vector3.Zero();
  12752. }
  12753. // Methods
  12754. Collider.prototype._initialize = function (source, dir, e) {
  12755. this.velocity = dir;
  12756. BABYLON.Vector3.NormalizeToRef(dir, this.normalizedVelocity);
  12757. this.basePoint = source;
  12758. source.multiplyToRef(this.radius, this.basePointWorld);
  12759. dir.multiplyToRef(this.radius, this.velocityWorld);
  12760. this.velocityWorldLength = this.velocityWorld.length();
  12761. this.epsilon = e;
  12762. this.collisionFound = false;
  12763. };
  12764. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  12765. pa.subtractToRef(point, this._tempVector);
  12766. pb.subtractToRef(point, this._tempVector2);
  12767. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  12768. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  12769. if (d < 0)
  12770. return false;
  12771. pc.subtractToRef(point, this._tempVector3);
  12772. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  12773. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  12774. if (d < 0)
  12775. return false;
  12776. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  12777. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  12778. return d >= 0;
  12779. };
  12780. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  12781. var distance = BABYLON.Vector3.Distance(this.basePointWorld, sphereCenter);
  12782. var max = Math.max(this.radius.x, this.radius.y, this.radius.z);
  12783. if (distance > this.velocityWorldLength + max + sphereRadius) {
  12784. return false;
  12785. }
  12786. if (!intersectBoxAASphere(vecMin, vecMax, this.basePointWorld, this.velocityWorldLength + max))
  12787. return false;
  12788. return true;
  12789. };
  12790. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  12791. var t0;
  12792. var embeddedInPlane = false;
  12793. //defensive programming, actually not needed.
  12794. if (!trianglePlaneArray) {
  12795. trianglePlaneArray = [];
  12796. }
  12797. if (!trianglePlaneArray[faceIndex]) {
  12798. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  12799. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  12800. }
  12801. var trianglePlane = trianglePlaneArray[faceIndex];
  12802. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this.normalizedVelocity, 0))
  12803. return;
  12804. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this.basePoint);
  12805. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this.velocity);
  12806. if (normalDotVelocity == 0) {
  12807. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  12808. return;
  12809. embeddedInPlane = true;
  12810. t0 = 0;
  12811. }
  12812. else {
  12813. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  12814. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  12815. if (t0 > t1) {
  12816. var temp = t1;
  12817. t1 = t0;
  12818. t0 = temp;
  12819. }
  12820. if (t0 > 1.0 || t1 < 0.0)
  12821. return;
  12822. if (t0 < 0)
  12823. t0 = 0;
  12824. if (t0 > 1.0)
  12825. t0 = 1.0;
  12826. }
  12827. this._collisionPoint.copyFromFloats(0, 0, 0);
  12828. var found = false;
  12829. var t = 1.0;
  12830. if (!embeddedInPlane) {
  12831. this.basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  12832. this.velocity.scaleToRef(t0, this._tempVector);
  12833. this._planeIntersectionPoint.addInPlace(this._tempVector);
  12834. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  12835. found = true;
  12836. t = t0;
  12837. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  12838. }
  12839. }
  12840. if (!found) {
  12841. var velocitySquaredLength = this.velocity.lengthSquared();
  12842. var a = velocitySquaredLength;
  12843. this.basePoint.subtractToRef(p1, this._tempVector);
  12844. var b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  12845. var c = this._tempVector.lengthSquared() - 1.0;
  12846. var lowestRoot = getLowestRoot(a, b, c, t);
  12847. if (lowestRoot.found) {
  12848. t = lowestRoot.root;
  12849. found = true;
  12850. this._collisionPoint.copyFrom(p1);
  12851. }
  12852. this.basePoint.subtractToRef(p2, this._tempVector);
  12853. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  12854. c = this._tempVector.lengthSquared() - 1.0;
  12855. lowestRoot = getLowestRoot(a, b, c, t);
  12856. if (lowestRoot.found) {
  12857. t = lowestRoot.root;
  12858. found = true;
  12859. this._collisionPoint.copyFrom(p2);
  12860. }
  12861. this.basePoint.subtractToRef(p3, this._tempVector);
  12862. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  12863. c = this._tempVector.lengthSquared() - 1.0;
  12864. lowestRoot = getLowestRoot(a, b, c, t);
  12865. if (lowestRoot.found) {
  12866. t = lowestRoot.root;
  12867. found = true;
  12868. this._collisionPoint.copyFrom(p3);
  12869. }
  12870. p2.subtractToRef(p1, this._edge);
  12871. p1.subtractToRef(this.basePoint, this._baseToVertex);
  12872. var edgeSquaredLength = this._edge.lengthSquared();
  12873. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  12874. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  12875. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  12876. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  12877. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  12878. lowestRoot = getLowestRoot(a, b, c, t);
  12879. if (lowestRoot.found) {
  12880. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  12881. if (f >= 0.0 && f <= 1.0) {
  12882. t = lowestRoot.root;
  12883. found = true;
  12884. this._edge.scaleInPlace(f);
  12885. p1.addToRef(this._edge, this._collisionPoint);
  12886. }
  12887. }
  12888. p3.subtractToRef(p2, this._edge);
  12889. p2.subtractToRef(this.basePoint, this._baseToVertex);
  12890. edgeSquaredLength = this._edge.lengthSquared();
  12891. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  12892. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  12893. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  12894. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  12895. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  12896. lowestRoot = getLowestRoot(a, b, c, t);
  12897. if (lowestRoot.found) {
  12898. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  12899. if (f >= 0.0 && f <= 1.0) {
  12900. t = lowestRoot.root;
  12901. found = true;
  12902. this._edge.scaleInPlace(f);
  12903. p2.addToRef(this._edge, this._collisionPoint);
  12904. }
  12905. }
  12906. p1.subtractToRef(p3, this._edge);
  12907. p3.subtractToRef(this.basePoint, this._baseToVertex);
  12908. edgeSquaredLength = this._edge.lengthSquared();
  12909. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  12910. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  12911. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  12912. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  12913. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  12914. lowestRoot = getLowestRoot(a, b, c, t);
  12915. if (lowestRoot.found) {
  12916. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  12917. if (f >= 0.0 && f <= 1.0) {
  12918. t = lowestRoot.root;
  12919. found = true;
  12920. this._edge.scaleInPlace(f);
  12921. p3.addToRef(this._edge, this._collisionPoint);
  12922. }
  12923. }
  12924. }
  12925. if (found) {
  12926. var distToCollision = t * this.velocity.length();
  12927. if (!this.collisionFound || distToCollision < this.nearestDistance) {
  12928. if (!this.intersectionPoint) {
  12929. this.intersectionPoint = this._collisionPoint.clone();
  12930. }
  12931. else {
  12932. this.intersectionPoint.copyFrom(this._collisionPoint);
  12933. }
  12934. this.nearestDistance = distToCollision;
  12935. this.collisionFound = true;
  12936. }
  12937. }
  12938. };
  12939. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  12940. for (var i = indexStart; i < indexEnd; i += 3) {
  12941. var p1 = pts[indices[i] - decal];
  12942. var p2 = pts[indices[i + 1] - decal];
  12943. var p3 = pts[indices[i + 2] - decal];
  12944. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  12945. }
  12946. };
  12947. Collider.prototype._getResponse = function (pos, vel) {
  12948. pos.addToRef(vel, this._destinationPoint);
  12949. vel.scaleInPlace((this.nearestDistance / vel.length()));
  12950. this.basePoint.addToRef(vel, pos);
  12951. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  12952. this._slidePlaneNormal.normalize();
  12953. this._slidePlaneNormal.scaleToRef(this.epsilon, this._displacementVector);
  12954. pos.addInPlace(this._displacementVector);
  12955. this.intersectionPoint.addInPlace(this._displacementVector);
  12956. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  12957. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  12958. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  12959. };
  12960. return Collider;
  12961. }());
  12962. BABYLON.Collider = Collider;
  12963. })(BABYLON || (BABYLON = {}));
  12964. //# sourceMappingURL=babylon.collider.js.map
  12965. var BABYLON;
  12966. (function (BABYLON) {
  12967. //WebWorker code will be inserted to this variable.
  12968. BABYLON.CollisionWorker = "";
  12969. var WorkerTaskType;
  12970. (function (WorkerTaskType) {
  12971. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  12972. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  12973. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  12974. })(WorkerTaskType = BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  12975. var WorkerReplyType;
  12976. (function (WorkerReplyType) {
  12977. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  12978. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  12979. })(WorkerReplyType = BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  12980. var CollisionCoordinatorWorker = (function () {
  12981. function CollisionCoordinatorWorker() {
  12982. var _this = this;
  12983. this._scaledPosition = BABYLON.Vector3.Zero();
  12984. this._scaledVelocity = BABYLON.Vector3.Zero();
  12985. this.onMeshUpdated = function (mesh) {
  12986. _this._addUpdateMeshesList[mesh.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(mesh);
  12987. };
  12988. this.onGeometryUpdated = function (geometry) {
  12989. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  12990. };
  12991. this._afterRender = function () {
  12992. if (!_this._init)
  12993. return;
  12994. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  12995. return;
  12996. }
  12997. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  12998. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  12999. if (_this._runningUpdated > 4) {
  13000. return;
  13001. }
  13002. ++_this._runningUpdated;
  13003. var payload = {
  13004. updatedMeshes: _this._addUpdateMeshesList,
  13005. updatedGeometries: _this._addUpdateGeometriesList,
  13006. removedGeometries: _this._toRemoveGeometryArray,
  13007. removedMeshes: _this._toRemoveMeshesArray
  13008. };
  13009. var message = {
  13010. payload: payload,
  13011. taskType: WorkerTaskType.UPDATE
  13012. };
  13013. var serializable = [];
  13014. for (var id in payload.updatedGeometries) {
  13015. if (payload.updatedGeometries.hasOwnProperty(id)) {
  13016. //prepare transferables
  13017. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  13018. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  13019. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  13020. }
  13021. }
  13022. _this._worker.postMessage(message, serializable);
  13023. _this._addUpdateMeshesList = {};
  13024. _this._addUpdateGeometriesList = {};
  13025. _this._toRemoveGeometryArray = [];
  13026. _this._toRemoveMeshesArray = [];
  13027. };
  13028. this._onMessageFromWorker = function (e) {
  13029. var returnData = e.data;
  13030. if (returnData.error != WorkerReplyType.SUCCESS) {
  13031. //TODO what errors can be returned from the worker?
  13032. BABYLON.Tools.Warn("error returned from worker!");
  13033. return;
  13034. }
  13035. switch (returnData.taskType) {
  13036. case WorkerTaskType.INIT:
  13037. _this._init = true;
  13038. //Update the worked with ALL of the scene's current state
  13039. _this._scene.meshes.forEach(function (mesh) {
  13040. _this.onMeshAdded(mesh);
  13041. });
  13042. _this._scene.getGeometries().forEach(function (geometry) {
  13043. _this.onGeometryAdded(geometry);
  13044. });
  13045. break;
  13046. case WorkerTaskType.UPDATE:
  13047. _this._runningUpdated--;
  13048. break;
  13049. case WorkerTaskType.COLLIDE:
  13050. _this._runningCollisionTask = false;
  13051. var returnPayload = returnData.payload;
  13052. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  13053. return;
  13054. _this._collisionsCallbackArray[returnPayload.collisionId](returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId));
  13055. //cleanup
  13056. _this._collisionsCallbackArray[returnPayload.collisionId] = undefined;
  13057. break;
  13058. }
  13059. };
  13060. this._collisionsCallbackArray = [];
  13061. this._init = false;
  13062. this._runningUpdated = 0;
  13063. this._runningCollisionTask = false;
  13064. this._addUpdateMeshesList = {};
  13065. this._addUpdateGeometriesList = {};
  13066. this._toRemoveGeometryArray = [];
  13067. this._toRemoveMeshesArray = [];
  13068. }
  13069. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, velocity, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  13070. if (!this._init)
  13071. return;
  13072. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  13073. return;
  13074. position.divideToRef(collider.radius, this._scaledPosition);
  13075. velocity.divideToRef(collider.radius, this._scaledVelocity);
  13076. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  13077. var payload = {
  13078. collider: {
  13079. position: this._scaledPosition.asArray(),
  13080. velocity: this._scaledVelocity.asArray(),
  13081. radius: collider.radius.asArray()
  13082. },
  13083. collisionId: collisionIndex,
  13084. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  13085. maximumRetry: maximumRetry
  13086. };
  13087. var message = {
  13088. payload: payload,
  13089. taskType: WorkerTaskType.COLLIDE
  13090. };
  13091. this._worker.postMessage(message);
  13092. };
  13093. CollisionCoordinatorWorker.prototype.init = function (scene) {
  13094. this._scene = scene;
  13095. this._scene.registerAfterRender(this._afterRender);
  13096. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  13097. this._worker = new Worker(workerUrl);
  13098. this._worker.onmessage = this._onMessageFromWorker;
  13099. var message = {
  13100. payload: {},
  13101. taskType: WorkerTaskType.INIT
  13102. };
  13103. this._worker.postMessage(message);
  13104. };
  13105. CollisionCoordinatorWorker.prototype.destroy = function () {
  13106. this._scene.unregisterAfterRender(this._afterRender);
  13107. this._worker.terminate();
  13108. };
  13109. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  13110. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  13111. this.onMeshUpdated(mesh);
  13112. };
  13113. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  13114. this._toRemoveMeshesArray.push(mesh.uniqueId);
  13115. };
  13116. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  13117. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  13118. geometry.onGeometryUpdated = this.onGeometryUpdated;
  13119. this.onGeometryUpdated(geometry);
  13120. };
  13121. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  13122. this._toRemoveGeometryArray.push(geometry.id);
  13123. };
  13124. return CollisionCoordinatorWorker;
  13125. }());
  13126. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  13127. var submeshes = [];
  13128. if (mesh.subMeshes) {
  13129. submeshes = mesh.subMeshes.map(function (sm, idx) {
  13130. return {
  13131. position: idx,
  13132. verticesStart: sm.verticesStart,
  13133. verticesCount: sm.verticesCount,
  13134. indexStart: sm.indexStart,
  13135. indexCount: sm.indexCount,
  13136. hasMaterial: !!sm.getMaterial(),
  13137. sphereCenter: sm.getBoundingInfo().boundingSphere.centerWorld.asArray(),
  13138. sphereRadius: sm.getBoundingInfo().boundingSphere.radiusWorld,
  13139. boxMinimum: sm.getBoundingInfo().boundingBox.minimumWorld.asArray(),
  13140. boxMaximum: sm.getBoundingInfo().boundingBox.maximumWorld.asArray()
  13141. };
  13142. });
  13143. }
  13144. var geometryId = null;
  13145. if (mesh instanceof BABYLON.Mesh) {
  13146. geometryId = mesh.geometry ? mesh.geometry.id : null;
  13147. }
  13148. else if (mesh instanceof BABYLON.InstancedMesh) {
  13149. geometryId = (mesh.sourceMesh && mesh.sourceMesh.geometry) ? mesh.sourceMesh.geometry.id : null;
  13150. }
  13151. return {
  13152. uniqueId: mesh.uniqueId,
  13153. id: mesh.id,
  13154. name: mesh.name,
  13155. geometryId: geometryId,
  13156. sphereCenter: mesh.getBoundingInfo().boundingSphere.centerWorld.asArray(),
  13157. sphereRadius: mesh.getBoundingInfo().boundingSphere.radiusWorld,
  13158. boxMinimum: mesh.getBoundingInfo().boundingBox.minimumWorld.asArray(),
  13159. boxMaximum: mesh.getBoundingInfo().boundingBox.maximumWorld.asArray(),
  13160. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  13161. subMeshes: submeshes,
  13162. checkCollisions: mesh.checkCollisions
  13163. };
  13164. };
  13165. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  13166. return {
  13167. id: geometry.id,
  13168. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  13169. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  13170. indices: new Int32Array(geometry.getIndices() || []),
  13171. };
  13172. };
  13173. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  13174. var CollisionCoordinatorLegacy = (function () {
  13175. function CollisionCoordinatorLegacy() {
  13176. this._scaledPosition = BABYLON.Vector3.Zero();
  13177. this._scaledVelocity = BABYLON.Vector3.Zero();
  13178. this._finalPosition = BABYLON.Vector3.Zero();
  13179. }
  13180. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, velocity, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  13181. position.divideToRef(collider.radius, this._scaledPosition);
  13182. velocity.divideToRef(collider.radius, this._scaledVelocity);
  13183. collider.collidedMesh = null;
  13184. collider.retry = 0;
  13185. collider.initialVelocity = this._scaledVelocity;
  13186. collider.initialPosition = this._scaledPosition;
  13187. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  13188. this._finalPosition.multiplyInPlace(collider.radius);
  13189. //run the callback
  13190. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  13191. };
  13192. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  13193. this._scene = scene;
  13194. };
  13195. CollisionCoordinatorLegacy.prototype.destroy = function () {
  13196. //Legacy need no destruction method.
  13197. };
  13198. //No update in legacy mode
  13199. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  13200. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  13201. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  13202. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  13203. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  13204. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  13205. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  13206. if (excludedMesh === void 0) { excludedMesh = null; }
  13207. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  13208. if (collider.retry >= maximumRetry) {
  13209. finalPosition.copyFrom(position);
  13210. return;
  13211. }
  13212. collider._initialize(position, velocity, closeDistance);
  13213. // Check all meshes
  13214. for (var index = 0; index < this._scene.meshes.length; index++) {
  13215. var mesh = this._scene.meshes[index];
  13216. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh) {
  13217. mesh._checkCollision(collider);
  13218. }
  13219. }
  13220. if (!collider.collisionFound) {
  13221. position.addToRef(velocity, finalPosition);
  13222. return;
  13223. }
  13224. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  13225. collider._getResponse(position, velocity);
  13226. }
  13227. if (velocity.length() <= closeDistance) {
  13228. finalPosition.copyFrom(position);
  13229. return;
  13230. }
  13231. collider.retry++;
  13232. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  13233. };
  13234. return CollisionCoordinatorLegacy;
  13235. }());
  13236. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  13237. })(BABYLON || (BABYLON = {}));
  13238. //# sourceMappingURL=babylon.collisionCoordinator.js.map
  13239. var BABYLON;
  13240. (function (BABYLON) {
  13241. var Camera = (function (_super) {
  13242. __extends(Camera, _super);
  13243. function Camera(name, position, scene) {
  13244. var _this = _super.call(this, name, scene) || this;
  13245. _this.upVector = BABYLON.Vector3.Up();
  13246. _this.orthoLeft = null;
  13247. _this.orthoRight = null;
  13248. _this.orthoBottom = null;
  13249. _this.orthoTop = null;
  13250. _this.fov = 0.8;
  13251. _this.minZ = 1.0;
  13252. _this.maxZ = 10000.0;
  13253. _this.inertia = 0.9;
  13254. _this.mode = Camera.PERSPECTIVE_CAMERA;
  13255. _this.isIntermediate = false;
  13256. _this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  13257. _this.layerMask = 0x0FFFFFFF;
  13258. _this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  13259. // Camera rig members
  13260. _this.cameraRigMode = Camera.RIG_MODE_NONE;
  13261. _this._rigCameras = new Array();
  13262. // Cache
  13263. _this._computedViewMatrix = BABYLON.Matrix.Identity();
  13264. _this._projectionMatrix = new BABYLON.Matrix();
  13265. _this._doNotComputeProjectionMatrix = false;
  13266. _this._postProcesses = new Array();
  13267. _this._transformMatrix = BABYLON.Matrix.Zero();
  13268. _this._webvrViewMatrix = BABYLON.Matrix.Identity();
  13269. _this._activeMeshes = new BABYLON.SmartArray(256);
  13270. _this._globalPosition = BABYLON.Vector3.Zero();
  13271. _this._refreshFrustumPlanes = true;
  13272. scene.addCamera(_this);
  13273. if (!scene.activeCamera) {
  13274. scene.activeCamera = _this;
  13275. }
  13276. _this.position = position;
  13277. return _this;
  13278. }
  13279. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  13280. get: function () {
  13281. return Camera._PERSPECTIVE_CAMERA;
  13282. },
  13283. enumerable: true,
  13284. configurable: true
  13285. });
  13286. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  13287. get: function () {
  13288. return Camera._ORTHOGRAPHIC_CAMERA;
  13289. },
  13290. enumerable: true,
  13291. configurable: true
  13292. });
  13293. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  13294. get: function () {
  13295. return Camera._FOVMODE_VERTICAL_FIXED;
  13296. },
  13297. enumerable: true,
  13298. configurable: true
  13299. });
  13300. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  13301. get: function () {
  13302. return Camera._FOVMODE_HORIZONTAL_FIXED;
  13303. },
  13304. enumerable: true,
  13305. configurable: true
  13306. });
  13307. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  13308. get: function () {
  13309. return Camera._RIG_MODE_NONE;
  13310. },
  13311. enumerable: true,
  13312. configurable: true
  13313. });
  13314. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  13315. get: function () {
  13316. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  13317. },
  13318. enumerable: true,
  13319. configurable: true
  13320. });
  13321. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  13322. get: function () {
  13323. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  13324. },
  13325. enumerable: true,
  13326. configurable: true
  13327. });
  13328. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  13329. get: function () {
  13330. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  13331. },
  13332. enumerable: true,
  13333. configurable: true
  13334. });
  13335. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  13336. get: function () {
  13337. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  13338. },
  13339. enumerable: true,
  13340. configurable: true
  13341. });
  13342. Object.defineProperty(Camera, "RIG_MODE_VR", {
  13343. get: function () {
  13344. return Camera._RIG_MODE_VR;
  13345. },
  13346. enumerable: true,
  13347. configurable: true
  13348. });
  13349. Object.defineProperty(Camera, "RIG_MODE_WEBVR", {
  13350. get: function () {
  13351. return Camera._RIG_MODE_WEBVR;
  13352. },
  13353. enumerable: true,
  13354. configurable: true
  13355. });
  13356. Camera.prototype.getClassName = function () {
  13357. return "Camera";
  13358. };
  13359. /**
  13360. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  13361. */
  13362. Camera.prototype.toString = function (fullDetails) {
  13363. var ret = "Name: " + this.name;
  13364. ret += ", type: " + this.getClassName();
  13365. if (this.animations) {
  13366. for (var i = 0; i < this.animations.length; i++) {
  13367. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  13368. }
  13369. }
  13370. if (fullDetails) {
  13371. }
  13372. return ret;
  13373. };
  13374. Object.defineProperty(Camera.prototype, "globalPosition", {
  13375. get: function () {
  13376. return this._globalPosition;
  13377. },
  13378. enumerable: true,
  13379. configurable: true
  13380. });
  13381. Camera.prototype.getActiveMeshes = function () {
  13382. return this._activeMeshes;
  13383. };
  13384. Camera.prototype.isActiveMesh = function (mesh) {
  13385. return (this._activeMeshes.indexOf(mesh) !== -1);
  13386. };
  13387. //Cache
  13388. Camera.prototype._initCache = function () {
  13389. _super.prototype._initCache.call(this);
  13390. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  13391. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  13392. this._cache.mode = undefined;
  13393. this._cache.minZ = undefined;
  13394. this._cache.maxZ = undefined;
  13395. this._cache.fov = undefined;
  13396. this._cache.fovMode = undefined;
  13397. this._cache.aspectRatio = undefined;
  13398. this._cache.orthoLeft = undefined;
  13399. this._cache.orthoRight = undefined;
  13400. this._cache.orthoBottom = undefined;
  13401. this._cache.orthoTop = undefined;
  13402. this._cache.renderWidth = undefined;
  13403. this._cache.renderHeight = undefined;
  13404. };
  13405. Camera.prototype._updateCache = function (ignoreParentClass) {
  13406. if (!ignoreParentClass) {
  13407. _super.prototype._updateCache.call(this);
  13408. }
  13409. var engine = this.getEngine();
  13410. this._cache.position.copyFrom(this.position);
  13411. this._cache.upVector.copyFrom(this.upVector);
  13412. this._cache.mode = this.mode;
  13413. this._cache.minZ = this.minZ;
  13414. this._cache.maxZ = this.maxZ;
  13415. this._cache.fov = this.fov;
  13416. this._cache.fovMode = this.fovMode;
  13417. this._cache.aspectRatio = engine.getAspectRatio(this);
  13418. this._cache.orthoLeft = this.orthoLeft;
  13419. this._cache.orthoRight = this.orthoRight;
  13420. this._cache.orthoBottom = this.orthoBottom;
  13421. this._cache.orthoTop = this.orthoTop;
  13422. this._cache.renderWidth = engine.getRenderWidth();
  13423. this._cache.renderHeight = engine.getRenderHeight();
  13424. };
  13425. Camera.prototype._updateFromScene = function () {
  13426. this.updateCache();
  13427. this.update();
  13428. };
  13429. // Synchronized
  13430. Camera.prototype._isSynchronized = function () {
  13431. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  13432. };
  13433. Camera.prototype._isSynchronizedViewMatrix = function () {
  13434. if (!_super.prototype._isSynchronized.call(this))
  13435. return false;
  13436. return this._cache.position.equals(this.position)
  13437. && this._cache.upVector.equals(this.upVector)
  13438. && this.isSynchronizedWithParent();
  13439. };
  13440. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  13441. var check = this._cache.mode === this.mode
  13442. && this._cache.minZ === this.minZ
  13443. && this._cache.maxZ === this.maxZ;
  13444. if (!check) {
  13445. return false;
  13446. }
  13447. var engine = this.getEngine();
  13448. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  13449. check = this._cache.fov === this.fov
  13450. && this._cache.fovMode === this.fovMode
  13451. && this._cache.aspectRatio === engine.getAspectRatio(this);
  13452. }
  13453. else {
  13454. check = this._cache.orthoLeft === this.orthoLeft
  13455. && this._cache.orthoRight === this.orthoRight
  13456. && this._cache.orthoBottom === this.orthoBottom
  13457. && this._cache.orthoTop === this.orthoTop
  13458. && this._cache.renderWidth === engine.getRenderWidth()
  13459. && this._cache.renderHeight === engine.getRenderHeight();
  13460. }
  13461. return check;
  13462. };
  13463. // Controls
  13464. Camera.prototype.attachControl = function (element, noPreventDefault) {
  13465. };
  13466. Camera.prototype.detachControl = function (element) {
  13467. };
  13468. Camera.prototype.update = function () {
  13469. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  13470. this._updateRigCameras();
  13471. }
  13472. this._checkInputs();
  13473. };
  13474. Camera.prototype._checkInputs = function () {
  13475. };
  13476. Camera.prototype._cascadePostProcessesToRigCams = function () {
  13477. // invalidate framebuffer
  13478. if (this._postProcesses.length > 0) {
  13479. this._postProcesses[0].markTextureDirty();
  13480. }
  13481. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  13482. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  13483. var cam = this._rigCameras[i];
  13484. var rigPostProcess = cam._rigPostProcess;
  13485. // for VR rig, there does not have to be a post process
  13486. if (rigPostProcess) {
  13487. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  13488. if (isPass) {
  13489. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  13490. cam.isIntermediate = this._postProcesses.length === 0;
  13491. }
  13492. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  13493. rigPostProcess.markTextureDirty();
  13494. }
  13495. else {
  13496. cam._postProcesses = this._postProcesses.slice(0);
  13497. }
  13498. }
  13499. };
  13500. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  13501. if (insertAt === void 0) { insertAt = null; }
  13502. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  13503. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  13504. return 0;
  13505. }
  13506. if (insertAt == null || insertAt < 0) {
  13507. this._postProcesses.push(postProcess);
  13508. }
  13509. else {
  13510. this._postProcesses.splice(insertAt, 0, postProcess);
  13511. }
  13512. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  13513. return this._postProcesses.indexOf(postProcess);
  13514. };
  13515. Camera.prototype.detachPostProcess = function (postProcess, atIndices) {
  13516. if (atIndices === void 0) { atIndices = null; }
  13517. var result = [];
  13518. var i;
  13519. var index;
  13520. if (!atIndices) {
  13521. var idx = this._postProcesses.indexOf(postProcess);
  13522. if (idx !== -1) {
  13523. this._postProcesses.splice(idx, 1);
  13524. }
  13525. }
  13526. else {
  13527. atIndices = (atIndices instanceof Array) ? atIndices : [atIndices];
  13528. // iterate descending, so can just splice as we go
  13529. for (i = atIndices.length - 1; i >= 0; i--) {
  13530. if (this._postProcesses[atIndices[i]] !== postProcess) {
  13531. result.push(i);
  13532. continue;
  13533. }
  13534. index = atIndices[i];
  13535. this._postProcesses.splice(index, 1);
  13536. }
  13537. }
  13538. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  13539. return result;
  13540. };
  13541. Camera.prototype.getWorldMatrix = function () {
  13542. if (!this._worldMatrix) {
  13543. this._worldMatrix = BABYLON.Matrix.Identity();
  13544. }
  13545. var viewMatrix = this.getViewMatrix();
  13546. viewMatrix.invertToRef(this._worldMatrix);
  13547. return this._worldMatrix;
  13548. };
  13549. Camera.prototype._getViewMatrix = function () {
  13550. return BABYLON.Matrix.Identity();
  13551. };
  13552. Camera.prototype.getViewMatrix = function (force) {
  13553. this._computedViewMatrix = this._computeViewMatrix(force);
  13554. if (!force && this._isSynchronizedViewMatrix()) {
  13555. return this._computedViewMatrix;
  13556. }
  13557. this._refreshFrustumPlanes = true;
  13558. if (!this.parent || !this.parent.getWorldMatrix) {
  13559. this._globalPosition.copyFrom(this.position);
  13560. }
  13561. else {
  13562. if (!this._worldMatrix) {
  13563. this._worldMatrix = BABYLON.Matrix.Identity();
  13564. }
  13565. this._computedViewMatrix.invertToRef(this._worldMatrix);
  13566. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  13567. this._globalPosition.copyFromFloats(this._computedViewMatrix.m[12], this._computedViewMatrix.m[13], this._computedViewMatrix.m[14]);
  13568. this._computedViewMatrix.invert();
  13569. this._markSyncedWithParent();
  13570. }
  13571. this._currentRenderId = this.getScene().getRenderId();
  13572. return this._computedViewMatrix;
  13573. };
  13574. Camera.prototype._computeViewMatrix = function (force) {
  13575. if (!force && this._isSynchronizedViewMatrix()) {
  13576. return this._computedViewMatrix;
  13577. }
  13578. this._computedViewMatrix = this._getViewMatrix();
  13579. this._currentRenderId = this.getScene().getRenderId();
  13580. return this._computedViewMatrix;
  13581. };
  13582. Camera.prototype.freezeProjectionMatrix = function (projection) {
  13583. this._doNotComputeProjectionMatrix = true;
  13584. if (projection !== undefined) {
  13585. this._projectionMatrix = projection;
  13586. }
  13587. };
  13588. ;
  13589. Camera.prototype.unfreezeProjectionMatrix = function () {
  13590. this._doNotComputeProjectionMatrix = false;
  13591. };
  13592. ;
  13593. Camera.prototype.getProjectionMatrix = function (force) {
  13594. if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {
  13595. return this._projectionMatrix;
  13596. }
  13597. this._refreshFrustumPlanes = true;
  13598. var engine = this.getEngine();
  13599. var scene = this.getScene();
  13600. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  13601. if (this.minZ <= 0) {
  13602. this.minZ = 0.1;
  13603. }
  13604. if (scene.useRightHandedSystem) {
  13605. BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  13606. }
  13607. else {
  13608. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  13609. }
  13610. return this._projectionMatrix;
  13611. }
  13612. var halfWidth = engine.getRenderWidth() / 2.0;
  13613. var halfHeight = engine.getRenderHeight() / 2.0;
  13614. if (scene.useRightHandedSystem) {
  13615. BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  13616. }
  13617. else {
  13618. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  13619. }
  13620. return this._projectionMatrix;
  13621. };
  13622. Camera.prototype.getTranformationMatrix = function () {
  13623. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  13624. return this._transformMatrix;
  13625. };
  13626. Camera.prototype.updateFrustumPlanes = function () {
  13627. if (!this._refreshFrustumPlanes) {
  13628. return;
  13629. }
  13630. this.getTranformationMatrix();
  13631. if (!this._frustumPlanes) {
  13632. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  13633. }
  13634. else {
  13635. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  13636. }
  13637. this._refreshFrustumPlanes = false;
  13638. };
  13639. Camera.prototype.isInFrustum = function (target) {
  13640. this.updateFrustumPlanes();
  13641. return target.isInFrustum(this._frustumPlanes);
  13642. };
  13643. Camera.prototype.isCompletelyInFrustum = function (target) {
  13644. this.updateFrustumPlanes();
  13645. return target.isCompletelyInFrustum(this._frustumPlanes);
  13646. };
  13647. Camera.prototype.dispose = function () {
  13648. // Animations
  13649. this.getScene().stopAnimation(this);
  13650. // Remove from scene
  13651. this.getScene().removeCamera(this);
  13652. while (this._rigCameras.length > 0) {
  13653. this._rigCameras.pop().dispose();
  13654. }
  13655. // Postprocesses
  13656. var i = this._postProcesses.length;
  13657. while (--i >= 0) {
  13658. this._postProcesses[i].dispose(this);
  13659. }
  13660. _super.prototype.dispose.call(this);
  13661. };
  13662. // ---- Camera rigs section ----
  13663. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  13664. while (this._rigCameras.length > 0) {
  13665. this._rigCameras.pop().dispose();
  13666. }
  13667. this.cameraRigMode = mode;
  13668. this._cameraRigParams = {};
  13669. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  13670. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  13671. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  13672. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  13673. // create the rig cameras, unless none
  13674. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  13675. this._rigCameras.push(this.createRigCamera(this.name + "_L", 0));
  13676. this._rigCameras.push(this.createRigCamera(this.name + "_R", 1));
  13677. }
  13678. switch (this.cameraRigMode) {
  13679. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  13680. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  13681. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  13682. break;
  13683. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  13684. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  13685. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  13686. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  13687. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  13688. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  13689. break;
  13690. case Camera.RIG_MODE_VR:
  13691. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  13692. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  13693. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  13694. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  13695. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  13696. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  13697. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  13698. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  13699. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  13700. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  13701. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  13702. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  13703. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  13704. if (metrics.compensateDistortion) {
  13705. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  13706. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  13707. }
  13708. break;
  13709. case Camera.RIG_MODE_WEBVR:
  13710. if (rigParams.vrDisplay) {
  13711. //var leftEye = rigParams.vrDisplay.getEyeParameters('left');
  13712. //var rightEye = rigParams.vrDisplay.getEyeParameters('right');
  13713. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  13714. this._rigCameras[0].setCameraRigParameter("left", true);
  13715. this._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData);
  13716. //this._rigCameras[0].setCameraRigParameter("vrOffsetMatrix", Matrix.Translation(-leftEye.offset[0], leftEye.offset[1], -leftEye.offset[2]));
  13717. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  13718. this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
  13719. //this._rigCameras[0]._getViewMatrix = this._getWebVRViewMatrix;
  13720. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  13721. this._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData);
  13722. //this._rigCameras[1].setCameraRigParameter("vrOffsetMatrix", Matrix.Translation(-rightEye.offset[0], rightEye.offset[1], -rightEye.offset[2]));
  13723. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  13724. this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
  13725. }
  13726. break;
  13727. }
  13728. this._cascadePostProcessesToRigCams();
  13729. this.
  13730. update();
  13731. };
  13732. Camera.prototype._getVRProjectionMatrix = function () {
  13733. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  13734. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  13735. return this._projectionMatrix;
  13736. };
  13737. Camera.prototype._getWebVRProjectionMatrix = function () {
  13738. var projectionArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftProjectionMatrix : this._cameraRigParams["frameData"].rightProjectionMatrix;
  13739. //babylon compatible matrix
  13740. [8, 9, 10, 11].forEach(function (num) {
  13741. projectionArray[num] *= -1;
  13742. });
  13743. BABYLON.Matrix.FromArrayToRef(projectionArray, 0, this._projectionMatrix);
  13744. return this._projectionMatrix;
  13745. };
  13746. //Can be used, but we'll use the free camera's view matrix calculation
  13747. Camera.prototype._getWebVRViewMatrix = function () {
  13748. var projectionArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftViewMatrix : this._cameraRigParams["frameData"].rightViewMatrix;
  13749. //babylon compatible matrix
  13750. [8, 9, 10, 11].forEach(function (num) {
  13751. projectionArray[num] *= -1;
  13752. });
  13753. BABYLON.Matrix.FromArrayToRef(projectionArray, 0, this._webvrViewMatrix);
  13754. return this._webvrViewMatrix;
  13755. };
  13756. Camera.prototype.setCameraRigParameter = function (name, value) {
  13757. if (!this._cameraRigParams) {
  13758. this._cameraRigParams = {};
  13759. }
  13760. this._cameraRigParams[name] = value;
  13761. //provisionnally:
  13762. if (name === "interaxialDistance") {
  13763. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  13764. }
  13765. };
  13766. /**
  13767. * needs to be overridden by children so sub has required properties to be copied
  13768. */
  13769. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  13770. return null;
  13771. };
  13772. /**
  13773. * May need to be overridden by children
  13774. */
  13775. Camera.prototype._updateRigCameras = function () {
  13776. for (var i = 0; i < this._rigCameras.length; i++) {
  13777. this._rigCameras[i].minZ = this.minZ;
  13778. this._rigCameras[i].maxZ = this.maxZ;
  13779. this._rigCameras[i].fov = this.fov;
  13780. }
  13781. // only update viewport when ANAGLYPH
  13782. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  13783. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  13784. }
  13785. };
  13786. Camera.prototype._setupInputs = function () {
  13787. };
  13788. Camera.prototype.serialize = function () {
  13789. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  13790. // Type
  13791. serializationObject.type = this.getClassName();
  13792. // Parent
  13793. if (this.parent) {
  13794. serializationObject.parentId = this.parent.id;
  13795. }
  13796. if (this.inputs) {
  13797. this.inputs.serialize(serializationObject);
  13798. }
  13799. // Animations
  13800. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  13801. serializationObject.ranges = this.serializeAnimationRanges();
  13802. return serializationObject;
  13803. };
  13804. Camera.prototype.clone = function (name) {
  13805. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  13806. };
  13807. Camera.prototype.getDirection = function (localAxis) {
  13808. var result = BABYLON.Vector3.Zero();
  13809. this.getDirectionToRef(localAxis, result);
  13810. return result;
  13811. };
  13812. Camera.prototype.getDirectionToRef = function (localAxis, result) {
  13813. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  13814. };
  13815. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  13816. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  13817. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  13818. switch (type) {
  13819. case "ArcRotateCamera":
  13820. return function () { return new BABYLON.ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  13821. case "DeviceOrientationCamera":
  13822. return function () { return new BABYLON.DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  13823. case "FollowCamera":
  13824. return function () { return new BABYLON.FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  13825. case "ArcFollowCamera":
  13826. return function () { return new BABYLON.ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  13827. case "GamepadCamera":
  13828. return function () { return new BABYLON.GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  13829. case "TouchCamera":
  13830. return function () { return new BABYLON.TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  13831. case "VirtualJoysticksCamera":
  13832. return function () { return new BABYLON.VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  13833. case "HolographicCamera":
  13834. return function () { return new BABYLON.HolographicCamera(name, scene); };
  13835. case "WebVRFreeCamera":
  13836. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  13837. case "VRDeviceOrientationFreeCamera":
  13838. return function () { return new BABYLON.VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  13839. case "AnaglyphArcRotateCamera":
  13840. return function () { return new BABYLON.AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  13841. case "AnaglyphFreeCamera":
  13842. return function () { return new BABYLON.AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  13843. case "AnaglyphGamepadCamera":
  13844. return function () { return new BABYLON.AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  13845. case "AnaglyphUniversalCamera":
  13846. return function () { return new BABYLON.AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  13847. case "StereoscopicArcRotateCamera":
  13848. return function () { return new BABYLON.StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  13849. case "StereoscopicFreeCamera":
  13850. return function () { return new BABYLON.StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  13851. case "StereoscopicGamepadCamera":
  13852. return function () { return new BABYLON.StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  13853. case "StereoscopicUniversalCamera":
  13854. return function () { return new BABYLON.StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  13855. case "FreeCamera":
  13856. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  13857. default:
  13858. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  13859. }
  13860. };
  13861. Camera.Parse = function (parsedCamera, scene) {
  13862. var type = parsedCamera.type;
  13863. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  13864. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  13865. // Parent
  13866. if (parsedCamera.parentId) {
  13867. camera._waitingParentId = parsedCamera.parentId;
  13868. }
  13869. //If camera has an input manager, let it parse inputs settings
  13870. if (camera.inputs) {
  13871. camera.inputs.parse(parsedCamera);
  13872. camera._setupInputs();
  13873. }
  13874. // Target
  13875. if (parsedCamera.target) {
  13876. if (camera.setTarget) {
  13877. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  13878. }
  13879. }
  13880. // Apply 3d rig, when found
  13881. if (parsedCamera.cameraRigMode) {
  13882. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  13883. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  13884. }
  13885. // Animations
  13886. if (parsedCamera.animations) {
  13887. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  13888. var parsedAnimation = parsedCamera.animations[animationIndex];
  13889. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  13890. }
  13891. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  13892. }
  13893. if (parsedCamera.autoAnimate) {
  13894. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  13895. }
  13896. return camera;
  13897. };
  13898. return Camera;
  13899. }(BABYLON.Node));
  13900. // Statics
  13901. Camera._PERSPECTIVE_CAMERA = 0;
  13902. Camera._ORTHOGRAPHIC_CAMERA = 1;
  13903. Camera._FOVMODE_VERTICAL_FIXED = 0;
  13904. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  13905. Camera._RIG_MODE_NONE = 0;
  13906. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  13907. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  13908. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  13909. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  13910. Camera._RIG_MODE_VR = 20;
  13911. Camera._RIG_MODE_WEBVR = 21;
  13912. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  13913. __decorate([
  13914. BABYLON.serializeAsVector3()
  13915. ], Camera.prototype, "position", void 0);
  13916. __decorate([
  13917. BABYLON.serializeAsVector3()
  13918. ], Camera.prototype, "upVector", void 0);
  13919. __decorate([
  13920. BABYLON.serialize()
  13921. ], Camera.prototype, "orthoLeft", void 0);
  13922. __decorate([
  13923. BABYLON.serialize()
  13924. ], Camera.prototype, "orthoRight", void 0);
  13925. __decorate([
  13926. BABYLON.serialize()
  13927. ], Camera.prototype, "orthoBottom", void 0);
  13928. __decorate([
  13929. BABYLON.serialize()
  13930. ], Camera.prototype, "orthoTop", void 0);
  13931. __decorate([
  13932. BABYLON.serialize()
  13933. ], Camera.prototype, "fov", void 0);
  13934. __decorate([
  13935. BABYLON.serialize()
  13936. ], Camera.prototype, "minZ", void 0);
  13937. __decorate([
  13938. BABYLON.serialize()
  13939. ], Camera.prototype, "maxZ", void 0);
  13940. __decorate([
  13941. BABYLON.serialize()
  13942. ], Camera.prototype, "inertia", void 0);
  13943. __decorate([
  13944. BABYLON.serialize()
  13945. ], Camera.prototype, "mode", void 0);
  13946. __decorate([
  13947. BABYLON.serialize()
  13948. ], Camera.prototype, "layerMask", void 0);
  13949. __decorate([
  13950. BABYLON.serialize()
  13951. ], Camera.prototype, "fovMode", void 0);
  13952. __decorate([
  13953. BABYLON.serialize()
  13954. ], Camera.prototype, "cameraRigMode", void 0);
  13955. __decorate([
  13956. BABYLON.serialize()
  13957. ], Camera.prototype, "interaxialDistance", void 0);
  13958. __decorate([
  13959. BABYLON.serialize()
  13960. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  13961. BABYLON.Camera = Camera;
  13962. })(BABYLON || (BABYLON = {}));
  13963. //# sourceMappingURL=babylon.camera.js.map
  13964. var BABYLON;
  13965. (function (BABYLON) {
  13966. BABYLON.CameraInputTypes = {};
  13967. var CameraInputsManager = (function () {
  13968. function CameraInputsManager(camera) {
  13969. this.attached = {};
  13970. this.camera = camera;
  13971. this.checkInputs = function () { };
  13972. }
  13973. CameraInputsManager.prototype.add = function (input) {
  13974. var type = input.getSimpleName();
  13975. if (this.attached[type]) {
  13976. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  13977. return;
  13978. }
  13979. this.attached[type] = input;
  13980. input.camera = this.camera;
  13981. //for checkInputs, we are dynamically creating a function
  13982. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  13983. if (input.checkInputs) {
  13984. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  13985. }
  13986. if (this.attachedElement) {
  13987. input.attachControl(this.attachedElement);
  13988. }
  13989. };
  13990. CameraInputsManager.prototype.remove = function (inputToRemove) {
  13991. for (var cam in this.attached) {
  13992. var input = this.attached[cam];
  13993. if (input === inputToRemove) {
  13994. input.detachControl(this.attachedElement);
  13995. delete this.attached[cam];
  13996. this.rebuildInputCheck();
  13997. }
  13998. }
  13999. };
  14000. CameraInputsManager.prototype.removeByType = function (inputType) {
  14001. for (var cam in this.attached) {
  14002. var input = this.attached[cam];
  14003. if (input.getTypeName() === inputType) {
  14004. input.detachControl(this.attachedElement);
  14005. delete this.attached[cam];
  14006. this.rebuildInputCheck();
  14007. }
  14008. }
  14009. };
  14010. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  14011. var current = this.checkInputs;
  14012. return function () {
  14013. current();
  14014. fn();
  14015. };
  14016. };
  14017. CameraInputsManager.prototype.attachInput = function (input) {
  14018. input.attachControl(this.attachedElement, this.noPreventDefault);
  14019. };
  14020. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  14021. if (this.attachedElement) {
  14022. return;
  14023. }
  14024. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  14025. this.attachedElement = element;
  14026. this.noPreventDefault = noPreventDefault;
  14027. for (var cam in this.attached) {
  14028. var input = this.attached[cam];
  14029. this.attached[cam].attachControl(element, noPreventDefault);
  14030. }
  14031. };
  14032. CameraInputsManager.prototype.detachElement = function (element) {
  14033. if (this.attachedElement !== element) {
  14034. return;
  14035. }
  14036. for (var cam in this.attached) {
  14037. var input = this.attached[cam];
  14038. this.attached[cam].detachControl(element);
  14039. }
  14040. this.attachedElement = null;
  14041. };
  14042. CameraInputsManager.prototype.rebuildInputCheck = function () {
  14043. this.checkInputs = function () { };
  14044. for (var cam in this.attached) {
  14045. var input = this.attached[cam];
  14046. if (input.checkInputs) {
  14047. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  14048. }
  14049. }
  14050. };
  14051. CameraInputsManager.prototype.clear = function () {
  14052. if (this.attachedElement) {
  14053. this.detachElement(this.attachedElement);
  14054. }
  14055. this.attached = {};
  14056. this.attachedElement = null;
  14057. this.checkInputs = function () { };
  14058. };
  14059. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  14060. var inputs = {};
  14061. for (var cam in this.attached) {
  14062. var input = this.attached[cam];
  14063. var res = BABYLON.SerializationHelper.Serialize(input);
  14064. inputs[input.getTypeName()] = res;
  14065. }
  14066. serializedCamera.inputsmgr = inputs;
  14067. };
  14068. CameraInputsManager.prototype.parse = function (parsedCamera) {
  14069. var parsedInputs = parsedCamera.inputsmgr;
  14070. if (parsedInputs) {
  14071. this.clear();
  14072. for (var n in parsedInputs) {
  14073. var construct = BABYLON.CameraInputTypes[n];
  14074. if (construct) {
  14075. var parsedinput = parsedInputs[n];
  14076. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  14077. this.add(input);
  14078. }
  14079. }
  14080. }
  14081. else {
  14082. //2016-03-08 this part is for managing backward compatibility
  14083. for (var n in this.attached) {
  14084. var construct = BABYLON.CameraInputTypes[this.attached[n].getTypeName()];
  14085. if (construct) {
  14086. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  14087. this.remove(this.attached[n]);
  14088. this.add(input);
  14089. }
  14090. }
  14091. }
  14092. };
  14093. return CameraInputsManager;
  14094. }());
  14095. BABYLON.CameraInputsManager = CameraInputsManager;
  14096. })(BABYLON || (BABYLON = {}));
  14097. //# sourceMappingURL=babylon.cameraInputsManager.js.map
  14098. var BABYLON;
  14099. (function (BABYLON) {
  14100. var FreeCameraMouseInput = (function () {
  14101. function FreeCameraMouseInput(touchEnabled) {
  14102. if (touchEnabled === void 0) { touchEnabled = true; }
  14103. this.touchEnabled = touchEnabled;
  14104. this.buttons = [0, 1, 2];
  14105. this.angularSensibility = 2000.0;
  14106. }
  14107. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  14108. var _this = this;
  14109. var engine = this.camera.getEngine();
  14110. if (!this._pointerInput) {
  14111. this._pointerInput = function (p, s) {
  14112. var evt = p.event;
  14113. if (!_this.touchEnabled && evt.pointerType === "touch") {
  14114. return;
  14115. }
  14116. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  14117. return;
  14118. }
  14119. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  14120. try {
  14121. evt.srcElement.setPointerCapture(evt.pointerId);
  14122. }
  14123. catch (e) {
  14124. }
  14125. _this.previousPosition = {
  14126. x: evt.clientX,
  14127. y: evt.clientY
  14128. };
  14129. if (!noPreventDefault) {
  14130. evt.preventDefault();
  14131. element.focus();
  14132. }
  14133. }
  14134. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  14135. try {
  14136. evt.srcElement.releasePointerCapture(evt.pointerId);
  14137. }
  14138. catch (e) {
  14139. }
  14140. _this.previousPosition = null;
  14141. if (!noPreventDefault) {
  14142. evt.preventDefault();
  14143. }
  14144. }
  14145. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  14146. if (!_this.previousPosition || engine.isPointerLock) {
  14147. return;
  14148. }
  14149. var offsetX = evt.clientX - _this.previousPosition.x;
  14150. var offsetY = evt.clientY - _this.previousPosition.y;
  14151. if (_this.camera.getScene().useRightHandedSystem) {
  14152. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  14153. }
  14154. else {
  14155. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  14156. }
  14157. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  14158. _this.previousPosition = {
  14159. x: evt.clientX,
  14160. y: evt.clientY
  14161. };
  14162. if (!noPreventDefault) {
  14163. evt.preventDefault();
  14164. }
  14165. }
  14166. };
  14167. }
  14168. this._onMouseMove = function (evt) {
  14169. if (!engine.isPointerLock) {
  14170. return;
  14171. }
  14172. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  14173. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  14174. if (_this.camera.getScene().useRightHandedSystem) {
  14175. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  14176. }
  14177. else {
  14178. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  14179. }
  14180. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  14181. _this.previousPosition = null;
  14182. if (!noPreventDefault) {
  14183. evt.preventDefault();
  14184. }
  14185. };
  14186. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  14187. element.addEventListener("mousemove", this._onMouseMove, false);
  14188. };
  14189. FreeCameraMouseInput.prototype.detachControl = function (element) {
  14190. if (this._observer && element) {
  14191. this.camera.getScene().onPointerObservable.remove(this._observer);
  14192. element.removeEventListener("mousemove", this._onMouseMove);
  14193. this._observer = null;
  14194. this._onMouseMove = null;
  14195. this.previousPosition = null;
  14196. }
  14197. };
  14198. FreeCameraMouseInput.prototype.getTypeName = function () {
  14199. return "FreeCameraMouseInput";
  14200. };
  14201. FreeCameraMouseInput.prototype.getSimpleName = function () {
  14202. return "mouse";
  14203. };
  14204. return FreeCameraMouseInput;
  14205. }());
  14206. __decorate([
  14207. BABYLON.serialize()
  14208. ], FreeCameraMouseInput.prototype, "buttons", void 0);
  14209. __decorate([
  14210. BABYLON.serialize()
  14211. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  14212. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  14213. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  14214. })(BABYLON || (BABYLON = {}));
  14215. //# sourceMappingURL=babylon.freecamera.input.mouse.js.map
  14216. var BABYLON;
  14217. (function (BABYLON) {
  14218. var FreeCameraKeyboardMoveInput = (function () {
  14219. function FreeCameraKeyboardMoveInput() {
  14220. this._keys = [];
  14221. this.keysUp = [38];
  14222. this.keysDown = [40];
  14223. this.keysLeft = [37];
  14224. this.keysRight = [39];
  14225. }
  14226. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  14227. var _this = this;
  14228. if (!this._onKeyDown) {
  14229. element.tabIndex = 1;
  14230. this._onKeyDown = function (evt) {
  14231. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  14232. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  14233. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  14234. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  14235. var index = _this._keys.indexOf(evt.keyCode);
  14236. if (index === -1) {
  14237. _this._keys.push(evt.keyCode);
  14238. }
  14239. if (!noPreventDefault) {
  14240. evt.preventDefault();
  14241. }
  14242. }
  14243. };
  14244. this._onKeyUp = function (evt) {
  14245. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  14246. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  14247. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  14248. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  14249. var index = _this._keys.indexOf(evt.keyCode);
  14250. if (index >= 0) {
  14251. _this._keys.splice(index, 1);
  14252. }
  14253. if (!noPreventDefault) {
  14254. evt.preventDefault();
  14255. }
  14256. }
  14257. };
  14258. element.addEventListener("keydown", this._onKeyDown, false);
  14259. element.addEventListener("keyup", this._onKeyUp, false);
  14260. BABYLON.Tools.RegisterTopRootEvents([
  14261. { name: "blur", handler: this._onLostFocus }
  14262. ]);
  14263. }
  14264. };
  14265. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  14266. if (this._onKeyDown) {
  14267. element.removeEventListener("keydown", this._onKeyDown);
  14268. element.removeEventListener("keyup", this._onKeyUp);
  14269. BABYLON.Tools.UnregisterTopRootEvents([
  14270. { name: "blur", handler: this._onLostFocus }
  14271. ]);
  14272. this._keys = [];
  14273. this._onKeyDown = null;
  14274. this._onKeyUp = null;
  14275. }
  14276. };
  14277. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  14278. if (this._onKeyDown) {
  14279. var camera = this.camera;
  14280. // Keyboard
  14281. for (var index = 0; index < this._keys.length; index++) {
  14282. var keyCode = this._keys[index];
  14283. var speed = camera._computeLocalCameraSpeed();
  14284. if (this.keysLeft.indexOf(keyCode) !== -1) {
  14285. camera._localDirection.copyFromFloats(-speed, 0, 0);
  14286. }
  14287. else if (this.keysUp.indexOf(keyCode) !== -1) {
  14288. camera._localDirection.copyFromFloats(0, 0, speed);
  14289. }
  14290. else if (this.keysRight.indexOf(keyCode) !== -1) {
  14291. camera._localDirection.copyFromFloats(speed, 0, 0);
  14292. }
  14293. else if (this.keysDown.indexOf(keyCode) !== -1) {
  14294. camera._localDirection.copyFromFloats(0, 0, -speed);
  14295. }
  14296. if (camera.getScene().useRightHandedSystem) {
  14297. camera._localDirection.z *= -1;
  14298. }
  14299. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  14300. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  14301. camera.cameraDirection.addInPlace(camera._transformedDirection);
  14302. }
  14303. }
  14304. };
  14305. FreeCameraKeyboardMoveInput.prototype.getTypeName = function () {
  14306. return "FreeCameraKeyboardMoveInput";
  14307. };
  14308. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  14309. this._keys = [];
  14310. };
  14311. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  14312. return "keyboard";
  14313. };
  14314. return FreeCameraKeyboardMoveInput;
  14315. }());
  14316. __decorate([
  14317. BABYLON.serialize()
  14318. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  14319. __decorate([
  14320. BABYLON.serialize()
  14321. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  14322. __decorate([
  14323. BABYLON.serialize()
  14324. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  14325. __decorate([
  14326. BABYLON.serialize()
  14327. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  14328. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  14329. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  14330. })(BABYLON || (BABYLON = {}));
  14331. //# sourceMappingURL=babylon.freecamera.input.keyboard.js.map
  14332. var BABYLON;
  14333. (function (BABYLON) {
  14334. var FreeCameraTouchInput = (function () {
  14335. function FreeCameraTouchInput() {
  14336. this._offsetX = null;
  14337. this._offsetY = null;
  14338. this._pointerCount = 0;
  14339. this._pointerPressed = [];
  14340. this.touchAngularSensibility = 200000.0;
  14341. this.touchMoveSensibility = 250.0;
  14342. }
  14343. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  14344. var _this = this;
  14345. var previousPosition;
  14346. if (this._pointerInput === undefined) {
  14347. this._onLostFocus = function (evt) {
  14348. _this._offsetX = null;
  14349. _this._offsetY = null;
  14350. };
  14351. this._pointerInput = function (p, s) {
  14352. var evt = p.event;
  14353. if (evt.pointerType === "mouse") {
  14354. return;
  14355. }
  14356. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  14357. if (!noPreventDefault) {
  14358. evt.preventDefault();
  14359. }
  14360. _this._pointerPressed.push(evt.pointerId);
  14361. if (_this._pointerPressed.length !== 1) {
  14362. return;
  14363. }
  14364. previousPosition = {
  14365. x: evt.clientX,
  14366. y: evt.clientY
  14367. };
  14368. }
  14369. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  14370. if (!noPreventDefault) {
  14371. evt.preventDefault();
  14372. }
  14373. var index = _this._pointerPressed.indexOf(evt.pointerId);
  14374. if (index === -1) {
  14375. return;
  14376. }
  14377. _this._pointerPressed.splice(index, 1);
  14378. if (index != 0) {
  14379. return;
  14380. }
  14381. previousPosition = null;
  14382. _this._offsetX = null;
  14383. _this._offsetY = null;
  14384. }
  14385. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  14386. if (!noPreventDefault) {
  14387. evt.preventDefault();
  14388. }
  14389. if (!previousPosition) {
  14390. return;
  14391. }
  14392. var index = _this._pointerPressed.indexOf(evt.pointerId);
  14393. if (index != 0) {
  14394. return;
  14395. }
  14396. _this._offsetX = evt.clientX - previousPosition.x;
  14397. _this._offsetY = -(evt.clientY - previousPosition.y);
  14398. }
  14399. };
  14400. }
  14401. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  14402. element.addEventListener("blur", this._onLostFocus);
  14403. };
  14404. FreeCameraTouchInput.prototype.detachControl = function (element) {
  14405. if (this._pointerInput && element) {
  14406. this.camera.getScene().onPointerObservable.remove(this._observer);
  14407. this._observer = null;
  14408. element.removeEventListener("blur", this._onLostFocus);
  14409. this._onLostFocus = null;
  14410. this._pointerPressed = [];
  14411. this._offsetX = null;
  14412. this._offsetY = null;
  14413. this._pointerCount = 0;
  14414. }
  14415. };
  14416. FreeCameraTouchInput.prototype.checkInputs = function () {
  14417. if (this._offsetX) {
  14418. var camera = this.camera;
  14419. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  14420. if (this._pointerPressed.length > 1) {
  14421. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  14422. }
  14423. else {
  14424. var speed = camera._computeLocalCameraSpeed();
  14425. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  14426. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  14427. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  14428. }
  14429. }
  14430. };
  14431. FreeCameraTouchInput.prototype.getTypeName = function () {
  14432. return "FreeCameraTouchInput";
  14433. };
  14434. FreeCameraTouchInput.prototype.getSimpleName = function () {
  14435. return "touch";
  14436. };
  14437. return FreeCameraTouchInput;
  14438. }());
  14439. __decorate([
  14440. BABYLON.serialize()
  14441. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  14442. __decorate([
  14443. BABYLON.serialize()
  14444. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  14445. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  14446. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  14447. })(BABYLON || (BABYLON = {}));
  14448. //# sourceMappingURL=babylon.freecamera.input.touch.js.map
  14449. var BABYLON;
  14450. (function (BABYLON) {
  14451. var FreeCameraDeviceOrientationInput = (function () {
  14452. function FreeCameraDeviceOrientationInput() {
  14453. var _this = this;
  14454. this._screenOrientationAngle = 0;
  14455. this._screenQuaternion = new BABYLON.Quaternion();
  14456. this._alpha = 0;
  14457. this._beta = 0;
  14458. this._gamma = 0;
  14459. this._orientationChanged = function () {
  14460. _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && window.screen.orientation['angle'] ? window.screen.orientation.angle : 0));
  14461. _this._screenOrientationAngle = -BABYLON.Tools.ToRadians(_this._screenOrientationAngle / 2);
  14462. _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle));
  14463. };
  14464. this._deviceOrientation = function (evt) {
  14465. _this._alpha = evt.alpha;
  14466. _this._beta = evt.beta;
  14467. _this._gamma = evt.gamma;
  14468. };
  14469. this._constantTranform = new BABYLON.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));
  14470. this._orientationChanged();
  14471. }
  14472. Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", {
  14473. get: function () {
  14474. return this._camera;
  14475. },
  14476. set: function (camera) {
  14477. this._camera = camera;
  14478. if (!this._camera.rotationQuaternion)
  14479. this._camera.rotationQuaternion = new BABYLON.Quaternion();
  14480. },
  14481. enumerable: true,
  14482. configurable: true
  14483. });
  14484. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  14485. window.addEventListener("orientationchange", this._orientationChanged);
  14486. window.addEventListener("deviceorientation", this._deviceOrientation);
  14487. //In certain cases, the attach control is called AFTER orientation was changed,
  14488. //So this is needed.
  14489. this._orientationChanged();
  14490. };
  14491. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  14492. window.removeEventListener("orientationchange", this._orientationChanged);
  14493. window.removeEventListener("deviceorientation", this._deviceOrientation);
  14494. };
  14495. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  14496. //if no device orientation provided, don't update the rotation.
  14497. //Only testing against alpha under the assumption thatnorientation will never be so exact when set.
  14498. if (!this._alpha)
  14499. return;
  14500. BABYLON.Quaternion.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(this._alpha), BABYLON.Tools.ToRadians(this._beta), -BABYLON.Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);
  14501. this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);
  14502. this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);
  14503. //Mirror on XY Plane
  14504. this._camera.rotationQuaternion.z *= -1;
  14505. this._camera.rotationQuaternion.w *= -1;
  14506. };
  14507. FreeCameraDeviceOrientationInput.prototype.getTypeName = function () {
  14508. return "FreeCameraDeviceOrientationInput";
  14509. };
  14510. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  14511. return "deviceOrientation";
  14512. };
  14513. return FreeCameraDeviceOrientationInput;
  14514. }());
  14515. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  14516. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  14517. })(BABYLON || (BABYLON = {}));
  14518. //# sourceMappingURL=babylon.freecamera.input.deviceorientation.js.map
  14519. var BABYLON;
  14520. (function (BABYLON) {
  14521. var FreeCameraGamepadInput = (function () {
  14522. function FreeCameraGamepadInput() {
  14523. this.gamepadAngularSensibility = 200;
  14524. this.gamepadMoveSensibility = 40;
  14525. }
  14526. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  14527. var _this = this;
  14528. this._gamepads = new BABYLON.Gamepads(function (gamepad) { _this._onNewGameConnected(gamepad); });
  14529. };
  14530. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  14531. if (this._gamepads) {
  14532. this._gamepads.dispose();
  14533. }
  14534. this.gamepad = null;
  14535. };
  14536. FreeCameraGamepadInput.prototype.checkInputs = function () {
  14537. if (this.gamepad) {
  14538. var camera = this.camera;
  14539. var LSValues = this.gamepad.leftStick;
  14540. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  14541. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  14542. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  14543. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  14544. var RSValues = this.gamepad.rightStick;
  14545. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  14546. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  14547. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  14548. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  14549. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  14550. var speed = camera._computeLocalCameraSpeed() * 50.0;
  14551. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(LSValues.x * speed, 0, -LSValues.y * speed), cameraTransform);
  14552. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  14553. camera.cameraRotation = camera.cameraRotation.add(new BABYLON.Vector2(RSValues.y, RSValues.x));
  14554. }
  14555. };
  14556. FreeCameraGamepadInput.prototype._onNewGameConnected = function (gamepad) {
  14557. // Only the first gamepad can control the camera
  14558. if (gamepad.index === 0) {
  14559. this.gamepad = gamepad;
  14560. }
  14561. };
  14562. FreeCameraGamepadInput.prototype.getTypeName = function () {
  14563. return "FreeCameraGamepadInput";
  14564. };
  14565. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  14566. return "gamepad";
  14567. };
  14568. return FreeCameraGamepadInput;
  14569. }());
  14570. __decorate([
  14571. BABYLON.serialize()
  14572. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  14573. __decorate([
  14574. BABYLON.serialize()
  14575. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  14576. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  14577. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  14578. })(BABYLON || (BABYLON = {}));
  14579. //# sourceMappingURL=babylon.freecamera.input.gamepad.js.map
  14580. var BABYLON;
  14581. (function (BABYLON) {
  14582. var ArcRotateCameraKeyboardMoveInput = (function () {
  14583. function ArcRotateCameraKeyboardMoveInput() {
  14584. this._keys = [];
  14585. this.keysUp = [38];
  14586. this.keysDown = [40];
  14587. this.keysLeft = [37];
  14588. this.keysRight = [39];
  14589. }
  14590. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  14591. var _this = this;
  14592. element.tabIndex = 1;
  14593. this._onKeyDown = function (evt) {
  14594. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  14595. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  14596. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  14597. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  14598. var index = _this._keys.indexOf(evt.keyCode);
  14599. if (index === -1) {
  14600. _this._keys.push(evt.keyCode);
  14601. }
  14602. if (evt.preventDefault) {
  14603. if (!noPreventDefault) {
  14604. evt.preventDefault();
  14605. }
  14606. }
  14607. }
  14608. };
  14609. this._onKeyUp = function (evt) {
  14610. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  14611. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  14612. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  14613. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  14614. var index = _this._keys.indexOf(evt.keyCode);
  14615. if (index >= 0) {
  14616. _this._keys.splice(index, 1);
  14617. }
  14618. if (evt.preventDefault) {
  14619. if (!noPreventDefault) {
  14620. evt.preventDefault();
  14621. }
  14622. }
  14623. }
  14624. };
  14625. this._onLostFocus = function () {
  14626. _this._keys = [];
  14627. };
  14628. element.addEventListener("keydown", this._onKeyDown, false);
  14629. element.addEventListener("keyup", this._onKeyUp, false);
  14630. BABYLON.Tools.RegisterTopRootEvents([
  14631. { name: "blur", handler: this._onLostFocus }
  14632. ]);
  14633. };
  14634. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  14635. if (element) {
  14636. element.removeEventListener("keydown", this._onKeyDown);
  14637. element.removeEventListener("keyup", this._onKeyUp);
  14638. }
  14639. BABYLON.Tools.UnregisterTopRootEvents([
  14640. { name: "blur", handler: this._onLostFocus }
  14641. ]);
  14642. this._keys = [];
  14643. this._onKeyDown = null;
  14644. this._onKeyUp = null;
  14645. this._onLostFocus = null;
  14646. };
  14647. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  14648. if (this._onKeyDown) {
  14649. var camera = this.camera;
  14650. for (var index = 0; index < this._keys.length; index++) {
  14651. var keyCode = this._keys[index];
  14652. if (this.keysLeft.indexOf(keyCode) !== -1) {
  14653. camera.inertialAlphaOffset -= 0.01;
  14654. }
  14655. else if (this.keysUp.indexOf(keyCode) !== -1) {
  14656. camera.inertialBetaOffset -= 0.01;
  14657. }
  14658. else if (this.keysRight.indexOf(keyCode) !== -1) {
  14659. camera.inertialAlphaOffset += 0.01;
  14660. }
  14661. else if (this.keysDown.indexOf(keyCode) !== -1) {
  14662. camera.inertialBetaOffset += 0.01;
  14663. }
  14664. }
  14665. }
  14666. };
  14667. ArcRotateCameraKeyboardMoveInput.prototype.getTypeName = function () {
  14668. return "ArcRotateCameraKeyboardMoveInput";
  14669. };
  14670. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  14671. return "keyboard";
  14672. };
  14673. return ArcRotateCameraKeyboardMoveInput;
  14674. }());
  14675. __decorate([
  14676. BABYLON.serialize()
  14677. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  14678. __decorate([
  14679. BABYLON.serialize()
  14680. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  14681. __decorate([
  14682. BABYLON.serialize()
  14683. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  14684. __decorate([
  14685. BABYLON.serialize()
  14686. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  14687. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  14688. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  14689. })(BABYLON || (BABYLON = {}));
  14690. //# sourceMappingURL=babylon.arcrotatecamera.input.keyboard.js.map
  14691. var BABYLON;
  14692. (function (BABYLON) {
  14693. var ArcRotateCameraMouseWheelInput = (function () {
  14694. function ArcRotateCameraMouseWheelInput() {
  14695. this.wheelPrecision = 3.0;
  14696. }
  14697. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  14698. var _this = this;
  14699. this._wheel = function (p, s) {
  14700. //sanity check - this should be a PointerWheel event.
  14701. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  14702. return;
  14703. var event = p.event;
  14704. var delta = 0;
  14705. if (event.wheelDelta) {
  14706. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  14707. }
  14708. else if (event.detail) {
  14709. delta = -event.detail / _this.wheelPrecision;
  14710. }
  14711. if (delta)
  14712. _this.camera.inertialRadiusOffset += delta;
  14713. if (event.preventDefault) {
  14714. if (!noPreventDefault) {
  14715. event.preventDefault();
  14716. }
  14717. }
  14718. };
  14719. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  14720. };
  14721. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  14722. if (this._observer && element) {
  14723. this.camera.getScene().onPointerObservable.remove(this._observer);
  14724. this._observer = null;
  14725. this._wheel = null;
  14726. }
  14727. };
  14728. ArcRotateCameraMouseWheelInput.prototype.getTypeName = function () {
  14729. return "ArcRotateCameraMouseWheelInput";
  14730. };
  14731. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  14732. return "mousewheel";
  14733. };
  14734. return ArcRotateCameraMouseWheelInput;
  14735. }());
  14736. __decorate([
  14737. BABYLON.serialize()
  14738. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  14739. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  14740. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  14741. })(BABYLON || (BABYLON = {}));
  14742. //# sourceMappingURL=babylon.arcrotatecamera.input.mousewheel.js.map
  14743. var BABYLON;
  14744. (function (BABYLON) {
  14745. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  14746. var ArcRotateCameraPointersInput = (function () {
  14747. function ArcRotateCameraPointersInput() {
  14748. this.buttons = [0, 1, 2];
  14749. this.angularSensibilityX = 1000.0;
  14750. this.angularSensibilityY = 1000.0;
  14751. this.pinchPrecision = 6.0;
  14752. this.panningSensibility = 50.0;
  14753. this._isPanClick = false;
  14754. this.pinchInwards = true;
  14755. }
  14756. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  14757. var _this = this;
  14758. var engine = this.camera.getEngine();
  14759. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  14760. var pointA, pointB;
  14761. var previousPinchDistance = 0;
  14762. this._pointerInput = function (p, s) {
  14763. var evt = p.event;
  14764. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  14765. return;
  14766. }
  14767. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  14768. try {
  14769. evt.srcElement.setPointerCapture(evt.pointerId);
  14770. }
  14771. catch (e) {
  14772. }
  14773. // Manage panning with pan button click
  14774. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  14775. // manage pointers
  14776. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  14777. if (pointA === undefined) {
  14778. pointA = cacheSoloPointer;
  14779. }
  14780. else if (pointB === undefined) {
  14781. pointB = cacheSoloPointer;
  14782. }
  14783. if (!noPreventDefault) {
  14784. evt.preventDefault();
  14785. element.focus();
  14786. }
  14787. }
  14788. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  14789. try {
  14790. evt.srcElement.releasePointerCapture(evt.pointerId);
  14791. }
  14792. catch (e) {
  14793. }
  14794. cacheSoloPointer = null;
  14795. previousPinchDistance = 0;
  14796. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  14797. //but emptying completly pointers collection is required to fix a bug on iPhone :
  14798. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  14799. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  14800. pointA = pointB = undefined;
  14801. if (!noPreventDefault) {
  14802. evt.preventDefault();
  14803. }
  14804. }
  14805. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  14806. if (!noPreventDefault) {
  14807. evt.preventDefault();
  14808. }
  14809. // One button down
  14810. if (pointA && pointB === undefined) {
  14811. if (_this.panningSensibility !== 0 &&
  14812. ((evt.ctrlKey && _this.camera._useCtrlForPanning) ||
  14813. (!_this.camera._useCtrlForPanning && _this._isPanClick))) {
  14814. _this.camera
  14815. .inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  14816. _this.camera
  14817. .inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  14818. }
  14819. else {
  14820. var offsetX = evt.clientX - cacheSoloPointer.x;
  14821. var offsetY = evt.clientY - cacheSoloPointer.y;
  14822. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  14823. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  14824. }
  14825. cacheSoloPointer.x = evt.clientX;
  14826. cacheSoloPointer.y = evt.clientY;
  14827. }
  14828. else if (pointA && pointB) {
  14829. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  14830. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  14831. ed.x = evt.clientX;
  14832. ed.y = evt.clientY;
  14833. var direction = _this.pinchInwards ? 1 : -1;
  14834. var distX = pointA.x - pointB.x;
  14835. var distY = pointA.y - pointB.y;
  14836. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  14837. if (previousPinchDistance === 0) {
  14838. previousPinchDistance = pinchSquaredDistance;
  14839. return;
  14840. }
  14841. if (pinchSquaredDistance !== previousPinchDistance) {
  14842. _this.camera
  14843. .inertialRadiusOffset += (pinchSquaredDistance - previousPinchDistance) /
  14844. (_this.pinchPrecision *
  14845. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  14846. direction);
  14847. previousPinchDistance = pinchSquaredDistance;
  14848. }
  14849. }
  14850. }
  14851. };
  14852. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  14853. this._onContextMenu = function (evt) {
  14854. evt.preventDefault();
  14855. };
  14856. if (!this.camera._useCtrlForPanning) {
  14857. element.addEventListener("contextmenu", this._onContextMenu, false);
  14858. }
  14859. this._onLostFocus = function () {
  14860. //this._keys = [];
  14861. pointA = pointB = undefined;
  14862. previousPinchDistance = 0;
  14863. cacheSoloPointer = null;
  14864. };
  14865. this._onMouseMove = function (evt) {
  14866. if (!engine.isPointerLock) {
  14867. return;
  14868. }
  14869. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  14870. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  14871. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  14872. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  14873. if (!noPreventDefault) {
  14874. evt.preventDefault();
  14875. }
  14876. };
  14877. this._onGestureStart = function (e) {
  14878. if (window.MSGesture === undefined) {
  14879. return;
  14880. }
  14881. if (!_this._MSGestureHandler) {
  14882. _this._MSGestureHandler = new MSGesture();
  14883. _this._MSGestureHandler.target = element;
  14884. }
  14885. _this._MSGestureHandler.addPointer(e.pointerId);
  14886. };
  14887. this._onGesture = function (e) {
  14888. _this.camera.radius *= e.scale;
  14889. if (e.preventDefault) {
  14890. if (!noPreventDefault) {
  14891. e.stopPropagation();
  14892. e.preventDefault();
  14893. }
  14894. }
  14895. };
  14896. element.addEventListener("mousemove", this._onMouseMove, false);
  14897. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  14898. element.addEventListener("MSGestureChange", this._onGesture, false);
  14899. element.addEventListener("keydown", this._onKeyDown, false);
  14900. element.addEventListener("keyup", this._onKeyUp, false);
  14901. BABYLON.Tools.RegisterTopRootEvents([
  14902. { name: "blur", handler: this._onLostFocus }
  14903. ]);
  14904. };
  14905. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  14906. if (element && this._observer) {
  14907. this.camera.getScene().onPointerObservable.remove(this._observer);
  14908. this._observer = null;
  14909. element.removeEventListener("contextmenu", this._onContextMenu);
  14910. element.removeEventListener("mousemove", this._onMouseMove);
  14911. element.removeEventListener("MSPointerDown", this._onGestureStart);
  14912. element.removeEventListener("MSGestureChange", this._onGesture);
  14913. element.removeEventListener("keydown", this._onKeyDown);
  14914. element.removeEventListener("keyup", this._onKeyUp);
  14915. this._isPanClick = false;
  14916. this.pinchInwards = true;
  14917. this._onKeyDown = null;
  14918. this._onKeyUp = null;
  14919. this._onMouseMove = null;
  14920. this._onGestureStart = null;
  14921. this._onGesture = null;
  14922. this._MSGestureHandler = null;
  14923. this._onLostFocus = null;
  14924. this._onContextMenu = null;
  14925. }
  14926. BABYLON.Tools.UnregisterTopRootEvents([
  14927. { name: "blur", handler: this._onLostFocus }
  14928. ]);
  14929. };
  14930. ArcRotateCameraPointersInput.prototype.getTypeName = function () {
  14931. return "ArcRotateCameraPointersInput";
  14932. };
  14933. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  14934. return "pointers";
  14935. };
  14936. return ArcRotateCameraPointersInput;
  14937. }());
  14938. __decorate([
  14939. BABYLON.serialize()
  14940. ], ArcRotateCameraPointersInput.prototype, "buttons", void 0);
  14941. __decorate([
  14942. BABYLON.serialize()
  14943. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  14944. __decorate([
  14945. BABYLON.serialize()
  14946. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  14947. __decorate([
  14948. BABYLON.serialize()
  14949. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  14950. __decorate([
  14951. BABYLON.serialize()
  14952. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  14953. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  14954. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  14955. })(BABYLON || (BABYLON = {}));
  14956. //# sourceMappingURL=babylon.arcrotatecamera.input.pointers.js.map
  14957. var BABYLON;
  14958. (function (BABYLON) {
  14959. var ArcRotateCameraGamepadInput = (function () {
  14960. function ArcRotateCameraGamepadInput() {
  14961. this.gamepadRotationSensibility = 80;
  14962. this.gamepadMoveSensibility = 40;
  14963. }
  14964. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  14965. var _this = this;
  14966. this._gamepads = new BABYLON.Gamepads(function (gamepad) { _this._onNewGameConnected(gamepad); });
  14967. };
  14968. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  14969. if (this._gamepads) {
  14970. this._gamepads.dispose();
  14971. }
  14972. this.gamepad = null;
  14973. };
  14974. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  14975. if (this.gamepad) {
  14976. var camera = this.camera;
  14977. var RSValues = this.gamepad.rightStick;
  14978. if (RSValues.x != 0) {
  14979. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  14980. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  14981. camera.inertialAlphaOffset += normalizedRX;
  14982. }
  14983. }
  14984. if (RSValues.y != 0) {
  14985. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  14986. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  14987. camera.inertialBetaOffset += normalizedRY;
  14988. }
  14989. }
  14990. var LSValues = this.gamepad.leftStick;
  14991. if (LSValues.y != 0) {
  14992. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  14993. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  14994. this.camera.inertialRadiusOffset -= normalizedLY;
  14995. }
  14996. }
  14997. }
  14998. };
  14999. ArcRotateCameraGamepadInput.prototype._onNewGameConnected = function (gamepad) {
  15000. // Only the first gamepad can control the camera
  15001. if (gamepad.index === 0) {
  15002. this.gamepad = gamepad;
  15003. }
  15004. };
  15005. ArcRotateCameraGamepadInput.prototype.getTypeName = function () {
  15006. return "ArcRotateCameraGamepadInput";
  15007. };
  15008. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  15009. return "gamepad";
  15010. };
  15011. return ArcRotateCameraGamepadInput;
  15012. }());
  15013. __decorate([
  15014. BABYLON.serialize()
  15015. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  15016. __decorate([
  15017. BABYLON.serialize()
  15018. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  15019. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  15020. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  15021. })(BABYLON || (BABYLON = {}));
  15022. //# sourceMappingURL=babylon.arcrotatecamera.input.gamepad.js.map
  15023. var BABYLON;
  15024. (function (BABYLON) {
  15025. var ArcRotateCameraVRDeviceOrientationInput = (function () {
  15026. function ArcRotateCameraVRDeviceOrientationInput() {
  15027. this.alphaCorrection = 1;
  15028. this.betaCorrection = 1;
  15029. this.gammaCorrection = 1;
  15030. this._alpha = 0;
  15031. this._beta = 0;
  15032. this._gamma = 0;
  15033. this._dirty = false;
  15034. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  15035. }
  15036. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  15037. this.camera.attachControl(element, noPreventDefault);
  15038. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  15039. };
  15040. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  15041. var camera = this.camera;
  15042. this._alpha = +evt.alpha | 0;
  15043. this._beta = +evt.beta | 0;
  15044. this._gamma = +evt.gamma | 0;
  15045. this._dirty = true;
  15046. };
  15047. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  15048. if (this._dirty) {
  15049. this._dirty = false;
  15050. if (this._gamma < 0) {
  15051. this._gamma = 180 + this._gamma;
  15052. }
  15053. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  15054. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  15055. }
  15056. };
  15057. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  15058. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  15059. };
  15060. ArcRotateCameraVRDeviceOrientationInput.prototype.getTypeName = function () {
  15061. return "ArcRotateCameraVRDeviceOrientationInput";
  15062. };
  15063. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  15064. return "VRDeviceOrientation";
  15065. };
  15066. return ArcRotateCameraVRDeviceOrientationInput;
  15067. }());
  15068. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  15069. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  15070. })(BABYLON || (BABYLON = {}));
  15071. //# sourceMappingURL=babylon.arcrotatecamera.input.vrdeviceorientation.js.map
  15072. var BABYLON;
  15073. (function (BABYLON) {
  15074. var TargetCamera = (function (_super) {
  15075. __extends(TargetCamera, _super);
  15076. function TargetCamera(name, position, scene) {
  15077. var _this = _super.call(this, name, position, scene) || this;
  15078. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  15079. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  15080. _this.rotation = new BABYLON.Vector3(0, 0, 0);
  15081. _this.speed = 2.0;
  15082. _this.noRotationConstraint = false;
  15083. _this.lockedTarget = null;
  15084. _this._currentTarget = BABYLON.Vector3.Zero();
  15085. _this._viewMatrix = BABYLON.Matrix.Zero();
  15086. _this._camMatrix = BABYLON.Matrix.Zero();
  15087. _this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  15088. _this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  15089. _this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  15090. _this._defaultUpVector = new BABYLON.Vector3(0, 1, 0);
  15091. _this._transformedReferencePoint = BABYLON.Vector3.Zero();
  15092. _this._lookAtTemp = BABYLON.Matrix.Zero();
  15093. _this._tempMatrix = BABYLON.Matrix.Zero();
  15094. return _this;
  15095. }
  15096. TargetCamera.prototype.getFrontPosition = function (distance) {
  15097. var direction = this.getTarget().subtract(this.position);
  15098. direction.normalize();
  15099. direction.scaleInPlace(distance);
  15100. return this.globalPosition.add(direction);
  15101. };
  15102. TargetCamera.prototype._getLockedTargetPosition = function () {
  15103. if (!this.lockedTarget) {
  15104. return null;
  15105. }
  15106. if (this.lockedTarget.absolutePosition) {
  15107. this.lockedTarget.computeWorldMatrix();
  15108. }
  15109. return this.lockedTarget.absolutePosition || this.lockedTarget;
  15110. };
  15111. // Cache
  15112. TargetCamera.prototype._initCache = function () {
  15113. _super.prototype._initCache.call(this);
  15114. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  15115. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  15116. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  15117. };
  15118. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  15119. if (!ignoreParentClass) {
  15120. _super.prototype._updateCache.call(this);
  15121. }
  15122. var lockedTargetPosition = this._getLockedTargetPosition();
  15123. if (!lockedTargetPosition) {
  15124. this._cache.lockedTarget = null;
  15125. }
  15126. else {
  15127. if (!this._cache.lockedTarget) {
  15128. this._cache.lockedTarget = lockedTargetPosition.clone();
  15129. }
  15130. else {
  15131. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  15132. }
  15133. }
  15134. this._cache.rotation.copyFrom(this.rotation);
  15135. if (this.rotationQuaternion)
  15136. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  15137. };
  15138. // Synchronized
  15139. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  15140. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  15141. return false;
  15142. }
  15143. var lockedTargetPosition = this._getLockedTargetPosition();
  15144. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  15145. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  15146. };
  15147. // Methods
  15148. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  15149. var engine = this.getEngine();
  15150. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  15151. };
  15152. // Target
  15153. TargetCamera.prototype.setTarget = function (target) {
  15154. this.upVector.normalize();
  15155. BABYLON.Matrix.LookAtLHToRef(this.position, target, this._defaultUpVector, this._camMatrix);
  15156. this._camMatrix.invert();
  15157. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  15158. var vDir = target.subtract(this.position);
  15159. if (vDir.x >= 0.0) {
  15160. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  15161. }
  15162. else {
  15163. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  15164. }
  15165. this.rotation.z = 0;
  15166. if (isNaN(this.rotation.x)) {
  15167. this.rotation.x = 0;
  15168. }
  15169. if (isNaN(this.rotation.y)) {
  15170. this.rotation.y = 0;
  15171. }
  15172. if (isNaN(this.rotation.z)) {
  15173. this.rotation.z = 0;
  15174. }
  15175. if (this.rotationQuaternion) {
  15176. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  15177. }
  15178. };
  15179. TargetCamera.prototype.getTarget = function () {
  15180. return this._currentTarget;
  15181. };
  15182. TargetCamera.prototype._decideIfNeedsToMove = function () {
  15183. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  15184. };
  15185. TargetCamera.prototype._updatePosition = function () {
  15186. this.position.addInPlace(this.cameraDirection);
  15187. };
  15188. TargetCamera.prototype._checkInputs = function () {
  15189. var needToMove = this._decideIfNeedsToMove();
  15190. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  15191. // Move
  15192. if (needToMove) {
  15193. this._updatePosition();
  15194. }
  15195. // Rotate
  15196. if (needToRotate) {
  15197. this.rotation.x += this.cameraRotation.x;
  15198. this.rotation.y += this.cameraRotation.y;
  15199. if (!this.noRotationConstraint) {
  15200. var limit = (Math.PI / 2) * 0.95;
  15201. if (this.rotation.x > limit)
  15202. this.rotation.x = limit;
  15203. if (this.rotation.x < -limit)
  15204. this.rotation.x = -limit;
  15205. }
  15206. }
  15207. // Inertia
  15208. if (needToMove) {
  15209. if (Math.abs(this.cameraDirection.x) < BABYLON.Epsilon) {
  15210. this.cameraDirection.x = 0;
  15211. }
  15212. if (Math.abs(this.cameraDirection.y) < BABYLON.Epsilon) {
  15213. this.cameraDirection.y = 0;
  15214. }
  15215. if (Math.abs(this.cameraDirection.z) < BABYLON.Epsilon) {
  15216. this.cameraDirection.z = 0;
  15217. }
  15218. this.cameraDirection.scaleInPlace(this.inertia);
  15219. }
  15220. if (needToRotate) {
  15221. if (Math.abs(this.cameraRotation.x) < BABYLON.Epsilon) {
  15222. this.cameraRotation.x = 0;
  15223. }
  15224. if (Math.abs(this.cameraRotation.y) < BABYLON.Epsilon) {
  15225. this.cameraRotation.y = 0;
  15226. }
  15227. this.cameraRotation.scaleInPlace(this.inertia);
  15228. }
  15229. _super.prototype._checkInputs.call(this);
  15230. };
  15231. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  15232. if (this.rotationQuaternion) {
  15233. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  15234. //update the up vector!
  15235. BABYLON.Vector3.TransformNormalToRef(this._defaultUpVector, this._cameraRotationMatrix, this.upVector);
  15236. }
  15237. else {
  15238. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  15239. }
  15240. };
  15241. TargetCamera.prototype._getViewMatrix = function () {
  15242. if (!this.lockedTarget) {
  15243. // Compute
  15244. this._updateCameraRotationMatrix();
  15245. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  15246. // Computing target and final matrix
  15247. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  15248. }
  15249. else {
  15250. this._currentTarget.copyFrom(this._getLockedTargetPosition());
  15251. }
  15252. if (this.getScene().useRightHandedSystem) {
  15253. BABYLON.Matrix.LookAtRHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  15254. }
  15255. else {
  15256. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  15257. }
  15258. return this._viewMatrix;
  15259. };
  15260. /**
  15261. * @override
  15262. * Override Camera.createRigCamera
  15263. */
  15264. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  15265. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  15266. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  15267. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
  15268. if (!this.rotationQuaternion) {
  15269. this.rotationQuaternion = new BABYLON.Quaternion();
  15270. }
  15271. rigCamera._cameraRigParams = {};
  15272. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  15273. }
  15274. return rigCamera;
  15275. }
  15276. return null;
  15277. };
  15278. /**
  15279. * @override
  15280. * Override Camera._updateRigCameras
  15281. */
  15282. TargetCamera.prototype._updateRigCameras = function () {
  15283. var camLeft = this._rigCameras[0];
  15284. var camRight = this._rigCameras[1];
  15285. switch (this.cameraRigMode) {
  15286. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  15287. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  15288. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  15289. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  15290. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  15291. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  15292. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  15293. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  15294. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  15295. camLeft.setTarget(this.getTarget());
  15296. camRight.setTarget(this.getTarget());
  15297. break;
  15298. case BABYLON.Camera.RIG_MODE_VR:
  15299. case BABYLON.Camera.RIG_MODE_WEBVR:
  15300. if (camLeft.rotationQuaternion) {
  15301. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  15302. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  15303. }
  15304. else {
  15305. camLeft.rotation.copyFrom(this.rotation);
  15306. camRight.rotation.copyFrom(this.rotation);
  15307. }
  15308. camLeft.position.copyFrom(this.position);
  15309. camRight.position.copyFrom(this.position);
  15310. break;
  15311. }
  15312. _super.prototype._updateRigCameras.call(this);
  15313. };
  15314. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  15315. if (!this._rigCamTransformMatrix) {
  15316. this._rigCamTransformMatrix = new BABYLON.Matrix();
  15317. }
  15318. var target = this.getTarget();
  15319. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  15320. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  15321. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  15322. };
  15323. TargetCamera.prototype.getClassName = function () {
  15324. return "TargetCamera";
  15325. };
  15326. return TargetCamera;
  15327. }(BABYLON.Camera));
  15328. __decorate([
  15329. BABYLON.serializeAsVector3()
  15330. ], TargetCamera.prototype, "rotation", void 0);
  15331. __decorate([
  15332. BABYLON.serialize()
  15333. ], TargetCamera.prototype, "speed", void 0);
  15334. __decorate([
  15335. BABYLON.serializeAsMeshReference("lockedTargetId")
  15336. ], TargetCamera.prototype, "lockedTarget", void 0);
  15337. BABYLON.TargetCamera = TargetCamera;
  15338. })(BABYLON || (BABYLON = {}));
  15339. //# sourceMappingURL=babylon.targetCamera.js.map
  15340. var BABYLON;
  15341. (function (BABYLON) {
  15342. var FreeCamera = (function (_super) {
  15343. __extends(FreeCamera, _super);
  15344. function FreeCamera(name, position, scene) {
  15345. var _this = _super.call(this, name, position, scene) || this;
  15346. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  15347. _this.checkCollisions = false;
  15348. _this.applyGravity = false;
  15349. _this._collider = new BABYLON.Collider();
  15350. _this._needMoveForGravity = false;
  15351. _this._oldPosition = BABYLON.Vector3.Zero();
  15352. _this._diffPosition = BABYLON.Vector3.Zero();
  15353. _this._newPosition = BABYLON.Vector3.Zero();
  15354. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  15355. if (collidedMesh === void 0) { collidedMesh = null; }
  15356. //TODO move this to the collision coordinator!
  15357. if (_this.getScene().workerCollisions)
  15358. newPosition.multiplyInPlace(_this._collider.radius);
  15359. var updatePosition = function (newPos) {
  15360. _this._newPosition.copyFrom(newPos);
  15361. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  15362. var oldPosition = _this.position.clone();
  15363. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  15364. _this.position.addInPlace(_this._diffPosition);
  15365. if (_this.onCollide && collidedMesh) {
  15366. _this.onCollide(collidedMesh);
  15367. }
  15368. }
  15369. };
  15370. updatePosition(newPosition);
  15371. };
  15372. _this.inputs = new BABYLON.FreeCameraInputsManager(_this);
  15373. _this.inputs.addKeyboard().addMouse();
  15374. return _this;
  15375. }
  15376. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  15377. //-- begin properties for backward compatibility for inputs
  15378. get: function () {
  15379. var mouse = this.inputs.attached["mouse"];
  15380. if (mouse)
  15381. return mouse.angularSensibility;
  15382. },
  15383. set: function (value) {
  15384. var mouse = this.inputs.attached["mouse"];
  15385. if (mouse)
  15386. mouse.angularSensibility = value;
  15387. },
  15388. enumerable: true,
  15389. configurable: true
  15390. });
  15391. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  15392. get: function () {
  15393. var keyboard = this.inputs.attached["keyboard"];
  15394. if (keyboard)
  15395. return keyboard.keysUp;
  15396. },
  15397. set: function (value) {
  15398. var keyboard = this.inputs.attached["keyboard"];
  15399. if (keyboard)
  15400. keyboard.keysUp = value;
  15401. },
  15402. enumerable: true,
  15403. configurable: true
  15404. });
  15405. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  15406. get: function () {
  15407. var keyboard = this.inputs.attached["keyboard"];
  15408. if (keyboard)
  15409. return keyboard.keysDown;
  15410. },
  15411. set: function (value) {
  15412. var keyboard = this.inputs.attached["keyboard"];
  15413. if (keyboard)
  15414. keyboard.keysDown = value;
  15415. },
  15416. enumerable: true,
  15417. configurable: true
  15418. });
  15419. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  15420. get: function () {
  15421. var keyboard = this.inputs.attached["keyboard"];
  15422. if (keyboard)
  15423. return keyboard.keysLeft;
  15424. },
  15425. set: function (value) {
  15426. var keyboard = this.inputs.attached["keyboard"];
  15427. if (keyboard)
  15428. keyboard.keysLeft = value;
  15429. },
  15430. enumerable: true,
  15431. configurable: true
  15432. });
  15433. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  15434. get: function () {
  15435. var keyboard = this.inputs.attached["keyboard"];
  15436. if (keyboard)
  15437. return keyboard.keysRight;
  15438. },
  15439. set: function (value) {
  15440. var keyboard = this.inputs.attached["keyboard"];
  15441. if (keyboard)
  15442. keyboard.keysRight = value;
  15443. },
  15444. enumerable: true,
  15445. configurable: true
  15446. });
  15447. // Controls
  15448. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  15449. this.inputs.attachElement(element, noPreventDefault);
  15450. };
  15451. FreeCamera.prototype.detachControl = function (element) {
  15452. this.inputs.detachElement(element);
  15453. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  15454. this.cameraRotation = new BABYLON.Vector2(0, 0);
  15455. };
  15456. FreeCamera.prototype._collideWithWorld = function (velocity) {
  15457. var globalPosition;
  15458. if (this.parent) {
  15459. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  15460. }
  15461. else {
  15462. globalPosition = this.position;
  15463. }
  15464. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  15465. this._collider.radius = this.ellipsoid;
  15466. //no need for clone, as long as gravity is not on.
  15467. var actualVelocity = velocity;
  15468. //add gravity to the velocity to prevent the dual-collision checking
  15469. if (this.applyGravity) {
  15470. //this prevents mending with cameraDirection, a global variable of the free camera class.
  15471. actualVelocity = velocity.add(this.getScene().gravity);
  15472. }
  15473. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  15474. };
  15475. FreeCamera.prototype._checkInputs = function () {
  15476. if (!this._localDirection) {
  15477. this._localDirection = BABYLON.Vector3.Zero();
  15478. this._transformedDirection = BABYLON.Vector3.Zero();
  15479. }
  15480. this.inputs.checkInputs();
  15481. _super.prototype._checkInputs.call(this);
  15482. };
  15483. FreeCamera.prototype._decideIfNeedsToMove = function () {
  15484. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  15485. };
  15486. FreeCamera.prototype._updatePosition = function () {
  15487. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  15488. this._collideWithWorld(this.cameraDirection);
  15489. }
  15490. else {
  15491. this.position.addInPlace(this.cameraDirection);
  15492. }
  15493. };
  15494. FreeCamera.prototype.dispose = function () {
  15495. this.inputs.clear();
  15496. _super.prototype.dispose.call(this);
  15497. };
  15498. FreeCamera.prototype.getClassName = function () {
  15499. return "FreeCamera";
  15500. };
  15501. return FreeCamera;
  15502. }(BABYLON.TargetCamera));
  15503. __decorate([
  15504. BABYLON.serializeAsVector3()
  15505. ], FreeCamera.prototype, "ellipsoid", void 0);
  15506. __decorate([
  15507. BABYLON.serialize()
  15508. ], FreeCamera.prototype, "checkCollisions", void 0);
  15509. __decorate([
  15510. BABYLON.serialize()
  15511. ], FreeCamera.prototype, "applyGravity", void 0);
  15512. BABYLON.FreeCamera = FreeCamera;
  15513. })(BABYLON || (BABYLON = {}));
  15514. //# sourceMappingURL=babylon.freeCamera.js.map
  15515. var BABYLON;
  15516. (function (BABYLON) {
  15517. var FreeCameraInputsManager = (function (_super) {
  15518. __extends(FreeCameraInputsManager, _super);
  15519. function FreeCameraInputsManager(camera) {
  15520. return _super.call(this, camera) || this;
  15521. }
  15522. FreeCameraInputsManager.prototype.addKeyboard = function () {
  15523. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  15524. return this;
  15525. };
  15526. FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  15527. if (touchEnabled === void 0) { touchEnabled = true; }
  15528. this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
  15529. return this;
  15530. };
  15531. FreeCameraInputsManager.prototype.addGamepad = function () {
  15532. this.add(new BABYLON.FreeCameraGamepadInput());
  15533. return this;
  15534. };
  15535. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  15536. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  15537. return this;
  15538. };
  15539. FreeCameraInputsManager.prototype.addTouch = function () {
  15540. this.add(new BABYLON.FreeCameraTouchInput());
  15541. return this;
  15542. };
  15543. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  15544. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  15545. return this;
  15546. };
  15547. return FreeCameraInputsManager;
  15548. }(BABYLON.CameraInputsManager));
  15549. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  15550. })(BABYLON || (BABYLON = {}));
  15551. //# sourceMappingURL=babylon.freeCameraInputsManager.js.map
  15552. var BABYLON;
  15553. (function (BABYLON) {
  15554. var FollowCamera = (function (_super) {
  15555. __extends(FollowCamera, _super);
  15556. function FollowCamera(name, position, scene, lockedTarget) {
  15557. var _this = _super.call(this, name, position, scene) || this;
  15558. _this.radius = 12;
  15559. _this.rotationOffset = 0;
  15560. _this.heightOffset = 4;
  15561. _this.cameraAcceleration = 0.05;
  15562. _this.maxCameraSpeed = 20;
  15563. _this.lockedTarget = lockedTarget;
  15564. return _this;
  15565. }
  15566. FollowCamera.prototype.getRadians = function (degrees) {
  15567. return degrees * Math.PI / 180;
  15568. };
  15569. FollowCamera.prototype.follow = function (cameraTarget) {
  15570. if (!cameraTarget)
  15571. return;
  15572. var yRotation;
  15573. if (cameraTarget.rotationQuaternion) {
  15574. var rotMatrix = new BABYLON.Matrix();
  15575. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  15576. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  15577. }
  15578. else {
  15579. yRotation = cameraTarget.rotation.y;
  15580. }
  15581. var radians = this.getRadians(this.rotationOffset) + yRotation;
  15582. var targetX = cameraTarget.position.x + Math.sin(radians) * this.radius;
  15583. var targetZ = cameraTarget.position.z + Math.cos(radians) * this.radius;
  15584. var dx = targetX - this.position.x;
  15585. var dy = (cameraTarget.position.y + this.heightOffset) - this.position.y;
  15586. var dz = (targetZ) - this.position.z;
  15587. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  15588. var vy = dy * this.cameraAcceleration;
  15589. var vz = dz * this.cameraAcceleration * 2;
  15590. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  15591. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  15592. }
  15593. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  15594. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  15595. }
  15596. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  15597. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  15598. }
  15599. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  15600. this.setTarget(cameraTarget.position);
  15601. };
  15602. FollowCamera.prototype._checkInputs = function () {
  15603. _super.prototype._checkInputs.call(this);
  15604. this.follow(this.lockedTarget);
  15605. };
  15606. FollowCamera.prototype.getClassName = function () {
  15607. return "FollowCamera";
  15608. };
  15609. return FollowCamera;
  15610. }(BABYLON.TargetCamera));
  15611. __decorate([
  15612. BABYLON.serialize()
  15613. ], FollowCamera.prototype, "radius", void 0);
  15614. __decorate([
  15615. BABYLON.serialize()
  15616. ], FollowCamera.prototype, "rotationOffset", void 0);
  15617. __decorate([
  15618. BABYLON.serialize()
  15619. ], FollowCamera.prototype, "heightOffset", void 0);
  15620. __decorate([
  15621. BABYLON.serialize()
  15622. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  15623. __decorate([
  15624. BABYLON.serialize()
  15625. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  15626. __decorate([
  15627. BABYLON.serializeAsMeshReference("lockedTargetId")
  15628. ], FollowCamera.prototype, "lockedTarget", void 0);
  15629. BABYLON.FollowCamera = FollowCamera;
  15630. var ArcFollowCamera = (function (_super) {
  15631. __extends(ArcFollowCamera, _super);
  15632. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  15633. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  15634. _this.alpha = alpha;
  15635. _this.beta = beta;
  15636. _this.radius = radius;
  15637. _this.target = target;
  15638. _this._cartesianCoordinates = BABYLON.Vector3.Zero();
  15639. _this.follow();
  15640. return _this;
  15641. }
  15642. ArcFollowCamera.prototype.follow = function () {
  15643. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  15644. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  15645. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  15646. this.position = this.target.position.add(this._cartesianCoordinates);
  15647. this.setTarget(this.target.position);
  15648. };
  15649. ArcFollowCamera.prototype._checkInputs = function () {
  15650. _super.prototype._checkInputs.call(this);
  15651. this.follow();
  15652. };
  15653. ArcFollowCamera.prototype.getClassName = function () {
  15654. return "ArcFollowCamera";
  15655. };
  15656. return ArcFollowCamera;
  15657. }(BABYLON.TargetCamera));
  15658. BABYLON.ArcFollowCamera = ArcFollowCamera;
  15659. })(BABYLON || (BABYLON = {}));
  15660. //# sourceMappingURL=babylon.followCamera.js.map
  15661. var BABYLON;
  15662. (function (BABYLON) {
  15663. // We're mainly based on the logic defined into the FreeCamera code
  15664. var TouchCamera = (function (_super) {
  15665. __extends(TouchCamera, _super);
  15666. //-- end properties for backward compatibility for inputs
  15667. function TouchCamera(name, position, scene) {
  15668. var _this = _super.call(this, name, position, scene) || this;
  15669. _this.inputs.addTouch();
  15670. _this._setupInputs();
  15671. return _this;
  15672. }
  15673. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  15674. //-- Begin properties for backward compatibility for inputs
  15675. get: function () {
  15676. var touch = this.inputs.attached["touch"];
  15677. if (touch)
  15678. return touch.touchAngularSensibility;
  15679. },
  15680. set: function (value) {
  15681. var touch = this.inputs.attached["touch"];
  15682. if (touch)
  15683. touch.touchAngularSensibility = value;
  15684. },
  15685. enumerable: true,
  15686. configurable: true
  15687. });
  15688. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  15689. get: function () {
  15690. var touch = this.inputs.attached["touch"];
  15691. if (touch)
  15692. return touch.touchMoveSensibility;
  15693. },
  15694. set: function (value) {
  15695. var touch = this.inputs.attached["touch"];
  15696. if (touch)
  15697. touch.touchMoveSensibility = value;
  15698. },
  15699. enumerable: true,
  15700. configurable: true
  15701. });
  15702. TouchCamera.prototype.getClassName = function () {
  15703. return "TouchCamera";
  15704. };
  15705. TouchCamera.prototype._setupInputs = function () {
  15706. var mouse = this.inputs.attached["mouse"];
  15707. if (mouse) {
  15708. mouse.touchEnabled = false;
  15709. }
  15710. };
  15711. return TouchCamera;
  15712. }(BABYLON.FreeCamera));
  15713. BABYLON.TouchCamera = TouchCamera;
  15714. })(BABYLON || (BABYLON = {}));
  15715. //# sourceMappingURL=babylon.touchCamera.js.map
  15716. var BABYLON;
  15717. (function (BABYLON) {
  15718. var ArcRotateCamera = (function (_super) {
  15719. __extends(ArcRotateCamera, _super);
  15720. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  15721. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  15722. _this.inertialAlphaOffset = 0;
  15723. _this.inertialBetaOffset = 0;
  15724. _this.inertialRadiusOffset = 0;
  15725. _this.lowerAlphaLimit = null;
  15726. _this.upperAlphaLimit = null;
  15727. _this.lowerBetaLimit = 0.01;
  15728. _this.upperBetaLimit = Math.PI;
  15729. _this.lowerRadiusLimit = null;
  15730. _this.upperRadiusLimit = null;
  15731. _this.inertialPanningX = 0;
  15732. _this.inertialPanningY = 0;
  15733. //-- end properties for backward compatibility for inputs
  15734. _this.zoomOnFactor = 1;
  15735. _this.targetScreenOffset = BABYLON.Vector2.Zero();
  15736. _this.allowUpsideDown = true;
  15737. _this._viewMatrix = new BABYLON.Matrix();
  15738. // Panning
  15739. _this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  15740. _this.checkCollisions = false;
  15741. _this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  15742. _this._collider = new BABYLON.Collider();
  15743. _this._previousPosition = BABYLON.Vector3.Zero();
  15744. _this._collisionVelocity = BABYLON.Vector3.Zero();
  15745. _this._newPosition = BABYLON.Vector3.Zero();
  15746. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  15747. if (collidedMesh === void 0) { collidedMesh = null; }
  15748. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  15749. newPosition.multiplyInPlace(_this._collider.radius);
  15750. }
  15751. if (!collidedMesh) {
  15752. _this._previousPosition.copyFrom(_this.position);
  15753. }
  15754. else {
  15755. _this.setPosition(newPosition);
  15756. if (_this.onCollide) {
  15757. _this.onCollide(collidedMesh);
  15758. }
  15759. }
  15760. // Recompute because of constraints
  15761. var cosa = Math.cos(_this.alpha);
  15762. var sina = Math.sin(_this.alpha);
  15763. var cosb = Math.cos(_this.beta);
  15764. var sinb = Math.sin(_this.beta);
  15765. if (sinb === 0) {
  15766. sinb = 0.0001;
  15767. }
  15768. var target = _this._getTargetPosition();
  15769. target.addToRef(new BABYLON.Vector3(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb), _this._newPosition);
  15770. _this.position.copyFrom(_this._newPosition);
  15771. var up = _this.upVector;
  15772. if (_this.allowUpsideDown && _this.beta < 0) {
  15773. up = up.clone();
  15774. up = up.negate();
  15775. }
  15776. BABYLON.Matrix.LookAtLHToRef(_this.position, target, up, _this._viewMatrix);
  15777. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  15778. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  15779. _this._collisionTriggered = false;
  15780. };
  15781. if (!target) {
  15782. _this.target = BABYLON.Vector3.Zero();
  15783. }
  15784. else {
  15785. _this.target = target;
  15786. }
  15787. _this.alpha = alpha;
  15788. _this.beta = beta;
  15789. _this.radius = radius;
  15790. _this.getViewMatrix();
  15791. _this.inputs = new BABYLON.ArcRotateCameraInputsManager(_this);
  15792. _this.inputs.addKeyboard().addMouseWheel().addPointers().addGamepad();
  15793. return _this;
  15794. }
  15795. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  15796. //-- begin properties for backward compatibility for inputs
  15797. get: function () {
  15798. var pointers = this.inputs.attached["pointers"];
  15799. if (pointers)
  15800. return pointers.angularSensibilityX;
  15801. },
  15802. set: function (value) {
  15803. var pointers = this.inputs.attached["pointers"];
  15804. if (pointers) {
  15805. pointers.angularSensibilityX = value;
  15806. }
  15807. },
  15808. enumerable: true,
  15809. configurable: true
  15810. });
  15811. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  15812. get: function () {
  15813. var pointers = this.inputs.attached["pointers"];
  15814. if (pointers)
  15815. return pointers.angularSensibilityY;
  15816. },
  15817. set: function (value) {
  15818. var pointers = this.inputs.attached["pointers"];
  15819. if (pointers) {
  15820. pointers.angularSensibilityY = value;
  15821. }
  15822. },
  15823. enumerable: true,
  15824. configurable: true
  15825. });
  15826. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  15827. get: function () {
  15828. var pointers = this.inputs.attached["pointers"];
  15829. if (pointers)
  15830. return pointers.pinchPrecision;
  15831. },
  15832. set: function (value) {
  15833. var pointers = this.inputs.attached["pointers"];
  15834. if (pointers) {
  15835. pointers.pinchPrecision = value;
  15836. }
  15837. },
  15838. enumerable: true,
  15839. configurable: true
  15840. });
  15841. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  15842. get: function () {
  15843. var pointers = this.inputs.attached["pointers"];
  15844. if (pointers)
  15845. return pointers.panningSensibility;
  15846. },
  15847. set: function (value) {
  15848. var pointers = this.inputs.attached["pointers"];
  15849. if (pointers) {
  15850. pointers.panningSensibility = value;
  15851. }
  15852. },
  15853. enumerable: true,
  15854. configurable: true
  15855. });
  15856. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  15857. get: function () {
  15858. var keyboard = this.inputs.attached["keyboard"];
  15859. if (keyboard)
  15860. return keyboard.keysUp;
  15861. },
  15862. set: function (value) {
  15863. var keyboard = this.inputs.attached["keyboard"];
  15864. if (keyboard)
  15865. keyboard.keysUp = value;
  15866. },
  15867. enumerable: true,
  15868. configurable: true
  15869. });
  15870. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  15871. get: function () {
  15872. var keyboard = this.inputs.attached["keyboard"];
  15873. if (keyboard)
  15874. return keyboard.keysDown;
  15875. },
  15876. set: function (value) {
  15877. var keyboard = this.inputs.attached["keyboard"];
  15878. if (keyboard)
  15879. keyboard.keysDown = value;
  15880. },
  15881. enumerable: true,
  15882. configurable: true
  15883. });
  15884. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  15885. get: function () {
  15886. var keyboard = this.inputs.attached["keyboard"];
  15887. if (keyboard)
  15888. return keyboard.keysLeft;
  15889. },
  15890. set: function (value) {
  15891. var keyboard = this.inputs.attached["keyboard"];
  15892. if (keyboard)
  15893. keyboard.keysLeft = value;
  15894. },
  15895. enumerable: true,
  15896. configurable: true
  15897. });
  15898. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  15899. get: function () {
  15900. var keyboard = this.inputs.attached["keyboard"];
  15901. if (keyboard)
  15902. return keyboard.keysRight;
  15903. },
  15904. set: function (value) {
  15905. var keyboard = this.inputs.attached["keyboard"];
  15906. if (keyboard)
  15907. keyboard.keysRight = value;
  15908. },
  15909. enumerable: true,
  15910. configurable: true
  15911. });
  15912. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  15913. get: function () {
  15914. var mousewheel = this.inputs.attached["mousewheel"];
  15915. if (mousewheel)
  15916. return mousewheel.wheelPrecision;
  15917. },
  15918. set: function (value) {
  15919. var mousewheel = this.inputs.attached["mousewheel"];
  15920. if (mousewheel)
  15921. mousewheel.wheelPrecision = value;
  15922. },
  15923. enumerable: true,
  15924. configurable: true
  15925. });
  15926. // Cache
  15927. ArcRotateCamera.prototype._initCache = function () {
  15928. _super.prototype._initCache.call(this);
  15929. this._cache.target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  15930. this._cache.alpha = undefined;
  15931. this._cache.beta = undefined;
  15932. this._cache.radius = undefined;
  15933. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  15934. };
  15935. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  15936. if (!ignoreParentClass) {
  15937. _super.prototype._updateCache.call(this);
  15938. }
  15939. this._cache.target.copyFrom(this._getTargetPosition());
  15940. this._cache.alpha = this.alpha;
  15941. this._cache.beta = this.beta;
  15942. this._cache.radius = this.radius;
  15943. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  15944. };
  15945. ArcRotateCamera.prototype._getTargetPosition = function () {
  15946. if (this.target.getAbsolutePosition) {
  15947. var pos = this.target.getAbsolutePosition();
  15948. return this._targetBoundingCenter ? pos.add(this._targetBoundingCenter) : pos;
  15949. }
  15950. return this.target;
  15951. };
  15952. // Synchronized
  15953. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  15954. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  15955. return false;
  15956. return this._cache.target.equals(this.target)
  15957. && this._cache.alpha === this.alpha
  15958. && this._cache.beta === this.beta
  15959. && this._cache.radius === this.radius
  15960. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  15961. };
  15962. // Methods
  15963. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  15964. var _this = this;
  15965. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  15966. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  15967. this._useCtrlForPanning = useCtrlForPanning;
  15968. this._panningMouseButton = panningMouseButton;
  15969. this.inputs.attachElement(element, noPreventDefault);
  15970. this._reset = function () {
  15971. _this.inertialAlphaOffset = 0;
  15972. _this.inertialBetaOffset = 0;
  15973. _this.inertialRadiusOffset = 0;
  15974. };
  15975. };
  15976. ArcRotateCamera.prototype.detachControl = function (element) {
  15977. this.inputs.detachElement(element);
  15978. if (this._reset) {
  15979. this._reset();
  15980. }
  15981. };
  15982. ArcRotateCamera.prototype._checkInputs = function () {
  15983. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  15984. if (this._collisionTriggered) {
  15985. return;
  15986. }
  15987. this.inputs.checkInputs();
  15988. // Inertia
  15989. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  15990. if (this.getScene().useRightHandedSystem) {
  15991. this.alpha -= this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  15992. }
  15993. else {
  15994. this.alpha += this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  15995. }
  15996. this.beta += this.inertialBetaOffset;
  15997. this.radius -= this.inertialRadiusOffset;
  15998. this.inertialAlphaOffset *= this.inertia;
  15999. this.inertialBetaOffset *= this.inertia;
  16000. this.inertialRadiusOffset *= this.inertia;
  16001. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)
  16002. this.inertialAlphaOffset = 0;
  16003. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)
  16004. this.inertialBetaOffset = 0;
  16005. if (Math.abs(this.inertialRadiusOffset) < BABYLON.Epsilon)
  16006. this.inertialRadiusOffset = 0;
  16007. }
  16008. // Panning inertia
  16009. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  16010. if (!this._localDirection) {
  16011. this._localDirection = BABYLON.Vector3.Zero();
  16012. this._transformedDirection = BABYLON.Vector3.Zero();
  16013. }
  16014. this.inertialPanningX *= this.inertia;
  16015. this.inertialPanningY *= this.inertia;
  16016. if (Math.abs(this.inertialPanningX) < BABYLON.Epsilon)
  16017. this.inertialPanningX = 0;
  16018. if (Math.abs(this.inertialPanningY) < BABYLON.Epsilon)
  16019. this.inertialPanningY = 0;
  16020. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  16021. this._localDirection.multiplyInPlace(this.panningAxis);
  16022. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  16023. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  16024. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  16025. if (!this.panningAxis.y) {
  16026. this._transformedDirection.y = 0;
  16027. }
  16028. if (!this.target.getAbsolutePosition) {
  16029. this.target.addInPlace(this._transformedDirection);
  16030. }
  16031. }
  16032. // Limits
  16033. this._checkLimits();
  16034. _super.prototype._checkInputs.call(this);
  16035. };
  16036. ArcRotateCamera.prototype._checkLimits = function () {
  16037. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  16038. if (this.allowUpsideDown && this.beta > Math.PI) {
  16039. this.beta = this.beta - (2 * Math.PI);
  16040. }
  16041. }
  16042. else {
  16043. if (this.beta < this.lowerBetaLimit) {
  16044. this.beta = this.lowerBetaLimit;
  16045. }
  16046. }
  16047. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  16048. if (this.allowUpsideDown && this.beta < -Math.PI) {
  16049. this.beta = this.beta + (2 * Math.PI);
  16050. }
  16051. }
  16052. else {
  16053. if (this.beta > this.upperBetaLimit) {
  16054. this.beta = this.upperBetaLimit;
  16055. }
  16056. }
  16057. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  16058. this.alpha = this.lowerAlphaLimit;
  16059. }
  16060. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  16061. this.alpha = this.upperAlphaLimit;
  16062. }
  16063. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  16064. this.radius = this.lowerRadiusLimit;
  16065. }
  16066. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  16067. this.radius = this.upperRadiusLimit;
  16068. }
  16069. };
  16070. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  16071. var radiusv3 = this.position.subtract(this._getTargetPosition());
  16072. this.radius = radiusv3.length();
  16073. // Alpha
  16074. this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
  16075. if (radiusv3.z < 0) {
  16076. this.alpha = 2 * Math.PI - this.alpha;
  16077. }
  16078. // Beta
  16079. this.beta = Math.acos(radiusv3.y / this.radius);
  16080. this._checkLimits();
  16081. };
  16082. ArcRotateCamera.prototype.setPosition = function (position) {
  16083. if (this.position.equals(position)) {
  16084. return;
  16085. }
  16086. this.position.copyFrom(position);
  16087. this.rebuildAnglesAndRadius();
  16088. };
  16089. ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter) {
  16090. if (toBoundingCenter === void 0) { toBoundingCenter = false; }
  16091. if (this._getTargetPosition().equals(target)) {
  16092. return;
  16093. }
  16094. if (toBoundingCenter && target.getBoundingInfo) {
  16095. this._targetBoundingCenter = target.getBoundingInfo().boundingBox.center.clone();
  16096. }
  16097. else {
  16098. this._targetBoundingCenter = null;
  16099. }
  16100. this.target = target;
  16101. this.rebuildAnglesAndRadius();
  16102. };
  16103. ArcRotateCamera.prototype._getViewMatrix = function () {
  16104. // Compute
  16105. var cosa = Math.cos(this.alpha);
  16106. var sina = Math.sin(this.alpha);
  16107. var cosb = Math.cos(this.beta);
  16108. var sinb = Math.sin(this.beta);
  16109. if (sinb === 0) {
  16110. sinb = 0.0001;
  16111. }
  16112. var target = this._getTargetPosition();
  16113. target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this._newPosition);
  16114. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  16115. this._collider.radius = this.collisionRadius;
  16116. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  16117. this._collisionTriggered = true;
  16118. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  16119. }
  16120. else {
  16121. this.position.copyFrom(this._newPosition);
  16122. var up = this.upVector;
  16123. if (this.allowUpsideDown && this.beta < 0) {
  16124. up = up.clone();
  16125. up = up.negate();
  16126. }
  16127. if (this.getScene().useRightHandedSystem) {
  16128. BABYLON.Matrix.LookAtRHToRef(this.position, target, up, this._viewMatrix);
  16129. }
  16130. else {
  16131. BABYLON.Matrix.LookAtLHToRef(this.position, target, up, this._viewMatrix);
  16132. }
  16133. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  16134. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  16135. }
  16136. this._currentTarget = target;
  16137. return this._viewMatrix;
  16138. };
  16139. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  16140. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  16141. meshes = meshes || this.getScene().meshes;
  16142. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  16143. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  16144. this.radius = distance * this.zoomOnFactor;
  16145. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  16146. };
  16147. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  16148. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  16149. var meshesOrMinMaxVector;
  16150. var distance;
  16151. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  16152. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  16153. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshesOrMinMaxVector);
  16154. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  16155. }
  16156. else {
  16157. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance;
  16158. distance = meshesOrMinMaxVectorAndDistance.distance;
  16159. }
  16160. this.target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  16161. if (!doNotUpdateMaxZ) {
  16162. this.maxZ = distance * 2;
  16163. }
  16164. };
  16165. /**
  16166. * @override
  16167. * Override Camera.createRigCamera
  16168. */
  16169. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  16170. var alphaShift;
  16171. switch (this.cameraRigMode) {
  16172. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  16173. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  16174. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  16175. case BABYLON.Camera.RIG_MODE_VR:
  16176. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  16177. break;
  16178. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  16179. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  16180. break;
  16181. }
  16182. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this.target, this.getScene());
  16183. rigCam._cameraRigParams = {};
  16184. return rigCam;
  16185. };
  16186. /**
  16187. * @override
  16188. * Override Camera._updateRigCameras
  16189. */
  16190. ArcRotateCamera.prototype._updateRigCameras = function () {
  16191. var camLeft = this._rigCameras[0];
  16192. var camRight = this._rigCameras[1];
  16193. camLeft.beta = camRight.beta = this.beta;
  16194. camLeft.radius = camRight.radius = this.radius;
  16195. switch (this.cameraRigMode) {
  16196. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  16197. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  16198. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  16199. case BABYLON.Camera.RIG_MODE_VR:
  16200. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  16201. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  16202. break;
  16203. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  16204. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  16205. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  16206. break;
  16207. }
  16208. _super.prototype._updateRigCameras.call(this);
  16209. };
  16210. ArcRotateCamera.prototype.dispose = function () {
  16211. this.inputs.clear();
  16212. _super.prototype.dispose.call(this);
  16213. };
  16214. ArcRotateCamera.prototype.getClassName = function () {
  16215. return "ArcRotateCamera";
  16216. };
  16217. return ArcRotateCamera;
  16218. }(BABYLON.TargetCamera));
  16219. __decorate([
  16220. BABYLON.serialize()
  16221. ], ArcRotateCamera.prototype, "alpha", void 0);
  16222. __decorate([
  16223. BABYLON.serialize()
  16224. ], ArcRotateCamera.prototype, "beta", void 0);
  16225. __decorate([
  16226. BABYLON.serialize()
  16227. ], ArcRotateCamera.prototype, "radius", void 0);
  16228. __decorate([
  16229. BABYLON.serializeAsVector3()
  16230. ], ArcRotateCamera.prototype, "target", void 0);
  16231. __decorate([
  16232. BABYLON.serialize()
  16233. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  16234. __decorate([
  16235. BABYLON.serialize()
  16236. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  16237. __decorate([
  16238. BABYLON.serialize()
  16239. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  16240. __decorate([
  16241. BABYLON.serialize()
  16242. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  16243. __decorate([
  16244. BABYLON.serialize()
  16245. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  16246. __decorate([
  16247. BABYLON.serialize()
  16248. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  16249. __decorate([
  16250. BABYLON.serialize()
  16251. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  16252. __decorate([
  16253. BABYLON.serialize()
  16254. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  16255. __decorate([
  16256. BABYLON.serialize()
  16257. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  16258. __decorate([
  16259. BABYLON.serialize()
  16260. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  16261. __decorate([
  16262. BABYLON.serialize()
  16263. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  16264. __decorate([
  16265. BABYLON.serialize()
  16266. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  16267. __decorate([
  16268. BABYLON.serialize()
  16269. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  16270. BABYLON.ArcRotateCamera = ArcRotateCamera;
  16271. })(BABYLON || (BABYLON = {}));
  16272. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  16273. var BABYLON;
  16274. (function (BABYLON) {
  16275. var ArcRotateCameraInputsManager = (function (_super) {
  16276. __extends(ArcRotateCameraInputsManager, _super);
  16277. function ArcRotateCameraInputsManager(camera) {
  16278. return _super.call(this, camera) || this;
  16279. }
  16280. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  16281. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  16282. return this;
  16283. };
  16284. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  16285. this.add(new BABYLON.ArcRotateCameraPointersInput());
  16286. return this;
  16287. };
  16288. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  16289. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  16290. return this;
  16291. };
  16292. ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  16293. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  16294. return this;
  16295. };
  16296. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  16297. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  16298. return this;
  16299. };
  16300. return ArcRotateCameraInputsManager;
  16301. }(BABYLON.CameraInputsManager));
  16302. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  16303. })(BABYLON || (BABYLON = {}));
  16304. //# sourceMappingURL=babylon.arcRotateCameraInputsManager.js.map
  16305. var BABYLON;
  16306. (function (BABYLON) {
  16307. var RenderingManager = (function () {
  16308. function RenderingManager(scene) {
  16309. this._renderingGroups = new Array();
  16310. this._autoClearDepthStencil = {};
  16311. this._customOpaqueSortCompareFn = {};
  16312. this._customAlphaTestSortCompareFn = {};
  16313. this._customTransparentSortCompareFn = {};
  16314. this._renderinGroupInfo = null;
  16315. this._scene = scene;
  16316. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  16317. this._autoClearDepthStencil[i] = { autoClear: true, depth: true, stencil: true };
  16318. }
  16319. }
  16320. RenderingManager.prototype._clearDepthStencilBuffer = function (depth, stencil) {
  16321. if (depth === void 0) { depth = true; }
  16322. if (stencil === void 0) { stencil = true; }
  16323. if (this._depthStencilBufferAlreadyCleaned) {
  16324. return;
  16325. }
  16326. this._scene.getEngine().clear(null, false, depth, stencil);
  16327. this._depthStencilBufferAlreadyCleaned = true;
  16328. };
  16329. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  16330. // Check if there's at least on observer on the onRenderingGroupObservable and initialize things to fire it
  16331. var observable = this._scene.onRenderingGroupObservable.hasObservers() ? this._scene.onRenderingGroupObservable : null;
  16332. var info = null;
  16333. if (observable) {
  16334. if (!this._renderinGroupInfo) {
  16335. this._renderinGroupInfo = new BABYLON.RenderingGroupInfo();
  16336. }
  16337. info = this._renderinGroupInfo;
  16338. info.scene = this._scene;
  16339. info.camera = this._scene.activeCamera;
  16340. }
  16341. // Dispatch sprites
  16342. if (renderSprites) {
  16343. for (var index = 0; index < this._scene.spriteManagers.length; index++) {
  16344. var manager = this._scene.spriteManagers[index];
  16345. this.dispatchSprites(manager);
  16346. }
  16347. }
  16348. // Render
  16349. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  16350. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  16351. var renderingGroup = this._renderingGroups[index];
  16352. if (!renderingGroup && !observable)
  16353. continue;
  16354. this._currentIndex = index;
  16355. var renderingGroupMask = 0;
  16356. // Fire PRECLEAR stage
  16357. if (observable) {
  16358. renderingGroupMask = Math.pow(2, index);
  16359. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRECLEAR;
  16360. info.renderingGroupId = index;
  16361. observable.notifyObservers(info, renderingGroupMask);
  16362. }
  16363. // Clear depth/stencil if needed
  16364. var autoClear = this._autoClearDepthStencil[index];
  16365. if (autoClear && autoClear.autoClear) {
  16366. this._clearDepthStencilBuffer(autoClear.depth, autoClear.stencil);
  16367. }
  16368. if (observable) {
  16369. // Fire PREOPAQUE stage
  16370. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PREOPAQUE;
  16371. observable.notifyObservers(info, renderingGroupMask);
  16372. // Fire PRETRANSPARENT stage
  16373. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRETRANSPARENT;
  16374. observable.notifyObservers(info, renderingGroupMask);
  16375. }
  16376. if (renderingGroup)
  16377. renderingGroup.render(customRenderFunction, renderSprites, renderParticles, activeMeshes);
  16378. // Fire POSTTRANSPARENT stage
  16379. if (observable) {
  16380. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_POSTTRANSPARENT;
  16381. observable.notifyObservers(info, renderingGroupMask);
  16382. }
  16383. }
  16384. };
  16385. RenderingManager.prototype.reset = function () {
  16386. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  16387. var renderingGroup = this._renderingGroups[index];
  16388. if (renderingGroup) {
  16389. renderingGroup.prepare();
  16390. }
  16391. }
  16392. };
  16393. RenderingManager.prototype._prepareRenderingGroup = function (renderingGroupId) {
  16394. if (!this._renderingGroups[renderingGroupId]) {
  16395. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  16396. }
  16397. };
  16398. RenderingManager.prototype.dispatchSprites = function (spriteManager) {
  16399. var renderingGroupId = spriteManager.renderingGroupId || 0;
  16400. this._prepareRenderingGroup(renderingGroupId);
  16401. this._renderingGroups[renderingGroupId].dispatchSprites(spriteManager);
  16402. };
  16403. RenderingManager.prototype.dispatchParticles = function (particleSystem) {
  16404. var renderingGroupId = particleSystem.renderingGroupId || 0;
  16405. this._prepareRenderingGroup(renderingGroupId);
  16406. this._renderingGroups[renderingGroupId].dispatchParticles(particleSystem);
  16407. };
  16408. RenderingManager.prototype.dispatch = function (subMesh) {
  16409. var mesh = subMesh.getMesh();
  16410. var renderingGroupId = mesh.renderingGroupId || 0;
  16411. this._prepareRenderingGroup(renderingGroupId);
  16412. this._renderingGroups[renderingGroupId].dispatch(subMesh);
  16413. };
  16414. /**
  16415. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  16416. * This allowed control for front to back rendering or reversly depending of the special needs.
  16417. *
  16418. * @param renderingGroupId The rendering group id corresponding to its index
  16419. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  16420. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  16421. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  16422. */
  16423. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  16424. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  16425. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  16426. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  16427. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  16428. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  16429. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  16430. if (this._renderingGroups[renderingGroupId]) {
  16431. var group = this._renderingGroups[renderingGroupId];
  16432. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  16433. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  16434. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  16435. }
  16436. };
  16437. /**
  16438. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  16439. *
  16440. * @param renderingGroupId The rendering group id corresponding to its index
  16441. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  16442. * @param depth Automatically clears depth between groups if true and autoClear is true.
  16443. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  16444. */
  16445. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  16446. if (depth === void 0) { depth = true; }
  16447. if (stencil === void 0) { stencil = true; }
  16448. this._autoClearDepthStencil[renderingGroupId] = {
  16449. autoClear: autoClearDepthStencil,
  16450. depth: depth,
  16451. stencil: stencil
  16452. };
  16453. };
  16454. return RenderingManager;
  16455. }());
  16456. /**
  16457. * The max id used for rendering groups (not included)
  16458. */
  16459. RenderingManager.MAX_RENDERINGGROUPS = 4;
  16460. /**
  16461. * The min id used for rendering groups (included)
  16462. */
  16463. RenderingManager.MIN_RENDERINGGROUPS = 0;
  16464. BABYLON.RenderingManager = RenderingManager;
  16465. })(BABYLON || (BABYLON = {}));
  16466. //# sourceMappingURL=babylon.renderingManager.js.map
  16467. var BABYLON;
  16468. (function (BABYLON) {
  16469. var RenderingGroup = (function () {
  16470. /**
  16471. * Creates a new rendering group.
  16472. * @param index The rendering group index
  16473. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  16474. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  16475. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  16476. */
  16477. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  16478. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  16479. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  16480. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  16481. this.index = index;
  16482. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  16483. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  16484. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  16485. this._particleSystems = new BABYLON.SmartArray(256);
  16486. this._spriteManagers = new BABYLON.SmartArray(256);
  16487. this._scene = scene;
  16488. this.opaqueSortCompareFn = opaqueSortCompareFn;
  16489. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  16490. this.transparentSortCompareFn = transparentSortCompareFn;
  16491. }
  16492. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  16493. /**
  16494. * Set the opaque sort comparison function.
  16495. * If null the sub meshes will be render in the order they were created
  16496. */
  16497. set: function (value) {
  16498. this._opaqueSortCompareFn = value;
  16499. if (value) {
  16500. this._renderOpaque = this.renderOpaqueSorted;
  16501. }
  16502. else {
  16503. this._renderOpaque = RenderingGroup.renderUnsorted;
  16504. }
  16505. },
  16506. enumerable: true,
  16507. configurable: true
  16508. });
  16509. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  16510. /**
  16511. * Set the alpha test sort comparison function.
  16512. * If null the sub meshes will be render in the order they were created
  16513. */
  16514. set: function (value) {
  16515. this._alphaTestSortCompareFn = value;
  16516. if (value) {
  16517. this._renderAlphaTest = this.renderAlphaTestSorted;
  16518. }
  16519. else {
  16520. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  16521. }
  16522. },
  16523. enumerable: true,
  16524. configurable: true
  16525. });
  16526. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  16527. /**
  16528. * Set the transparent sort comparison function.
  16529. * If null the sub meshes will be render in the order they were created
  16530. */
  16531. set: function (value) {
  16532. if (value) {
  16533. this._transparentSortCompareFn = value;
  16534. }
  16535. else {
  16536. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  16537. }
  16538. this._renderTransparent = this.renderTransparentSorted;
  16539. },
  16540. enumerable: true,
  16541. configurable: true
  16542. });
  16543. /**
  16544. * Render all the sub meshes contained in the group.
  16545. * @param customRenderFunction Used to override the default render behaviour of the group.
  16546. * @returns true if rendered some submeshes.
  16547. */
  16548. RenderingGroup.prototype.render = function (customRenderFunction, renderSprites, renderParticles, activeMeshes) {
  16549. if (customRenderFunction) {
  16550. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes);
  16551. return;
  16552. }
  16553. var engine = this._scene.getEngine();
  16554. // Opaque
  16555. if (this._opaqueSubMeshes.length !== 0) {
  16556. this._renderOpaque(this._opaqueSubMeshes);
  16557. }
  16558. // Alpha test
  16559. if (this._alphaTestSubMeshes.length !== 0) {
  16560. engine.setAlphaTesting(true);
  16561. this._renderAlphaTest(this._alphaTestSubMeshes);
  16562. engine.setAlphaTesting(false);
  16563. }
  16564. // Sprites
  16565. if (renderSprites) {
  16566. this._renderSprites();
  16567. }
  16568. // Particles
  16569. if (renderParticles) {
  16570. this._renderParticles(activeMeshes);
  16571. }
  16572. if (this.onBeforeTransparentRendering) {
  16573. this.onBeforeTransparentRendering();
  16574. }
  16575. // Transparent
  16576. if (this._transparentSubMeshes.length !== 0) {
  16577. this._renderTransparent(this._transparentSubMeshes);
  16578. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  16579. }
  16580. };
  16581. /**
  16582. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  16583. * @param subMeshes The submeshes to render
  16584. */
  16585. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  16586. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera.globalPosition, false);
  16587. };
  16588. /**
  16589. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  16590. * @param subMeshes The submeshes to render
  16591. */
  16592. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  16593. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera.globalPosition, false);
  16594. };
  16595. /**
  16596. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  16597. * @param subMeshes The submeshes to render
  16598. */
  16599. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  16600. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera.globalPosition, true);
  16601. };
  16602. /**
  16603. * Renders the submeshes in a specified order.
  16604. * @param subMeshes The submeshes to sort before render
  16605. * @param sortCompareFn The comparison function use to sort
  16606. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  16607. * @param transparent Specifies to activate blending if true
  16608. */
  16609. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, cameraPosition, transparent) {
  16610. var subIndex = 0;
  16611. var subMesh;
  16612. for (; subIndex < subMeshes.length; subIndex++) {
  16613. subMesh = subMeshes.data[subIndex];
  16614. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  16615. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  16616. }
  16617. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  16618. sortedArray.sort(sortCompareFn);
  16619. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  16620. subMesh = sortedArray[subIndex];
  16621. subMesh.render(transparent);
  16622. }
  16623. };
  16624. /**
  16625. * Renders the submeshes in the order they were dispatched (no sort applied).
  16626. * @param subMeshes The submeshes to render
  16627. */
  16628. RenderingGroup.renderUnsorted = function (subMeshes) {
  16629. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  16630. var submesh = subMeshes.data[subIndex];
  16631. submesh.render(false);
  16632. }
  16633. };
  16634. /**
  16635. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  16636. * are rendered back to front if in the same alpha index.
  16637. *
  16638. * @param a The first submesh
  16639. * @param b The second submesh
  16640. * @returns The result of the comparison
  16641. */
  16642. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  16643. // Alpha index first
  16644. if (a._alphaIndex > b._alphaIndex) {
  16645. return 1;
  16646. }
  16647. if (a._alphaIndex < b._alphaIndex) {
  16648. return -1;
  16649. }
  16650. // Then distance to camera
  16651. return RenderingGroup.backToFrontSortCompare(a, b);
  16652. };
  16653. /**
  16654. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  16655. * are rendered back to front.
  16656. *
  16657. * @param a The first submesh
  16658. * @param b The second submesh
  16659. * @returns The result of the comparison
  16660. */
  16661. RenderingGroup.backToFrontSortCompare = function (a, b) {
  16662. // Then distance to camera
  16663. if (a._distanceToCamera < b._distanceToCamera) {
  16664. return 1;
  16665. }
  16666. if (a._distanceToCamera > b._distanceToCamera) {
  16667. return -1;
  16668. }
  16669. return 0;
  16670. };
  16671. /**
  16672. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  16673. * are rendered front to back (prevent overdraw).
  16674. *
  16675. * @param a The first submesh
  16676. * @param b The second submesh
  16677. * @returns The result of the comparison
  16678. */
  16679. RenderingGroup.frontToBackSortCompare = function (a, b) {
  16680. // Then distance to camera
  16681. if (a._distanceToCamera < b._distanceToCamera) {
  16682. return -1;
  16683. }
  16684. if (a._distanceToCamera > b._distanceToCamera) {
  16685. return 1;
  16686. }
  16687. return 0;
  16688. };
  16689. /**
  16690. * Resets the different lists of submeshes to prepare a new frame.
  16691. */
  16692. RenderingGroup.prototype.prepare = function () {
  16693. this._opaqueSubMeshes.reset();
  16694. this._transparentSubMeshes.reset();
  16695. this._alphaTestSubMeshes.reset();
  16696. this._particleSystems.reset();
  16697. this._spriteManagers.reset();
  16698. };
  16699. /**
  16700. * Inserts the submesh in its correct queue depending on its material.
  16701. * @param subMesh The submesh to dispatch
  16702. */
  16703. RenderingGroup.prototype.dispatch = function (subMesh) {
  16704. var material = subMesh.getMaterial();
  16705. var mesh = subMesh.getMesh();
  16706. if (material.needAlphaBlending() || mesh.visibility < 1.0 || mesh.hasVertexAlpha) {
  16707. this._transparentSubMeshes.push(subMesh);
  16708. }
  16709. else if (material.needAlphaTesting()) {
  16710. this._alphaTestSubMeshes.push(subMesh);
  16711. }
  16712. else {
  16713. this._opaqueSubMeshes.push(subMesh); // Opaque
  16714. }
  16715. };
  16716. RenderingGroup.prototype.dispatchSprites = function (spriteManager) {
  16717. this._spriteManagers.push(spriteManager);
  16718. };
  16719. RenderingGroup.prototype.dispatchParticles = function (particleSystem) {
  16720. this._particleSystems.push(particleSystem);
  16721. };
  16722. RenderingGroup.prototype._renderParticles = function (activeMeshes) {
  16723. if (this._particleSystems.length === 0) {
  16724. return;
  16725. }
  16726. // Particles
  16727. var activeCamera = this._scene.activeCamera;
  16728. this._scene._particlesDuration.beginMonitoring();
  16729. for (var particleIndex = 0; particleIndex < this._scene._activeParticleSystems.length; particleIndex++) {
  16730. var particleSystem = this._scene._activeParticleSystems.data[particleIndex];
  16731. if ((activeCamera.layerMask & particleSystem.layerMask) === 0) {
  16732. continue;
  16733. }
  16734. if (!particleSystem.emitter.position || !activeMeshes || activeMeshes.indexOf(particleSystem.emitter) !== -1) {
  16735. this._scene._activeParticles.addCount(particleSystem.render(), false);
  16736. }
  16737. }
  16738. this._scene._particlesDuration.endMonitoring(false);
  16739. };
  16740. RenderingGroup.prototype._renderSprites = function () {
  16741. if (!this._scene.spritesEnabled || this._spriteManagers.length === 0) {
  16742. return;
  16743. }
  16744. // Sprites
  16745. var activeCamera = this._scene.activeCamera;
  16746. this._scene._spritesDuration.beginMonitoring();
  16747. for (var id = 0; id < this._spriteManagers.length; id++) {
  16748. var spriteManager = this._scene.spriteManagers[id];
  16749. if (((activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  16750. spriteManager.render();
  16751. }
  16752. }
  16753. this._scene._spritesDuration.endMonitoring(false);
  16754. };
  16755. return RenderingGroup;
  16756. }());
  16757. BABYLON.RenderingGroup = RenderingGroup;
  16758. })(BABYLON || (BABYLON = {}));
  16759. //# sourceMappingURL=babylon.renderingGroup.js.map
  16760. var BABYLON;
  16761. (function (BABYLON) {
  16762. var PointerEventTypes = (function () {
  16763. function PointerEventTypes() {
  16764. }
  16765. Object.defineProperty(PointerEventTypes, "POINTERDOWN", {
  16766. get: function () {
  16767. return PointerEventTypes._POINTERDOWN;
  16768. },
  16769. enumerable: true,
  16770. configurable: true
  16771. });
  16772. Object.defineProperty(PointerEventTypes, "POINTERUP", {
  16773. get: function () {
  16774. return PointerEventTypes._POINTERUP;
  16775. },
  16776. enumerable: true,
  16777. configurable: true
  16778. });
  16779. Object.defineProperty(PointerEventTypes, "POINTERMOVE", {
  16780. get: function () {
  16781. return PointerEventTypes._POINTERMOVE;
  16782. },
  16783. enumerable: true,
  16784. configurable: true
  16785. });
  16786. Object.defineProperty(PointerEventTypes, "POINTERWHEEL", {
  16787. get: function () {
  16788. return PointerEventTypes._POINTERWHEEL;
  16789. },
  16790. enumerable: true,
  16791. configurable: true
  16792. });
  16793. Object.defineProperty(PointerEventTypes, "POINTERPICK", {
  16794. get: function () {
  16795. return PointerEventTypes._POINTERPICK;
  16796. },
  16797. enumerable: true,
  16798. configurable: true
  16799. });
  16800. return PointerEventTypes;
  16801. }());
  16802. PointerEventTypes._POINTERDOWN = 0x01;
  16803. PointerEventTypes._POINTERUP = 0x02;
  16804. PointerEventTypes._POINTERMOVE = 0x04;
  16805. PointerEventTypes._POINTERWHEEL = 0x08;
  16806. PointerEventTypes._POINTERPICK = 0x10;
  16807. BABYLON.PointerEventTypes = PointerEventTypes;
  16808. var PointerInfoBase = (function () {
  16809. function PointerInfoBase(type, event) {
  16810. this.type = type;
  16811. this.event = event;
  16812. }
  16813. return PointerInfoBase;
  16814. }());
  16815. BABYLON.PointerInfoBase = PointerInfoBase;
  16816. /**
  16817. * This class is used to store pointer related info for the onPrePointerObservable event.
  16818. * Set the skipOnPointerObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onPointerObservable
  16819. */
  16820. var PointerInfoPre = (function (_super) {
  16821. __extends(PointerInfoPre, _super);
  16822. function PointerInfoPre(type, event, localX, localY) {
  16823. var _this = _super.call(this, type, event) || this;
  16824. _this.skipOnPointerObservable = false;
  16825. _this.localPosition = new BABYLON.Vector2(localX, localY);
  16826. return _this;
  16827. }
  16828. return PointerInfoPre;
  16829. }(PointerInfoBase));
  16830. BABYLON.PointerInfoPre = PointerInfoPre;
  16831. /**
  16832. * This type contains all the data related to a pointer event in Babylon.js.
  16833. * 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.
  16834. */
  16835. var PointerInfo = (function (_super) {
  16836. __extends(PointerInfo, _super);
  16837. function PointerInfo(type, event, pickInfo) {
  16838. var _this = _super.call(this, type, event) || this;
  16839. _this.pickInfo = pickInfo;
  16840. return _this;
  16841. }
  16842. return PointerInfo;
  16843. }(PointerInfoBase));
  16844. BABYLON.PointerInfo = PointerInfo;
  16845. /**
  16846. * This class is used by the onRenderingGroupObservable
  16847. */
  16848. var RenderingGroupInfo = (function () {
  16849. function RenderingGroupInfo() {
  16850. }
  16851. return RenderingGroupInfo;
  16852. }());
  16853. /**
  16854. * Stage corresponding to the very first hook in the renderingGroup phase: before the render buffer may be cleared
  16855. * This stage will be fired no matter what
  16856. */
  16857. RenderingGroupInfo.STAGE_PRECLEAR = 1;
  16858. /**
  16859. * Called before opaque object are rendered.
  16860. * This stage will be fired only if there's 3D Opaque content to render
  16861. */
  16862. RenderingGroupInfo.STAGE_PREOPAQUE = 2;
  16863. /**
  16864. * Called after the opaque objects are rendered and before the transparent ones
  16865. * This stage will be fired only if there's 3D transparent content to render
  16866. */
  16867. RenderingGroupInfo.STAGE_PRETRANSPARENT = 3;
  16868. /**
  16869. * Called after the transparent object are rendered, last hook of the renderingGroup phase
  16870. * This stage will be fired no matter what
  16871. */
  16872. RenderingGroupInfo.STAGE_POSTTRANSPARENT = 4;
  16873. BABYLON.RenderingGroupInfo = RenderingGroupInfo;
  16874. /**
  16875. * Represents a scene to be rendered by the engine.
  16876. * @see http://doc.babylonjs.com/page.php?p=21911
  16877. */
  16878. var Scene = (function () {
  16879. /**
  16880. * @constructor
  16881. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  16882. */
  16883. function Scene(engine) {
  16884. // Members
  16885. this.autoClear = true;
  16886. this.clearColor = new BABYLON.Color4(0.2, 0.2, 0.3, 1.0);
  16887. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  16888. this.forceWireframe = false;
  16889. this.forcePointsCloud = false;
  16890. this.forceShowBoundingBoxes = false;
  16891. this.animationsEnabled = true;
  16892. this.constantlyUpdateMeshUnderPointer = false;
  16893. this.useRightHandedSystem = false;
  16894. this.hoverCursor = "pointer";
  16895. // Metadata
  16896. this.metadata = null;
  16897. // Events
  16898. /**
  16899. * An event triggered when the scene is disposed.
  16900. * @type {BABYLON.Observable}
  16901. */
  16902. this.onDisposeObservable = new BABYLON.Observable();
  16903. /**
  16904. * An event triggered before rendering the scene
  16905. * @type {BABYLON.Observable}
  16906. */
  16907. this.onBeforeRenderObservable = new BABYLON.Observable();
  16908. /**
  16909. * An event triggered after rendering the scene
  16910. * @type {BABYLON.Observable}
  16911. */
  16912. this.onAfterRenderObservable = new BABYLON.Observable();
  16913. /**
  16914. * An event triggered when the scene is ready
  16915. * @type {BABYLON.Observable}
  16916. */
  16917. this.onReadyObservable = new BABYLON.Observable();
  16918. /**
  16919. * An event triggered before rendering a camera
  16920. * @type {BABYLON.Observable}
  16921. */
  16922. this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  16923. /**
  16924. * An event triggered after rendering a camera
  16925. * @type {BABYLON.Observable}
  16926. */
  16927. this.onAfterCameraRenderObservable = new BABYLON.Observable();
  16928. /**
  16929. * An event triggered when a camera is created
  16930. * @type {BABYLON.Observable}
  16931. */
  16932. this.onNewCameraAddedObservable = new BABYLON.Observable();
  16933. /**
  16934. * An event triggered when a camera is removed
  16935. * @type {BABYLON.Observable}
  16936. */
  16937. this.onCameraRemovedObservable = new BABYLON.Observable();
  16938. /**
  16939. * An event triggered when a light is created
  16940. * @type {BABYLON.Observable}
  16941. */
  16942. this.onNewLightAddedObservable = new BABYLON.Observable();
  16943. /**
  16944. * An event triggered when a light is removed
  16945. * @type {BABYLON.Observable}
  16946. */
  16947. this.onLightRemovedObservable = new BABYLON.Observable();
  16948. /**
  16949. * An event triggered when a geometry is created
  16950. * @type {BABYLON.Observable}
  16951. */
  16952. this.onNewGeometryAddedObservable = new BABYLON.Observable();
  16953. /**
  16954. * An event triggered when a geometry is removed
  16955. * @type {BABYLON.Observable}
  16956. */
  16957. this.onGeometryRemovedObservable = new BABYLON.Observable();
  16958. /**
  16959. * An event triggered when a mesh is created
  16960. * @type {BABYLON.Observable}
  16961. */
  16962. this.onNewMeshAddedObservable = new BABYLON.Observable();
  16963. /**
  16964. * An event triggered when a mesh is removed
  16965. * @type {BABYLON.Observable}
  16966. */
  16967. this.onMeshRemovedObservable = new BABYLON.Observable();
  16968. /**
  16969. * This Observable will be triggered for each stage of each renderingGroup of each rendered camera.
  16970. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  16971. * 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)
  16972. */
  16973. this.onRenderingGroupObservable = new BABYLON.Observable();
  16974. // Animations
  16975. this.animations = [];
  16976. /**
  16977. * 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).
  16978. * You have the possibility to skip the 3D Engine process and the call to onPointerObservable by setting PointerInfoBase.skipOnPointerObservable to true
  16979. */
  16980. this.onPrePointerObservable = new BABYLON.Observable();
  16981. /**
  16982. * Observable event triggered each time an input event is received from the rendering canvas
  16983. */
  16984. this.onPointerObservable = new BABYLON.Observable();
  16985. 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
  16986. this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  16987. this._startingPointerTime = 0;
  16988. // Fog
  16989. /**
  16990. * is fog enabled on this scene.
  16991. * @type {boolean}
  16992. */
  16993. this.fogEnabled = true;
  16994. this.fogMode = Scene.FOGMODE_NONE;
  16995. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  16996. this.fogDensity = 0.1;
  16997. this.fogStart = 0;
  16998. this.fogEnd = 1000.0;
  16999. // Lights
  17000. /**
  17001. * is shadow enabled on this scene.
  17002. * @type {boolean}
  17003. */
  17004. this.shadowsEnabled = true;
  17005. /**
  17006. * is light enabled on this scene.
  17007. * @type {boolean}
  17008. */
  17009. this.lightsEnabled = true;
  17010. /**
  17011. * All of the lights added to this scene.
  17012. * @see BABYLON.Light
  17013. * @type {BABYLON.Light[]}
  17014. */
  17015. this.lights = new Array();
  17016. // Cameras
  17017. /**
  17018. * All of the cameras added to this scene.
  17019. * @see BABYLON.Camera
  17020. * @type {BABYLON.Camera[]}
  17021. */
  17022. this.cameras = new Array();
  17023. this.activeCameras = new Array();
  17024. // Meshes
  17025. /**
  17026. * All of the (abstract) meshes added to this scene.
  17027. * @see BABYLON.AbstractMesh
  17028. * @type {BABYLON.AbstractMesh[]}
  17029. */
  17030. this.meshes = new Array();
  17031. // Geometries
  17032. this._geometries = new Array();
  17033. this.materials = new Array();
  17034. this.multiMaterials = new Array();
  17035. // Textures
  17036. this.texturesEnabled = true;
  17037. this.textures = new Array();
  17038. // Particles
  17039. this.particlesEnabled = true;
  17040. this.particleSystems = new Array();
  17041. // Sprites
  17042. this.spritesEnabled = true;
  17043. this.spriteManagers = new Array();
  17044. // Layers
  17045. this.layers = new Array();
  17046. this.highlightLayers = new Array();
  17047. // Skeletons
  17048. this.skeletonsEnabled = true;
  17049. this.skeletons = new Array();
  17050. // Lens flares
  17051. this.lensFlaresEnabled = true;
  17052. this.lensFlareSystems = new Array();
  17053. // Collisions
  17054. this.collisionsEnabled = true;
  17055. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  17056. // Postprocesses
  17057. this.postProcessesEnabled = true;
  17058. // Customs render targets
  17059. this.renderTargetsEnabled = true;
  17060. this.dumpNextRenderTargets = false;
  17061. this.customRenderTargets = new Array();
  17062. // Imported meshes
  17063. this.importedMeshesFiles = new Array();
  17064. // Probes
  17065. this.probesEnabled = true;
  17066. this.reflectionProbes = new Array();
  17067. this._actionManagers = new Array();
  17068. this._meshesForIntersections = new BABYLON.SmartArray(256);
  17069. // Procedural textures
  17070. this.proceduralTexturesEnabled = true;
  17071. this._proceduralTextures = new Array();
  17072. this.soundTracks = new Array();
  17073. this._audioEnabled = true;
  17074. this._headphone = false;
  17075. // Performance counters
  17076. this._totalMeshesCounter = new BABYLON.PerfCounter();
  17077. this._totalLightsCounter = new BABYLON.PerfCounter();
  17078. this._totalMaterialsCounter = new BABYLON.PerfCounter();
  17079. this._totalTexturesCounter = new BABYLON.PerfCounter();
  17080. this._totalVertices = new BABYLON.PerfCounter();
  17081. this._activeIndices = new BABYLON.PerfCounter();
  17082. this._activeParticles = new BABYLON.PerfCounter();
  17083. this._lastFrameDuration = new BABYLON.PerfCounter();
  17084. this._evaluateActiveMeshesDuration = new BABYLON.PerfCounter();
  17085. this._renderTargetsDuration = new BABYLON.PerfCounter();
  17086. this._particlesDuration = new BABYLON.PerfCounter();
  17087. this._renderDuration = new BABYLON.PerfCounter();
  17088. this._spritesDuration = new BABYLON.PerfCounter();
  17089. this._activeBones = new BABYLON.PerfCounter();
  17090. this._animationTime = 0;
  17091. this.animationTimeScale = 1;
  17092. this._renderId = 0;
  17093. this._executeWhenReadyTimeoutId = -1;
  17094. this._intermediateRendering = false;
  17095. this._toBeDisposed = new BABYLON.SmartArray(256);
  17096. this._pendingData = []; //ANY
  17097. this._activeMeshes = new BABYLON.SmartArray(256);
  17098. this._processedMaterials = new BABYLON.SmartArray(256);
  17099. this._renderTargets = new BABYLON.SmartArray(256);
  17100. this._activeParticleSystems = new BABYLON.SmartArray(256);
  17101. this._activeSkeletons = new BABYLON.SmartArray(32);
  17102. this._softwareSkinnedMeshes = new BABYLON.SmartArray(32);
  17103. this._activeAnimatables = new Array();
  17104. this._transformMatrix = BABYLON.Matrix.Zero();
  17105. this._edgesRenderers = new BABYLON.SmartArray(16);
  17106. this._uniqueIdCounter = 0;
  17107. this._engine = engine;
  17108. engine.scenes.push(this);
  17109. this._externalData = new BABYLON.StringDictionary();
  17110. this._uid = null;
  17111. this._renderingManager = new BABYLON.RenderingManager(this);
  17112. this.postProcessManager = new BABYLON.PostProcessManager(this);
  17113. this.postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  17114. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  17115. if (BABYLON.OutlineRenderer) {
  17116. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  17117. }
  17118. this.attachControl();
  17119. if (BABYLON.SoundTrack) {
  17120. this.mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  17121. }
  17122. //simplification queue
  17123. if (BABYLON.SimplificationQueue) {
  17124. this.simplificationQueue = new BABYLON.SimplificationQueue();
  17125. }
  17126. //collision coordinator initialization. For now legacy per default.
  17127. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  17128. }
  17129. Object.defineProperty(Scene, "FOGMODE_NONE", {
  17130. get: function () {
  17131. return Scene._FOGMODE_NONE;
  17132. },
  17133. enumerable: true,
  17134. configurable: true
  17135. });
  17136. Object.defineProperty(Scene, "FOGMODE_EXP", {
  17137. get: function () {
  17138. return Scene._FOGMODE_EXP;
  17139. },
  17140. enumerable: true,
  17141. configurable: true
  17142. });
  17143. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  17144. get: function () {
  17145. return Scene._FOGMODE_EXP2;
  17146. },
  17147. enumerable: true,
  17148. configurable: true
  17149. });
  17150. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  17151. get: function () {
  17152. return Scene._FOGMODE_LINEAR;
  17153. },
  17154. enumerable: true,
  17155. configurable: true
  17156. });
  17157. Object.defineProperty(Scene.prototype, "onDispose", {
  17158. set: function (callback) {
  17159. if (this._onDisposeObserver) {
  17160. this.onDisposeObservable.remove(this._onDisposeObserver);
  17161. }
  17162. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  17163. },
  17164. enumerable: true,
  17165. configurable: true
  17166. });
  17167. Object.defineProperty(Scene.prototype, "beforeRender", {
  17168. set: function (callback) {
  17169. if (this._onBeforeRenderObserver) {
  17170. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  17171. }
  17172. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  17173. },
  17174. enumerable: true,
  17175. configurable: true
  17176. });
  17177. Object.defineProperty(Scene.prototype, "afterRender", {
  17178. set: function (callback) {
  17179. if (this._onAfterRenderObserver) {
  17180. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  17181. }
  17182. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  17183. },
  17184. enumerable: true,
  17185. configurable: true
  17186. });
  17187. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  17188. set: function (callback) {
  17189. if (this._onBeforeCameraRenderObserver) {
  17190. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  17191. }
  17192. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  17193. },
  17194. enumerable: true,
  17195. configurable: true
  17196. });
  17197. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  17198. set: function (callback) {
  17199. if (this._onAfterCameraRenderObserver) {
  17200. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  17201. }
  17202. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  17203. },
  17204. enumerable: true,
  17205. configurable: true
  17206. });
  17207. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  17208. get: function () {
  17209. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  17210. },
  17211. enumerable: true,
  17212. configurable: true
  17213. });
  17214. Object.defineProperty(Scene.prototype, "defaultMaterial", {
  17215. get: function () {
  17216. if (!this._defaultMaterial) {
  17217. this._defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  17218. }
  17219. return this._defaultMaterial;
  17220. },
  17221. enumerable: true,
  17222. configurable: true
  17223. });
  17224. Object.defineProperty(Scene.prototype, "frustumPlanes", {
  17225. get: function () {
  17226. return this._frustumPlanes;
  17227. },
  17228. enumerable: true,
  17229. configurable: true
  17230. });
  17231. Object.defineProperty(Scene.prototype, "debugLayer", {
  17232. // Properties
  17233. get: function () {
  17234. if (!this._debugLayer) {
  17235. this._debugLayer = new BABYLON.DebugLayer(this);
  17236. }
  17237. return this._debugLayer;
  17238. },
  17239. enumerable: true,
  17240. configurable: true
  17241. });
  17242. Object.defineProperty(Scene.prototype, "workerCollisions", {
  17243. get: function () {
  17244. return this._workerCollisions;
  17245. },
  17246. set: function (enabled) {
  17247. enabled = (enabled && !!Worker);
  17248. this._workerCollisions = enabled;
  17249. if (this.collisionCoordinator) {
  17250. this.collisionCoordinator.destroy();
  17251. }
  17252. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  17253. this.collisionCoordinator.init(this);
  17254. },
  17255. enumerable: true,
  17256. configurable: true
  17257. });
  17258. Object.defineProperty(Scene.prototype, "SelectionOctree", {
  17259. get: function () {
  17260. return this._selectionOctree;
  17261. },
  17262. enumerable: true,
  17263. configurable: true
  17264. });
  17265. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  17266. /**
  17267. * The mesh that is currently under the pointer.
  17268. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  17269. */
  17270. get: function () {
  17271. return this._pointerOverMesh;
  17272. },
  17273. enumerable: true,
  17274. configurable: true
  17275. });
  17276. Object.defineProperty(Scene.prototype, "pointerX", {
  17277. /**
  17278. * Current on-screen X position of the pointer
  17279. * @return {number} X position of the pointer
  17280. */
  17281. get: function () {
  17282. return this._pointerX;
  17283. },
  17284. enumerable: true,
  17285. configurable: true
  17286. });
  17287. Object.defineProperty(Scene.prototype, "pointerY", {
  17288. /**
  17289. * Current on-screen Y position of the pointer
  17290. * @return {number} Y position of the pointer
  17291. */
  17292. get: function () {
  17293. return this._pointerY;
  17294. },
  17295. enumerable: true,
  17296. configurable: true
  17297. });
  17298. Scene.prototype.getCachedMaterial = function () {
  17299. return this._cachedMaterial;
  17300. };
  17301. Scene.prototype.getBoundingBoxRenderer = function () {
  17302. return this._boundingBoxRenderer;
  17303. };
  17304. Scene.prototype.getOutlineRenderer = function () {
  17305. return this._outlineRenderer;
  17306. };
  17307. Scene.prototype.getEngine = function () {
  17308. return this._engine;
  17309. };
  17310. Scene.prototype.getTotalVertices = function () {
  17311. return this._totalVertices.current;
  17312. };
  17313. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  17314. get: function () {
  17315. return this._totalVertices;
  17316. },
  17317. enumerable: true,
  17318. configurable: true
  17319. });
  17320. Scene.prototype.getActiveIndices = function () {
  17321. return this._activeIndices.current;
  17322. };
  17323. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  17324. get: function () {
  17325. return this._activeIndices;
  17326. },
  17327. enumerable: true,
  17328. configurable: true
  17329. });
  17330. Scene.prototype.getActiveParticles = function () {
  17331. return this._activeParticles.current;
  17332. };
  17333. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  17334. get: function () {
  17335. return this._activeParticles;
  17336. },
  17337. enumerable: true,
  17338. configurable: true
  17339. });
  17340. Scene.prototype.getActiveBones = function () {
  17341. return this._activeBones.current;
  17342. };
  17343. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  17344. get: function () {
  17345. return this._activeBones;
  17346. },
  17347. enumerable: true,
  17348. configurable: true
  17349. });
  17350. // Stats
  17351. Scene.prototype.getLastFrameDuration = function () {
  17352. return this._lastFrameDuration.current;
  17353. };
  17354. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  17355. get: function () {
  17356. return this._lastFrameDuration;
  17357. },
  17358. enumerable: true,
  17359. configurable: true
  17360. });
  17361. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  17362. return this._evaluateActiveMeshesDuration.current;
  17363. };
  17364. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  17365. get: function () {
  17366. return this._evaluateActiveMeshesDuration;
  17367. },
  17368. enumerable: true,
  17369. configurable: true
  17370. });
  17371. Scene.prototype.getActiveMeshes = function () {
  17372. return this._activeMeshes;
  17373. };
  17374. Scene.prototype.getRenderTargetsDuration = function () {
  17375. return this._renderTargetsDuration.current;
  17376. };
  17377. Scene.prototype.getRenderDuration = function () {
  17378. return this._renderDuration.current;
  17379. };
  17380. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  17381. get: function () {
  17382. return this._renderDuration;
  17383. },
  17384. enumerable: true,
  17385. configurable: true
  17386. });
  17387. Scene.prototype.getParticlesDuration = function () {
  17388. return this._particlesDuration.current;
  17389. };
  17390. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  17391. get: function () {
  17392. return this._particlesDuration;
  17393. },
  17394. enumerable: true,
  17395. configurable: true
  17396. });
  17397. Scene.prototype.getSpritesDuration = function () {
  17398. return this._spritesDuration.current;
  17399. };
  17400. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  17401. get: function () {
  17402. return this._spritesDuration;
  17403. },
  17404. enumerable: true,
  17405. configurable: true
  17406. });
  17407. Scene.prototype.getAnimationRatio = function () {
  17408. return this._animationRatio;
  17409. };
  17410. Scene.prototype.getRenderId = function () {
  17411. return this._renderId;
  17412. };
  17413. Scene.prototype.incrementRenderId = function () {
  17414. this._renderId++;
  17415. };
  17416. Scene.prototype._updatePointerPosition = function (evt) {
  17417. var canvasRect = this._engine.getRenderingCanvasClientRect();
  17418. this._pointerX = evt.clientX - canvasRect.left;
  17419. this._pointerY = evt.clientY - canvasRect.top;
  17420. this._unTranslatedPointerX = this._pointerX;
  17421. this._unTranslatedPointerY = this._pointerY;
  17422. if (this.cameraToUseForPointers) {
  17423. this._pointerX = this._pointerX - this.cameraToUseForPointers.viewport.x * this._engine.getRenderWidth();
  17424. this._pointerY = this._pointerY - this.cameraToUseForPointers.viewport.y * this._engine.getRenderHeight();
  17425. }
  17426. };
  17427. // Pointers handling
  17428. /**
  17429. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  17430. * @param attachUp defines if you want to attach events to pointerup
  17431. * @param attachDown defines if you want to attach events to pointerdown
  17432. * @param attachMove defines if you want to attach events to pointermove
  17433. */
  17434. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  17435. var _this = this;
  17436. if (attachUp === void 0) { attachUp = true; }
  17437. if (attachDown === void 0) { attachDown = true; }
  17438. if (attachMove === void 0) { attachMove = true; }
  17439. var spritePredicate = function (sprite) {
  17440. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  17441. };
  17442. this._onPointerMove = function (evt) {
  17443. _this._updatePointerPosition(evt);
  17444. // PreObservable support
  17445. if (_this.onPrePointerObservable.hasObservers()) {
  17446. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? PointerEventTypes.POINTERWHEEL : PointerEventTypes.POINTERMOVE;
  17447. var pi = new PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  17448. _this.onPrePointerObservable.notifyObservers(pi, type);
  17449. if (pi.skipOnPointerObservable) {
  17450. return;
  17451. }
  17452. }
  17453. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  17454. return;
  17455. }
  17456. var canvas = _this._engine.getRenderingCanvas();
  17457. if (!_this.pointerMovePredicate) {
  17458. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && (_this.constantlyUpdateMeshUnderPointer || mesh.actionManager !== null && mesh.actionManager !== undefined); };
  17459. }
  17460. // Meshes
  17461. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  17462. if (pickResult.hit && pickResult.pickedMesh) {
  17463. _this.setPointerOverSprite(null);
  17464. _this.setPointerOverMesh(pickResult.pickedMesh);
  17465. if (_this._pointerOverMesh.actionManager && _this._pointerOverMesh.actionManager.hasPointerTriggers) {
  17466. if (_this._pointerOverMesh.actionManager.hoverCursor) {
  17467. canvas.style.cursor = _this._pointerOverMesh.actionManager.hoverCursor;
  17468. }
  17469. else {
  17470. canvas.style.cursor = _this.hoverCursor;
  17471. }
  17472. }
  17473. else {
  17474. canvas.style.cursor = "";
  17475. }
  17476. }
  17477. else {
  17478. _this.setPointerOverMesh(null);
  17479. // Sprites
  17480. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, spritePredicate, false, _this.cameraToUseForPointers);
  17481. if (pickResult.hit && pickResult.pickedSprite) {
  17482. _this.setPointerOverSprite(pickResult.pickedSprite);
  17483. if (_this._pointerOverSprite.actionManager && _this._pointerOverSprite.actionManager.hoverCursor) {
  17484. canvas.style.cursor = _this._pointerOverSprite.actionManager.hoverCursor;
  17485. }
  17486. else {
  17487. canvas.style.cursor = _this.hoverCursor;
  17488. }
  17489. }
  17490. else {
  17491. _this.setPointerOverSprite(null);
  17492. // Restore pointer
  17493. canvas.style.cursor = "";
  17494. }
  17495. }
  17496. if (_this.onPointerMove) {
  17497. _this.onPointerMove(evt, pickResult);
  17498. }
  17499. if (_this.onPointerObservable.hasObservers()) {
  17500. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? PointerEventTypes.POINTERWHEEL : PointerEventTypes.POINTERMOVE;
  17501. var pi = new PointerInfo(type, evt, pickResult);
  17502. _this.onPointerObservable.notifyObservers(pi, type);
  17503. }
  17504. };
  17505. this._onPointerDown = function (evt) {
  17506. _this._updatePointerPosition(evt);
  17507. // PreObservable support
  17508. if (_this.onPrePointerObservable.hasObservers()) {
  17509. var type = PointerEventTypes.POINTERDOWN;
  17510. var pi = new PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  17511. _this.onPrePointerObservable.notifyObservers(pi, type);
  17512. if (pi.skipOnPointerObservable) {
  17513. return;
  17514. }
  17515. }
  17516. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  17517. return;
  17518. }
  17519. _this._startingPointerPosition.x = _this._pointerX;
  17520. _this._startingPointerPosition.y = _this._pointerY;
  17521. _this._startingPointerTime = new Date().getTime();
  17522. if (!_this.pointerDownPredicate) {
  17523. _this.pointerDownPredicate = function (mesh) {
  17524. return mesh.isPickable && mesh.isVisible && mesh.isReady();
  17525. };
  17526. }
  17527. // Meshes
  17528. _this._pickedDownMesh = null;
  17529. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  17530. if (pickResult.hit && pickResult.pickedMesh) {
  17531. if (pickResult.pickedMesh.actionManager) {
  17532. _this._pickedDownMesh = pickResult.pickedMesh;
  17533. if (pickResult.pickedMesh.actionManager.hasPickTriggers) {
  17534. switch (evt.button) {
  17535. case 0:
  17536. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  17537. break;
  17538. case 1:
  17539. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  17540. break;
  17541. case 2:
  17542. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  17543. break;
  17544. }
  17545. if (pickResult.pickedMesh.actionManager) {
  17546. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  17547. }
  17548. }
  17549. if (pickResult.pickedMesh.actionManager && pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  17550. var that = _this;
  17551. window.setTimeout(function () {
  17552. 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);
  17553. if (pickResult.hit && pickResult.pickedMesh) {
  17554. if (pickResult.pickedMesh.actionManager) {
  17555. 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)) {
  17556. that._startingPointerTime = 0;
  17557. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  17558. }
  17559. }
  17560. }
  17561. }, BABYLON.ActionManager.LongPressDelay);
  17562. }
  17563. }
  17564. }
  17565. if (_this.onPointerDown) {
  17566. _this.onPointerDown(evt, pickResult);
  17567. }
  17568. if (_this.onPointerObservable.hasObservers()) {
  17569. var type = PointerEventTypes.POINTERDOWN;
  17570. var pi = new PointerInfo(type, evt, pickResult);
  17571. _this.onPointerObservable.notifyObservers(pi, type);
  17572. }
  17573. // Sprites
  17574. _this._pickedDownSprite = null;
  17575. if (_this.spriteManagers.length > 0) {
  17576. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, spritePredicate, false, _this.cameraToUseForPointers);
  17577. if (pickResult.hit && pickResult.pickedSprite) {
  17578. if (pickResult.pickedSprite.actionManager) {
  17579. _this._pickedDownSprite = pickResult.pickedSprite;
  17580. switch (evt.button) {
  17581. case 0:
  17582. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  17583. break;
  17584. case 1:
  17585. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  17586. break;
  17587. case 2:
  17588. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  17589. break;
  17590. }
  17591. if (pickResult.pickedSprite.actionManager) {
  17592. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  17593. }
  17594. }
  17595. }
  17596. }
  17597. };
  17598. this._onPointerUp = function (evt) {
  17599. _this._updatePointerPosition(evt);
  17600. // PreObservable support
  17601. if (_this.onPrePointerObservable.hasObservers()) {
  17602. var type = PointerEventTypes.POINTERUP;
  17603. var pi = new PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  17604. _this.onPrePointerObservable.notifyObservers(pi, type);
  17605. if (pi.skipOnPointerObservable) {
  17606. return;
  17607. }
  17608. }
  17609. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  17610. return;
  17611. }
  17612. if (!_this.pointerUpPredicate) {
  17613. _this.pointerUpPredicate = function (mesh) {
  17614. return mesh.isPickable && mesh.isVisible && mesh.isReady();
  17615. };
  17616. }
  17617. // Meshes
  17618. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerUpPredicate, false, _this.cameraToUseForPointers);
  17619. if (pickResult.hit && pickResult.pickedMesh) {
  17620. if (_this._pickedDownMesh != null && pickResult.pickedMesh == _this._pickedDownMesh) {
  17621. if (_this.onPointerPick) {
  17622. _this.onPointerPick(evt, pickResult);
  17623. }
  17624. if (_this.onPointerObservable.hasObservers()) {
  17625. var type = PointerEventTypes.POINTERPICK;
  17626. var pi = new PointerInfo(type, evt, pickResult);
  17627. _this.onPointerObservable.notifyObservers(pi, type);
  17628. }
  17629. }
  17630. if (pickResult.pickedMesh.actionManager) {
  17631. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  17632. if (pickResult.pickedMesh.actionManager) {
  17633. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < BABYLON.ActionManager.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < BABYLON.ActionManager.DragMovementThreshold) {
  17634. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  17635. }
  17636. }
  17637. }
  17638. }
  17639. if (_this._pickedDownMesh && _this._pickedDownMesh.actionManager && _this._pickedDownMesh !== pickResult.pickedMesh) {
  17640. _this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(_this._pickedDownMesh, evt));
  17641. }
  17642. if (_this.onPointerUp) {
  17643. _this.onPointerUp(evt, pickResult);
  17644. }
  17645. if (_this.onPointerObservable.hasObservers()) {
  17646. var type = PointerEventTypes.POINTERUP;
  17647. var pi = new PointerInfo(type, evt, pickResult);
  17648. _this.onPointerObservable.notifyObservers(pi, type);
  17649. }
  17650. _this._startingPointerTime = 0;
  17651. // Sprites
  17652. if (_this.spriteManagers.length > 0) {
  17653. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, spritePredicate, false, _this.cameraToUseForPointers);
  17654. if (pickResult.hit && pickResult.pickedSprite) {
  17655. if (pickResult.pickedSprite.actionManager) {
  17656. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  17657. if (pickResult.pickedSprite.actionManager) {
  17658. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < BABYLON.ActionManager.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < BABYLON.ActionManager.DragMovementThreshold) {
  17659. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  17660. }
  17661. }
  17662. }
  17663. }
  17664. if (_this._pickedDownSprite && _this._pickedDownSprite.actionManager && _this._pickedDownSprite !== pickResult.pickedSprite) {
  17665. _this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(_this._pickedDownSprite, _this, evt));
  17666. }
  17667. }
  17668. };
  17669. this._onKeyDown = function (evt) {
  17670. if (_this.actionManager) {
  17671. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  17672. }
  17673. };
  17674. this._onKeyUp = function (evt) {
  17675. if (_this.actionManager) {
  17676. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  17677. }
  17678. };
  17679. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  17680. var canvas = this._engine.getRenderingCanvas();
  17681. if (attachMove) {
  17682. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  17683. // Wheel
  17684. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  17685. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  17686. }
  17687. if (attachDown) {
  17688. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  17689. }
  17690. if (attachUp) {
  17691. canvas.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  17692. }
  17693. canvas.tabIndex = 1;
  17694. canvas.addEventListener("keydown", this._onKeyDown, false);
  17695. canvas.addEventListener("keyup", this._onKeyUp, false);
  17696. };
  17697. Scene.prototype.detachControl = function () {
  17698. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  17699. var canvas = this._engine.getRenderingCanvas();
  17700. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  17701. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  17702. canvas.removeEventListener(eventPrefix + "up", this._onPointerUp);
  17703. // Wheel
  17704. canvas.removeEventListener('mousewheel', this._onPointerMove);
  17705. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  17706. canvas.removeEventListener("keydown", this._onKeyDown);
  17707. canvas.removeEventListener("keyup", this._onKeyUp);
  17708. };
  17709. // Ready
  17710. Scene.prototype.isReady = function () {
  17711. if (this._pendingData.length > 0) {
  17712. return false;
  17713. }
  17714. var index;
  17715. for (index = 0; index < this._geometries.length; index++) {
  17716. var geometry = this._geometries[index];
  17717. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  17718. return false;
  17719. }
  17720. }
  17721. for (index = 0; index < this.meshes.length; index++) {
  17722. var mesh = this.meshes[index];
  17723. if (!mesh.isReady()) {
  17724. return false;
  17725. }
  17726. var mat = mesh.material;
  17727. if (mat) {
  17728. if (!mat.isReady(mesh)) {
  17729. return false;
  17730. }
  17731. }
  17732. }
  17733. return true;
  17734. };
  17735. Scene.prototype.resetCachedMaterial = function () {
  17736. this._cachedMaterial = null;
  17737. };
  17738. Scene.prototype.registerBeforeRender = function (func) {
  17739. this.onBeforeRenderObservable.add(func);
  17740. };
  17741. Scene.prototype.unregisterBeforeRender = function (func) {
  17742. this.onBeforeRenderObservable.removeCallback(func);
  17743. };
  17744. Scene.prototype.registerAfterRender = function (func) {
  17745. this.onAfterRenderObservable.add(func);
  17746. };
  17747. Scene.prototype.unregisterAfterRender = function (func) {
  17748. this.onAfterRenderObservable.removeCallback(func);
  17749. };
  17750. Scene.prototype._addPendingData = function (data) {
  17751. this._pendingData.push(data);
  17752. };
  17753. Scene.prototype._removePendingData = function (data) {
  17754. var index = this._pendingData.indexOf(data);
  17755. if (index !== -1) {
  17756. this._pendingData.splice(index, 1);
  17757. }
  17758. };
  17759. Scene.prototype.getWaitingItemsCount = function () {
  17760. return this._pendingData.length;
  17761. };
  17762. /**
  17763. * Registers a function to be executed when the scene is ready.
  17764. * @param {Function} func - the function to be executed.
  17765. */
  17766. Scene.prototype.executeWhenReady = function (func) {
  17767. var _this = this;
  17768. this.onReadyObservable.add(func);
  17769. if (this._executeWhenReadyTimeoutId !== -1) {
  17770. return;
  17771. }
  17772. this._executeWhenReadyTimeoutId = setTimeout(function () {
  17773. _this._checkIsReady();
  17774. }, 150);
  17775. };
  17776. Scene.prototype._checkIsReady = function () {
  17777. var _this = this;
  17778. if (this.isReady()) {
  17779. this.onReadyObservable.notifyObservers(this);
  17780. this.onReadyObservable.clear();
  17781. this._executeWhenReadyTimeoutId = -1;
  17782. return;
  17783. }
  17784. this._executeWhenReadyTimeoutId = setTimeout(function () {
  17785. _this._checkIsReady();
  17786. }, 150);
  17787. };
  17788. // Animations
  17789. /**
  17790. * Will start the animation sequence of a given target
  17791. * @param target - the target
  17792. * @param {number} from - from which frame should animation start
  17793. * @param {number} to - till which frame should animation run.
  17794. * @param {boolean} [loop] - should the animation loop
  17795. * @param {number} [speedRatio] - the speed in which to run the animation
  17796. * @param {Function} [onAnimationEnd] function to be executed when the animation ended.
  17797. * @param {BABYLON.Animatable} [animatable] an animatable object. If not provided a new one will be created from the given params.
  17798. * @return {BABYLON.Animatable} the animatable object created for this animation
  17799. * @see BABYLON.Animatable
  17800. * @see http://doc.babylonjs.com/page.php?p=22081
  17801. */
  17802. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  17803. if (speedRatio === void 0) { speedRatio = 1.0; }
  17804. this.stopAnimation(target);
  17805. if (!animatable) {
  17806. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  17807. }
  17808. // Local animations
  17809. if (target.animations) {
  17810. animatable.appendAnimations(target, target.animations);
  17811. }
  17812. // Children animations
  17813. if (target.getAnimatables) {
  17814. var animatables = target.getAnimatables();
  17815. for (var index = 0; index < animatables.length; index++) {
  17816. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  17817. }
  17818. }
  17819. animatable.reset();
  17820. return animatable;
  17821. };
  17822. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  17823. if (speedRatio === undefined) {
  17824. speedRatio = 1.0;
  17825. }
  17826. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  17827. return animatable;
  17828. };
  17829. Scene.prototype.getAnimatableByTarget = function (target) {
  17830. for (var index = 0; index < this._activeAnimatables.length; index++) {
  17831. if (this._activeAnimatables[index].target === target) {
  17832. return this._activeAnimatables[index];
  17833. }
  17834. }
  17835. return null;
  17836. };
  17837. Object.defineProperty(Scene.prototype, "Animatables", {
  17838. get: function () {
  17839. return this._activeAnimatables;
  17840. },
  17841. enumerable: true,
  17842. configurable: true
  17843. });
  17844. /**
  17845. * Will stop the animation of the given target
  17846. * @param target - the target
  17847. * @param animationName - the name of the animation to stop (all animations will be stopped is empty)
  17848. * @see beginAnimation
  17849. */
  17850. Scene.prototype.stopAnimation = function (target, animationName) {
  17851. var animatable = this.getAnimatableByTarget(target);
  17852. if (animatable) {
  17853. animatable.stop(animationName);
  17854. }
  17855. };
  17856. Scene.prototype._animate = function () {
  17857. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  17858. return;
  17859. }
  17860. // Getting time
  17861. var now = BABYLON.Tools.Now;
  17862. if (!this._animationTimeLast) {
  17863. if (this._pendingData.length > 0) {
  17864. return;
  17865. }
  17866. this._animationTimeLast = now;
  17867. }
  17868. var deltaTime = (now - this._animationTimeLast) * this.animationTimeScale;
  17869. this._animationTime += deltaTime;
  17870. this._animationTimeLast = now;
  17871. for (var index = 0; index < this._activeAnimatables.length; index++) {
  17872. this._activeAnimatables[index]._animate(this._animationTime);
  17873. }
  17874. };
  17875. // Matrix
  17876. Scene.prototype.getViewMatrix = function () {
  17877. return this._viewMatrix;
  17878. };
  17879. Scene.prototype.getProjectionMatrix = function () {
  17880. return this._projectionMatrix;
  17881. };
  17882. Scene.prototype.getTransformMatrix = function () {
  17883. return this._transformMatrix;
  17884. };
  17885. Scene.prototype.setTransformMatrix = function (view, projection) {
  17886. this._viewMatrix = view;
  17887. this._projectionMatrix = projection;
  17888. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  17889. // Update frustum
  17890. if (!this._frustumPlanes) {
  17891. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  17892. }
  17893. else {
  17894. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  17895. }
  17896. };
  17897. // Methods
  17898. Scene.prototype.addMesh = function (newMesh) {
  17899. newMesh.uniqueId = this._uniqueIdCounter++;
  17900. var position = this.meshes.push(newMesh);
  17901. //notify the collision coordinator
  17902. this.collisionCoordinator.onMeshAdded(newMesh);
  17903. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  17904. };
  17905. Scene.prototype.removeMesh = function (toRemove) {
  17906. var index = this.meshes.indexOf(toRemove);
  17907. if (index !== -1) {
  17908. // Remove from the scene if mesh found
  17909. this.meshes.splice(index, 1);
  17910. }
  17911. //notify the collision coordinator
  17912. this.collisionCoordinator.onMeshRemoved(toRemove);
  17913. this.onMeshRemovedObservable.notifyObservers(toRemove);
  17914. return index;
  17915. };
  17916. Scene.prototype.removeSkeleton = function (toRemove) {
  17917. var index = this.skeletons.indexOf(toRemove);
  17918. if (index !== -1) {
  17919. // Remove from the scene if mesh found
  17920. this.skeletons.splice(index, 1);
  17921. }
  17922. return index;
  17923. };
  17924. Scene.prototype.removeLight = function (toRemove) {
  17925. var index = this.lights.indexOf(toRemove);
  17926. if (index !== -1) {
  17927. // Remove from the scene if mesh found
  17928. this.lights.splice(index, 1);
  17929. }
  17930. this.onLightRemovedObservable.notifyObservers(toRemove);
  17931. return index;
  17932. };
  17933. Scene.prototype.removeCamera = function (toRemove) {
  17934. var index = this.cameras.indexOf(toRemove);
  17935. if (index !== -1) {
  17936. // Remove from the scene if mesh found
  17937. this.cameras.splice(index, 1);
  17938. }
  17939. // Remove from activeCameras
  17940. var index2 = this.activeCameras.indexOf(toRemove);
  17941. if (index2 !== -1) {
  17942. // Remove from the scene if mesh found
  17943. this.activeCameras.splice(index2, 1);
  17944. }
  17945. // Reset the activeCamera
  17946. if (this.activeCamera === toRemove) {
  17947. if (this.cameras.length > 0) {
  17948. this.activeCamera = this.cameras[0];
  17949. }
  17950. else {
  17951. this.activeCamera = null;
  17952. }
  17953. }
  17954. this.onCameraRemovedObservable.notifyObservers(toRemove);
  17955. return index;
  17956. };
  17957. Scene.prototype.addLight = function (newLight) {
  17958. newLight.uniqueId = this._uniqueIdCounter++;
  17959. var position = this.lights.push(newLight);
  17960. this.onNewLightAddedObservable.notifyObservers(newLight);
  17961. };
  17962. Scene.prototype.addCamera = function (newCamera) {
  17963. newCamera.uniqueId = this._uniqueIdCounter++;
  17964. var position = this.cameras.push(newCamera);
  17965. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  17966. };
  17967. /**
  17968. * Switch active camera
  17969. * @param {Camera} newCamera - new active camera
  17970. * @param {boolean} attachControl - call attachControl for the new active camera (default: true)
  17971. */
  17972. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  17973. if (attachControl === void 0) { attachControl = true; }
  17974. var canvas = this._engine.getRenderingCanvas();
  17975. this.activeCamera.detachControl(canvas);
  17976. this.activeCamera = newCamera;
  17977. if (attachControl) {
  17978. newCamera.attachControl(canvas);
  17979. }
  17980. };
  17981. /**
  17982. * sets the active camera of the scene using its ID
  17983. * @param {string} id - the camera's ID
  17984. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  17985. * @see activeCamera
  17986. */
  17987. Scene.prototype.setActiveCameraByID = function (id) {
  17988. var camera = this.getCameraByID(id);
  17989. if (camera) {
  17990. this.activeCamera = camera;
  17991. return camera;
  17992. }
  17993. return null;
  17994. };
  17995. /**
  17996. * sets the active camera of the scene using its name
  17997. * @param {string} name - the camera's name
  17998. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  17999. * @see activeCamera
  18000. */
  18001. Scene.prototype.setActiveCameraByName = function (name) {
  18002. var camera = this.getCameraByName(name);
  18003. if (camera) {
  18004. this.activeCamera = camera;
  18005. return camera;
  18006. }
  18007. return null;
  18008. };
  18009. /**
  18010. * get a material using its id
  18011. * @param {string} the material's ID
  18012. * @return {BABYLON.Material|null} the material or null if none found.
  18013. */
  18014. Scene.prototype.getMaterialByID = function (id) {
  18015. for (var index = 0; index < this.materials.length; index++) {
  18016. if (this.materials[index].id === id) {
  18017. return this.materials[index];
  18018. }
  18019. }
  18020. return null;
  18021. };
  18022. /**
  18023. * get a material using its name
  18024. * @param {string} the material's name
  18025. * @return {BABYLON.Material|null} the material or null if none found.
  18026. */
  18027. Scene.prototype.getMaterialByName = function (name) {
  18028. for (var index = 0; index < this.materials.length; index++) {
  18029. if (this.materials[index].name === name) {
  18030. return this.materials[index];
  18031. }
  18032. }
  18033. return null;
  18034. };
  18035. Scene.prototype.getLensFlareSystemByName = function (name) {
  18036. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  18037. if (this.lensFlareSystems[index].name === name) {
  18038. return this.lensFlareSystems[index];
  18039. }
  18040. }
  18041. return null;
  18042. };
  18043. Scene.prototype.getLensFlareSystemByID = function (id) {
  18044. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  18045. if (this.lensFlareSystems[index].id === id) {
  18046. return this.lensFlareSystems[index];
  18047. }
  18048. }
  18049. return null;
  18050. };
  18051. Scene.prototype.getCameraByID = function (id) {
  18052. for (var index = 0; index < this.cameras.length; index++) {
  18053. if (this.cameras[index].id === id) {
  18054. return this.cameras[index];
  18055. }
  18056. }
  18057. return null;
  18058. };
  18059. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  18060. for (var index = 0; index < this.cameras.length; index++) {
  18061. if (this.cameras[index].uniqueId === uniqueId) {
  18062. return this.cameras[index];
  18063. }
  18064. }
  18065. return null;
  18066. };
  18067. /**
  18068. * get a camera using its name
  18069. * @param {string} the camera's name
  18070. * @return {BABYLON.Camera|null} the camera or null if none found.
  18071. */
  18072. Scene.prototype.getCameraByName = function (name) {
  18073. for (var index = 0; index < this.cameras.length; index++) {
  18074. if (this.cameras[index].name === name) {
  18075. return this.cameras[index];
  18076. }
  18077. }
  18078. return null;
  18079. };
  18080. /**
  18081. * get a bone using its id
  18082. * @param {string} the bone's id
  18083. * @return {BABYLON.Bone|null} the bone or null if not found
  18084. */
  18085. Scene.prototype.getBoneByID = function (id) {
  18086. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  18087. var skeleton = this.skeletons[skeletonIndex];
  18088. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  18089. if (skeleton.bones[boneIndex].id === id) {
  18090. return skeleton.bones[boneIndex];
  18091. }
  18092. }
  18093. }
  18094. return null;
  18095. };
  18096. /**
  18097. * get a bone using its id
  18098. * @param {string} the bone's name
  18099. * @return {BABYLON.Bone|null} the bone or null if not found
  18100. */
  18101. Scene.prototype.getBoneByName = function (name) {
  18102. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  18103. var skeleton = this.skeletons[skeletonIndex];
  18104. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  18105. if (skeleton.bones[boneIndex].name === name) {
  18106. return skeleton.bones[boneIndex];
  18107. }
  18108. }
  18109. }
  18110. return null;
  18111. };
  18112. /**
  18113. * get a light node using its name
  18114. * @param {string} the light's name
  18115. * @return {BABYLON.Light|null} the light or null if none found.
  18116. */
  18117. Scene.prototype.getLightByName = function (name) {
  18118. for (var index = 0; index < this.lights.length; index++) {
  18119. if (this.lights[index].name === name) {
  18120. return this.lights[index];
  18121. }
  18122. }
  18123. return null;
  18124. };
  18125. /**
  18126. * get a light node using its ID
  18127. * @param {string} the light's id
  18128. * @return {BABYLON.Light|null} the light or null if none found.
  18129. */
  18130. Scene.prototype.getLightByID = function (id) {
  18131. for (var index = 0; index < this.lights.length; index++) {
  18132. if (this.lights[index].id === id) {
  18133. return this.lights[index];
  18134. }
  18135. }
  18136. return null;
  18137. };
  18138. /**
  18139. * get a light node using its scene-generated unique ID
  18140. * @param {number} the light's unique id
  18141. * @return {BABYLON.Light|null} the light or null if none found.
  18142. */
  18143. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  18144. for (var index = 0; index < this.lights.length; index++) {
  18145. if (this.lights[index].uniqueId === uniqueId) {
  18146. return this.lights[index];
  18147. }
  18148. }
  18149. return null;
  18150. };
  18151. /**
  18152. * get a particle system by id
  18153. * @param id {number} the particle system id
  18154. * @return {BABYLON.ParticleSystem|null} the corresponding system or null if none found.
  18155. */
  18156. Scene.prototype.getParticleSystemByID = function (id) {
  18157. for (var index = 0; index < this.particleSystems.length; index++) {
  18158. if (this.particleSystems[index].id === id) {
  18159. return this.particleSystems[index];
  18160. }
  18161. }
  18162. return null;
  18163. };
  18164. /**
  18165. * get a geometry using its ID
  18166. * @param {string} the geometry's id
  18167. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  18168. */
  18169. Scene.prototype.getGeometryByID = function (id) {
  18170. for (var index = 0; index < this._geometries.length; index++) {
  18171. if (this._geometries[index].id === id) {
  18172. return this._geometries[index];
  18173. }
  18174. }
  18175. return null;
  18176. };
  18177. /**
  18178. * add a new geometry to this scene.
  18179. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  18180. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  18181. * @return {boolean} was the geometry added or not
  18182. */
  18183. Scene.prototype.pushGeometry = function (geometry, force) {
  18184. if (!force && this.getGeometryByID(geometry.id)) {
  18185. return false;
  18186. }
  18187. this._geometries.push(geometry);
  18188. //notify the collision coordinator
  18189. this.collisionCoordinator.onGeometryAdded(geometry);
  18190. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  18191. return true;
  18192. };
  18193. /**
  18194. * Removes an existing geometry
  18195. * @param {BABYLON.Geometry} geometry - the geometry to be removed from the scene.
  18196. * @return {boolean} was the geometry removed or not
  18197. */
  18198. Scene.prototype.removeGeometry = function (geometry) {
  18199. var index = this._geometries.indexOf(geometry);
  18200. if (index > -1) {
  18201. this._geometries.splice(index, 1);
  18202. //notify the collision coordinator
  18203. this.collisionCoordinator.onGeometryDeleted(geometry);
  18204. this.onGeometryRemovedObservable.notifyObservers(geometry);
  18205. return true;
  18206. }
  18207. return false;
  18208. };
  18209. Scene.prototype.getGeometries = function () {
  18210. return this._geometries;
  18211. };
  18212. /**
  18213. * Get the first added mesh found of a given ID
  18214. * @param {string} id - the id to search for
  18215. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  18216. */
  18217. Scene.prototype.getMeshByID = function (id) {
  18218. for (var index = 0; index < this.meshes.length; index++) {
  18219. if (this.meshes[index].id === id) {
  18220. return this.meshes[index];
  18221. }
  18222. }
  18223. return null;
  18224. };
  18225. Scene.prototype.getMeshesByID = function (id) {
  18226. return this.meshes.filter(function (m) {
  18227. return m.id === id;
  18228. });
  18229. };
  18230. /**
  18231. * Get a mesh with its auto-generated unique id
  18232. * @param {number} uniqueId - the unique id to search for
  18233. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  18234. */
  18235. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  18236. for (var index = 0; index < this.meshes.length; index++) {
  18237. if (this.meshes[index].uniqueId === uniqueId) {
  18238. return this.meshes[index];
  18239. }
  18240. }
  18241. return null;
  18242. };
  18243. /**
  18244. * Get a the last added mesh found of a given ID
  18245. * @param {string} id - the id to search for
  18246. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  18247. */
  18248. Scene.prototype.getLastMeshByID = function (id) {
  18249. for (var index = this.meshes.length - 1; index >= 0; index--) {
  18250. if (this.meshes[index].id === id) {
  18251. return this.meshes[index];
  18252. }
  18253. }
  18254. return null;
  18255. };
  18256. /**
  18257. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  18258. * @param {string} id - the id to search for
  18259. * @return {BABYLON.Node|null} the node found or null if not found at all.
  18260. */
  18261. Scene.prototype.getLastEntryByID = function (id) {
  18262. var index;
  18263. for (index = this.meshes.length - 1; index >= 0; index--) {
  18264. if (this.meshes[index].id === id) {
  18265. return this.meshes[index];
  18266. }
  18267. }
  18268. for (index = this.cameras.length - 1; index >= 0; index--) {
  18269. if (this.cameras[index].id === id) {
  18270. return this.cameras[index];
  18271. }
  18272. }
  18273. for (index = this.lights.length - 1; index >= 0; index--) {
  18274. if (this.lights[index].id === id) {
  18275. return this.lights[index];
  18276. }
  18277. }
  18278. return null;
  18279. };
  18280. Scene.prototype.getNodeByID = function (id) {
  18281. var mesh = this.getMeshByID(id);
  18282. if (mesh) {
  18283. return mesh;
  18284. }
  18285. var light = this.getLightByID(id);
  18286. if (light) {
  18287. return light;
  18288. }
  18289. var camera = this.getCameraByID(id);
  18290. if (camera) {
  18291. return camera;
  18292. }
  18293. var bone = this.getBoneByID(id);
  18294. return bone;
  18295. };
  18296. Scene.prototype.getNodeByName = function (name) {
  18297. var mesh = this.getMeshByName(name);
  18298. if (mesh) {
  18299. return mesh;
  18300. }
  18301. var light = this.getLightByName(name);
  18302. if (light) {
  18303. return light;
  18304. }
  18305. var camera = this.getCameraByName(name);
  18306. if (camera) {
  18307. return camera;
  18308. }
  18309. var bone = this.getBoneByName(name);
  18310. return bone;
  18311. };
  18312. Scene.prototype.getMeshByName = function (name) {
  18313. for (var index = 0; index < this.meshes.length; index++) {
  18314. if (this.meshes[index].name === name) {
  18315. return this.meshes[index];
  18316. }
  18317. }
  18318. return null;
  18319. };
  18320. Scene.prototype.getSoundByName = function (name) {
  18321. var index;
  18322. if (BABYLON.AudioEngine) {
  18323. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  18324. if (this.mainSoundTrack.soundCollection[index].name === name) {
  18325. return this.mainSoundTrack.soundCollection[index];
  18326. }
  18327. }
  18328. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  18329. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  18330. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  18331. return this.soundTracks[sdIndex].soundCollection[index];
  18332. }
  18333. }
  18334. }
  18335. }
  18336. return null;
  18337. };
  18338. Scene.prototype.getLastSkeletonByID = function (id) {
  18339. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  18340. if (this.skeletons[index].id === id) {
  18341. return this.skeletons[index];
  18342. }
  18343. }
  18344. return null;
  18345. };
  18346. Scene.prototype.getSkeletonById = function (id) {
  18347. for (var index = 0; index < this.skeletons.length; index++) {
  18348. if (this.skeletons[index].id === id) {
  18349. return this.skeletons[index];
  18350. }
  18351. }
  18352. return null;
  18353. };
  18354. Scene.prototype.getSkeletonByName = function (name) {
  18355. for (var index = 0; index < this.skeletons.length; index++) {
  18356. if (this.skeletons[index].name === name) {
  18357. return this.skeletons[index];
  18358. }
  18359. }
  18360. return null;
  18361. };
  18362. Scene.prototype.isActiveMesh = function (mesh) {
  18363. return (this._activeMeshes.indexOf(mesh) !== -1);
  18364. };
  18365. Object.defineProperty(Scene.prototype, "uid", {
  18366. /**
  18367. * Return a unique id as a string which can serve as an identifier for the scene
  18368. */
  18369. get: function () {
  18370. if (!this._uid) {
  18371. this._uid = BABYLON.Tools.RandomId();
  18372. }
  18373. return this._uid;
  18374. },
  18375. enumerable: true,
  18376. configurable: true
  18377. });
  18378. /**
  18379. * Add an externaly attached data from its key.
  18380. * This method call will fail and return false, if such key already exists.
  18381. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  18382. * @param key the unique key that identifies the data
  18383. * @param data the data object to associate to the key for this Engine instance
  18384. * @return true if no such key were already present and the data was added successfully, false otherwise
  18385. */
  18386. Scene.prototype.addExternalData = function (key, data) {
  18387. return this._externalData.add(key, data);
  18388. };
  18389. /**
  18390. * Get an externaly attached data from its key
  18391. * @param key the unique key that identifies the data
  18392. * @return the associated data, if present (can be null), or undefined if not present
  18393. */
  18394. Scene.prototype.getExternalData = function (key) {
  18395. return this._externalData.get(key);
  18396. };
  18397. /**
  18398. * Get an externaly attached data from its key, create it using a factory if it's not already present
  18399. * @param key the unique key that identifies the data
  18400. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  18401. * @return the associated data, can be null if the factory returned null.
  18402. */
  18403. Scene.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  18404. return this._externalData.getOrAddWithFactory(key, factory);
  18405. };
  18406. /**
  18407. * Remove an externaly attached data from the Engine instance
  18408. * @param key the unique key that identifies the data
  18409. * @return true if the data was successfully removed, false if it doesn't exist
  18410. */
  18411. Scene.prototype.removeExternalData = function (key) {
  18412. return this._externalData.remove(key);
  18413. };
  18414. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  18415. if (mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  18416. var material = subMesh.getMaterial();
  18417. if (mesh.showSubMeshesBoundingBox) {
  18418. this._boundingBoxRenderer.renderList.push(subMesh.getBoundingInfo().boundingBox);
  18419. }
  18420. if (material) {
  18421. // Render targets
  18422. if (material.getRenderTargetTextures) {
  18423. if (this._processedMaterials.indexOf(material) === -1) {
  18424. this._processedMaterials.push(material);
  18425. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  18426. }
  18427. }
  18428. // Dispatch
  18429. this._activeIndices.addCount(subMesh.indexCount, false);
  18430. this._renderingManager.dispatch(subMesh);
  18431. }
  18432. }
  18433. };
  18434. Scene.prototype._isInIntermediateRendering = function () {
  18435. return this._intermediateRendering;
  18436. };
  18437. Scene.prototype._evaluateActiveMeshes = function () {
  18438. this.activeCamera._activeMeshes.reset();
  18439. this._activeMeshes.reset();
  18440. this._renderingManager.reset();
  18441. this._processedMaterials.reset();
  18442. this._activeParticleSystems.reset();
  18443. this._activeSkeletons.reset();
  18444. this._softwareSkinnedMeshes.reset();
  18445. this._boundingBoxRenderer.reset();
  18446. this._edgesRenderers.reset();
  18447. // Meshes
  18448. var meshes;
  18449. var len;
  18450. if (this._selectionOctree) {
  18451. var selection = this._selectionOctree.select(this._frustumPlanes);
  18452. meshes = selection.data;
  18453. len = selection.length;
  18454. }
  18455. else {
  18456. len = this.meshes.length;
  18457. meshes = this.meshes;
  18458. }
  18459. for (var meshIndex = 0; meshIndex < len; meshIndex++) {
  18460. var mesh = meshes[meshIndex];
  18461. if (mesh.isBlocked) {
  18462. continue;
  18463. }
  18464. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  18465. if (!mesh.isReady() || !mesh.isEnabled()) {
  18466. continue;
  18467. }
  18468. mesh.computeWorldMatrix();
  18469. // Intersections
  18470. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  18471. this._meshesForIntersections.pushNoDuplicate(mesh);
  18472. }
  18473. // Switch to current LOD
  18474. var meshLOD = mesh.getLOD(this.activeCamera);
  18475. if (!meshLOD) {
  18476. continue;
  18477. }
  18478. mesh._preActivate();
  18479. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  18480. this._activeMeshes.push(mesh);
  18481. this.activeCamera._activeMeshes.push(mesh);
  18482. mesh._activate(this._renderId);
  18483. this._activeMesh(mesh, meshLOD);
  18484. }
  18485. }
  18486. // Particle systems
  18487. this._particlesDuration.beginMonitoring();
  18488. var beforeParticlesDate = BABYLON.Tools.Now;
  18489. if (this.particlesEnabled) {
  18490. BABYLON.Tools.StartPerformanceCounter("Particles", this.particleSystems.length > 0);
  18491. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  18492. var particleSystem = this.particleSystems[particleIndex];
  18493. if (!particleSystem.isStarted()) {
  18494. continue;
  18495. }
  18496. if (!particleSystem.emitter.position || (particleSystem.emitter && particleSystem.emitter.isEnabled())) {
  18497. this._activeParticleSystems.push(particleSystem);
  18498. particleSystem.animate();
  18499. this._renderingManager.dispatchParticles(particleSystem);
  18500. }
  18501. }
  18502. BABYLON.Tools.EndPerformanceCounter("Particles", this.particleSystems.length > 0);
  18503. }
  18504. this._particlesDuration.endMonitoring(false);
  18505. };
  18506. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  18507. if (mesh.skeleton && this.skeletonsEnabled) {
  18508. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  18509. mesh.skeleton.prepare();
  18510. }
  18511. if (!mesh.computeBonesUsingShaders) {
  18512. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  18513. }
  18514. }
  18515. if (sourceMesh.showBoundingBox || this.forceShowBoundingBoxes) {
  18516. this._boundingBoxRenderer.renderList.push(sourceMesh.getBoundingInfo().boundingBox);
  18517. }
  18518. if (sourceMesh._edgesRenderer) {
  18519. this._edgesRenderers.push(sourceMesh._edgesRenderer);
  18520. }
  18521. if (mesh && mesh.subMeshes) {
  18522. // Submeshes Octrees
  18523. var len;
  18524. var subMeshes;
  18525. if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) {
  18526. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  18527. len = intersections.length;
  18528. subMeshes = intersections.data;
  18529. }
  18530. else {
  18531. subMeshes = mesh.subMeshes;
  18532. len = subMeshes.length;
  18533. }
  18534. for (var subIndex = 0; subIndex < len; subIndex++) {
  18535. var subMesh = subMeshes[subIndex];
  18536. this._evaluateSubMesh(subMesh, mesh);
  18537. }
  18538. }
  18539. };
  18540. Scene.prototype.updateTransformMatrix = function (force) {
  18541. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  18542. };
  18543. Scene.prototype._renderForCamera = function (camera) {
  18544. var engine = this._engine;
  18545. var startTime = BABYLON.Tools.Now;
  18546. this.activeCamera = camera;
  18547. if (!this.activeCamera)
  18548. throw new Error("Active camera not set");
  18549. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  18550. // Viewport
  18551. engine.setViewport(this.activeCamera.viewport);
  18552. // Camera
  18553. this.resetCachedMaterial();
  18554. this._renderId++;
  18555. this.updateTransformMatrix();
  18556. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  18557. // Meshes
  18558. this._evaluateActiveMeshesDuration.beginMonitoring();
  18559. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  18560. this._evaluateActiveMeshes();
  18561. this._evaluateActiveMeshesDuration.endMonitoring(false);
  18562. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  18563. // Software skinning
  18564. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  18565. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  18566. mesh.applySkeleton(mesh.skeleton);
  18567. }
  18568. // Render targets
  18569. this._renderTargetsDuration.beginMonitoring();
  18570. var needsRestoreFrameBuffer = false;
  18571. var beforeRenderTargetDate = BABYLON.Tools.Now;
  18572. if (this.renderTargetsEnabled && this._renderTargets.length > 0) {
  18573. this._intermediateRendering = true;
  18574. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  18575. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  18576. var renderTarget = this._renderTargets.data[renderIndex];
  18577. if (renderTarget._shouldRender()) {
  18578. this._renderId++;
  18579. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  18580. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  18581. }
  18582. }
  18583. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  18584. this._intermediateRendering = false;
  18585. this._renderId++;
  18586. needsRestoreFrameBuffer = true; // Restore back buffer
  18587. }
  18588. // Render HighlightLayer Texture
  18589. var stencilState = this._engine.getStencilBuffer();
  18590. var renderhighlights = false;
  18591. if (this.renderTargetsEnabled && this.highlightLayers && this.highlightLayers.length > 0) {
  18592. this._intermediateRendering = true;
  18593. for (var i = 0; i < this.highlightLayers.length; i++) {
  18594. var highlightLayer = this.highlightLayers[i];
  18595. if (highlightLayer.shouldRender() &&
  18596. (!highlightLayer.camera ||
  18597. (highlightLayer.camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE && camera === highlightLayer.camera) ||
  18598. (highlightLayer.camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE && highlightLayer.camera._rigCameras.indexOf(camera) > -1))) {
  18599. renderhighlights = true;
  18600. var renderTarget = highlightLayer._mainTexture;
  18601. if (renderTarget._shouldRender()) {
  18602. this._renderId++;
  18603. renderTarget.render(false, false);
  18604. needsRestoreFrameBuffer = true;
  18605. }
  18606. }
  18607. }
  18608. this._intermediateRendering = false;
  18609. this._renderId++;
  18610. }
  18611. if (needsRestoreFrameBuffer) {
  18612. engine.restoreDefaultFramebuffer();
  18613. }
  18614. this._renderTargetsDuration.endMonitoring(false);
  18615. // Prepare Frame
  18616. this.postProcessManager._prepareFrame();
  18617. this._renderDuration.beginMonitoring();
  18618. // Backgrounds
  18619. var layerIndex;
  18620. var layer;
  18621. if (this.layers.length) {
  18622. engine.setDepthBuffer(false);
  18623. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  18624. layer = this.layers[layerIndex];
  18625. if (layer.isBackground) {
  18626. layer.render();
  18627. }
  18628. }
  18629. engine.setDepthBuffer(true);
  18630. }
  18631. // Render
  18632. BABYLON.Tools.StartPerformanceCounter("Main render");
  18633. // Activate HighlightLayer stencil
  18634. if (renderhighlights) {
  18635. this._engine.setStencilBuffer(true);
  18636. }
  18637. this._renderingManager.render(null, null, true, true);
  18638. // Restore HighlightLayer stencil
  18639. if (renderhighlights) {
  18640. this._engine.setStencilBuffer(stencilState);
  18641. }
  18642. BABYLON.Tools.EndPerformanceCounter("Main render");
  18643. // Bounding boxes
  18644. this._boundingBoxRenderer.render();
  18645. // Edges
  18646. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  18647. this._edgesRenderers.data[edgesRendererIndex].render();
  18648. }
  18649. // Lens flares
  18650. if (this.lensFlaresEnabled) {
  18651. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  18652. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  18653. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  18654. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  18655. lensFlareSystem.render();
  18656. }
  18657. }
  18658. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  18659. }
  18660. // Foregrounds
  18661. if (this.layers.length) {
  18662. engine.setDepthBuffer(false);
  18663. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  18664. layer = this.layers[layerIndex];
  18665. if (!layer.isBackground) {
  18666. layer.render();
  18667. }
  18668. }
  18669. engine.setDepthBuffer(true);
  18670. }
  18671. // Highlight Layer
  18672. if (renderhighlights) {
  18673. engine.setDepthBuffer(false);
  18674. for (var i = 0; i < this.highlightLayers.length; i++) {
  18675. if (this.highlightLayers[i].shouldRender()) {
  18676. this.highlightLayers[i].render();
  18677. }
  18678. }
  18679. engine.setDepthBuffer(true);
  18680. }
  18681. this._renderDuration.endMonitoring(false);
  18682. // Finalize frame
  18683. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  18684. // Update camera
  18685. this.activeCamera._updateFromScene();
  18686. // Reset some special arrays
  18687. this._renderTargets.reset();
  18688. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  18689. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  18690. };
  18691. Scene.prototype._processSubCameras = function (camera) {
  18692. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  18693. this._renderForCamera(camera);
  18694. return;
  18695. }
  18696. // rig cameras
  18697. for (var index = 0; index < camera._rigCameras.length; index++) {
  18698. this._renderForCamera(camera._rigCameras[index]);
  18699. }
  18700. this.activeCamera = camera;
  18701. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  18702. // Update camera
  18703. this.activeCamera._updateFromScene();
  18704. };
  18705. Scene.prototype._checkIntersections = function () {
  18706. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  18707. var sourceMesh = this._meshesForIntersections.data[index];
  18708. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  18709. var action = sourceMesh.actionManager.actions[actionIndex];
  18710. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  18711. var parameters = action.getTriggerParameter();
  18712. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  18713. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  18714. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  18715. if (areIntersecting && currentIntersectionInProgress === -1) {
  18716. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  18717. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  18718. sourceMesh._intersectionsInProgress.push(otherMesh);
  18719. }
  18720. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  18721. sourceMesh._intersectionsInProgress.push(otherMesh);
  18722. }
  18723. }
  18724. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  18725. //They intersected, and now they don't.
  18726. //is this trigger an exit trigger? execute an event.
  18727. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  18728. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  18729. }
  18730. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  18731. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  18732. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  18733. }
  18734. }
  18735. }
  18736. }
  18737. }
  18738. };
  18739. Scene.prototype.render = function () {
  18740. this._lastFrameDuration.beginMonitoring();
  18741. this._particlesDuration.fetchNewFrame();
  18742. this._spritesDuration.fetchNewFrame();
  18743. this._activeParticles.fetchNewFrame();
  18744. this._renderDuration.fetchNewFrame();
  18745. this._renderTargetsDuration.fetchNewFrame();
  18746. this._evaluateActiveMeshesDuration.fetchNewFrame();
  18747. this._totalVertices.fetchNewFrame();
  18748. this._activeIndices.fetchNewFrame();
  18749. this._activeBones.fetchNewFrame();
  18750. this.getEngine().drawCallsPerfCounter.fetchNewFrame();
  18751. this._meshesForIntersections.reset();
  18752. this.resetCachedMaterial();
  18753. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  18754. // Actions
  18755. if (this.actionManager) {
  18756. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger, null);
  18757. }
  18758. //Simplification Queue
  18759. if (this.simplificationQueue && !this.simplificationQueue.running) {
  18760. this.simplificationQueue.executeNext();
  18761. }
  18762. // Animations
  18763. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  18764. this._animationRatio = deltaTime * (60.0 / 1000.0);
  18765. this._animate();
  18766. // Physics
  18767. if (this._physicsEngine) {
  18768. BABYLON.Tools.StartPerformanceCounter("Physics");
  18769. this._physicsEngine._step(deltaTime / 1000.0);
  18770. BABYLON.Tools.EndPerformanceCounter("Physics");
  18771. }
  18772. // Before render
  18773. this.onBeforeRenderObservable.notifyObservers(this);
  18774. // Customs render targets
  18775. this._renderTargetsDuration.beginMonitoring();
  18776. var beforeRenderTargetDate = BABYLON.Tools.Now;
  18777. var engine = this.getEngine();
  18778. var currentActiveCamera = this.activeCamera;
  18779. if (this.renderTargetsEnabled) {
  18780. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  18781. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  18782. var renderTarget = this.customRenderTargets[customIndex];
  18783. if (renderTarget._shouldRender()) {
  18784. this._renderId++;
  18785. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  18786. if (!this.activeCamera)
  18787. throw new Error("Active camera not set");
  18788. // Viewport
  18789. engine.setViewport(this.activeCamera.viewport);
  18790. // Camera
  18791. this.updateTransformMatrix();
  18792. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  18793. }
  18794. }
  18795. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  18796. this._renderId++;
  18797. }
  18798. if (this.customRenderTargets.length > 0) {
  18799. engine.restoreDefaultFramebuffer();
  18800. }
  18801. this._renderTargetsDuration.endMonitoring();
  18802. this.activeCamera = currentActiveCamera;
  18803. // Procedural textures
  18804. if (this.proceduralTexturesEnabled) {
  18805. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  18806. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  18807. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  18808. if (proceduralTexture._shouldRender()) {
  18809. proceduralTexture.render();
  18810. }
  18811. }
  18812. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  18813. }
  18814. // Clear
  18815. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, true, true);
  18816. // Shadows
  18817. if (this.shadowsEnabled) {
  18818. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  18819. var light = this.lights[lightIndex];
  18820. var shadowGenerator = light.getShadowGenerator();
  18821. if (light.isEnabled() && shadowGenerator && shadowGenerator.getShadowMap().getScene().textures.indexOf(shadowGenerator.getShadowMap()) !== -1) {
  18822. this._renderTargets.push(shadowGenerator.getShadowMap());
  18823. }
  18824. }
  18825. }
  18826. // Depth renderer
  18827. if (this._depthRenderer) {
  18828. this._renderTargets.push(this._depthRenderer.getDepthMap());
  18829. }
  18830. // RenderPipeline
  18831. this.postProcessRenderPipelineManager.update();
  18832. // Multi-cameras?
  18833. if (this.activeCameras.length > 0) {
  18834. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  18835. if (cameraIndex > 0) {
  18836. this._engine.clear(null, false, true, true);
  18837. }
  18838. this._processSubCameras(this.activeCameras[cameraIndex]);
  18839. }
  18840. }
  18841. else {
  18842. if (!this.activeCamera) {
  18843. throw new Error("No camera defined");
  18844. }
  18845. this._processSubCameras(this.activeCamera);
  18846. }
  18847. // Intersection checks
  18848. this._checkIntersections();
  18849. // Update the audio listener attached to the camera
  18850. if (BABYLON.AudioEngine) {
  18851. this._updateAudioParameters();
  18852. }
  18853. // After render
  18854. if (this.afterRender) {
  18855. this.afterRender();
  18856. }
  18857. this.onAfterRenderObservable.notifyObservers(this);
  18858. // Cleaning
  18859. for (var index = 0; index < this._toBeDisposed.length; index++) {
  18860. this._toBeDisposed.data[index].dispose();
  18861. this._toBeDisposed[index] = null;
  18862. }
  18863. this._toBeDisposed.reset();
  18864. if (this.dumpNextRenderTargets) {
  18865. this.dumpNextRenderTargets = false;
  18866. }
  18867. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  18868. this._lastFrameDuration.endMonitoring();
  18869. this._totalMeshesCounter.addCount(this.meshes.length, true);
  18870. this._totalLightsCounter.addCount(this.lights.length, true);
  18871. this._totalMaterialsCounter.addCount(this.materials.length, true);
  18872. this._totalTexturesCounter.addCount(this.textures.length, true);
  18873. this._activeBones.addCount(0, true);
  18874. this._activeIndices.addCount(0, true);
  18875. this._activeParticles.addCount(0, true);
  18876. };
  18877. Scene.prototype._updateAudioParameters = function () {
  18878. if (!this.audioEnabled || (this.mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  18879. return;
  18880. }
  18881. var listeningCamera;
  18882. var audioEngine = BABYLON.Engine.audioEngine;
  18883. if (this.activeCameras.length > 0) {
  18884. listeningCamera = this.activeCameras[0];
  18885. }
  18886. else {
  18887. listeningCamera = this.activeCamera;
  18888. }
  18889. if (listeningCamera && audioEngine.canUseWebAudio) {
  18890. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  18891. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  18892. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  18893. cameraDirection.normalize();
  18894. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  18895. var i;
  18896. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  18897. var sound = this.mainSoundTrack.soundCollection[i];
  18898. if (sound.useCustomAttenuation) {
  18899. sound.updateDistanceFromListener();
  18900. }
  18901. }
  18902. for (i = 0; i < this.soundTracks.length; i++) {
  18903. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  18904. sound = this.soundTracks[i].soundCollection[j];
  18905. if (sound.useCustomAttenuation) {
  18906. sound.updateDistanceFromListener();
  18907. }
  18908. }
  18909. }
  18910. }
  18911. };
  18912. Object.defineProperty(Scene.prototype, "audioEnabled", {
  18913. // Audio
  18914. get: function () {
  18915. return this._audioEnabled;
  18916. },
  18917. set: function (value) {
  18918. this._audioEnabled = value;
  18919. if (BABYLON.AudioEngine) {
  18920. if (this._audioEnabled) {
  18921. this._enableAudio();
  18922. }
  18923. else {
  18924. this._disableAudio();
  18925. }
  18926. }
  18927. },
  18928. enumerable: true,
  18929. configurable: true
  18930. });
  18931. Scene.prototype._disableAudio = function () {
  18932. var i;
  18933. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  18934. this.mainSoundTrack.soundCollection[i].pause();
  18935. }
  18936. for (i = 0; i < this.soundTracks.length; i++) {
  18937. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  18938. this.soundTracks[i].soundCollection[j].pause();
  18939. }
  18940. }
  18941. };
  18942. Scene.prototype._enableAudio = function () {
  18943. var i;
  18944. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  18945. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  18946. this.mainSoundTrack.soundCollection[i].play();
  18947. }
  18948. }
  18949. for (i = 0; i < this.soundTracks.length; i++) {
  18950. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  18951. if (this.soundTracks[i].soundCollection[j].isPaused) {
  18952. this.soundTracks[i].soundCollection[j].play();
  18953. }
  18954. }
  18955. }
  18956. };
  18957. Object.defineProperty(Scene.prototype, "headphone", {
  18958. get: function () {
  18959. return this._headphone;
  18960. },
  18961. set: function (value) {
  18962. this._headphone = value;
  18963. if (BABYLON.AudioEngine) {
  18964. if (this._headphone) {
  18965. this._switchAudioModeForHeadphones();
  18966. }
  18967. else {
  18968. this._switchAudioModeForNormalSpeakers();
  18969. }
  18970. }
  18971. },
  18972. enumerable: true,
  18973. configurable: true
  18974. });
  18975. Scene.prototype._switchAudioModeForHeadphones = function () {
  18976. this.mainSoundTrack.switchPanningModelToHRTF();
  18977. for (var i = 0; i < this.soundTracks.length; i++) {
  18978. this.soundTracks[i].switchPanningModelToHRTF();
  18979. }
  18980. };
  18981. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  18982. this.mainSoundTrack.switchPanningModelToEqualPower();
  18983. for (var i = 0; i < this.soundTracks.length; i++) {
  18984. this.soundTracks[i].switchPanningModelToEqualPower();
  18985. }
  18986. };
  18987. Scene.prototype.enableDepthRenderer = function () {
  18988. if (this._depthRenderer) {
  18989. return this._depthRenderer;
  18990. }
  18991. this._depthRenderer = new BABYLON.DepthRenderer(this);
  18992. return this._depthRenderer;
  18993. };
  18994. Scene.prototype.disableDepthRenderer = function () {
  18995. if (!this._depthRenderer) {
  18996. return;
  18997. }
  18998. this._depthRenderer.dispose();
  18999. this._depthRenderer = null;
  19000. };
  19001. Scene.prototype.freezeMaterials = function () {
  19002. for (var i = 0; i < this.materials.length; i++) {
  19003. this.materials[i].freeze();
  19004. }
  19005. };
  19006. Scene.prototype.unfreezeMaterials = function () {
  19007. for (var i = 0; i < this.materials.length; i++) {
  19008. this.materials[i].unfreeze();
  19009. }
  19010. };
  19011. Scene.prototype.dispose = function () {
  19012. this.beforeRender = null;
  19013. this.afterRender = null;
  19014. this.skeletons = [];
  19015. this._boundingBoxRenderer.dispose();
  19016. if (this._depthRenderer) {
  19017. this._depthRenderer.dispose();
  19018. }
  19019. // Debug layer
  19020. if (this._debugLayer) {
  19021. this._debugLayer.hide();
  19022. }
  19023. // Events
  19024. this.onDisposeObservable.notifyObservers(this);
  19025. this.onDisposeObservable.clear();
  19026. this.onBeforeRenderObservable.clear();
  19027. this.onAfterRenderObservable.clear();
  19028. this.detachControl();
  19029. // Release sounds & sounds tracks
  19030. if (BABYLON.AudioEngine) {
  19031. this.disposeSounds();
  19032. }
  19033. // Detach cameras
  19034. var canvas = this._engine.getRenderingCanvas();
  19035. var index;
  19036. for (index = 0; index < this.cameras.length; index++) {
  19037. this.cameras[index].detachControl(canvas);
  19038. }
  19039. // Release lights
  19040. while (this.lights.length) {
  19041. this.lights[0].dispose();
  19042. }
  19043. // Release meshes
  19044. while (this.meshes.length) {
  19045. this.meshes[0].dispose(true);
  19046. }
  19047. // Release cameras
  19048. while (this.cameras.length) {
  19049. this.cameras[0].dispose();
  19050. }
  19051. // Release materials
  19052. while (this.materials.length) {
  19053. this.materials[0].dispose();
  19054. }
  19055. // Release particles
  19056. while (this.particleSystems.length) {
  19057. this.particleSystems[0].dispose();
  19058. }
  19059. // Release sprites
  19060. while (this.spriteManagers.length) {
  19061. this.spriteManagers[0].dispose();
  19062. }
  19063. // Release layers
  19064. while (this.layers.length) {
  19065. this.layers[0].dispose();
  19066. }
  19067. while (this.highlightLayers.length) {
  19068. this.highlightLayers[0].dispose();
  19069. }
  19070. // Release textures
  19071. while (this.textures.length) {
  19072. this.textures[0].dispose();
  19073. }
  19074. // Post-processes
  19075. this.postProcessManager.dispose();
  19076. // Physics
  19077. if (this._physicsEngine) {
  19078. this.disablePhysicsEngine();
  19079. }
  19080. // Remove from engine
  19081. index = this._engine.scenes.indexOf(this);
  19082. if (index > -1) {
  19083. this._engine.scenes.splice(index, 1);
  19084. }
  19085. this._engine.wipeCaches();
  19086. };
  19087. // Release sounds & sounds tracks
  19088. Scene.prototype.disposeSounds = function () {
  19089. this.mainSoundTrack.dispose();
  19090. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  19091. this.soundTracks[scIndex].dispose();
  19092. }
  19093. };
  19094. // Octrees
  19095. Scene.prototype.getWorldExtends = function () {
  19096. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  19097. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  19098. for (var index = 0; index < this.meshes.length; index++) {
  19099. var mesh = this.meshes[index];
  19100. mesh.computeWorldMatrix(true);
  19101. var minBox = mesh.getBoundingInfo().boundingBox.minimumWorld;
  19102. var maxBox = mesh.getBoundingInfo().boundingBox.maximumWorld;
  19103. BABYLON.Tools.CheckExtends(minBox, min, max);
  19104. BABYLON.Tools.CheckExtends(maxBox, min, max);
  19105. }
  19106. return {
  19107. min: min,
  19108. max: max
  19109. };
  19110. };
  19111. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  19112. if (maxCapacity === void 0) { maxCapacity = 64; }
  19113. if (maxDepth === void 0) { maxDepth = 2; }
  19114. if (!this._selectionOctree) {
  19115. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  19116. }
  19117. var worldExtends = this.getWorldExtends();
  19118. // Update octree
  19119. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  19120. return this._selectionOctree;
  19121. };
  19122. // Picking
  19123. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  19124. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  19125. var engine = this._engine;
  19126. if (!camera) {
  19127. if (!this.activeCamera)
  19128. throw new Error("Active camera not set");
  19129. camera = this.activeCamera;
  19130. }
  19131. var cameraViewport = camera.viewport;
  19132. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  19133. // Moving coordinates to local viewport world
  19134. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  19135. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  19136. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  19137. // return BABYLON.Ray.CreateNew(x / window.devicePixelRatio, y / window.devicePixelRatio, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  19138. };
  19139. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  19140. var engine = this._engine;
  19141. if (!camera) {
  19142. if (!this.activeCamera)
  19143. throw new Error("Active camera not set");
  19144. camera = this.activeCamera;
  19145. }
  19146. var cameraViewport = camera.viewport;
  19147. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  19148. var identity = BABYLON.Matrix.Identity();
  19149. // Moving coordinates to local viewport world
  19150. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  19151. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  19152. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  19153. };
  19154. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  19155. var pickingInfo = null;
  19156. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  19157. var mesh = this.meshes[meshIndex];
  19158. if (predicate) {
  19159. if (!predicate(mesh)) {
  19160. continue;
  19161. }
  19162. }
  19163. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  19164. continue;
  19165. }
  19166. var world = mesh.getWorldMatrix();
  19167. var ray = rayFunction(world);
  19168. var result = mesh.intersects(ray, fastCheck);
  19169. if (!result || !result.hit)
  19170. continue;
  19171. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  19172. continue;
  19173. pickingInfo = result;
  19174. if (fastCheck) {
  19175. break;
  19176. }
  19177. }
  19178. return pickingInfo || new BABYLON.PickingInfo();
  19179. };
  19180. Scene.prototype._internalMultiPick = function (rayFunction, predicate) {
  19181. var pickingInfos = new Array();
  19182. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  19183. var mesh = this.meshes[meshIndex];
  19184. if (predicate) {
  19185. if (!predicate(mesh)) {
  19186. continue;
  19187. }
  19188. }
  19189. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  19190. continue;
  19191. }
  19192. var world = mesh.getWorldMatrix();
  19193. var ray = rayFunction(world);
  19194. var result = mesh.intersects(ray, false);
  19195. if (!result || !result.hit)
  19196. continue;
  19197. pickingInfos.push(result);
  19198. }
  19199. return pickingInfos;
  19200. };
  19201. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  19202. var pickingInfo = null;
  19203. camera = camera || this.activeCamera;
  19204. if (this.spriteManagers.length > 0) {
  19205. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  19206. var spriteManager = this.spriteManagers[spriteIndex];
  19207. if (!spriteManager.isPickable) {
  19208. continue;
  19209. }
  19210. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  19211. if (!result || !result.hit)
  19212. continue;
  19213. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  19214. continue;
  19215. pickingInfo = result;
  19216. if (fastCheck) {
  19217. break;
  19218. }
  19219. }
  19220. }
  19221. return pickingInfo || new BABYLON.PickingInfo();
  19222. };
  19223. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  19224. /// <param name="x">X position on screen</param>
  19225. /// <param name="y">Y position on screen</param>
  19226. /// <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>
  19227. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  19228. /// <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>
  19229. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  19230. var _this = this;
  19231. return this._internalPick(function (world) { return _this.createPickingRay(x, y, world, camera); }, predicate, fastCheck);
  19232. };
  19233. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  19234. /// <param name="x">X position on screen</param>
  19235. /// <param name="y">Y position on screen</param>
  19236. /// <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>
  19237. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  19238. /// <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>
  19239. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  19240. return this._internalPickSprites(this.createPickingRayInCameraSpace(x, y, camera), predicate, fastCheck, camera);
  19241. };
  19242. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  19243. var _this = this;
  19244. return this._internalPick(function (world) {
  19245. if (!_this._pickWithRayInverseMatrix) {
  19246. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  19247. }
  19248. world.invertToRef(_this._pickWithRayInverseMatrix);
  19249. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  19250. }, predicate, fastCheck);
  19251. };
  19252. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  19253. /// <param name="x">X position on screen</param>
  19254. /// <param name="y">Y position on screen</param>
  19255. /// <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>
  19256. /// <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>
  19257. Scene.prototype.multiPick = function (x, y, predicate, camera) {
  19258. var _this = this;
  19259. return this._internalMultiPick(function (world) { return _this.createPickingRay(x, y, world, camera); }, predicate);
  19260. };
  19261. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  19262. /// <param name="ray">Ray to use</param>
  19263. /// <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>
  19264. Scene.prototype.multiPickWithRay = function (ray, predicate) {
  19265. var _this = this;
  19266. return this._internalMultiPick(function (world) {
  19267. if (!_this._pickWithRayInverseMatrix) {
  19268. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  19269. }
  19270. world.invertToRef(_this._pickWithRayInverseMatrix);
  19271. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  19272. }, predicate);
  19273. };
  19274. Scene.prototype.setPointerOverMesh = function (mesh) {
  19275. if (this._pointerOverMesh === mesh) {
  19276. return;
  19277. }
  19278. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  19279. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  19280. }
  19281. this._pointerOverMesh = mesh;
  19282. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  19283. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  19284. }
  19285. };
  19286. Scene.prototype.getPointerOverMesh = function () {
  19287. return this._pointerOverMesh;
  19288. };
  19289. Scene.prototype.setPointerOverSprite = function (sprite) {
  19290. if (this._pointerOverSprite === sprite) {
  19291. return;
  19292. }
  19293. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  19294. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  19295. }
  19296. this._pointerOverSprite = sprite;
  19297. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  19298. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  19299. }
  19300. };
  19301. Scene.prototype.getPointerOverSprite = function () {
  19302. return this._pointerOverSprite;
  19303. };
  19304. // Physics
  19305. Scene.prototype.getPhysicsEngine = function () {
  19306. return this._physicsEngine;
  19307. };
  19308. /**
  19309. * Enables physics to the current scene
  19310. * @param {BABYLON.Vector3} [gravity] - the scene's gravity for the physics engine
  19311. * @param {BABYLON.IPhysicsEnginePlugin} [plugin] - The physics engine to be used. defaults to OimoJS.
  19312. * @return {boolean} was the physics engine initialized
  19313. */
  19314. Scene.prototype.enablePhysics = function (gravity, plugin) {
  19315. if (this._physicsEngine) {
  19316. return true;
  19317. }
  19318. try {
  19319. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  19320. return true;
  19321. }
  19322. catch (e) {
  19323. BABYLON.Tools.Error(e.message);
  19324. return false;
  19325. }
  19326. };
  19327. Scene.prototype.disablePhysicsEngine = function () {
  19328. if (!this._physicsEngine) {
  19329. return;
  19330. }
  19331. this._physicsEngine.dispose();
  19332. this._physicsEngine = undefined;
  19333. };
  19334. Scene.prototype.isPhysicsEnabled = function () {
  19335. return this._physicsEngine !== undefined;
  19336. };
  19337. /**
  19338. *
  19339. * Sets the gravity of the physics engine (and NOT of the scene)
  19340. * @param {BABYLON.Vector3} [gravity] - the new gravity to be used
  19341. */
  19342. Scene.prototype.setGravity = function (gravity) {
  19343. BABYLON.Tools.Warn("Deprecated, please use 'scene.getPhysicsEngine().setGravity()'");
  19344. if (!this._physicsEngine) {
  19345. return;
  19346. }
  19347. this._physicsEngine.setGravity(gravity);
  19348. };
  19349. /**
  19350. * Legacy support, using the new API
  19351. * @Deprecated
  19352. */
  19353. Scene.prototype.createCompoundImpostor = function (parts, options) {
  19354. BABYLON.Tools.Warn("Scene.createCompoundImpostor is deprecated. Please use PhysicsImpostor parent/child");
  19355. if (parts.parts) {
  19356. options = parts;
  19357. parts = parts.parts;
  19358. }
  19359. var mainMesh = parts[0].mesh;
  19360. mainMesh.physicsImpostor = new BABYLON.PhysicsImpostor(mainMesh, parts[0].impostor, options, this);
  19361. for (var index = 1; index < parts.length; index++) {
  19362. var mesh = parts[index].mesh;
  19363. if (mesh.parent !== mainMesh) {
  19364. mesh.position = mesh.position.subtract(mainMesh.position);
  19365. mesh.parent = mainMesh;
  19366. }
  19367. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parts[index].impostor, options, this);
  19368. }
  19369. mainMesh.physicsImpostor.forceUpdate();
  19370. };
  19371. Scene.prototype.deleteCompoundImpostor = function (compound) {
  19372. var mesh = compound.parts[0].mesh;
  19373. mesh.physicsImpostor.dispose();
  19374. mesh.physicsImpostor = null;
  19375. };
  19376. // Misc.
  19377. Scene.prototype.createDefaultCameraOrLight = function (createArcRotateCamera) {
  19378. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  19379. // Light
  19380. if (this.lights.length === 0) {
  19381. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  19382. }
  19383. // Camera
  19384. if (!this.activeCamera) {
  19385. // Compute position
  19386. var worldExtends = this.getWorldExtends();
  19387. var worldCenter = worldExtends.min.add(worldExtends.max.subtract(worldExtends.min).scale(0.5));
  19388. var camera;
  19389. if (createArcRotateCamera) {
  19390. camera = new BABYLON.ArcRotateCamera("default camera", 0, 0, 10, BABYLON.Vector3.Zero(), this);
  19391. camera.setPosition(new BABYLON.Vector3(worldCenter.x, worldCenter.y, worldExtends.min.z - (worldExtends.max.z - worldExtends.min.z)));
  19392. camera.setTarget(worldCenter);
  19393. }
  19394. else {
  19395. camera = new BABYLON.FreeCamera("default camera", BABYLON.Vector3.Zero(), this);
  19396. camera.position = new BABYLON.Vector3(worldCenter.x, worldCenter.y, worldExtends.min.z - (worldExtends.max.z - worldExtends.min.z));
  19397. camera.setTarget(worldCenter);
  19398. }
  19399. this.activeCamera = camera;
  19400. }
  19401. };
  19402. // Tags
  19403. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  19404. if (tagsQuery === undefined) {
  19405. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  19406. return list;
  19407. }
  19408. var listByTags = [];
  19409. forEach = forEach || (function (item) { return; });
  19410. for (var i in list) {
  19411. var item = list[i];
  19412. if (BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  19413. listByTags.push(item);
  19414. forEach(item);
  19415. }
  19416. }
  19417. return listByTags;
  19418. };
  19419. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  19420. return this._getByTags(this.meshes, tagsQuery, forEach);
  19421. };
  19422. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  19423. return this._getByTags(this.cameras, tagsQuery, forEach);
  19424. };
  19425. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  19426. return this._getByTags(this.lights, tagsQuery, forEach);
  19427. };
  19428. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  19429. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  19430. };
  19431. /**
  19432. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  19433. * This allowed control for front to back rendering or reversly depending of the special needs.
  19434. *
  19435. * @param renderingGroupId The rendering group id corresponding to its index
  19436. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  19437. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  19438. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  19439. */
  19440. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  19441. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  19442. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  19443. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  19444. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  19445. };
  19446. /**
  19447. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  19448. *
  19449. * @param renderingGroupId The rendering group id corresponding to its index
  19450. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  19451. * @param depth Automatically clears depth between groups if true and autoClear is true.
  19452. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  19453. */
  19454. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  19455. if (depth === void 0) { depth = true; }
  19456. if (stencil === void 0) { stencil = true; }
  19457. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
  19458. };
  19459. return Scene;
  19460. }());
  19461. // Statics
  19462. Scene._FOGMODE_NONE = 0;
  19463. Scene._FOGMODE_EXP = 1;
  19464. Scene._FOGMODE_EXP2 = 2;
  19465. Scene._FOGMODE_LINEAR = 3;
  19466. Scene.MinDeltaTime = 1.0;
  19467. Scene.MaxDeltaTime = 1000.0;
  19468. BABYLON.Scene = Scene;
  19469. })(BABYLON || (BABYLON = {}));
  19470. //# sourceMappingURL=babylon.scene.js.map
  19471. var BABYLON;
  19472. (function (BABYLON) {
  19473. var Buffer = (function () {
  19474. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced) {
  19475. if (engine instanceof BABYLON.Mesh) {
  19476. this._engine = engine.getScene().getEngine();
  19477. }
  19478. else {
  19479. this._engine = engine;
  19480. }
  19481. this._updatable = updatable;
  19482. this._data = data;
  19483. this._strideSize = stride;
  19484. if (!postponeInternalCreation) {
  19485. this.create();
  19486. }
  19487. this._instanced = instanced;
  19488. }
  19489. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride) {
  19490. // a lot of these parameters are ignored as they are overriden by the buffer
  19491. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, stride ? stride : this._strideSize, this._instanced, offset, size);
  19492. };
  19493. // Properties
  19494. Buffer.prototype.isUpdatable = function () {
  19495. return this._updatable;
  19496. };
  19497. Buffer.prototype.getData = function () {
  19498. return this._data;
  19499. };
  19500. Buffer.prototype.getBuffer = function () {
  19501. return this._buffer;
  19502. };
  19503. Buffer.prototype.getStrideSize = function () {
  19504. return this._strideSize;
  19505. };
  19506. Buffer.prototype.getIsInstanced = function () {
  19507. return this._instanced;
  19508. };
  19509. // Methods
  19510. Buffer.prototype.create = function (data) {
  19511. if (!data && this._buffer) {
  19512. return; // nothing to do
  19513. }
  19514. data = data || this._data;
  19515. if (!this._buffer) {
  19516. if (this._updatable) {
  19517. this._buffer = this._engine.createDynamicVertexBuffer(data);
  19518. this._data = data;
  19519. }
  19520. else {
  19521. this._buffer = this._engine.createVertexBuffer(data);
  19522. }
  19523. }
  19524. else if (this._updatable) {
  19525. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  19526. this._data = data;
  19527. }
  19528. };
  19529. Buffer.prototype.update = function (data) {
  19530. this.create(data);
  19531. };
  19532. Buffer.prototype.updateDirectly = function (data, offset, vertexCount) {
  19533. if (!this._buffer) {
  19534. return;
  19535. }
  19536. if (this._updatable) {
  19537. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset, (vertexCount ? vertexCount * this.getStrideSize() : undefined));
  19538. this._data = null;
  19539. }
  19540. };
  19541. Buffer.prototype.dispose = function () {
  19542. if (!this._buffer) {
  19543. return;
  19544. }
  19545. if (this._engine._releaseBuffer(this._buffer)) {
  19546. this._buffer = null;
  19547. }
  19548. };
  19549. return Buffer;
  19550. }());
  19551. BABYLON.Buffer = Buffer;
  19552. })(BABYLON || (BABYLON = {}));
  19553. //# sourceMappingURL=babylon.buffer.js.map
  19554. var BABYLON;
  19555. (function (BABYLON) {
  19556. var VertexBuffer = (function () {
  19557. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size) {
  19558. if (!stride) {
  19559. // Deduce stride from kind
  19560. switch (kind) {
  19561. case VertexBuffer.PositionKind:
  19562. stride = 3;
  19563. break;
  19564. case VertexBuffer.NormalKind:
  19565. stride = 3;
  19566. break;
  19567. case VertexBuffer.UVKind:
  19568. case VertexBuffer.UV2Kind:
  19569. case VertexBuffer.UV3Kind:
  19570. case VertexBuffer.UV4Kind:
  19571. case VertexBuffer.UV5Kind:
  19572. case VertexBuffer.UV6Kind:
  19573. stride = 2;
  19574. break;
  19575. case VertexBuffer.ColorKind:
  19576. stride = 4;
  19577. break;
  19578. case VertexBuffer.MatricesIndicesKind:
  19579. case VertexBuffer.MatricesIndicesExtraKind:
  19580. stride = 4;
  19581. break;
  19582. case VertexBuffer.MatricesWeightsKind:
  19583. case VertexBuffer.MatricesWeightsExtraKind:
  19584. stride = 4;
  19585. break;
  19586. }
  19587. }
  19588. if (data instanceof BABYLON.Buffer) {
  19589. if (!stride) {
  19590. stride = data.getStrideSize();
  19591. }
  19592. this._buffer = data;
  19593. this._ownsBuffer = false;
  19594. }
  19595. else {
  19596. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced);
  19597. this._ownsBuffer = true;
  19598. }
  19599. this._stride = stride;
  19600. this._offset = offset ? offset : 0;
  19601. this._size = size ? size : stride;
  19602. this._kind = kind;
  19603. }
  19604. VertexBuffer.prototype.getKind = function () {
  19605. return this._kind;
  19606. };
  19607. // Properties
  19608. VertexBuffer.prototype.isUpdatable = function () {
  19609. return this._buffer.isUpdatable();
  19610. };
  19611. VertexBuffer.prototype.getData = function () {
  19612. return this._buffer.getData();
  19613. };
  19614. VertexBuffer.prototype.getBuffer = function () {
  19615. return this._buffer.getBuffer();
  19616. };
  19617. VertexBuffer.prototype.getStrideSize = function () {
  19618. return this._stride;
  19619. };
  19620. VertexBuffer.prototype.getOffset = function () {
  19621. return this._offset;
  19622. };
  19623. VertexBuffer.prototype.getSize = function () {
  19624. return this._size;
  19625. };
  19626. VertexBuffer.prototype.getIsInstanced = function () {
  19627. return this._buffer.getIsInstanced();
  19628. };
  19629. // Methods
  19630. VertexBuffer.prototype.create = function (data) {
  19631. return this._buffer.create(data);
  19632. };
  19633. VertexBuffer.prototype.update = function (data) {
  19634. return this._buffer.update(data);
  19635. };
  19636. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  19637. return this._buffer.updateDirectly(data, offset);
  19638. };
  19639. VertexBuffer.prototype.dispose = function () {
  19640. if (this._ownsBuffer) {
  19641. this._buffer.dispose();
  19642. }
  19643. };
  19644. Object.defineProperty(VertexBuffer, "PositionKind", {
  19645. get: function () {
  19646. return VertexBuffer._PositionKind;
  19647. },
  19648. enumerable: true,
  19649. configurable: true
  19650. });
  19651. Object.defineProperty(VertexBuffer, "NormalKind", {
  19652. get: function () {
  19653. return VertexBuffer._NormalKind;
  19654. },
  19655. enumerable: true,
  19656. configurable: true
  19657. });
  19658. Object.defineProperty(VertexBuffer, "UVKind", {
  19659. get: function () {
  19660. return VertexBuffer._UVKind;
  19661. },
  19662. enumerable: true,
  19663. configurable: true
  19664. });
  19665. Object.defineProperty(VertexBuffer, "UV2Kind", {
  19666. get: function () {
  19667. return VertexBuffer._UV2Kind;
  19668. },
  19669. enumerable: true,
  19670. configurable: true
  19671. });
  19672. Object.defineProperty(VertexBuffer, "UV3Kind", {
  19673. get: function () {
  19674. return VertexBuffer._UV3Kind;
  19675. },
  19676. enumerable: true,
  19677. configurable: true
  19678. });
  19679. Object.defineProperty(VertexBuffer, "UV4Kind", {
  19680. get: function () {
  19681. return VertexBuffer._UV4Kind;
  19682. },
  19683. enumerable: true,
  19684. configurable: true
  19685. });
  19686. Object.defineProperty(VertexBuffer, "UV5Kind", {
  19687. get: function () {
  19688. return VertexBuffer._UV5Kind;
  19689. },
  19690. enumerable: true,
  19691. configurable: true
  19692. });
  19693. Object.defineProperty(VertexBuffer, "UV6Kind", {
  19694. get: function () {
  19695. return VertexBuffer._UV6Kind;
  19696. },
  19697. enumerable: true,
  19698. configurable: true
  19699. });
  19700. Object.defineProperty(VertexBuffer, "ColorKind", {
  19701. get: function () {
  19702. return VertexBuffer._ColorKind;
  19703. },
  19704. enumerable: true,
  19705. configurable: true
  19706. });
  19707. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  19708. get: function () {
  19709. return VertexBuffer._MatricesIndicesKind;
  19710. },
  19711. enumerable: true,
  19712. configurable: true
  19713. });
  19714. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  19715. get: function () {
  19716. return VertexBuffer._MatricesWeightsKind;
  19717. },
  19718. enumerable: true,
  19719. configurable: true
  19720. });
  19721. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  19722. get: function () {
  19723. return VertexBuffer._MatricesIndicesExtraKind;
  19724. },
  19725. enumerable: true,
  19726. configurable: true
  19727. });
  19728. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  19729. get: function () {
  19730. return VertexBuffer._MatricesWeightsExtraKind;
  19731. },
  19732. enumerable: true,
  19733. configurable: true
  19734. });
  19735. return VertexBuffer;
  19736. }());
  19737. // Enums
  19738. VertexBuffer._PositionKind = "position";
  19739. VertexBuffer._NormalKind = "normal";
  19740. VertexBuffer._UVKind = "uv";
  19741. VertexBuffer._UV2Kind = "uv2";
  19742. VertexBuffer._UV3Kind = "uv3";
  19743. VertexBuffer._UV4Kind = "uv4";
  19744. VertexBuffer._UV5Kind = "uv5";
  19745. VertexBuffer._UV6Kind = "uv6";
  19746. VertexBuffer._ColorKind = "color";
  19747. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  19748. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  19749. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  19750. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  19751. BABYLON.VertexBuffer = VertexBuffer;
  19752. })(BABYLON || (BABYLON = {}));
  19753. //# sourceMappingURL=babylon.vertexBuffer.js.map
  19754. var BABYLON;
  19755. (function (BABYLON) {
  19756. /**
  19757. * Creates an instance based on a source mesh.
  19758. */
  19759. var InstancedMesh = (function (_super) {
  19760. __extends(InstancedMesh, _super);
  19761. function InstancedMesh(name, source) {
  19762. var _this = _super.call(this, name, source.getScene()) || this;
  19763. source.instances.push(_this);
  19764. _this._sourceMesh = source;
  19765. _this.position.copyFrom(source.position);
  19766. _this.rotation.copyFrom(source.rotation);
  19767. _this.scaling.copyFrom(source.scaling);
  19768. if (source.rotationQuaternion) {
  19769. _this.rotationQuaternion = source.rotationQuaternion.clone();
  19770. }
  19771. _this.infiniteDistance = source.infiniteDistance;
  19772. _this.setPivotMatrix(source.getPivotMatrix());
  19773. _this.refreshBoundingInfo();
  19774. _this._syncSubMeshes();
  19775. return _this;
  19776. }
  19777. InstancedMesh.prototype.getClassName = function () {
  19778. return "InstancedMesh";
  19779. };
  19780. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  19781. // Methods
  19782. get: function () {
  19783. return this._sourceMesh.receiveShadows;
  19784. },
  19785. enumerable: true,
  19786. configurable: true
  19787. });
  19788. Object.defineProperty(InstancedMesh.prototype, "material", {
  19789. get: function () {
  19790. return this._sourceMesh.material;
  19791. },
  19792. enumerable: true,
  19793. configurable: true
  19794. });
  19795. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  19796. get: function () {
  19797. return this._sourceMesh.visibility;
  19798. },
  19799. enumerable: true,
  19800. configurable: true
  19801. });
  19802. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  19803. get: function () {
  19804. return this._sourceMesh.skeleton;
  19805. },
  19806. enumerable: true,
  19807. configurable: true
  19808. });
  19809. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  19810. get: function () {
  19811. return this._sourceMesh.renderingGroupId;
  19812. },
  19813. enumerable: true,
  19814. configurable: true
  19815. });
  19816. InstancedMesh.prototype.getTotalVertices = function () {
  19817. return this._sourceMesh.getTotalVertices();
  19818. };
  19819. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  19820. get: function () {
  19821. return this._sourceMesh;
  19822. },
  19823. enumerable: true,
  19824. configurable: true
  19825. });
  19826. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  19827. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  19828. };
  19829. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  19830. return this._sourceMesh.isVerticesDataPresent(kind);
  19831. };
  19832. InstancedMesh.prototype.getIndices = function () {
  19833. return this._sourceMesh.getIndices();
  19834. };
  19835. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  19836. get: function () {
  19837. return this._sourceMesh._positions;
  19838. },
  19839. enumerable: true,
  19840. configurable: true
  19841. });
  19842. InstancedMesh.prototype.refreshBoundingInfo = function () {
  19843. var meshBB = this._sourceMesh.getBoundingInfo();
  19844. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  19845. this._updateBoundingInfo();
  19846. };
  19847. InstancedMesh.prototype._preActivate = function () {
  19848. if (this._currentLOD) {
  19849. this._currentLOD._preActivate();
  19850. }
  19851. };
  19852. InstancedMesh.prototype._activate = function (renderId) {
  19853. if (this._currentLOD) {
  19854. this._currentLOD._registerInstanceForRenderId(this, renderId);
  19855. }
  19856. };
  19857. InstancedMesh.prototype.getLOD = function (camera) {
  19858. this._currentLOD = this.sourceMesh.getLOD(this.getScene().activeCamera, this.getBoundingInfo().boundingSphere);
  19859. if (this._currentLOD === this.sourceMesh) {
  19860. return this;
  19861. }
  19862. return this._currentLOD;
  19863. };
  19864. InstancedMesh.prototype._syncSubMeshes = function () {
  19865. this.releaseSubMeshes();
  19866. if (this._sourceMesh.subMeshes) {
  19867. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  19868. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  19869. }
  19870. }
  19871. };
  19872. InstancedMesh.prototype._generatePointsArray = function () {
  19873. return this._sourceMesh._generatePointsArray();
  19874. };
  19875. // Clone
  19876. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  19877. var result = this._sourceMesh.createInstance(name);
  19878. // Deep copy
  19879. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes"], []);
  19880. // Bounding info
  19881. this.refreshBoundingInfo();
  19882. // Parent
  19883. if (newParent) {
  19884. result.parent = newParent;
  19885. }
  19886. if (!doNotCloneChildren) {
  19887. // Children
  19888. for (var index = 0; index < this.getScene().meshes.length; index++) {
  19889. var mesh = this.getScene().meshes[index];
  19890. if (mesh.parent === this) {
  19891. mesh.clone(mesh.name, result);
  19892. }
  19893. }
  19894. }
  19895. result.computeWorldMatrix(true);
  19896. return result;
  19897. };
  19898. // Dispose
  19899. InstancedMesh.prototype.dispose = function (doNotRecurse) {
  19900. // Remove from mesh
  19901. var index = this._sourceMesh.instances.indexOf(this);
  19902. this._sourceMesh.instances.splice(index, 1);
  19903. _super.prototype.dispose.call(this, doNotRecurse);
  19904. };
  19905. return InstancedMesh;
  19906. }(BABYLON.AbstractMesh));
  19907. BABYLON.InstancedMesh = InstancedMesh;
  19908. })(BABYLON || (BABYLON = {}));
  19909. //# sourceMappingURL=babylon.instancedMesh.js.map
  19910. var BABYLON;
  19911. (function (BABYLON) {
  19912. var _InstancesBatch = (function () {
  19913. function _InstancesBatch() {
  19914. this.mustReturn = false;
  19915. this.visibleInstances = new Array();
  19916. this.renderSelf = new Array();
  19917. }
  19918. return _InstancesBatch;
  19919. }());
  19920. BABYLON._InstancesBatch = _InstancesBatch;
  19921. var Mesh = (function (_super) {
  19922. __extends(Mesh, _super);
  19923. /**
  19924. * @constructor
  19925. * @param {string} name The value used by scene.getMeshByName() to do a lookup.
  19926. * @param {Scene} scene The scene to add this mesh to.
  19927. * @param {Node} parent The parent of this mesh, if it has one
  19928. * @param {Mesh} source An optional Mesh from which geometry is shared, cloned.
  19929. * @param {boolean} doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  19930. * When false, achieved by calling a clone(), also passing False.
  19931. * This will make creation of children, recursive.
  19932. * @param {boolean} clonePhysicsImpostor When cloning, include cloning mesh physics impostor, default True.
  19933. */
  19934. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  19935. if (parent === void 0) { parent = null; }
  19936. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  19937. var _this = _super.call(this, name, scene) || this;
  19938. // Events
  19939. /**
  19940. * An event triggered before rendering the mesh
  19941. * @type {BABYLON.Observable}
  19942. */
  19943. _this.onBeforeRenderObservable = new BABYLON.Observable();
  19944. /**
  19945. * An event triggered after rendering the mesh
  19946. * @type {BABYLON.Observable}
  19947. */
  19948. _this.onAfterRenderObservable = new BABYLON.Observable();
  19949. /**
  19950. * An event triggered before drawing the mesh
  19951. * @type {BABYLON.Observable}
  19952. */
  19953. _this.onBeforeDrawObservable = new BABYLON.Observable();
  19954. // Members
  19955. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  19956. _this.instances = new Array();
  19957. _this._LODLevels = new Array();
  19958. _this._visibleInstances = {};
  19959. _this._renderIdForInstances = new Array();
  19960. _this._batchCache = new _InstancesBatch();
  19961. _this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  19962. _this._sideOrientation = Mesh._DEFAULTSIDE;
  19963. _this._areNormalsFrozen = false; // Will be used by ribbons mainly
  19964. _this._facetNb = 0; // facet number
  19965. _this._partitioningSubdivisions = 10; // number of subdivisions per axis in the partioning space
  19966. _this._partitioningBBoxRatio = 1.01; // the partioning array space is by default 1% bigger than the bounding box
  19967. _this._facetDataEnabled = false; // is the facet data feature enabled on this mesh ?
  19968. _this._facetParameters = {}; // keep a reference to the object parameters to avoid memory re-allocation
  19969. _this._bbSize = BABYLON.Vector3.Zero(); // bbox size approximated for facet data
  19970. _this._subDiv = {
  19971. max: 1,
  19972. X: 1,
  19973. Y: 1,
  19974. Z: 1
  19975. };
  19976. // Will be used to save a source mesh reference, If any
  19977. _this._source = null;
  19978. if (source) {
  19979. // Source mesh
  19980. _this._source = source;
  19981. // Geometry
  19982. if (source._geometry) {
  19983. source._geometry.applyToMesh(_this);
  19984. }
  19985. // Deep copy
  19986. BABYLON.Tools.DeepCopy(source, _this, ["name", "material", "skeleton", "instances", "parent"], ["_poseMatrix"]);
  19987. // Parent
  19988. _this.parent = source.parent;
  19989. // Pivot
  19990. _this.setPivotMatrix(source.getPivotMatrix());
  19991. _this.id = name + "." + source.id;
  19992. // Material
  19993. _this.material = source.material;
  19994. var index;
  19995. if (!doNotCloneChildren) {
  19996. // Children
  19997. for (index = 0; index < scene.meshes.length; index++) {
  19998. var mesh = scene.meshes[index];
  19999. if (mesh.parent === source) {
  20000. // doNotCloneChildren is always going to be False
  20001. var newChild = mesh.clone(name + "." + mesh.name, _this, doNotCloneChildren);
  20002. }
  20003. }
  20004. }
  20005. // Physics clone
  20006. var physicsEngine = _this.getScene().getPhysicsEngine();
  20007. if (clonePhysicsImpostor && physicsEngine) {
  20008. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  20009. if (impostor) {
  20010. _this.physicsImpostor = impostor.clone(_this);
  20011. }
  20012. }
  20013. // Particles
  20014. for (index = 0; index < scene.particleSystems.length; index++) {
  20015. var system = scene.particleSystems[index];
  20016. if (system.emitter === source) {
  20017. system.clone(system.name, _this);
  20018. }
  20019. }
  20020. _this.computeWorldMatrix(true);
  20021. }
  20022. // Parent
  20023. if (parent !== null) {
  20024. _this.parent = parent;
  20025. }
  20026. return _this;
  20027. }
  20028. Object.defineProperty(Mesh, "FRONTSIDE", {
  20029. /**
  20030. * Mesh side orientation : usually the external or front surface
  20031. */
  20032. get: function () {
  20033. return Mesh._FRONTSIDE;
  20034. },
  20035. enumerable: true,
  20036. configurable: true
  20037. });
  20038. Object.defineProperty(Mesh, "BACKSIDE", {
  20039. /**
  20040. * Mesh side orientation : usually the internal or back surface
  20041. */
  20042. get: function () {
  20043. return Mesh._BACKSIDE;
  20044. },
  20045. enumerable: true,
  20046. configurable: true
  20047. });
  20048. Object.defineProperty(Mesh, "DOUBLESIDE", {
  20049. /**
  20050. * Mesh side orientation : both internal and external or front and back surfaces
  20051. */
  20052. get: function () {
  20053. return Mesh._DOUBLESIDE;
  20054. },
  20055. enumerable: true,
  20056. configurable: true
  20057. });
  20058. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  20059. /**
  20060. * Mesh side orientation : by default, `FRONTSIDE`
  20061. */
  20062. get: function () {
  20063. return Mesh._DEFAULTSIDE;
  20064. },
  20065. enumerable: true,
  20066. configurable: true
  20067. });
  20068. Object.defineProperty(Mesh, "NO_CAP", {
  20069. /**
  20070. * Mesh cap setting : no cap
  20071. */
  20072. get: function () {
  20073. return Mesh._NO_CAP;
  20074. },
  20075. enumerable: true,
  20076. configurable: true
  20077. });
  20078. Object.defineProperty(Mesh, "CAP_START", {
  20079. /**
  20080. * Mesh cap setting : one cap at the beginning of the mesh
  20081. */
  20082. get: function () {
  20083. return Mesh._CAP_START;
  20084. },
  20085. enumerable: true,
  20086. configurable: true
  20087. });
  20088. Object.defineProperty(Mesh, "CAP_END", {
  20089. /**
  20090. * Mesh cap setting : one cap at the end of the mesh
  20091. */
  20092. get: function () {
  20093. return Mesh._CAP_END;
  20094. },
  20095. enumerable: true,
  20096. configurable: true
  20097. });
  20098. Object.defineProperty(Mesh, "CAP_ALL", {
  20099. /**
  20100. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  20101. */
  20102. get: function () {
  20103. return Mesh._CAP_ALL;
  20104. },
  20105. enumerable: true,
  20106. configurable: true
  20107. });
  20108. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  20109. set: function (callback) {
  20110. if (this._onBeforeDrawObserver) {
  20111. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  20112. }
  20113. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  20114. },
  20115. enumerable: true,
  20116. configurable: true
  20117. });
  20118. Object.defineProperty(Mesh.prototype, "facetNb", {
  20119. /**
  20120. * Read-only : the number of facets in the mesh
  20121. */
  20122. get: function () {
  20123. return this._facetNb;
  20124. },
  20125. enumerable: true,
  20126. configurable: true
  20127. });
  20128. Object.defineProperty(Mesh.prototype, "partitioningSubdivisions", {
  20129. /**
  20130. * The number of subdivisions per axis in the partioning space
  20131. */
  20132. get: function () {
  20133. return this._partitioningSubdivisions;
  20134. },
  20135. set: function (nb) {
  20136. this._partitioningSubdivisions = nb;
  20137. },
  20138. enumerable: true,
  20139. configurable: true
  20140. });
  20141. Object.defineProperty(Mesh.prototype, "partitioningBBoxRatio", {
  20142. /**
  20143. * The ratio to apply to the bouding box size to set to the partioning space.
  20144. * Ex : 1.01 (default) the partioning space is 1% bigger than the bounding box.
  20145. */
  20146. get: function () {
  20147. return this._partitioningBBoxRatio;
  20148. },
  20149. set: function (ratio) {
  20150. this._partitioningBBoxRatio = ratio;
  20151. },
  20152. enumerable: true,
  20153. configurable: true
  20154. });
  20155. Object.defineProperty(Mesh.prototype, "isFacetDataEnabled", {
  20156. /**
  20157. * Read-only : is the feature facetData enabled ?
  20158. */
  20159. get: function () {
  20160. return this._facetDataEnabled;
  20161. },
  20162. enumerable: true,
  20163. configurable: true
  20164. });
  20165. Object.defineProperty(Mesh.prototype, "source", {
  20166. get: function () {
  20167. return this._source;
  20168. },
  20169. enumerable: true,
  20170. configurable: true
  20171. });
  20172. // Methods
  20173. Mesh.prototype.getClassName = function () {
  20174. return "Mesh";
  20175. };
  20176. /**
  20177. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  20178. */
  20179. Mesh.prototype.toString = function (fullDetails) {
  20180. var ret = _super.prototype.toString.call(this, fullDetails);
  20181. ret += ", n vertices: " + this.getTotalVertices();
  20182. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  20183. if (this.animations) {
  20184. for (var i = 0; i < this.animations.length; i++) {
  20185. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  20186. }
  20187. }
  20188. if (fullDetails) {
  20189. ret += ", flat shading: " + (this._geometry ? (this.getVerticesData(BABYLON.VertexBuffer.PositionKind).length / 3 === this.getIndices().length ? "YES" : "NO") : "UNKNOWN");
  20190. }
  20191. return ret;
  20192. };
  20193. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  20194. get: function () {
  20195. return this._LODLevels.length > 0;
  20196. },
  20197. enumerable: true,
  20198. configurable: true
  20199. });
  20200. Mesh.prototype._sortLODLevels = function () {
  20201. this._LODLevels.sort(function (a, b) {
  20202. if (a.distance < b.distance) {
  20203. return 1;
  20204. }
  20205. if (a.distance > b.distance) {
  20206. return -1;
  20207. }
  20208. return 0;
  20209. });
  20210. };
  20211. /**
  20212. * Add a mesh as LOD level triggered at the given distance.
  20213. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  20214. * @param {number} distance The distance from the center of the object to show this level
  20215. * @param {Mesh} mesh The mesh to be added as LOD level
  20216. * @return {Mesh} This mesh (for chaining)
  20217. */
  20218. Mesh.prototype.addLODLevel = function (distance, mesh) {
  20219. if (mesh && mesh._masterMesh) {
  20220. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  20221. return this;
  20222. }
  20223. var level = new BABYLON.Internals.MeshLODLevel(distance, mesh);
  20224. this._LODLevels.push(level);
  20225. if (mesh) {
  20226. mesh._masterMesh = this;
  20227. }
  20228. this._sortLODLevels();
  20229. return this;
  20230. };
  20231. /**
  20232. * Returns the LOD level mesh at the passed distance or null if not found.
  20233. * It is related to the method `addLODLevel(distance, mesh)`.
  20234. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  20235. */
  20236. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  20237. for (var index = 0; index < this._LODLevels.length; index++) {
  20238. var level = this._LODLevels[index];
  20239. if (level.distance === distance) {
  20240. return level.mesh;
  20241. }
  20242. }
  20243. return null;
  20244. };
  20245. /**
  20246. * Remove a mesh from the LOD array
  20247. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  20248. * @param {Mesh} mesh The mesh to be removed.
  20249. * @return {Mesh} This mesh (for chaining)
  20250. */
  20251. Mesh.prototype.removeLODLevel = function (mesh) {
  20252. for (var index = 0; index < this._LODLevels.length; index++) {
  20253. if (this._LODLevels[index].mesh === mesh) {
  20254. this._LODLevels.splice(index, 1);
  20255. if (mesh) {
  20256. mesh._masterMesh = null;
  20257. }
  20258. }
  20259. }
  20260. this._sortLODLevels();
  20261. return this;
  20262. };
  20263. /**
  20264. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  20265. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  20266. */
  20267. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  20268. if (!this._LODLevels || this._LODLevels.length === 0) {
  20269. return this;
  20270. }
  20271. var distanceToCamera = (boundingSphere ? boundingSphere : this.getBoundingInfo().boundingSphere).centerWorld.subtract(camera.globalPosition).length();
  20272. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  20273. if (this.onLODLevelSelection) {
  20274. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  20275. }
  20276. return this;
  20277. }
  20278. for (var index = 0; index < this._LODLevels.length; index++) {
  20279. var level = this._LODLevels[index];
  20280. if (level.distance < distanceToCamera) {
  20281. if (level.mesh) {
  20282. level.mesh._preActivate();
  20283. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  20284. }
  20285. if (this.onLODLevelSelection) {
  20286. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  20287. }
  20288. return level.mesh;
  20289. }
  20290. }
  20291. if (this.onLODLevelSelection) {
  20292. this.onLODLevelSelection(distanceToCamera, this, this);
  20293. }
  20294. return this;
  20295. };
  20296. Object.defineProperty(Mesh.prototype, "geometry", {
  20297. /**
  20298. * Returns the mesh internal Geometry object.
  20299. */
  20300. get: function () {
  20301. return this._geometry;
  20302. },
  20303. enumerable: true,
  20304. configurable: true
  20305. });
  20306. /**
  20307. * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  20308. */
  20309. Mesh.prototype.getTotalVertices = function () {
  20310. if (!this._geometry) {
  20311. return 0;
  20312. }
  20313. return this._geometry.getTotalVertices();
  20314. };
  20315. /**
  20316. * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
  20317. * 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.
  20318. * Returns null if the mesh has no geometry or no vertex buffer.
  20319. * Possible `kind` values :
  20320. * - BABYLON.VertexBuffer.PositionKind
  20321. * - BABYLON.VertexBuffer.UVKind
  20322. * - BABYLON.VertexBuffer.UV2Kind
  20323. * - BABYLON.VertexBuffer.UV3Kind
  20324. * - BABYLON.VertexBuffer.UV4Kind
  20325. * - BABYLON.VertexBuffer.UV5Kind
  20326. * - BABYLON.VertexBuffer.UV6Kind
  20327. * - BABYLON.VertexBuffer.ColorKind
  20328. * - BABYLON.VertexBuffer.MatricesIndicesKind
  20329. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  20330. * - BABYLON.VertexBuffer.MatricesWeightsKind
  20331. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  20332. */
  20333. Mesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  20334. if (!this._geometry) {
  20335. return null;
  20336. }
  20337. return this._geometry.getVerticesData(kind, copyWhenShared);
  20338. };
  20339. /**
  20340. * Returns the mesh VertexBuffer object from the requested `kind` : positions, indices, normals, etc.
  20341. * Returns `undefined` if the mesh has no geometry.
  20342. * Possible `kind` values :
  20343. * - BABYLON.VertexBuffer.PositionKind
  20344. * - BABYLON.VertexBuffer.UVKind
  20345. * - BABYLON.VertexBuffer.UV2Kind
  20346. * - BABYLON.VertexBuffer.UV3Kind
  20347. * - BABYLON.VertexBuffer.UV4Kind
  20348. * - BABYLON.VertexBuffer.UV5Kind
  20349. * - BABYLON.VertexBuffer.UV6Kind
  20350. * - BABYLON.VertexBuffer.ColorKind
  20351. * - BABYLON.VertexBuffer.MatricesIndicesKind
  20352. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  20353. * - BABYLON.VertexBuffer.MatricesWeightsKind
  20354. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  20355. */
  20356. Mesh.prototype.getVertexBuffer = function (kind) {
  20357. if (!this._geometry) {
  20358. return undefined;
  20359. }
  20360. return this._geometry.getVertexBuffer(kind);
  20361. };
  20362. /**
  20363. * Returns a boolean depending on the existence of the Vertex Data for the requested `kind`.
  20364. * Possible `kind` values :
  20365. * - BABYLON.VertexBuffer.PositionKind
  20366. * - BABYLON.VertexBuffer.UVKind
  20367. * - BABYLON.VertexBuffer.UV2Kind
  20368. * - BABYLON.VertexBuffer.UV3Kind
  20369. * - BABYLON.VertexBuffer.UV4Kind
  20370. * - BABYLON.VertexBuffer.UV5Kind
  20371. * - BABYLON.VertexBuffer.UV6Kind
  20372. * - BABYLON.VertexBuffer.ColorKind
  20373. * - BABYLON.VertexBuffer.MatricesIndicesKind
  20374. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  20375. * - BABYLON.VertexBuffer.MatricesWeightsKind
  20376. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  20377. */
  20378. Mesh.prototype.isVerticesDataPresent = function (kind) {
  20379. if (!this._geometry) {
  20380. if (this._delayInfo) {
  20381. return this._delayInfo.indexOf(kind) !== -1;
  20382. }
  20383. return false;
  20384. }
  20385. return this._geometry.isVerticesDataPresent(kind);
  20386. };
  20387. /**
  20388. * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
  20389. * Possible `kind` values :
  20390. * - BABYLON.VertexBuffer.PositionKind
  20391. * - BABYLON.VertexBuffer.UVKind
  20392. * - BABYLON.VertexBuffer.UV2Kind
  20393. * - BABYLON.VertexBuffer.UV3Kind
  20394. * - BABYLON.VertexBuffer.UV4Kind
  20395. * - BABYLON.VertexBuffer.UV5Kind
  20396. * - BABYLON.VertexBuffer.UV6Kind
  20397. * - BABYLON.VertexBuffer.ColorKind
  20398. * - BABYLON.VertexBuffer.MatricesIndicesKind
  20399. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  20400. * - BABYLON.VertexBuffer.MatricesWeightsKind
  20401. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  20402. */
  20403. Mesh.prototype.getVerticesDataKinds = function () {
  20404. if (!this._geometry) {
  20405. var result = [];
  20406. if (this._delayInfo) {
  20407. this._delayInfo.forEach(function (kind, index, array) {
  20408. result.push(kind);
  20409. });
  20410. }
  20411. return result;
  20412. }
  20413. return this._geometry.getVerticesDataKinds();
  20414. };
  20415. /**
  20416. * Returns a positive integer : the total number of indices in this mesh geometry.
  20417. * Returns zero if the mesh has no geometry.
  20418. */
  20419. Mesh.prototype.getTotalIndices = function () {
  20420. if (!this._geometry) {
  20421. return 0;
  20422. }
  20423. return this._geometry.getTotalIndices();
  20424. };
  20425. /**
  20426. * Returns an array of integers or a Int32Array populated with the mesh indices.
  20427. * 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.
  20428. * Returns an empty array if the mesh has no geometry.
  20429. */
  20430. Mesh.prototype.getIndices = function (copyWhenShared) {
  20431. if (!this._geometry) {
  20432. return [];
  20433. }
  20434. return this._geometry.getIndices(copyWhenShared);
  20435. };
  20436. Object.defineProperty(Mesh.prototype, "isBlocked", {
  20437. get: function () {
  20438. return this._masterMesh !== null && this._masterMesh !== undefined;
  20439. },
  20440. enumerable: true,
  20441. configurable: true
  20442. });
  20443. /**
  20444. * Boolean : true once the mesh is ready after all the delayed process (loading, etc) are complete.
  20445. */
  20446. Mesh.prototype.isReady = function () {
  20447. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  20448. return false;
  20449. }
  20450. return _super.prototype.isReady.call(this);
  20451. };
  20452. /**
  20453. * Boolean : true if the mesh has been disposed.
  20454. */
  20455. Mesh.prototype.isDisposed = function () {
  20456. return this._isDisposed;
  20457. };
  20458. Object.defineProperty(Mesh.prototype, "sideOrientation", {
  20459. get: function () {
  20460. return this._sideOrientation;
  20461. },
  20462. /**
  20463. * Sets the mesh side orientation : BABYLON.Mesh.FRONTSIDE, BABYLON.Mesh.BACKSIDE, BABYLON.Mesh.DOUBLESIDE or BABYLON.Mesh.DEFAULTSIDE
  20464. * tuto : http://doc.babylonjs.com/tutorials/Discover_Basic_Elements#side-orientation
  20465. */
  20466. set: function (sideO) {
  20467. this._sideOrientation = sideO;
  20468. },
  20469. enumerable: true,
  20470. configurable: true
  20471. });
  20472. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  20473. /**
  20474. * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
  20475. * This property is pertinent only for updatable parametric shapes.
  20476. */
  20477. get: function () {
  20478. return this._areNormalsFrozen;
  20479. },
  20480. enumerable: true,
  20481. configurable: true
  20482. });
  20483. /**
  20484. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  20485. * It has no effect at all on other shapes.
  20486. * It prevents the mesh normals from being recomputed on next `positions` array update.
  20487. */
  20488. Mesh.prototype.freezeNormals = function () {
  20489. this._areNormalsFrozen = true;
  20490. };
  20491. /**
  20492. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  20493. * It has no effect at all on other shapes.
  20494. * It reactivates the mesh normals computation if it was previously frozen.
  20495. */
  20496. Mesh.prototype.unfreezeNormals = function () {
  20497. this._areNormalsFrozen = false;
  20498. };
  20499. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  20500. /**
  20501. * Overrides instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  20502. */
  20503. set: function (count) {
  20504. this._overridenInstanceCount = count;
  20505. },
  20506. enumerable: true,
  20507. configurable: true
  20508. });
  20509. // Methods
  20510. Mesh.prototype._preActivate = function () {
  20511. var sceneRenderId = this.getScene().getRenderId();
  20512. if (this._preActivateId === sceneRenderId) {
  20513. return;
  20514. }
  20515. this._preActivateId = sceneRenderId;
  20516. this._visibleInstances = null;
  20517. };
  20518. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  20519. if (this._visibleInstances) {
  20520. this._visibleInstances.intermediateDefaultRenderId = renderId;
  20521. }
  20522. };
  20523. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  20524. if (!this._visibleInstances) {
  20525. this._visibleInstances = {};
  20526. this._visibleInstances.defaultRenderId = renderId;
  20527. this._visibleInstances.selfDefaultRenderId = this._renderId;
  20528. }
  20529. if (!this._visibleInstances[renderId]) {
  20530. this._visibleInstances[renderId] = new Array();
  20531. }
  20532. this._visibleInstances[renderId].push(instance);
  20533. };
  20534. /**
  20535. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  20536. * This means the mesh underlying bounding box and sphere are recomputed.
  20537. */
  20538. Mesh.prototype.refreshBoundingInfo = function () {
  20539. if (this._boundingInfo.isLocked) {
  20540. return;
  20541. }
  20542. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  20543. if (data) {
  20544. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  20545. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  20546. }
  20547. if (this.subMeshes) {
  20548. for (var index = 0; index < this.subMeshes.length; index++) {
  20549. this.subMeshes[index].refreshBoundingInfo();
  20550. }
  20551. }
  20552. this._updateBoundingInfo();
  20553. };
  20554. Mesh.prototype._createGlobalSubMesh = function () {
  20555. var totalVertices = this.getTotalVertices();
  20556. if (!totalVertices || !this.getIndices()) {
  20557. return null;
  20558. }
  20559. this.releaseSubMeshes();
  20560. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  20561. };
  20562. Mesh.prototype.subdivide = function (count) {
  20563. if (count < 1) {
  20564. return;
  20565. }
  20566. var totalIndices = this.getTotalIndices();
  20567. var subdivisionSize = (totalIndices / count) | 0;
  20568. var offset = 0;
  20569. // Ensure that subdivisionSize is a multiple of 3
  20570. while (subdivisionSize % 3 !== 0) {
  20571. subdivisionSize++;
  20572. }
  20573. this.releaseSubMeshes();
  20574. for (var index = 0; index < count; index++) {
  20575. if (offset >= totalIndices) {
  20576. break;
  20577. }
  20578. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  20579. offset += subdivisionSize;
  20580. }
  20581. this.synchronizeInstances();
  20582. };
  20583. /**
  20584. * Sets the vertex data of the mesh geometry for the requested `kind`.
  20585. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  20586. * The `data` are either a numeric array either a Float32Array.
  20587. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  20588. * 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).
  20589. * Note that a new underlying VertexBuffer object is created each call.
  20590. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  20591. *
  20592. * Possible `kind` values :
  20593. * - BABYLON.VertexBuffer.PositionKind
  20594. * - BABYLON.VertexBuffer.UVKind
  20595. * - BABYLON.VertexBuffer.UV2Kind
  20596. * - BABYLON.VertexBuffer.UV3Kind
  20597. * - BABYLON.VertexBuffer.UV4Kind
  20598. * - BABYLON.VertexBuffer.UV5Kind
  20599. * - BABYLON.VertexBuffer.UV6Kind
  20600. * - BABYLON.VertexBuffer.ColorKind
  20601. * - BABYLON.VertexBuffer.MatricesIndicesKind
  20602. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  20603. * - BABYLON.VertexBuffer.MatricesWeightsKind
  20604. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  20605. */
  20606. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  20607. if (!this._geometry) {
  20608. var vertexData = new BABYLON.VertexData();
  20609. vertexData.set(data, kind);
  20610. var scene = this.getScene();
  20611. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  20612. }
  20613. else {
  20614. this._geometry.setVerticesData(kind, data, updatable, stride);
  20615. }
  20616. };
  20617. Mesh.prototype.setVerticesBuffer = function (buffer) {
  20618. if (!this._geometry) {
  20619. var scene = this.getScene();
  20620. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene).applyToMesh(this);
  20621. }
  20622. this._geometry.setVerticesBuffer(buffer);
  20623. };
  20624. /**
  20625. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  20626. * If the mesh has no geometry, it is simply returned as it is.
  20627. * The `data` are either a numeric array either a Float32Array.
  20628. * No new underlying VertexBuffer object is created.
  20629. * 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.
  20630. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  20631. *
  20632. * Possible `kind` values :
  20633. * - BABYLON.VertexBuffer.PositionKind
  20634. * - BABYLON.VertexBuffer.UVKind
  20635. * - BABYLON.VertexBuffer.UV2Kind
  20636. * - BABYLON.VertexBuffer.UV3Kind
  20637. * - BABYLON.VertexBuffer.UV4Kind
  20638. * - BABYLON.VertexBuffer.UV5Kind
  20639. * - BABYLON.VertexBuffer.UV6Kind
  20640. * - BABYLON.VertexBuffer.ColorKind
  20641. * - BABYLON.VertexBuffer.MatricesIndicesKind
  20642. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  20643. * - BABYLON.VertexBuffer.MatricesWeightsKind
  20644. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  20645. */
  20646. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  20647. if (!this._geometry) {
  20648. return;
  20649. }
  20650. if (!makeItUnique) {
  20651. this._geometry.updateVerticesData(kind, data, updateExtends);
  20652. }
  20653. else {
  20654. this.makeGeometryUnique();
  20655. this.updateVerticesData(kind, data, updateExtends, false);
  20656. }
  20657. };
  20658. /**
  20659. * Deprecated since BabylonJS v2.3
  20660. */
  20661. Mesh.prototype.updateVerticesDataDirectly = function (kind, data, offset, makeItUnique) {
  20662. BABYLON.Tools.Warn("Mesh.updateVerticesDataDirectly deprecated since 2.3.");
  20663. if (!this._geometry) {
  20664. return;
  20665. }
  20666. if (!makeItUnique) {
  20667. this._geometry.updateVerticesDataDirectly(kind, data, offset);
  20668. }
  20669. else {
  20670. this.makeGeometryUnique();
  20671. this.updateVerticesDataDirectly(kind, data, offset, false);
  20672. }
  20673. };
  20674. /**
  20675. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  20676. * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  20677. * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
  20678. * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
  20679. */
  20680. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  20681. if (computeNormals === void 0) { computeNormals = true; }
  20682. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  20683. positionFunction(positions);
  20684. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  20685. if (computeNormals) {
  20686. var indices = this.getIndices();
  20687. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  20688. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  20689. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  20690. }
  20691. };
  20692. Mesh.prototype.makeGeometryUnique = function () {
  20693. if (!this._geometry) {
  20694. return;
  20695. }
  20696. var oldGeometry = this._geometry;
  20697. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  20698. oldGeometry.releaseForMesh(this, true);
  20699. geometry.applyToMesh(this);
  20700. };
  20701. /**
  20702. * Sets the mesh indices.
  20703. * Expects an array populated with integers or a Int32Array.
  20704. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  20705. * This method creates a new index buffer each call.
  20706. */
  20707. Mesh.prototype.setIndices = function (indices, totalVertices) {
  20708. if (!this._geometry) {
  20709. var vertexData = new BABYLON.VertexData();
  20710. vertexData.indices = indices;
  20711. var scene = this.getScene();
  20712. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, false, this);
  20713. }
  20714. else {
  20715. this._geometry.setIndices(indices, totalVertices);
  20716. }
  20717. };
  20718. /**
  20719. * Invert the geometry to move from a right handed system to a left handed one.
  20720. */
  20721. Mesh.prototype.toLeftHanded = function () {
  20722. if (!this._geometry) {
  20723. return;
  20724. }
  20725. this._geometry.toLeftHanded();
  20726. };
  20727. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  20728. var engine = this.getScene().getEngine();
  20729. // Wireframe
  20730. var indexToBind;
  20731. if (this._unIndexed) {
  20732. indexToBind = null;
  20733. }
  20734. else {
  20735. switch (fillMode) {
  20736. case BABYLON.Material.PointFillMode:
  20737. indexToBind = null;
  20738. break;
  20739. case BABYLON.Material.WireFrameFillMode:
  20740. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  20741. break;
  20742. default:
  20743. case BABYLON.Material.TriangleFillMode:
  20744. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  20745. break;
  20746. }
  20747. }
  20748. // VBOs
  20749. this._geometry._bind(effect, indexToBind);
  20750. };
  20751. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  20752. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  20753. return;
  20754. }
  20755. this.onBeforeDrawObservable.notifyObservers(this);
  20756. var engine = this.getScene().getEngine();
  20757. // Draw order
  20758. switch (fillMode) {
  20759. case BABYLON.Material.PointFillMode:
  20760. engine.drawPointClouds(subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  20761. break;
  20762. case BABYLON.Material.WireFrameFillMode:
  20763. if (this._unIndexed) {
  20764. engine.drawUnIndexed(false, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  20765. }
  20766. else {
  20767. engine.draw(false, 0, instancesCount > 0 ? subMesh.linesIndexCount / 2 : subMesh.linesIndexCount, instancesCount);
  20768. }
  20769. break;
  20770. default:
  20771. if (this._unIndexed) {
  20772. engine.drawUnIndexed(true, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  20773. }
  20774. else {
  20775. engine.draw(true, subMesh.indexStart, subMesh.indexCount, instancesCount);
  20776. }
  20777. }
  20778. };
  20779. /**
  20780. * Registers for this mesh a javascript function called just before the rendering process.
  20781. * This function is passed the current mesh and doesn't return anything.
  20782. */
  20783. Mesh.prototype.registerBeforeRender = function (func) {
  20784. this.onBeforeRenderObservable.add(func);
  20785. };
  20786. /**
  20787. * Disposes a previously registered javascript function called before the rendering.
  20788. * This function is passed the current mesh and doesn't return anything.
  20789. */
  20790. Mesh.prototype.unregisterBeforeRender = function (func) {
  20791. this.onBeforeRenderObservable.removeCallback(func);
  20792. };
  20793. /**
  20794. * Registers for this mesh a javascript function called just after the rendering is complete.
  20795. * This function is passed the current mesh and doesn't return anything.
  20796. */
  20797. Mesh.prototype.registerAfterRender = function (func) {
  20798. this.onAfterRenderObservable.add(func);
  20799. };
  20800. /**
  20801. * Disposes a previously registered javascript function called after the rendering.
  20802. * This function is passed the current mesh and doesn't return anything.
  20803. */
  20804. Mesh.prototype.unregisterAfterRender = function (func) {
  20805. this.onAfterRenderObservable.removeCallback(func);
  20806. };
  20807. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  20808. var scene = this.getScene();
  20809. this._batchCache.mustReturn = false;
  20810. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  20811. this._batchCache.visibleInstances[subMeshId] = null;
  20812. if (this._visibleInstances) {
  20813. var currentRenderId = scene.getRenderId();
  20814. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  20815. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  20816. var selfRenderId = this._renderId;
  20817. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  20818. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  20819. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  20820. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  20821. }
  20822. if (this._batchCache.visibleInstances[subMeshId] && this._batchCache.visibleInstances[subMeshId].length) {
  20823. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  20824. this._batchCache.mustReturn = true;
  20825. return this._batchCache;
  20826. }
  20827. if (currentRenderId !== selfRenderId) {
  20828. this._batchCache.renderSelf[subMeshId] = false;
  20829. }
  20830. }
  20831. this._renderIdForInstances[subMeshId] = currentRenderId;
  20832. }
  20833. return this._batchCache;
  20834. };
  20835. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  20836. var visibleInstances = batch.visibleInstances[subMesh._id];
  20837. var matricesCount = visibleInstances.length + 1;
  20838. var bufferSize = matricesCount * 16 * 4;
  20839. var currentInstancesBufferSize = this._instancesBufferSize;
  20840. var instancesBuffer = this._instancesBuffer;
  20841. while (this._instancesBufferSize < bufferSize) {
  20842. this._instancesBufferSize *= 2;
  20843. }
  20844. if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) {
  20845. this._instancesData = new Float32Array(this._instancesBufferSize / 4);
  20846. }
  20847. var offset = 0;
  20848. var instancesCount = 0;
  20849. var world = this.getWorldMatrix();
  20850. if (batch.renderSelf[subMesh._id]) {
  20851. world.copyToArray(this._instancesData, offset);
  20852. offset += 16;
  20853. instancesCount++;
  20854. }
  20855. if (visibleInstances) {
  20856. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  20857. var instance = visibleInstances[instanceIndex];
  20858. instance.getWorldMatrix().copyToArray(this._instancesData, offset);
  20859. offset += 16;
  20860. instancesCount++;
  20861. }
  20862. }
  20863. if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) {
  20864. if (instancesBuffer) {
  20865. instancesBuffer.dispose();
  20866. }
  20867. instancesBuffer = new BABYLON.Buffer(engine, this._instancesData, true, 16, false, true);
  20868. this._instancesBuffer = instancesBuffer;
  20869. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  20870. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  20871. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  20872. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  20873. }
  20874. else {
  20875. instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount);
  20876. }
  20877. this.geometry._bind(effect);
  20878. this._draw(subMesh, fillMode, instancesCount);
  20879. engine.unbindInstanceAttributes();
  20880. };
  20881. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  20882. var scene = this.getScene();
  20883. var engine = scene.getEngine();
  20884. if (hardwareInstancedRendering) {
  20885. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  20886. }
  20887. else {
  20888. if (batch.renderSelf[subMesh._id]) {
  20889. // Draw
  20890. if (onBeforeDraw) {
  20891. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  20892. }
  20893. this._draw(subMesh, fillMode, this._overridenInstanceCount);
  20894. }
  20895. if (batch.visibleInstances[subMesh._id]) {
  20896. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  20897. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  20898. // World
  20899. var world = instance.getWorldMatrix();
  20900. if (onBeforeDraw) {
  20901. onBeforeDraw(true, world, effectiveMaterial);
  20902. }
  20903. // Draw
  20904. this._draw(subMesh, fillMode);
  20905. }
  20906. }
  20907. }
  20908. };
  20909. /**
  20910. * Triggers the draw call for the mesh.
  20911. * Usually, you don't need to call this method by your own because the mesh rendering is handled by the scene rendering manager.
  20912. */
  20913. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  20914. var scene = this.getScene();
  20915. // Managing instances
  20916. var batch = this._getInstancesRenderList(subMesh._id);
  20917. if (batch.mustReturn) {
  20918. return;
  20919. }
  20920. // Checking geometry state
  20921. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  20922. return;
  20923. }
  20924. var callbackIndex;
  20925. this.onBeforeRenderObservable.notifyObservers(this);
  20926. var engine = scene.getEngine();
  20927. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  20928. // Material
  20929. var effectiveMaterial = subMesh.getMaterial();
  20930. if (!effectiveMaterial || !effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  20931. return;
  20932. }
  20933. // Outline - step 1
  20934. var savedDepthWrite = engine.getDepthWrite();
  20935. if (this.renderOutline) {
  20936. engine.setDepthWrite(false);
  20937. scene.getOutlineRenderer().render(subMesh, batch);
  20938. engine.setDepthWrite(savedDepthWrite);
  20939. }
  20940. effectiveMaterial._preBind();
  20941. var effect = effectiveMaterial.getEffect();
  20942. // Bind
  20943. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : effectiveMaterial.fillMode);
  20944. this._bind(subMesh, effect, fillMode);
  20945. var world = this.getWorldMatrix();
  20946. effectiveMaterial.bind(world, this);
  20947. // Alpha mode
  20948. if (enableAlphaMode) {
  20949. engine.setAlphaMode(effectiveMaterial.alphaMode);
  20950. }
  20951. // Draw
  20952. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, effectiveMaterial);
  20953. // Unbind
  20954. effectiveMaterial.unbind();
  20955. // Outline - step 2
  20956. if (this.renderOutline && savedDepthWrite) {
  20957. engine.setDepthWrite(true);
  20958. engine.setColorWrite(false);
  20959. scene.getOutlineRenderer().render(subMesh, batch);
  20960. engine.setColorWrite(true);
  20961. }
  20962. // Overlay
  20963. if (this.renderOverlay) {
  20964. var currentMode = engine.getAlphaMode();
  20965. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  20966. scene.getOutlineRenderer().render(subMesh, batch, true);
  20967. engine.setAlphaMode(currentMode);
  20968. }
  20969. this.onAfterRenderObservable.notifyObservers(this);
  20970. };
  20971. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  20972. if (isInstance) {
  20973. effectiveMaterial.bindOnlyWorldMatrix(world);
  20974. }
  20975. };
  20976. /**
  20977. * Returns an array populated with ParticleSystem objects whose the mesh is the emitter.
  20978. */
  20979. Mesh.prototype.getEmittedParticleSystems = function () {
  20980. var results = new Array();
  20981. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  20982. var particleSystem = this.getScene().particleSystems[index];
  20983. if (particleSystem.emitter === this) {
  20984. results.push(particleSystem);
  20985. }
  20986. }
  20987. return results;
  20988. };
  20989. /**
  20990. * Returns an array populated with ParticleSystem objects whose the mesh or its children are the emitter.
  20991. */
  20992. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  20993. var results = new Array();
  20994. var descendants = this.getDescendants();
  20995. descendants.push(this);
  20996. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  20997. var particleSystem = this.getScene().particleSystems[index];
  20998. if (descendants.indexOf(particleSystem.emitter) !== -1) {
  20999. results.push(particleSystem);
  21000. }
  21001. }
  21002. return results;
  21003. };
  21004. Mesh.prototype._checkDelayState = function () {
  21005. var scene = this.getScene();
  21006. if (this._geometry) {
  21007. this._geometry.load(scene);
  21008. }
  21009. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  21010. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  21011. this._queueLoad(this, scene);
  21012. }
  21013. };
  21014. Mesh.prototype._queueLoad = function (mesh, scene) {
  21015. var _this = this;
  21016. scene._addPendingData(mesh);
  21017. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  21018. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  21019. if (data instanceof ArrayBuffer) {
  21020. _this._delayLoadingFunction(data, _this);
  21021. }
  21022. else {
  21023. _this._delayLoadingFunction(JSON.parse(data), _this);
  21024. }
  21025. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  21026. scene._removePendingData(_this);
  21027. }, function () { }, scene.database, getBinaryData);
  21028. };
  21029. /**
  21030. * Boolean, true is the mesh in the frustum defined by the Plane objects from the `frustumPlanes` array parameter.
  21031. */
  21032. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  21033. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  21034. return false;
  21035. }
  21036. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  21037. return false;
  21038. }
  21039. this._checkDelayState();
  21040. return true;
  21041. };
  21042. /**
  21043. * Sets the mesh material by the material or multiMaterial `id` property.
  21044. * The material `id` is a string identifying the material or the multiMaterial.
  21045. * This method returns nothing.
  21046. */
  21047. Mesh.prototype.setMaterialByID = function (id) {
  21048. var materials = this.getScene().materials;
  21049. var index;
  21050. for (index = 0; index < materials.length; index++) {
  21051. if (materials[index].id === id) {
  21052. this.material = materials[index];
  21053. return;
  21054. }
  21055. }
  21056. // Multi
  21057. var multiMaterials = this.getScene().multiMaterials;
  21058. for (index = 0; index < multiMaterials.length; index++) {
  21059. if (multiMaterials[index].id === id) {
  21060. this.material = multiMaterials[index];
  21061. return;
  21062. }
  21063. }
  21064. };
  21065. /**
  21066. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  21067. */
  21068. Mesh.prototype.getAnimatables = function () {
  21069. var results = [];
  21070. if (this.material) {
  21071. results.push(this.material);
  21072. }
  21073. if (this.skeleton) {
  21074. results.push(this.skeleton);
  21075. }
  21076. return results;
  21077. };
  21078. /**
  21079. * Modifies the mesh geometry according to the passed transformation matrix.
  21080. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  21081. * The mesh normals are modified accordingly the same transformation.
  21082. * tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  21083. * Note that, under the hood, this method sets a new VertexBuffer each call.
  21084. */
  21085. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  21086. // Position
  21087. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  21088. return;
  21089. }
  21090. var submeshes = this.subMeshes.splice(0);
  21091. this._resetPointsArrayCache();
  21092. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21093. var temp = [];
  21094. var index;
  21095. for (index = 0; index < data.length; index += 3) {
  21096. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  21097. }
  21098. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  21099. // Normals
  21100. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  21101. return;
  21102. }
  21103. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  21104. temp = [];
  21105. for (index = 0; index < data.length; index += 3) {
  21106. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  21107. }
  21108. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  21109. // flip faces?
  21110. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  21111. this.flipFaces();
  21112. }
  21113. // Restore submeshes
  21114. this.releaseSubMeshes();
  21115. this.subMeshes = submeshes;
  21116. };
  21117. /**
  21118. * Modifies the mesh geometry according to its own current World Matrix.
  21119. * The mesh World Matrix is then reset.
  21120. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  21121. * tuto : tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  21122. * Note that, under the hood, this method sets a new VertexBuffer each call.
  21123. */
  21124. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  21125. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  21126. this.scaling.copyFromFloats(1, 1, 1);
  21127. this.position.copyFromFloats(0, 0, 0);
  21128. this.rotation.copyFromFloats(0, 0, 0);
  21129. //only if quaternion is already set
  21130. if (this.rotationQuaternion) {
  21131. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  21132. }
  21133. this._worldMatrix = BABYLON.Matrix.Identity();
  21134. };
  21135. // Cache
  21136. Mesh.prototype._resetPointsArrayCache = function () {
  21137. this._positions = null;
  21138. };
  21139. Mesh.prototype._generatePointsArray = function () {
  21140. if (this._positions)
  21141. return true;
  21142. this._positions = [];
  21143. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21144. if (!data) {
  21145. return false;
  21146. }
  21147. for (var index = 0; index < data.length; index += 3) {
  21148. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  21149. }
  21150. return true;
  21151. };
  21152. /**
  21153. * Returns a new Mesh object generated from the current mesh properties.
  21154. * This method must not get confused with createInstance().
  21155. * The parameter `name` is a string, the name given to the new mesh.
  21156. * The optional parameter `newParent` can be any Node object (default `null`).
  21157. * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any.
  21158. * 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.
  21159. */
  21160. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  21161. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  21162. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  21163. };
  21164. /**
  21165. * Disposes the mesh.
  21166. * This also frees the memory allocated under the hood to all the buffers used by WebGL.
  21167. */
  21168. Mesh.prototype.dispose = function (doNotRecurse) {
  21169. var _this = this;
  21170. if (this._geometry) {
  21171. this._geometry.releaseForMesh(this, true);
  21172. }
  21173. // Sources
  21174. var meshes = this.getScene().meshes;
  21175. meshes.forEach(function (mesh) {
  21176. if (mesh._source && mesh._source === _this) {
  21177. mesh._source = null;
  21178. }
  21179. });
  21180. this._source = null;
  21181. // Instances
  21182. if (this._instancesBuffer) {
  21183. this._instancesBuffer.dispose();
  21184. this._instancesBuffer = null;
  21185. }
  21186. while (this.instances.length) {
  21187. this.instances[0].dispose();
  21188. }
  21189. // Highlight layers.
  21190. var highlightLayers = this.getScene().highlightLayers;
  21191. for (var i = 0; i < highlightLayers.length; i++) {
  21192. var highlightLayer = highlightLayers[i];
  21193. if (highlightLayer) {
  21194. highlightLayer.removeMesh(this);
  21195. highlightLayer.removeExcludedMesh(this);
  21196. }
  21197. }
  21198. // facet data
  21199. if (this._facetDataEnabled) {
  21200. this.disableFacetData();
  21201. }
  21202. _super.prototype.dispose.call(this, doNotRecurse);
  21203. };
  21204. /**
  21205. * Modifies the mesh geometry according to a displacement map.
  21206. * 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.
  21207. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  21208. * This method returns nothing.
  21209. * The parameter `url` is a string, the URL from the image file is to be downloaded.
  21210. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  21211. * 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.
  21212. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  21213. * The parameter `uvScale` is an optional vector2 used to scale UV.
  21214. */
  21215. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess, uvOffset, uvScale) {
  21216. var _this = this;
  21217. var scene = this.getScene();
  21218. var onload = function (img) {
  21219. // Getting height map data
  21220. var canvas = document.createElement("canvas");
  21221. var context = canvas.getContext("2d");
  21222. var heightMapWidth = img.width;
  21223. var heightMapHeight = img.height;
  21224. canvas.width = heightMapWidth;
  21225. canvas.height = heightMapHeight;
  21226. context.drawImage(img, 0, 0);
  21227. // Create VertexData from map data
  21228. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  21229. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  21230. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale);
  21231. //execute success callback, if set
  21232. if (onSuccess) {
  21233. onSuccess(_this);
  21234. }
  21235. };
  21236. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  21237. };
  21238. /**
  21239. * Modifies the mesh geometry according to a displacementMap buffer.
  21240. * 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.
  21241. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  21242. * This method returns nothing.
  21243. * 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.
  21244. * The parameters `heightMapWidth` and `heightMapHeight` are positive integers to set the width and height of the buffer image.
  21245. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  21246. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  21247. * The parameter `uvScale` is an optional vector2 used to scale UV.
  21248. */
  21249. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale) {
  21250. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  21251. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  21252. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  21253. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  21254. return;
  21255. }
  21256. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21257. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  21258. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  21259. var position = BABYLON.Vector3.Zero();
  21260. var normal = BABYLON.Vector3.Zero();
  21261. var uv = BABYLON.Vector2.Zero();
  21262. uvOffset = uvOffset || BABYLON.Vector2.Zero();
  21263. uvScale = uvScale || new BABYLON.Vector2(1, 1);
  21264. for (var index = 0; index < positions.length; index += 3) {
  21265. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  21266. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  21267. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  21268. // Compute height
  21269. var u = ((Math.abs(uv.x * uvScale.x + uvOffset.x) * heightMapWidth) % heightMapWidth) | 0;
  21270. var v = ((Math.abs(uv.y * uvScale.y + uvOffset.y) * heightMapHeight) % heightMapHeight) | 0;
  21271. var pos = (u + v * heightMapWidth) * 4;
  21272. var r = buffer[pos] / 255.0;
  21273. var g = buffer[pos + 1] / 255.0;
  21274. var b = buffer[pos + 2] / 255.0;
  21275. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  21276. normal.normalize();
  21277. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  21278. position = position.add(normal);
  21279. position.toArray(positions, index);
  21280. }
  21281. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  21282. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  21283. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  21284. };
  21285. /**
  21286. * Modify the mesh to get a flat shading rendering.
  21287. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  21288. * This method returns nothing.
  21289. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  21290. */
  21291. Mesh.prototype.convertToFlatShadedMesh = function () {
  21292. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  21293. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  21294. var kinds = this.getVerticesDataKinds();
  21295. var vbs = [];
  21296. var data = [];
  21297. var newdata = [];
  21298. var updatableNormals = false;
  21299. var kindIndex;
  21300. var kind;
  21301. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  21302. kind = kinds[kindIndex];
  21303. var vertexBuffer = this.getVertexBuffer(kind);
  21304. if (kind === BABYLON.VertexBuffer.NormalKind) {
  21305. updatableNormals = vertexBuffer.isUpdatable();
  21306. kinds.splice(kindIndex, 1);
  21307. kindIndex--;
  21308. continue;
  21309. }
  21310. vbs[kind] = vertexBuffer;
  21311. data[kind] = vbs[kind].getData();
  21312. newdata[kind] = [];
  21313. }
  21314. // Save previous submeshes
  21315. var previousSubmeshes = this.subMeshes.slice(0);
  21316. var indices = this.getIndices();
  21317. var totalIndices = this.getTotalIndices();
  21318. // Generating unique vertices per face
  21319. var index;
  21320. for (index = 0; index < totalIndices; index++) {
  21321. var vertexIndex = indices[index];
  21322. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  21323. kind = kinds[kindIndex];
  21324. var stride = vbs[kind].getStrideSize();
  21325. for (var offset = 0; offset < stride; offset++) {
  21326. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  21327. }
  21328. }
  21329. }
  21330. // Updating faces & normal
  21331. var normals = [];
  21332. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  21333. for (index = 0; index < totalIndices; index += 3) {
  21334. indices[index] = index;
  21335. indices[index + 1] = index + 1;
  21336. indices[index + 2] = index + 2;
  21337. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  21338. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  21339. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  21340. var p1p2 = p1.subtract(p2);
  21341. var p3p2 = p3.subtract(p2);
  21342. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  21343. // Store same normals for every vertex
  21344. for (var localIndex = 0; localIndex < 3; localIndex++) {
  21345. normals.push(normal.x);
  21346. normals.push(normal.y);
  21347. normals.push(normal.z);
  21348. }
  21349. }
  21350. this.setIndices(indices);
  21351. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  21352. // Updating vertex buffers
  21353. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  21354. kind = kinds[kindIndex];
  21355. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  21356. }
  21357. // Updating submeshes
  21358. this.releaseSubMeshes();
  21359. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  21360. var previousOne = previousSubmeshes[submeshIndex];
  21361. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  21362. }
  21363. this.synchronizeInstances();
  21364. };
  21365. /**
  21366. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  21367. * In other words, more vertices, no more indices and a single bigger VBO.
  21368. * This method returns nothing.
  21369. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  21370. *
  21371. */
  21372. Mesh.prototype.convertToUnIndexedMesh = function () {
  21373. /// <summary>Remove indices by unfolding faces into buffers</summary>
  21374. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  21375. var kinds = this.getVerticesDataKinds();
  21376. var vbs = [];
  21377. var data = [];
  21378. var newdata = [];
  21379. var updatableNormals = false;
  21380. var kindIndex;
  21381. var kind;
  21382. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  21383. kind = kinds[kindIndex];
  21384. var vertexBuffer = this.getVertexBuffer(kind);
  21385. vbs[kind] = vertexBuffer;
  21386. data[kind] = vbs[kind].getData();
  21387. newdata[kind] = [];
  21388. }
  21389. // Save previous submeshes
  21390. var previousSubmeshes = this.subMeshes.slice(0);
  21391. var indices = this.getIndices();
  21392. var totalIndices = this.getTotalIndices();
  21393. // Generating unique vertices per face
  21394. var index;
  21395. for (index = 0; index < totalIndices; index++) {
  21396. var vertexIndex = indices[index];
  21397. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  21398. kind = kinds[kindIndex];
  21399. var stride = vbs[kind].getStrideSize();
  21400. for (var offset = 0; offset < stride; offset++) {
  21401. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  21402. }
  21403. }
  21404. }
  21405. // Updating indices
  21406. for (index = 0; index < totalIndices; index += 3) {
  21407. indices[index] = index;
  21408. indices[index + 1] = index + 1;
  21409. indices[index + 2] = index + 2;
  21410. }
  21411. this.setIndices(indices);
  21412. // Updating vertex buffers
  21413. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  21414. kind = kinds[kindIndex];
  21415. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  21416. }
  21417. // Updating submeshes
  21418. this.releaseSubMeshes();
  21419. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  21420. var previousOne = previousSubmeshes[submeshIndex];
  21421. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  21422. }
  21423. this._unIndexed = true;
  21424. this.synchronizeInstances();
  21425. };
  21426. /**
  21427. * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true.
  21428. * This method returns nothing.
  21429. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  21430. */
  21431. Mesh.prototype.flipFaces = function (flipNormals) {
  21432. if (flipNormals === void 0) { flipNormals = false; }
  21433. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  21434. var i;
  21435. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  21436. for (i = 0; i < vertex_data.normals.length; i++) {
  21437. vertex_data.normals[i] *= -1;
  21438. }
  21439. }
  21440. var temp;
  21441. for (i = 0; i < vertex_data.indices.length; i += 3) {
  21442. // reassign indices
  21443. temp = vertex_data.indices[i + 1];
  21444. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  21445. vertex_data.indices[i + 2] = temp;
  21446. }
  21447. vertex_data.applyToMesh(this);
  21448. };
  21449. // Instances
  21450. /**
  21451. * Creates a new InstancedMesh object from the mesh model.
  21452. * An instance shares the same properties and the same material than its model.
  21453. * Only these properties of each instance can then be set individually :
  21454. * - position
  21455. * - rotation
  21456. * - rotationQuaternion
  21457. * - setPivotMatrix
  21458. * - scaling
  21459. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_Instances
  21460. * Warning : this method is not supported for Line mesh and LineSystem
  21461. */
  21462. Mesh.prototype.createInstance = function (name) {
  21463. return new BABYLON.InstancedMesh(name, this);
  21464. };
  21465. /**
  21466. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  21467. * After this call, all the mesh instances have the same submeshes than the current mesh.
  21468. * This method returns nothing.
  21469. */
  21470. Mesh.prototype.synchronizeInstances = function () {
  21471. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  21472. var instance = this.instances[instanceIndex];
  21473. instance._syncSubMeshes();
  21474. }
  21475. };
  21476. /**
  21477. * Simplify the mesh according to the given array of settings.
  21478. * Function will return immediately and will simplify async. It returns nothing.
  21479. * @param settings a collection of simplification settings.
  21480. * @param parallelProcessing should all levels calculate parallel or one after the other.
  21481. * @param type the type of simplification to run.
  21482. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  21483. */
  21484. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  21485. if (parallelProcessing === void 0) { parallelProcessing = true; }
  21486. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  21487. this.getScene().simplificationQueue.addTask({
  21488. settings: settings,
  21489. parallelProcessing: parallelProcessing,
  21490. mesh: this,
  21491. simplificationType: simplificationType,
  21492. successCallback: successCallback
  21493. });
  21494. };
  21495. /**
  21496. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  21497. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  21498. * This should be used together with the simplification to avoid disappearing triangles.
  21499. * @param successCallback an optional success callback to be called after the optimization finished.
  21500. */
  21501. Mesh.prototype.optimizeIndices = function (successCallback) {
  21502. var _this = this;
  21503. var indices = this.getIndices();
  21504. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21505. var vectorPositions = [];
  21506. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  21507. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  21508. }
  21509. var dupes = [];
  21510. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  21511. var realPos = vectorPositions.length - 1 - iteration;
  21512. var testedPosition = vectorPositions[realPos];
  21513. for (var j = 0; j < realPos; ++j) {
  21514. var againstPosition = vectorPositions[j];
  21515. if (testedPosition.equals(againstPosition)) {
  21516. dupes[realPos] = j;
  21517. break;
  21518. }
  21519. }
  21520. }, function () {
  21521. for (var i = 0; i < indices.length; ++i) {
  21522. indices[i] = dupes[indices[i]] || indices[i];
  21523. }
  21524. //indices are now reordered
  21525. var originalSubMeshes = _this.subMeshes.slice(0);
  21526. _this.setIndices(indices);
  21527. _this.subMeshes = originalSubMeshes;
  21528. if (successCallback) {
  21529. successCallback(_this);
  21530. }
  21531. });
  21532. };
  21533. // Facet data
  21534. /**
  21535. * Initialize the facet data arrays : facetNormals, facetPositions and facetPartitioning
  21536. */
  21537. Mesh.prototype._initFacetData = function () {
  21538. if (!this._facetNormals) {
  21539. this._facetNormals = new Array();
  21540. }
  21541. if (!this._facetPositions) {
  21542. this._facetPositions = new Array();
  21543. }
  21544. if (!this._facetPartitioning) {
  21545. this._facetPartitioning = new Array();
  21546. }
  21547. this._facetNb = this.getIndices().length / 3;
  21548. this._partitioningSubdivisions = (this._partitioningSubdivisions) ? this._partitioningSubdivisions : 10; // default nb of partitioning subdivisions = 10
  21549. this._partitioningBBoxRatio = (this._partitioningBBoxRatio) ? this._partitioningBBoxRatio : 1.01; // default ratio 1.01 = the partitioning is 1% bigger than the bounding box
  21550. for (var f = 0; f < this._facetNb; f++) {
  21551. this._facetNormals[f] = BABYLON.Vector3.Zero();
  21552. this._facetPositions[f] = BABYLON.Vector3.Zero();
  21553. }
  21554. this._facetDataEnabled = true;
  21555. return this;
  21556. };
  21557. /**
  21558. * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated.
  21559. * This method can be called within the render loop.
  21560. * 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.
  21561. */
  21562. Mesh.prototype.updateFacetData = function () {
  21563. if (!this._facetDataEnabled) {
  21564. this._initFacetData();
  21565. }
  21566. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21567. var indices = this.getIndices();
  21568. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  21569. var bInfo = this.getBoundingInfo();
  21570. this._bbSize.x = (bInfo.maximum.x - bInfo.minimum.x > BABYLON.Epsilon) ? bInfo.maximum.x - bInfo.minimum.x : BABYLON.Epsilon;
  21571. this._bbSize.y = (bInfo.maximum.y - bInfo.minimum.y > BABYLON.Epsilon) ? bInfo.maximum.y - bInfo.minimum.y : BABYLON.Epsilon;
  21572. this._bbSize.z = (bInfo.maximum.z - bInfo.minimum.z > BABYLON.Epsilon) ? bInfo.maximum.z - bInfo.minimum.z : BABYLON.Epsilon;
  21573. var bbSizeMax = (this._bbSize.x > this._bbSize.y) ? this._bbSize.x : this._bbSize.y;
  21574. bbSizeMax = (bbSizeMax > this._bbSize.z) ? bbSizeMax : this._bbSize.z;
  21575. this._subDiv.max = this._partitioningSubdivisions;
  21576. this._subDiv.X = Math.floor(this._subDiv.max * this._bbSize.x / bbSizeMax); // adjust the number of subdivisions per axis
  21577. this._subDiv.Y = Math.floor(this._subDiv.max * this._bbSize.y / bbSizeMax); // according to each bbox size per axis
  21578. this._subDiv.Z = Math.floor(this._subDiv.max * this._bbSize.z / bbSizeMax);
  21579. this._subDiv.X = this._subDiv.X < 1 ? 1 : this._subDiv.X; // at least one subdivision
  21580. this._subDiv.Y = this._subDiv.Y < 1 ? 1 : this._subDiv.Y;
  21581. this._subDiv.Z = this._subDiv.Z < 1 ? 1 : this._subDiv.Z;
  21582. // set the parameters for ComputeNormals()
  21583. this._facetParameters.facetNormals = this.getFacetLocalNormals();
  21584. this._facetParameters.facetPositions = this.getFacetLocalPositions();
  21585. this._facetParameters.facetPartitioning = this.getFacetLocalPartitioning();
  21586. this._facetParameters.bInfo = bInfo;
  21587. this._facetParameters.bbSize = this._bbSize;
  21588. this._facetParameters.subDiv = this._subDiv;
  21589. this._facetParameters.ratio = this.partitioningBBoxRatio;
  21590. BABYLON.VertexData.ComputeNormals(positions, indices, normals, this._facetParameters);
  21591. return this;
  21592. };
  21593. /**
  21594. * Returns the facetLocalNormals array.
  21595. * The normals are expressed in the mesh local space.
  21596. */
  21597. Mesh.prototype.getFacetLocalNormals = function () {
  21598. if (!this._facetNormals) {
  21599. this.updateFacetData();
  21600. }
  21601. return this._facetNormals;
  21602. };
  21603. /**
  21604. * Returns the facetLocalPositions array.
  21605. * The facet positions are expressed in the mesh local space.
  21606. */
  21607. Mesh.prototype.getFacetLocalPositions = function () {
  21608. if (!this._facetPositions) {
  21609. this.updateFacetData();
  21610. }
  21611. return this._facetPositions;
  21612. };
  21613. /**
  21614. * Returns the facetLocalPartioning array
  21615. */
  21616. Mesh.prototype.getFacetLocalPartitioning = function () {
  21617. if (!this._facetPartitioning) {
  21618. this.updateFacetData();
  21619. }
  21620. return this._facetPartitioning;
  21621. };
  21622. /**
  21623. * Returns the i-th facet position in the world system.
  21624. * This method allocates a new Vector3 per call.
  21625. */
  21626. Mesh.prototype.getFacetPosition = function (i) {
  21627. var pos = BABYLON.Vector3.Zero();
  21628. this.getFacetPositionToRef(i, pos);
  21629. return pos;
  21630. };
  21631. /**
  21632. * Sets the reference Vector3 with the i-th facet position in the world system.
  21633. * Returns the mesh.
  21634. */
  21635. Mesh.prototype.getFacetPositionToRef = function (i, ref) {
  21636. var localPos = (this.getFacetLocalPositions())[i];
  21637. var world = this.getWorldMatrix();
  21638. BABYLON.Vector3.TransformCoordinatesToRef(localPos, world, ref);
  21639. return this;
  21640. };
  21641. /**
  21642. * Returns the i-th facet normal in the world system.
  21643. * This method allocates a new Vector3 per call.
  21644. */
  21645. Mesh.prototype.getFacetNormal = function (i) {
  21646. var norm = BABYLON.Vector3.Zero();
  21647. this.getFacetNormalToRef(i, norm);
  21648. return norm;
  21649. };
  21650. /**
  21651. * Sets the reference Vector3 with the i-th facet normal in the world system.
  21652. * Returns the mesh.
  21653. */
  21654. Mesh.prototype.getFacetNormalToRef = function (i, ref) {
  21655. var localNorm = (this.getFacetLocalNormals())[i];
  21656. (this.getWorldMatrix()).getRotationMatrixToRef(BABYLON.Tmp.Matrix[0]);
  21657. BABYLON.Vector3.TransformCoordinatesToRef(localNorm, BABYLON.Tmp.Matrix[0], ref);
  21658. return this;
  21659. };
  21660. /**
  21661. * 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).
  21662. */
  21663. Mesh.prototype.getFacetsAtLocalCoordinates = function (x, y, z) {
  21664. var bInfo = this.getBoundingInfo();
  21665. var ox = Math.floor((x - bInfo.minimum.x * this._partitioningBBoxRatio) * this._subDiv.X * this._partitioningBBoxRatio / this._bbSize.x);
  21666. var oy = Math.floor((y - bInfo.minimum.y * this._partitioningBBoxRatio) * this._subDiv.Y * this._partitioningBBoxRatio / this._bbSize.y);
  21667. var oz = Math.floor((z - bInfo.minimum.z * this._partitioningBBoxRatio) * this._subDiv.Z * this._partitioningBBoxRatio / this._bbSize.z);
  21668. if (ox < 0 || ox > this._subDiv.max || oy < 0 || oy > this._subDiv.max || oz < 0 || oz > this._subDiv.max) {
  21669. return null;
  21670. }
  21671. return this._facetPartitioning[ox + this._subDiv.max * oy + this._subDiv.max * this._subDiv.max * oz];
  21672. };
  21673. /**
  21674. * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found.
  21675. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) World projection on the facet.
  21676. * 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.
  21677. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  21678. * 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.
  21679. */
  21680. Mesh.prototype.getClosestFacetAtCoordinates = function (x, y, z, projected, checkFace, facing) {
  21681. if (checkFace === void 0) { checkFace = false; }
  21682. if (facing === void 0) { facing = true; }
  21683. var world = this.getWorldMatrix();
  21684. var invMat = BABYLON.Tmp.Matrix[5];
  21685. world.invertToRef(invMat);
  21686. var invVect = BABYLON.Tmp.Vector3[8];
  21687. var closest = null;
  21688. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, invMat, invVect); // transform (x,y,z) to coordinates in the mesh local space
  21689. closest = this.getClosestFacetAtLocalCoordinates(invVect.x, invVect.y, invVect.z, projected, checkFace, facing);
  21690. if (projected) {
  21691. // tranform the local computed projected vector to world coordinates
  21692. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(projected.x, projected.y, projected.z, world, projected);
  21693. }
  21694. return closest;
  21695. };
  21696. /**
  21697. * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found.
  21698. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) local projection on the facet.
  21699. * 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.
  21700. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  21701. * 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.
  21702. */
  21703. Mesh.prototype.getClosestFacetAtLocalCoordinates = function (x, y, z, projected, checkFace, facing) {
  21704. if (checkFace === void 0) { checkFace = false; }
  21705. if (facing === void 0) { facing = true; }
  21706. var closest = null;
  21707. var tmpx = 0.0;
  21708. var tmpy = 0.0;
  21709. var tmpz = 0.0;
  21710. var d = 0.0; // tmp dot facet normal * facet position
  21711. var t0 = 0.0;
  21712. var projx = 0.0;
  21713. var projy = 0.0;
  21714. var projz = 0.0;
  21715. // Get all the facets in the same partitioning block than (x, y, z)
  21716. var facetPositions = this.getFacetLocalPositions();
  21717. var facetNormals = this.getFacetLocalNormals();
  21718. var facetsInBlock = this.getFacetsAtLocalCoordinates(x, y, z);
  21719. if (!facetsInBlock) {
  21720. return null;
  21721. }
  21722. // Get the closest facet to (x, y, z)
  21723. var shortest = Number.MAX_VALUE; // init distance vars
  21724. var tmpDistance = shortest;
  21725. var fib; // current facet in the block
  21726. var norm; // current facet normal
  21727. var p0; // current facet barycenter position
  21728. // loop on all the facets in the current partitioning block
  21729. for (var idx = 0; idx < facetsInBlock.length; idx++) {
  21730. fib = facetsInBlock[idx];
  21731. norm = facetNormals[fib];
  21732. p0 = facetPositions[fib];
  21733. d = (x - p0.x) * norm.x + (y - p0.y) * norm.y + (z - p0.z) * norm.z;
  21734. if (!checkFace || (checkFace && facing && d >= 0.0) || (checkFace && !facing && d <= 0.0)) {
  21735. // compute (x,y,z) projection on the facet = (projx, projy, projz)
  21736. d = norm.x * p0.x + norm.y * p0.y + norm.z * p0.z;
  21737. t0 = -(norm.x * x + norm.y * y + norm.z * z - d) / (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);
  21738. projx = x + norm.x * t0;
  21739. projy = y + norm.y * t0;
  21740. projz = z + norm.z * t0;
  21741. tmpx = projx - x;
  21742. tmpy = projy - y;
  21743. tmpz = projz - z;
  21744. tmpDistance = tmpx * tmpx + tmpy * tmpy + tmpz * tmpz; // compute length between (x, y, z) and its projection on the facet
  21745. if (tmpDistance < shortest) {
  21746. shortest = tmpDistance;
  21747. closest = fib;
  21748. if (projected) {
  21749. projected.x = projx;
  21750. projected.y = projy;
  21751. projected.z = projz;
  21752. }
  21753. }
  21754. }
  21755. }
  21756. return closest;
  21757. };
  21758. /**
  21759. * Returns the object "parameter" set with all the expected parameters for facetData computation by ComputeNormals()
  21760. */
  21761. Mesh.prototype.getFacetDataParameters = function () {
  21762. return this._facetParameters;
  21763. };
  21764. /**
  21765. * Disables the feature FacetData and frees the related memory.
  21766. * Returns the mesh.
  21767. */
  21768. Mesh.prototype.disableFacetData = function () {
  21769. if (this._facetDataEnabled) {
  21770. this._facetDataEnabled = false;
  21771. this._facetPositions = null;
  21772. this._facetNormals = null;
  21773. this._facetPartitioning = null;
  21774. this._facetParameters = null;
  21775. }
  21776. return this;
  21777. };
  21778. // Statics
  21779. /**
  21780. * Returns a new Mesh object what is a deep copy of the passed mesh.
  21781. * The parameter `parsedMesh` is the mesh to be copied.
  21782. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  21783. */
  21784. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  21785. var mesh = new Mesh(parsedMesh.name, scene);
  21786. mesh.id = parsedMesh.id;
  21787. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  21788. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  21789. if (parsedMesh.metadata !== undefined) {
  21790. mesh.metadata = parsedMesh.metadata;
  21791. }
  21792. if (parsedMesh.rotationQuaternion) {
  21793. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  21794. }
  21795. else if (parsedMesh.rotation) {
  21796. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  21797. }
  21798. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  21799. if (parsedMesh.localMatrix) {
  21800. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  21801. }
  21802. else if (parsedMesh.pivotMatrix) {
  21803. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  21804. }
  21805. mesh.setEnabled(parsedMesh.isEnabled);
  21806. mesh.isVisible = parsedMesh.isVisible;
  21807. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  21808. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  21809. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  21810. if (parsedMesh.applyFog !== undefined) {
  21811. mesh.applyFog = parsedMesh.applyFog;
  21812. }
  21813. if (parsedMesh.pickable !== undefined) {
  21814. mesh.isPickable = parsedMesh.pickable;
  21815. }
  21816. if (parsedMesh.alphaIndex !== undefined) {
  21817. mesh.alphaIndex = parsedMesh.alphaIndex;
  21818. }
  21819. mesh.receiveShadows = parsedMesh.receiveShadows;
  21820. mesh.billboardMode = parsedMesh.billboardMode;
  21821. if (parsedMesh.visibility !== undefined) {
  21822. mesh.visibility = parsedMesh.visibility;
  21823. }
  21824. mesh.checkCollisions = parsedMesh.checkCollisions;
  21825. if (parsedMesh.isBlocker !== undefined) {
  21826. mesh.isBlocker = parsedMesh.isBlocker;
  21827. }
  21828. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  21829. // freezeWorldMatrix
  21830. if (parsedMesh.freezeWorldMatrix) {
  21831. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  21832. }
  21833. // Parent
  21834. if (parsedMesh.parentId) {
  21835. mesh._waitingParentId = parsedMesh.parentId;
  21836. }
  21837. // Actions
  21838. if (parsedMesh.actions !== undefined) {
  21839. mesh._waitingActions = parsedMesh.actions;
  21840. }
  21841. // Overlay
  21842. if (parsedMesh.overlayAlpha !== undefined) {
  21843. mesh.overlayAlpha = parsedMesh.overlayAlpha;
  21844. }
  21845. if (parsedMesh.overlayColor !== undefined) {
  21846. mesh.overlayColor = BABYLON.Color3.FromArray(parsedMesh.overlayColor);
  21847. }
  21848. if (parsedMesh.renderOverlay !== undefined) {
  21849. mesh.renderOverlay = parsedMesh.renderOverlay;
  21850. }
  21851. // Geometry
  21852. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  21853. if (parsedMesh.delayLoadingFile) {
  21854. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  21855. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  21856. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  21857. if (parsedMesh._binaryInfo) {
  21858. mesh._binaryInfo = parsedMesh._binaryInfo;
  21859. }
  21860. mesh._delayInfo = [];
  21861. if (parsedMesh.hasUVs) {
  21862. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  21863. }
  21864. if (parsedMesh.hasUVs2) {
  21865. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  21866. }
  21867. if (parsedMesh.hasUVs3) {
  21868. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  21869. }
  21870. if (parsedMesh.hasUVs4) {
  21871. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  21872. }
  21873. if (parsedMesh.hasUVs5) {
  21874. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  21875. }
  21876. if (parsedMesh.hasUVs6) {
  21877. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  21878. }
  21879. if (parsedMesh.hasColors) {
  21880. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  21881. }
  21882. if (parsedMesh.hasMatricesIndices) {
  21883. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  21884. }
  21885. if (parsedMesh.hasMatricesWeights) {
  21886. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  21887. }
  21888. mesh._delayLoadingFunction = BABYLON.Geometry.ImportGeometry;
  21889. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  21890. mesh._checkDelayState();
  21891. }
  21892. }
  21893. else {
  21894. BABYLON.Geometry.ImportGeometry(parsedMesh, mesh);
  21895. }
  21896. // Material
  21897. if (parsedMesh.materialId) {
  21898. mesh.setMaterialByID(parsedMesh.materialId);
  21899. }
  21900. else {
  21901. mesh.material = null;
  21902. }
  21903. // Skeleton
  21904. if (parsedMesh.skeletonId > -1) {
  21905. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  21906. if (parsedMesh.numBoneInfluencers) {
  21907. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  21908. }
  21909. }
  21910. // Animations
  21911. if (parsedMesh.animations) {
  21912. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  21913. var parsedAnimation = parsedMesh.animations[animationIndex];
  21914. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  21915. }
  21916. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  21917. }
  21918. if (parsedMesh.autoAnimate) {
  21919. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  21920. }
  21921. // Layer Mask
  21922. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  21923. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  21924. }
  21925. else {
  21926. mesh.layerMask = 0x0FFFFFFF;
  21927. }
  21928. //(Deprecated) physics
  21929. if (parsedMesh.physicsImpostor) {
  21930. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  21931. mass: parsedMesh.physicsMass,
  21932. friction: parsedMesh.physicsFriction,
  21933. restitution: parsedMesh.physicsRestitution
  21934. }, scene);
  21935. }
  21936. // Instances
  21937. if (parsedMesh.instances) {
  21938. for (var index = 0; index < parsedMesh.instances.length; index++) {
  21939. var parsedInstance = parsedMesh.instances[index];
  21940. var instance = mesh.createInstance(parsedInstance.name);
  21941. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  21942. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  21943. if (parsedInstance.parentId) {
  21944. instance._waitingParentId = parsedInstance.parentId;
  21945. }
  21946. if (parsedInstance.rotationQuaternion) {
  21947. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  21948. }
  21949. else if (parsedInstance.rotation) {
  21950. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  21951. }
  21952. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  21953. instance.checkCollisions = mesh.checkCollisions;
  21954. if (parsedMesh.animations) {
  21955. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  21956. parsedAnimation = parsedMesh.animations[animationIndex];
  21957. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  21958. }
  21959. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  21960. }
  21961. }
  21962. }
  21963. return mesh;
  21964. };
  21965. /**
  21966. * Creates a ribbon mesh.
  21967. * Please consider using the same method from the MeshBuilder class instead.
  21968. * 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.
  21969. *
  21970. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  21971. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  21972. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  21973. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  21974. * 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.
  21975. * 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.
  21976. * 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
  21977. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21978. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21979. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21980. */
  21981. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  21982. return BABYLON.MeshBuilder.CreateRibbon(name, {
  21983. pathArray: pathArray,
  21984. closeArray: closeArray,
  21985. closePath: closePath,
  21986. offset: offset,
  21987. updatable: updatable,
  21988. sideOrientation: sideOrientation,
  21989. instance: instance
  21990. }, scene);
  21991. };
  21992. /**
  21993. * Creates a plane polygonal mesh. By default, this is a disc.
  21994. * Please consider using the same method from the MeshBuilder class instead.
  21995. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  21996. * 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.
  21997. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21998. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21999. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22000. */
  22001. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  22002. var options = {
  22003. radius: radius,
  22004. tessellation: tessellation,
  22005. sideOrientation: sideOrientation,
  22006. updatable: updatable
  22007. };
  22008. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  22009. };
  22010. /**
  22011. * Creates a box mesh.
  22012. * Please consider using the same method from the MeshBuilder class instead.
  22013. * The parameter `size` sets the size (float) of each box side (default 1).
  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.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  22019. var options = {
  22020. size: size,
  22021. sideOrientation: sideOrientation,
  22022. updatable: updatable
  22023. };
  22024. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  22025. };
  22026. /**
  22027. * Creates a sphere mesh.
  22028. * Please consider using the same method from the MeshBuilder class instead.
  22029. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  22030. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  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.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  22036. var options = {
  22037. segments: segments,
  22038. diameterX: diameter,
  22039. diameterY: diameter,
  22040. diameterZ: diameter,
  22041. sideOrientation: sideOrientation,
  22042. updatable: updatable
  22043. };
  22044. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  22045. };
  22046. /**
  22047. * Creates a cylinder or a cone mesh.
  22048. * Please consider using the same method from the MeshBuilder class instead.
  22049. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  22050. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  22051. * 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.
  22052. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  22053. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  22054. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22055. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22056. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22057. */
  22058. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  22059. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  22060. if (scene !== undefined) {
  22061. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  22062. updatable = scene;
  22063. }
  22064. scene = subdivisions;
  22065. subdivisions = 1;
  22066. }
  22067. var options = {
  22068. height: height,
  22069. diameterTop: diameterTop,
  22070. diameterBottom: diameterBottom,
  22071. tessellation: tessellation,
  22072. subdivisions: subdivisions,
  22073. sideOrientation: sideOrientation,
  22074. updatable: updatable
  22075. };
  22076. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  22077. };
  22078. // Torus (Code from SharpDX.org)
  22079. /**
  22080. * Creates a torus mesh.
  22081. * Please consider using the same method from the MeshBuilder class instead.
  22082. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  22083. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  22084. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  22085. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22086. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22087. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22088. */
  22089. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  22090. var options = {
  22091. diameter: diameter,
  22092. thickness: thickness,
  22093. tessellation: tessellation,
  22094. sideOrientation: sideOrientation,
  22095. updatable: updatable
  22096. };
  22097. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  22098. };
  22099. /**
  22100. * Creates a torus knot mesh.
  22101. * Please consider using the same method from the MeshBuilder class instead.
  22102. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  22103. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  22104. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  22105. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  22106. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22107. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22108. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22109. */
  22110. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  22111. var options = {
  22112. radius: radius,
  22113. tube: tube,
  22114. radialSegments: radialSegments,
  22115. tubularSegments: tubularSegments,
  22116. p: p,
  22117. q: q,
  22118. sideOrientation: sideOrientation,
  22119. updatable: updatable
  22120. };
  22121. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  22122. };
  22123. /**
  22124. * Creates a line mesh.
  22125. * Please consider using the same method from the MeshBuilder class instead.
  22126. * 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.
  22127. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  22128. * The parameter `points` is an array successive Vector3.
  22129. * 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
  22130. * When updating an instance, remember that only point positions can change, not the number of points.
  22131. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22132. */
  22133. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  22134. var options = {
  22135. points: points,
  22136. updatable: updatable,
  22137. instance: instance
  22138. };
  22139. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  22140. };
  22141. /**
  22142. * Creates a dashed line mesh.
  22143. * Please consider using the same method from the MeshBuilder class instead.
  22144. * 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.
  22145. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  22146. * The parameter `points` is an array successive Vector3.
  22147. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  22148. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  22149. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  22150. * 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
  22151. * When updating an instance, remember that only point positions can change, not the number of points.
  22152. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22153. */
  22154. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  22155. var options = {
  22156. points: points,
  22157. dashSize: dashSize,
  22158. gapSize: gapSize,
  22159. dashNb: dashNb,
  22160. updatable: updatable,
  22161. instance: instance
  22162. };
  22163. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  22164. };
  22165. /**
  22166. * Creates an extruded shape mesh.
  22167. * 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.
  22168. * Please consider using the same method from the MeshBuilder class instead.
  22169. *
  22170. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  22171. * 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
  22172. * extruded along the Z axis.
  22173. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  22174. * 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.
  22175. * The parameter `scale` (float, default 1) is the value to scale the shape.
  22176. * 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
  22177. * 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
  22178. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  22179. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22180. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22181. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22182. */
  22183. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  22184. var options = {
  22185. shape: shape,
  22186. path: path,
  22187. scale: scale,
  22188. rotation: rotation,
  22189. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  22190. sideOrientation: sideOrientation,
  22191. instance: instance,
  22192. updatable: updatable
  22193. };
  22194. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  22195. };
  22196. /**
  22197. * Creates an custom extruded shape mesh.
  22198. * 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.
  22199. * Please consider using the same method from the MeshBuilder class instead.
  22200. *
  22201. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  22202. * 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
  22203. * extruded along the Z axis.
  22204. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  22205. * 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
  22206. * and the distance of this point from the begining of the path :
  22207. * ```javascript
  22208. * var rotationFunction = function(i, distance) {
  22209. * // do things
  22210. * return rotationValue; }
  22211. * ```
  22212. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  22213. * 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
  22214. * and the distance of this point from the begining of the path :
  22215. * ```javascript
  22216. * var scaleFunction = function(i, distance) {
  22217. * // do things
  22218. * return scaleValue;}
  22219. * ```
  22220. * It must returns a float value that will be the scale value applied to the shape on each path point.
  22221. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  22222. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  22223. * 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
  22224. * 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
  22225. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  22226. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22227. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22228. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22229. */
  22230. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  22231. var options = {
  22232. shape: shape,
  22233. path: path,
  22234. scaleFunction: scaleFunction,
  22235. rotationFunction: rotationFunction,
  22236. ribbonCloseArray: ribbonCloseArray,
  22237. ribbonClosePath: ribbonClosePath,
  22238. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  22239. sideOrientation: sideOrientation,
  22240. instance: instance,
  22241. updatable: updatable
  22242. };
  22243. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  22244. };
  22245. /**
  22246. * Creates lathe mesh.
  22247. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  22248. * Please consider using the same method from the MeshBuilder class instead.
  22249. * 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
  22250. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  22251. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  22252. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  22253. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22254. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22255. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22256. */
  22257. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  22258. var options = {
  22259. shape: shape,
  22260. radius: radius,
  22261. tessellation: tessellation,
  22262. sideOrientation: sideOrientation,
  22263. updatable: updatable
  22264. };
  22265. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  22266. };
  22267. /**
  22268. * Creates a plane mesh.
  22269. * Please consider using the same method from the MeshBuilder class instead.
  22270. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  22271. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22272. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22273. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22274. */
  22275. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  22276. var options = {
  22277. size: size,
  22278. width: size,
  22279. height: size,
  22280. sideOrientation: sideOrientation,
  22281. updatable: updatable
  22282. };
  22283. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  22284. };
  22285. /**
  22286. * Creates a ground mesh.
  22287. * Please consider using the same method from the MeshBuilder class instead.
  22288. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  22289. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  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.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  22293. var options = {
  22294. width: width,
  22295. height: height,
  22296. subdivisions: subdivisions,
  22297. updatable: updatable
  22298. };
  22299. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  22300. };
  22301. /**
  22302. * Creates a tiled ground mesh.
  22303. * Please consider using the same method from the MeshBuilder class instead.
  22304. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  22305. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  22306. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  22307. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  22308. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  22309. * numbers of subdivisions on the ground width and height of each tile.
  22310. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22311. */
  22312. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  22313. var options = {
  22314. xmin: xmin,
  22315. zmin: zmin,
  22316. xmax: xmax,
  22317. zmax: zmax,
  22318. subdivisions: subdivisions,
  22319. precision: precision,
  22320. updatable: updatable
  22321. };
  22322. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  22323. };
  22324. /**
  22325. * Creates a ground mesh from a height map.
  22326. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  22327. * Please consider using the same method from the MeshBuilder class instead.
  22328. * The parameter `url` sets the URL of the height map image resource.
  22329. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  22330. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  22331. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  22332. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  22333. * 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).
  22334. * This function is passed the newly built mesh :
  22335. * ```javascript
  22336. * function(mesh) { // do things
  22337. * return; }
  22338. * ```
  22339. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22340. */
  22341. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  22342. var options = {
  22343. width: width,
  22344. height: height,
  22345. subdivisions: subdivisions,
  22346. minHeight: minHeight,
  22347. maxHeight: maxHeight,
  22348. updatable: updatable,
  22349. onReady: onReady
  22350. };
  22351. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  22352. };
  22353. /**
  22354. * Creates a tube mesh.
  22355. * 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.
  22356. * Please consider using the same method from the MeshBuilder class instead.
  22357. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  22358. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  22359. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  22360. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  22361. * 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.
  22362. * It must return a radius value (positive float) :
  22363. * ```javascript
  22364. * var radiusFunction = function(i, distance) {
  22365. * // do things
  22366. * return radius; }
  22367. * ```
  22368. * 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
  22369. * 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
  22370. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22371. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22372. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22373. */
  22374. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  22375. var options = {
  22376. path: path,
  22377. radius: radius,
  22378. tessellation: tessellation,
  22379. radiusFunction: radiusFunction,
  22380. arc: 1,
  22381. cap: cap,
  22382. updatable: updatable,
  22383. sideOrientation: sideOrientation,
  22384. instance: instance
  22385. };
  22386. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  22387. };
  22388. /**
  22389. * Creates a polyhedron mesh.
  22390. * Please consider using the same method from the MeshBuilder class instead.
  22391. * 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
  22392. * to choose the wanted type.
  22393. * The parameter `size` (positive float, default 1) sets the polygon size.
  22394. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  22395. * 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`.
  22396. * 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
  22397. * 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)`).
  22398. * 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
  22399. * 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.
  22400. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22401. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22402. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22403. */
  22404. Mesh.CreatePolyhedron = function (name, options, scene) {
  22405. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  22406. };
  22407. /**
  22408. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  22409. * Please consider using the same method from the MeshBuilder class instead.
  22410. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  22411. * 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`).
  22412. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  22413. * 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.
  22414. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22415. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22416. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22417. */
  22418. Mesh.CreateIcoSphere = function (name, options, scene) {
  22419. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  22420. };
  22421. /**
  22422. * Creates a decal mesh.
  22423. * Please consider using the same method from the MeshBuilder class instead.
  22424. * 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.
  22425. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  22426. * The parameter `normal` (Vector3, default Vector3.Up) sets the normal of the mesh where the decal is applied onto in World coordinates.
  22427. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  22428. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  22429. */
  22430. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  22431. var options = {
  22432. position: position,
  22433. normal: normal,
  22434. size: size,
  22435. angle: angle
  22436. };
  22437. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  22438. };
  22439. // Skeletons
  22440. /**
  22441. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  22442. */
  22443. Mesh.prototype.setPositionsForCPUSkinning = function () {
  22444. var source;
  22445. if (!this._sourcePositions) {
  22446. source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  22447. this._sourcePositions = new Float32Array(source);
  22448. if (!this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable()) {
  22449. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  22450. }
  22451. }
  22452. return this._sourcePositions;
  22453. };
  22454. /**
  22455. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  22456. */
  22457. Mesh.prototype.setNormalsForCPUSkinning = function () {
  22458. var source;
  22459. if (!this._sourceNormals) {
  22460. source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  22461. this._sourceNormals = new Float32Array(source);
  22462. if (!this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable()) {
  22463. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  22464. }
  22465. }
  22466. return this._sourceNormals;
  22467. };
  22468. /**
  22469. * Update the vertex buffers by applying transformation from the bones
  22470. * @param {skeleton} skeleton to apply
  22471. */
  22472. Mesh.prototype.applySkeleton = function (skeleton) {
  22473. if (!this.geometry) {
  22474. return;
  22475. }
  22476. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  22477. return;
  22478. }
  22479. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  22480. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  22481. return this;
  22482. }
  22483. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  22484. return this;
  22485. }
  22486. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  22487. return this;
  22488. }
  22489. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  22490. return this;
  22491. }
  22492. if (!this._sourcePositions) {
  22493. var submeshes = this.subMeshes.slice();
  22494. this.setPositionsForCPUSkinning();
  22495. this.subMeshes = submeshes;
  22496. }
  22497. if (!this._sourceNormals) {
  22498. this.setNormalsForCPUSkinning();
  22499. }
  22500. // positionsData checks for not being Float32Array will only pass at most once
  22501. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  22502. if (!(positionsData instanceof Float32Array)) {
  22503. positionsData = new Float32Array(positionsData);
  22504. }
  22505. // normalsData checks for not being Float32Array will only pass at most once
  22506. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  22507. if (!(normalsData instanceof Float32Array)) {
  22508. normalsData = new Float32Array(normalsData);
  22509. }
  22510. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  22511. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  22512. var needExtras = this.numBoneInfluencers > 4;
  22513. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  22514. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  22515. var skeletonMatrices = skeleton.getTransformMatrices(this);
  22516. var tempVector3 = BABYLON.Vector3.Zero();
  22517. var finalMatrix = new BABYLON.Matrix();
  22518. var tempMatrix = new BABYLON.Matrix();
  22519. var matWeightIdx = 0;
  22520. var inf;
  22521. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  22522. var weight;
  22523. for (inf = 0; inf < 4; inf++) {
  22524. weight = matricesWeightsData[matWeightIdx + inf];
  22525. if (weight > 0) {
  22526. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[matWeightIdx + inf] * 16, weight, tempMatrix);
  22527. finalMatrix.addToSelf(tempMatrix);
  22528. }
  22529. else
  22530. break;
  22531. }
  22532. if (needExtras) {
  22533. for (inf = 0; inf < 4; inf++) {
  22534. weight = matricesWeightsExtraData[matWeightIdx + inf];
  22535. if (weight > 0) {
  22536. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesExtraData[matWeightIdx + inf] * 16, weight, tempMatrix);
  22537. finalMatrix.addToSelf(tempMatrix);
  22538. }
  22539. else
  22540. break;
  22541. }
  22542. }
  22543. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  22544. tempVector3.toArray(positionsData, index);
  22545. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  22546. tempVector3.toArray(normalsData, index);
  22547. finalMatrix.reset();
  22548. }
  22549. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  22550. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  22551. return this;
  22552. };
  22553. // Tools
  22554. /**
  22555. * Returns an object `{min:` Vector3`, max:` Vector3`}`
  22556. * This min and max Vector3 are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system
  22557. */
  22558. Mesh.MinMax = function (meshes) {
  22559. var minVector = null;
  22560. var maxVector = null;
  22561. meshes.forEach(function (mesh, index, array) {
  22562. var boundingBox = mesh.getBoundingInfo().boundingBox;
  22563. if (!minVector) {
  22564. minVector = boundingBox.minimumWorld;
  22565. maxVector = boundingBox.maximumWorld;
  22566. }
  22567. else {
  22568. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  22569. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  22570. }
  22571. });
  22572. return {
  22573. min: minVector,
  22574. max: maxVector
  22575. };
  22576. };
  22577. /**
  22578. * Returns a Vector3, the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array.
  22579. */
  22580. Mesh.Center = function (meshesOrMinMaxVector) {
  22581. var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? BABYLON.Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
  22582. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  22583. };
  22584. /**
  22585. * Merge the array of meshes into a single mesh for performance reasons.
  22586. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  22587. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  22588. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  22589. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  22590. */
  22591. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass) {
  22592. if (disposeSource === void 0) { disposeSource = true; }
  22593. var index;
  22594. if (!allow32BitsIndices) {
  22595. var totalVertices = 0;
  22596. // Counting vertices
  22597. for (index = 0; index < meshes.length; index++) {
  22598. if (meshes[index]) {
  22599. totalVertices += meshes[index].getTotalVertices();
  22600. if (totalVertices > 65536) {
  22601. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  22602. return null;
  22603. }
  22604. }
  22605. }
  22606. }
  22607. // Merge
  22608. var vertexData;
  22609. var otherVertexData;
  22610. var source;
  22611. for (index = 0; index < meshes.length; index++) {
  22612. if (meshes[index]) {
  22613. meshes[index].computeWorldMatrix(true);
  22614. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  22615. otherVertexData.transform(meshes[index].getWorldMatrix());
  22616. if (vertexData) {
  22617. vertexData.merge(otherVertexData);
  22618. }
  22619. else {
  22620. vertexData = otherVertexData;
  22621. source = meshes[index];
  22622. }
  22623. }
  22624. }
  22625. if (!meshSubclass) {
  22626. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  22627. }
  22628. vertexData.applyToMesh(meshSubclass);
  22629. // Setting properties
  22630. meshSubclass.material = source.material;
  22631. meshSubclass.checkCollisions = source.checkCollisions;
  22632. // Cleaning
  22633. if (disposeSource) {
  22634. for (index = 0; index < meshes.length; index++) {
  22635. if (meshes[index]) {
  22636. meshes[index].dispose();
  22637. }
  22638. }
  22639. }
  22640. return meshSubclass;
  22641. };
  22642. return Mesh;
  22643. }(BABYLON.AbstractMesh));
  22644. // Consts
  22645. Mesh._FRONTSIDE = 0;
  22646. Mesh._BACKSIDE = 1;
  22647. Mesh._DOUBLESIDE = 2;
  22648. Mesh._DEFAULTSIDE = 0;
  22649. Mesh._NO_CAP = 0;
  22650. Mesh._CAP_START = 1;
  22651. Mesh._CAP_END = 2;
  22652. Mesh._CAP_ALL = 3;
  22653. BABYLON.Mesh = Mesh;
  22654. })(BABYLON || (BABYLON = {}));
  22655. //# sourceMappingURL=babylon.mesh.js.map
  22656. var BABYLON;
  22657. (function (BABYLON) {
  22658. var SubMesh = (function () {
  22659. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  22660. if (createBoundingBox === void 0) { createBoundingBox = true; }
  22661. this.materialIndex = materialIndex;
  22662. this.verticesStart = verticesStart;
  22663. this.verticesCount = verticesCount;
  22664. this.indexStart = indexStart;
  22665. this.indexCount = indexCount;
  22666. this._renderId = 0;
  22667. this._mesh = mesh;
  22668. this._renderingMesh = renderingMesh || mesh;
  22669. mesh.subMeshes.push(this);
  22670. this._trianglePlanes = [];
  22671. this._id = mesh.subMeshes.length - 1;
  22672. if (createBoundingBox) {
  22673. this.refreshBoundingInfo();
  22674. mesh.computeWorldMatrix(true);
  22675. }
  22676. }
  22677. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  22678. get: function () {
  22679. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  22680. },
  22681. enumerable: true,
  22682. configurable: true
  22683. });
  22684. SubMesh.prototype.getBoundingInfo = function () {
  22685. if (this.IsGlobal) {
  22686. return this._mesh.getBoundingInfo();
  22687. }
  22688. return this._boundingInfo;
  22689. };
  22690. SubMesh.prototype.setBoundingInfo = function (boundingInfo) {
  22691. this._boundingInfo = boundingInfo;
  22692. };
  22693. SubMesh.prototype.getMesh = function () {
  22694. return this._mesh;
  22695. };
  22696. SubMesh.prototype.getRenderingMesh = function () {
  22697. return this._renderingMesh;
  22698. };
  22699. SubMesh.prototype.getMaterial = function () {
  22700. var rootMaterial = this._renderingMesh.material;
  22701. if (rootMaterial && rootMaterial instanceof BABYLON.MultiMaterial) {
  22702. var multiMaterial = rootMaterial;
  22703. return multiMaterial.getSubMaterial(this.materialIndex);
  22704. }
  22705. if (!rootMaterial) {
  22706. return this._mesh.getScene().defaultMaterial;
  22707. }
  22708. return rootMaterial;
  22709. };
  22710. // Methods
  22711. SubMesh.prototype.refreshBoundingInfo = function () {
  22712. this._lastColliderWorldVertices = null;
  22713. if (this.IsGlobal) {
  22714. return;
  22715. }
  22716. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  22717. if (!data) {
  22718. this._boundingInfo = this._mesh._boundingInfo;
  22719. return;
  22720. }
  22721. var indices = this._renderingMesh.getIndices();
  22722. var extend;
  22723. //is this the only submesh?
  22724. if (this.indexStart === 0 && this.indexCount === indices.length) {
  22725. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  22726. extend = { minimum: this._renderingMesh.getBoundingInfo().minimum.clone(), maximum: this._renderingMesh.getBoundingInfo().maximum.clone() };
  22727. }
  22728. else {
  22729. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  22730. }
  22731. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  22732. };
  22733. SubMesh.prototype._checkCollision = function (collider) {
  22734. return this.getBoundingInfo()._checkCollision(collider);
  22735. };
  22736. SubMesh.prototype.updateBoundingInfo = function (world) {
  22737. if (!this.getBoundingInfo()) {
  22738. this.refreshBoundingInfo();
  22739. }
  22740. this.getBoundingInfo().update(world);
  22741. };
  22742. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  22743. return this.getBoundingInfo().isInFrustum(frustumPlanes);
  22744. };
  22745. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  22746. return this.getBoundingInfo().isCompletelyInFrustum(frustumPlanes);
  22747. };
  22748. SubMesh.prototype.render = function (enableAlphaMode) {
  22749. this._renderingMesh.render(this, enableAlphaMode);
  22750. };
  22751. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  22752. if (!this._linesIndexBuffer) {
  22753. var linesIndices = [];
  22754. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  22755. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  22756. }
  22757. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  22758. this.linesIndexCount = linesIndices.length;
  22759. }
  22760. return this._linesIndexBuffer;
  22761. };
  22762. SubMesh.prototype.canIntersects = function (ray) {
  22763. return ray.intersectsBox(this.getBoundingInfo().boundingBox);
  22764. };
  22765. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  22766. var intersectInfo = null;
  22767. // LineMesh first as it's also a Mesh...
  22768. if (this._mesh instanceof BABYLON.LinesMesh) {
  22769. var lineMesh = this._mesh;
  22770. // Line test
  22771. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  22772. var p0 = positions[indices[index]];
  22773. var p1 = positions[indices[index + 1]];
  22774. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  22775. if (length < 0) {
  22776. continue;
  22777. }
  22778. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  22779. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  22780. if (fastCheck) {
  22781. break;
  22782. }
  22783. }
  22784. }
  22785. }
  22786. else {
  22787. // Triangles test
  22788. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  22789. var p0 = positions[indices[index]];
  22790. var p1 = positions[indices[index + 1]];
  22791. var p2 = positions[indices[index + 2]];
  22792. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  22793. if (currentIntersectInfo) {
  22794. if (currentIntersectInfo.distance < 0) {
  22795. continue;
  22796. }
  22797. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  22798. intersectInfo = currentIntersectInfo;
  22799. intersectInfo.faceId = index / 3;
  22800. if (fastCheck) {
  22801. break;
  22802. }
  22803. }
  22804. }
  22805. }
  22806. }
  22807. return intersectInfo;
  22808. };
  22809. // Clone
  22810. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  22811. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  22812. if (!this.IsGlobal) {
  22813. result._boundingInfo = new BABYLON.BoundingInfo(this.getBoundingInfo().minimum, this.getBoundingInfo().maximum);
  22814. }
  22815. return result;
  22816. };
  22817. // Dispose
  22818. SubMesh.prototype.dispose = function () {
  22819. if (this._linesIndexBuffer) {
  22820. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  22821. this._linesIndexBuffer = null;
  22822. }
  22823. // Remove from mesh
  22824. var index = this._mesh.subMeshes.indexOf(this);
  22825. this._mesh.subMeshes.splice(index, 1);
  22826. };
  22827. // Statics
  22828. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  22829. var minVertexIndex = Number.MAX_VALUE;
  22830. var maxVertexIndex = -Number.MAX_VALUE;
  22831. renderingMesh = renderingMesh || mesh;
  22832. var indices = renderingMesh.getIndices();
  22833. for (var index = startIndex; index < startIndex + indexCount; index++) {
  22834. var vertexIndex = indices[index];
  22835. if (vertexIndex < minVertexIndex)
  22836. minVertexIndex = vertexIndex;
  22837. if (vertexIndex > maxVertexIndex)
  22838. maxVertexIndex = vertexIndex;
  22839. }
  22840. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  22841. };
  22842. return SubMesh;
  22843. }());
  22844. BABYLON.SubMesh = SubMesh;
  22845. })(BABYLON || (BABYLON = {}));
  22846. //# sourceMappingURL=babylon.subMesh.js.map
  22847. var BABYLON;
  22848. (function (BABYLON) {
  22849. var MeshBuilder = (function () {
  22850. function MeshBuilder() {
  22851. }
  22852. MeshBuilder.updateSideOrientation = function (orientation, scene) {
  22853. if (orientation == BABYLON.Mesh.DOUBLESIDE) {
  22854. return BABYLON.Mesh.DOUBLESIDE;
  22855. }
  22856. if (orientation === undefined || orientation === null) {
  22857. return BABYLON.Mesh.FRONTSIDE;
  22858. }
  22859. return orientation;
  22860. };
  22861. /**
  22862. * Creates a box mesh.
  22863. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  22864. * The parameter `size` sets the size (float) of each box side (default 1).
  22865. * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`).
  22866. * 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).
  22867. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  22868. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22869. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22870. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22871. */
  22872. MeshBuilder.CreateBox = function (name, options, scene) {
  22873. var box = new BABYLON.Mesh(name, scene);
  22874. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  22875. box.sideOrientation = options.sideOrientation;
  22876. var vertexData = BABYLON.VertexData.CreateBox(options);
  22877. vertexData.applyToMesh(box, options.updatable);
  22878. return box;
  22879. };
  22880. /**
  22881. * Creates a sphere mesh.
  22882. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  22883. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  22884. * 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`).
  22885. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  22886. * 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
  22887. * 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).
  22888. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22889. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22890. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22891. */
  22892. MeshBuilder.CreateSphere = function (name, options, scene) {
  22893. var sphere = new BABYLON.Mesh(name, scene);
  22894. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  22895. sphere.sideOrientation = options.sideOrientation;
  22896. var vertexData = BABYLON.VertexData.CreateSphere(options);
  22897. vertexData.applyToMesh(sphere, options.updatable);
  22898. return sphere;
  22899. };
  22900. /**
  22901. * Creates a plane polygonal mesh. By default, this is a disc.
  22902. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#disc
  22903. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  22904. * 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.
  22905. * 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
  22906. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22907. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22908. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22909. */
  22910. MeshBuilder.CreateDisc = function (name, options, scene) {
  22911. var disc = new BABYLON.Mesh(name, scene);
  22912. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  22913. disc.sideOrientation = options.sideOrientation;
  22914. var vertexData = BABYLON.VertexData.CreateDisc(options);
  22915. vertexData.applyToMesh(disc, options.updatable);
  22916. return disc;
  22917. };
  22918. /**
  22919. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  22920. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#icosphere
  22921. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  22922. * 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`).
  22923. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  22924. * 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.
  22925. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22926. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22927. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22928. */
  22929. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  22930. var sphere = new BABYLON.Mesh(name, scene);
  22931. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  22932. sphere.sideOrientation = options.sideOrientation;
  22933. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  22934. vertexData.applyToMesh(sphere, options.updatable);
  22935. return sphere;
  22936. };
  22937. ;
  22938. /**
  22939. * Creates a ribbon mesh.
  22940. * 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.
  22941. *
  22942. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  22943. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  22944. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  22945. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  22946. * 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.
  22947. * 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.
  22948. * 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
  22949. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22950. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22951. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  22952. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22953. */
  22954. MeshBuilder.CreateRibbon = function (name, options, scene) {
  22955. var pathArray = options.pathArray;
  22956. var closeArray = options.closeArray;
  22957. var closePath = options.closePath;
  22958. var offset = options.offset;
  22959. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  22960. var instance = options.instance;
  22961. var updatable = options.updatable;
  22962. if (instance) {
  22963. // positionFunction : ribbon case
  22964. // only pathArray and sideOrientation parameters are taken into account for positions update
  22965. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum
  22966. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]);
  22967. var positionFunction = function (positions) {
  22968. var minlg = pathArray[0].length;
  22969. var i = 0;
  22970. var ns = (instance.sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  22971. for (var si = 1; si <= ns; si++) {
  22972. for (var p = 0; p < pathArray.length; p++) {
  22973. var path = pathArray[p];
  22974. var l = path.length;
  22975. minlg = (minlg < l) ? minlg : l;
  22976. var j = 0;
  22977. while (j < minlg) {
  22978. positions[i] = path[j].x;
  22979. positions[i + 1] = path[j].y;
  22980. positions[i + 2] = path[j].z;
  22981. if (path[j].x < BABYLON.Tmp.Vector3[0].x) {
  22982. BABYLON.Tmp.Vector3[0].x = path[j].x;
  22983. }
  22984. if (path[j].x > BABYLON.Tmp.Vector3[1].x) {
  22985. BABYLON.Tmp.Vector3[1].x = path[j].x;
  22986. }
  22987. if (path[j].y < BABYLON.Tmp.Vector3[0].y) {
  22988. BABYLON.Tmp.Vector3[0].y = path[j].y;
  22989. }
  22990. if (path[j].y > BABYLON.Tmp.Vector3[1].y) {
  22991. BABYLON.Tmp.Vector3[1].y = path[j].y;
  22992. }
  22993. if (path[j].z < BABYLON.Tmp.Vector3[0].z) {
  22994. BABYLON.Tmp.Vector3[0].z = path[j].z;
  22995. }
  22996. if (path[j].z > BABYLON.Tmp.Vector3[1].z) {
  22997. BABYLON.Tmp.Vector3[1].z = path[j].z;
  22998. }
  22999. j++;
  23000. i += 3;
  23001. }
  23002. if (instance._closePath) {
  23003. positions[i] = path[0].x;
  23004. positions[i + 1] = path[0].y;
  23005. positions[i + 2] = path[0].z;
  23006. i += 3;
  23007. }
  23008. }
  23009. }
  23010. };
  23011. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  23012. positionFunction(positions);
  23013. instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Vector3[1]);
  23014. instance._boundingInfo.update(instance._worldMatrix);
  23015. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  23016. if (!instance.areNormalsFrozen || instance.isFacetDataEnabled) {
  23017. var indices = instance.getIndices();
  23018. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  23019. var params = instance.isFacetDataEnabled ? instance.getFacetDataParameters() : null;
  23020. BABYLON.VertexData.ComputeNormals(positions, indices, normals, params);
  23021. if (instance._closePath) {
  23022. var indexFirst = 0;
  23023. var indexLast = 0;
  23024. for (var p = 0; p < pathArray.length; p++) {
  23025. indexFirst = instance._idx[p] * 3;
  23026. if (p + 1 < pathArray.length) {
  23027. indexLast = (instance._idx[p + 1] - 1) * 3;
  23028. }
  23029. else {
  23030. indexLast = normals.length - 3;
  23031. }
  23032. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  23033. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  23034. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  23035. normals[indexLast] = normals[indexFirst];
  23036. normals[indexLast + 1] = normals[indexFirst + 1];
  23037. normals[indexLast + 2] = normals[indexFirst + 2];
  23038. }
  23039. }
  23040. if (!(instance.areNormalsFrozen)) {
  23041. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  23042. }
  23043. }
  23044. return instance;
  23045. }
  23046. else {
  23047. var ribbon = new BABYLON.Mesh(name, scene);
  23048. ribbon.sideOrientation = sideOrientation;
  23049. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  23050. if (closePath) {
  23051. ribbon._idx = vertexData._idx;
  23052. }
  23053. ribbon._closePath = closePath;
  23054. ribbon._closeArray = closeArray;
  23055. vertexData.applyToMesh(ribbon, updatable);
  23056. return ribbon;
  23057. }
  23058. };
  23059. /**
  23060. * Creates a cylinder or a cone mesh.
  23061. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  23062. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  23063. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  23064. * 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.
  23065. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  23066. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  23067. * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  23068. * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  23069. * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  23070. * 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).
  23071. * 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
  23072. * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  23073. * 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
  23074. * 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.
  23075. * If `enclose` is false, a ring surface is one element.
  23076. * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  23077. * 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
  23078. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  23079. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  23080. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23081. */
  23082. MeshBuilder.CreateCylinder = function (name, options, scene) {
  23083. var cylinder = new BABYLON.Mesh(name, scene);
  23084. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  23085. cylinder.sideOrientation = options.sideOrientation;
  23086. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  23087. vertexData.applyToMesh(cylinder, options.updatable);
  23088. return cylinder;
  23089. };
  23090. /**
  23091. * Creates a torus mesh.
  23092. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  23093. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  23094. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  23095. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  23096. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  23097. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  23098. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23099. */
  23100. MeshBuilder.CreateTorus = function (name, options, scene) {
  23101. var torus = new BABYLON.Mesh(name, scene);
  23102. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  23103. torus.sideOrientation = options.sideOrientation;
  23104. var vertexData = BABYLON.VertexData.CreateTorus(options);
  23105. vertexData.applyToMesh(torus, options.updatable);
  23106. return torus;
  23107. };
  23108. /**
  23109. * Creates a torus knot mesh.
  23110. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  23111. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  23112. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  23113. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  23114. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  23115. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  23116. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  23117. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23118. */
  23119. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  23120. var torusKnot = new BABYLON.Mesh(name, scene);
  23121. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  23122. torusKnot.sideOrientation = options.sideOrientation;
  23123. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  23124. vertexData.applyToMesh(torusKnot, options.updatable);
  23125. return torusKnot;
  23126. };
  23127. /**
  23128. * Creates a line system mesh.
  23129. * A line system is a pool of many lines gathered in a single mesh.
  23130. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#linesystem
  23131. * 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.
  23132. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function.
  23133. * The parameter `lines` is an array of lines, each line being an array of successive Vector3.
  23134. * 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
  23135. * 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
  23136. * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines.
  23137. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23138. */
  23139. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  23140. var instance = options.instance;
  23141. var lines = options.lines;
  23142. if (instance) {
  23143. var positionFunction = function (positions) {
  23144. var i = 0;
  23145. for (var l = 0; l < lines.length; l++) {
  23146. var points = lines[l];
  23147. for (var p = 0; p < points.length; p++) {
  23148. positions[i] = points[p].x;
  23149. positions[i + 1] = points[p].y;
  23150. positions[i + 2] = points[p].z;
  23151. i += 3;
  23152. }
  23153. }
  23154. };
  23155. instance.updateMeshPositions(positionFunction, false);
  23156. return instance;
  23157. }
  23158. // line system creation
  23159. var lineSystem = new BABYLON.LinesMesh(name, scene);
  23160. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  23161. vertexData.applyToMesh(lineSystem, options.updatable);
  23162. return lineSystem;
  23163. };
  23164. /**
  23165. * Creates a line mesh.
  23166. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lines
  23167. * 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.
  23168. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  23169. * The parameter `points` is an array successive Vector3.
  23170. * 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
  23171. * When updating an instance, remember that only point positions can change, not the number of points.
  23172. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23173. */
  23174. MeshBuilder.CreateLines = function (name, options, scene) {
  23175. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance }, scene);
  23176. return lines;
  23177. };
  23178. /**
  23179. * Creates a dashed line mesh.
  23180. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#dashed-lines
  23181. * 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.
  23182. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  23183. * The parameter `points` is an array successive Vector3.
  23184. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  23185. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  23186. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  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.CreateDashedLines = function (name, options, scene) {
  23192. var points = options.points;
  23193. var instance = options.instance;
  23194. var gapSize = options.gapSize;
  23195. var dashNb = options.dashNb;
  23196. var dashSize = options.dashSize;
  23197. if (instance) {
  23198. var positionFunction = function (positions) {
  23199. var curvect = BABYLON.Vector3.Zero();
  23200. var nbSeg = positions.length / 6;
  23201. var lg = 0;
  23202. var nb = 0;
  23203. var shft = 0;
  23204. var dashshft = 0;
  23205. var curshft = 0;
  23206. var p = 0;
  23207. var i = 0;
  23208. var j = 0;
  23209. for (i = 0; i < points.length - 1; i++) {
  23210. points[i + 1].subtractToRef(points[i], curvect);
  23211. lg += curvect.length();
  23212. }
  23213. shft = lg / nbSeg;
  23214. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  23215. for (i = 0; i < points.length - 1; i++) {
  23216. points[i + 1].subtractToRef(points[i], curvect);
  23217. nb = Math.floor(curvect.length() / shft);
  23218. curvect.normalize();
  23219. j = 0;
  23220. while (j < nb && p < positions.length) {
  23221. curshft = shft * j;
  23222. positions[p] = points[i].x + curshft * curvect.x;
  23223. positions[p + 1] = points[i].y + curshft * curvect.y;
  23224. positions[p + 2] = points[i].z + curshft * curvect.z;
  23225. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  23226. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  23227. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  23228. p += 6;
  23229. j++;
  23230. }
  23231. }
  23232. while (p < positions.length) {
  23233. positions[p] = points[i].x;
  23234. positions[p + 1] = points[i].y;
  23235. positions[p + 2] = points[i].z;
  23236. p += 3;
  23237. }
  23238. };
  23239. instance.updateMeshPositions(positionFunction, false);
  23240. return instance;
  23241. }
  23242. // dashed lines creation
  23243. var dashedLines = new BABYLON.LinesMesh(name, scene);
  23244. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  23245. vertexData.applyToMesh(dashedLines, options.updatable);
  23246. dashedLines.dashSize = dashSize;
  23247. dashedLines.gapSize = gapSize;
  23248. return dashedLines;
  23249. };
  23250. /**
  23251. * Creates an extruded shape mesh.
  23252. * 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.
  23253. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#extruded-shapes
  23254. *
  23255. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  23256. * 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
  23257. * extruded along the Z axis.
  23258. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  23259. * 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.
  23260. * The parameter `scale` (float, default 1) is the value to scale the shape.
  23261. * 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
  23262. * 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
  23263. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  23264. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  23265. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  23266. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  23267. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23268. */
  23269. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  23270. var path = options.path;
  23271. var shape = options.shape;
  23272. var scale = options.scale || 1;
  23273. var rotation = options.rotation || 0;
  23274. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  23275. var updatable = options.updatable;
  23276. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  23277. var instance = options.instance;
  23278. var invertUV = options.invertUV || false;
  23279. return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, scale, rotation, null, null, false, false, cap, false, scene, updatable, sideOrientation, instance, invertUV);
  23280. };
  23281. /**
  23282. * Creates an custom extruded shape mesh.
  23283. * 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.
  23284. * tuto :http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#custom-extruded-shapes
  23285. *
  23286. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  23287. * 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
  23288. * extruded along the Z axis.
  23289. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  23290. * 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
  23291. * and the distance of this point from the begining of the path :
  23292. * ```javascript
  23293. * var rotationFunction = function(i, distance) {
  23294. * // do things
  23295. * return rotationValue; }
  23296. * ```
  23297. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  23298. * 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
  23299. * and the distance of this point from the begining of the path :
  23300. * ```javascript
  23301. * var scaleFunction = function(i, distance) {
  23302. * // do things
  23303. * return scaleValue;}
  23304. * ```
  23305. * It must returns a float value that will be the scale value applied to the shape on each path point.
  23306. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  23307. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  23308. * 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
  23309. * 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
  23310. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  23311. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  23312. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  23313. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  23314. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23315. */
  23316. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  23317. var path = options.path;
  23318. var shape = options.shape;
  23319. var scaleFunction = options.scaleFunction || (function () { return 1; });
  23320. var rotationFunction = options.rotationFunction || (function () { return 0; });
  23321. var ribbonCloseArray = options.ribbonCloseArray || false;
  23322. var ribbonClosePath = options.ribbonClosePath || false;
  23323. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  23324. var updatable = options.updatable;
  23325. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  23326. var instance = options.instance;
  23327. var invertUV = options.invertUV || false;
  23328. return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, null, null, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, true, scene, updatable, sideOrientation, instance, invertUV);
  23329. };
  23330. /**
  23331. * Creates lathe mesh.
  23332. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  23333. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lathe
  23334. *
  23335. * 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
  23336. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  23337. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  23338. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  23339. * 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.
  23340. * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc".
  23341. * 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
  23342. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  23343. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  23344. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  23345. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23346. */
  23347. MeshBuilder.CreateLathe = function (name, options, scene) {
  23348. var arc = options.arc ? ((options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc) : 1.0;
  23349. var closed = (options.closed === undefined) ? true : options.closed;
  23350. var shape = options.shape;
  23351. var radius = options.radius || 1;
  23352. var tessellation = options.tessellation || 64;
  23353. var updatable = options.updatable;
  23354. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  23355. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  23356. var pi2 = Math.PI * 2;
  23357. var paths = new Array();
  23358. var invertUV = options.invertUV || false;
  23359. var i = 0;
  23360. var p = 0;
  23361. var step = pi2 / tessellation * arc;
  23362. var rotated;
  23363. var path = new Array();
  23364. ;
  23365. for (i = 0; i <= tessellation; i++) {
  23366. var path = [];
  23367. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  23368. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  23369. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  23370. }
  23371. for (p = 0; p < shape.length; p++) {
  23372. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  23373. path.push(rotated);
  23374. }
  23375. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  23376. 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));
  23377. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  23378. }
  23379. paths.push(path);
  23380. }
  23381. // lathe ribbon
  23382. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV }, scene);
  23383. return lathe;
  23384. };
  23385. /**
  23386. * Creates a plane mesh.
  23387. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  23388. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  23389. * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`).
  23390. * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane.
  23391. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  23392. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  23393. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23394. */
  23395. MeshBuilder.CreatePlane = function (name, options, scene) {
  23396. var plane = new BABYLON.Mesh(name, scene);
  23397. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  23398. plane.sideOrientation = options.sideOrientation;
  23399. var vertexData = BABYLON.VertexData.CreatePlane(options);
  23400. vertexData.applyToMesh(plane, options.updatable);
  23401. if (options.sourcePlane) {
  23402. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  23403. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  23404. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  23405. plane.rotate(vectorProduct, product);
  23406. }
  23407. return plane;
  23408. };
  23409. /**
  23410. * Creates a ground mesh.
  23411. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  23412. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  23413. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  23414. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23415. */
  23416. MeshBuilder.CreateGround = function (name, options, scene) {
  23417. var ground = new BABYLON.GroundMesh(name, scene);
  23418. ground._setReady(false);
  23419. ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  23420. ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  23421. ground._width = options.width || 1;
  23422. ground._height = options.height || 1;
  23423. ground._maxX = ground._width / 2;
  23424. ground._maxZ = ground._height / 2;
  23425. ground._minX = -ground._maxX;
  23426. ground._minZ = -ground._maxZ;
  23427. var vertexData = BABYLON.VertexData.CreateGround(options);
  23428. vertexData.applyToMesh(ground, options.updatable);
  23429. ground._setReady(true);
  23430. return ground;
  23431. };
  23432. /**
  23433. * Creates a tiled ground mesh.
  23434. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  23435. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  23436. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  23437. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  23438. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  23439. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  23440. * numbers of subdivisions on the ground width and height of each tile.
  23441. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23442. */
  23443. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  23444. var tiledGround = new BABYLON.Mesh(name, scene);
  23445. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  23446. vertexData.applyToMesh(tiledGround, options.updatable);
  23447. return tiledGround;
  23448. };
  23449. /**
  23450. * Creates a ground mesh from a height map.
  23451. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  23452. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  23453. * The parameter `url` sets the URL of the height map image resource.
  23454. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  23455. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  23456. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  23457. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  23458. * 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).
  23459. * This function is passed the newly built mesh :
  23460. * ```javascript
  23461. * function(mesh) { // do things
  23462. * return; }
  23463. * ```
  23464. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23465. */
  23466. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  23467. var width = options.width || 10.0;
  23468. var height = options.height || 10.0;
  23469. var subdivisions = options.subdivisions || 1 | 0;
  23470. var minHeight = options.minHeight || 0.0;
  23471. var maxHeight = options.maxHeight || 10.0;
  23472. var updatable = options.updatable;
  23473. var onReady = options.onReady;
  23474. var ground = new BABYLON.GroundMesh(name, scene);
  23475. ground._subdivisionsX = subdivisions;
  23476. ground._subdivisionsY = subdivisions;
  23477. ground._width = width;
  23478. ground._height = height;
  23479. ground._maxX = ground._width / 2.0;
  23480. ground._maxZ = ground._height / 2.0;
  23481. ground._minX = -ground._maxX;
  23482. ground._minZ = -ground._maxZ;
  23483. ground._setReady(false);
  23484. var onload = function (img) {
  23485. // Getting height map data
  23486. var canvas = document.createElement("canvas");
  23487. var context = canvas.getContext("2d");
  23488. var bufferWidth = img.width;
  23489. var bufferHeight = img.height;
  23490. canvas.width = bufferWidth;
  23491. canvas.height = bufferHeight;
  23492. context.drawImage(img, 0, 0);
  23493. // Create VertexData from map data
  23494. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  23495. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  23496. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  23497. width: width, height: height,
  23498. subdivisions: subdivisions,
  23499. minHeight: minHeight, maxHeight: maxHeight,
  23500. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  23501. });
  23502. vertexData.applyToMesh(ground, updatable);
  23503. ground._setReady(true);
  23504. //execute ready callback, if set
  23505. if (onReady) {
  23506. onReady(ground);
  23507. }
  23508. };
  23509. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  23510. return ground;
  23511. };
  23512. /**
  23513. * Creates a tube mesh.
  23514. * 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.
  23515. *
  23516. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  23517. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  23518. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  23519. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  23520. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  23521. * 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.
  23522. * It must return a radius value (positive float) :
  23523. * ```javascript
  23524. * var radiusFunction = function(i, distance) {
  23525. * // do things
  23526. * return radius; }
  23527. * ```
  23528. * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc.
  23529. * 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
  23530. * 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
  23531. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  23532. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  23533. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  23534. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23535. */
  23536. MeshBuilder.CreateTube = function (name, options, scene) {
  23537. var path = options.path;
  23538. var radius = options.radius || 1.0;
  23539. var tessellation = options.tessellation || 64 | 0;
  23540. var radiusFunction = options.radiusFunction;
  23541. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  23542. var invertUV = options.invertUV || false;
  23543. var updatable = options.updatable;
  23544. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  23545. var instance = options.instance;
  23546. options.arc = (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  23547. // tube geometry
  23548. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  23549. var tangents = path3D.getTangents();
  23550. var normals = path3D.getNormals();
  23551. var distances = path3D.getDistances();
  23552. var pi2 = Math.PI * 2;
  23553. var step = pi2 / tessellation * arc;
  23554. var returnRadius = function () { return radius; };
  23555. var radiusFunctionFinal = radiusFunction || returnRadius;
  23556. var circlePath;
  23557. var rad;
  23558. var normal;
  23559. var rotated;
  23560. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  23561. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  23562. for (var i = 0; i < path.length; i++) {
  23563. rad = radiusFunctionFinal(i, distances[i]); // current radius
  23564. circlePath = Array(); // current circle array
  23565. normal = normals[i]; // current normal
  23566. for (var t = 0; t < tessellation; t++) {
  23567. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  23568. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  23569. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  23570. rotated.scaleInPlace(rad).addInPlace(path[i]);
  23571. circlePath[t] = rotated;
  23572. }
  23573. circlePaths[index] = circlePath;
  23574. index++;
  23575. }
  23576. // cap
  23577. var capPath = function (nbPoints, pathIndex) {
  23578. var pointCap = Array();
  23579. for (var i = 0; i < nbPoints; i++) {
  23580. pointCap.push(path[pathIndex]);
  23581. }
  23582. return pointCap;
  23583. };
  23584. switch (cap) {
  23585. case BABYLON.Mesh.NO_CAP:
  23586. break;
  23587. case BABYLON.Mesh.CAP_START:
  23588. circlePaths[0] = capPath(tessellation, 0);
  23589. circlePaths[1] = circlePaths[2].slice(0);
  23590. break;
  23591. case BABYLON.Mesh.CAP_END:
  23592. circlePaths[index] = circlePaths[index - 1].slice(0);
  23593. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  23594. break;
  23595. case BABYLON.Mesh.CAP_ALL:
  23596. circlePaths[0] = capPath(tessellation, 0);
  23597. circlePaths[1] = circlePaths[2].slice(0);
  23598. circlePaths[index] = circlePaths[index - 1].slice(0);
  23599. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  23600. break;
  23601. default:
  23602. break;
  23603. }
  23604. return circlePaths;
  23605. };
  23606. var path3D;
  23607. var pathArray;
  23608. if (instance) {
  23609. var arc = options.arc || instance.arc;
  23610. path3D = (instance.path3D).update(path);
  23611. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  23612. instance = MeshBuilder.CreateRibbon(null, { pathArray: pathArray, instance: instance });
  23613. instance.path3D = path3D;
  23614. instance.pathArray = pathArray;
  23615. instance.arc = arc;
  23616. return instance;
  23617. }
  23618. // tube creation
  23619. path3D = new BABYLON.Path3D(path);
  23620. var newPathArray = new Array();
  23621. cap = (cap < 0 || cap > 3) ? 0 : cap;
  23622. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  23623. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV }, scene);
  23624. tube.pathArray = pathArray;
  23625. tube.path3D = path3D;
  23626. tube.tessellation = tessellation;
  23627. tube.cap = cap;
  23628. tube.arc = options.arc;
  23629. return tube;
  23630. };
  23631. /**
  23632. * Creates a polyhedron mesh.
  23633. *
  23634. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#polyhedron
  23635. * 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
  23636. * to choose the wanted type.
  23637. * The parameter `size` (positive float, default 1) sets the polygon size.
  23638. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  23639. * 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`.
  23640. * 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
  23641. * 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)`).
  23642. * 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
  23643. * 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.
  23644. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  23645. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  23646. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23647. */
  23648. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  23649. var polyhedron = new BABYLON.Mesh(name, scene);
  23650. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  23651. polyhedron.sideOrientation = options.sideOrientation;
  23652. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  23653. vertexData.applyToMesh(polyhedron, options.updatable);
  23654. return polyhedron;
  23655. };
  23656. /**
  23657. * Creates a decal mesh.
  23658. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#decals
  23659. * 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.
  23660. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  23661. * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates.
  23662. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  23663. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  23664. */
  23665. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  23666. var indices = sourceMesh.getIndices();
  23667. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  23668. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  23669. var position = options.position || BABYLON.Vector3.Zero();
  23670. var normal = options.normal || BABYLON.Vector3.Up();
  23671. var size = options.size || new BABYLON.Vector3(1, 1, 1);
  23672. var angle = options.angle || 0;
  23673. // Getting correct rotation
  23674. if (!normal) {
  23675. var target = new BABYLON.Vector3(0, 0, 1);
  23676. var camera = sourceMesh.getScene().activeCamera;
  23677. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  23678. normal = camera.globalPosition.subtract(cameraWorldTarget);
  23679. }
  23680. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  23681. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  23682. var pitch = Math.atan2(normal.y, len);
  23683. // Matrix
  23684. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  23685. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  23686. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  23687. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  23688. var vertexData = new BABYLON.VertexData();
  23689. vertexData.indices = [];
  23690. vertexData.positions = [];
  23691. vertexData.normals = [];
  23692. vertexData.uvs = [];
  23693. var currentVertexDataIndex = 0;
  23694. var extractDecalVector3 = function (indexId) {
  23695. var vertexId = indices[indexId];
  23696. var result = new BABYLON.PositionNormalVertex();
  23697. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  23698. // Send vector to decal local world
  23699. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  23700. // Get normal
  23701. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  23702. result.normal = BABYLON.Vector3.TransformNormal(result.normal, transformMatrix);
  23703. return result;
  23704. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  23705. var clip = function (vertices, axis) {
  23706. if (vertices.length === 0) {
  23707. return vertices;
  23708. }
  23709. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  23710. var clipVertices = function (v0, v1) {
  23711. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  23712. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  23713. };
  23714. var result = new Array();
  23715. for (var index = 0; index < vertices.length; index += 3) {
  23716. var v1Out;
  23717. var v2Out;
  23718. var v3Out;
  23719. var total = 0;
  23720. var nV1, nV2, nV3, nV4;
  23721. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  23722. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  23723. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  23724. v1Out = d1 > 0;
  23725. v2Out = d2 > 0;
  23726. v3Out = d3 > 0;
  23727. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  23728. switch (total) {
  23729. case 0:
  23730. result.push(vertices[index]);
  23731. result.push(vertices[index + 1]);
  23732. result.push(vertices[index + 2]);
  23733. break;
  23734. case 1:
  23735. if (v1Out) {
  23736. nV1 = vertices[index + 1];
  23737. nV2 = vertices[index + 2];
  23738. nV3 = clipVertices(vertices[index], nV1);
  23739. nV4 = clipVertices(vertices[index], nV2);
  23740. }
  23741. if (v2Out) {
  23742. nV1 = vertices[index];
  23743. nV2 = vertices[index + 2];
  23744. nV3 = clipVertices(vertices[index + 1], nV1);
  23745. nV4 = clipVertices(vertices[index + 1], nV2);
  23746. result.push(nV3);
  23747. result.push(nV2.clone());
  23748. result.push(nV1.clone());
  23749. result.push(nV2.clone());
  23750. result.push(nV3.clone());
  23751. result.push(nV4);
  23752. break;
  23753. }
  23754. if (v3Out) {
  23755. nV1 = vertices[index];
  23756. nV2 = vertices[index + 1];
  23757. nV3 = clipVertices(vertices[index + 2], nV1);
  23758. nV4 = clipVertices(vertices[index + 2], nV2);
  23759. }
  23760. result.push(nV1.clone());
  23761. result.push(nV2.clone());
  23762. result.push(nV3);
  23763. result.push(nV4);
  23764. result.push(nV3.clone());
  23765. result.push(nV2.clone());
  23766. break;
  23767. case 2:
  23768. if (!v1Out) {
  23769. nV1 = vertices[index].clone();
  23770. nV2 = clipVertices(nV1, vertices[index + 1]);
  23771. nV3 = clipVertices(nV1, vertices[index + 2]);
  23772. result.push(nV1);
  23773. result.push(nV2);
  23774. result.push(nV3);
  23775. }
  23776. if (!v2Out) {
  23777. nV1 = vertices[index + 1].clone();
  23778. nV2 = clipVertices(nV1, vertices[index + 2]);
  23779. nV3 = clipVertices(nV1, vertices[index]);
  23780. result.push(nV1);
  23781. result.push(nV2);
  23782. result.push(nV3);
  23783. }
  23784. if (!v3Out) {
  23785. nV1 = vertices[index + 2].clone();
  23786. nV2 = clipVertices(nV1, vertices[index]);
  23787. nV3 = clipVertices(nV1, vertices[index + 1]);
  23788. result.push(nV1);
  23789. result.push(nV2);
  23790. result.push(nV3);
  23791. }
  23792. break;
  23793. case 3:
  23794. break;
  23795. }
  23796. }
  23797. return result;
  23798. };
  23799. for (var index = 0; index < indices.length; index += 3) {
  23800. var faceVertices = new Array();
  23801. faceVertices.push(extractDecalVector3(index));
  23802. faceVertices.push(extractDecalVector3(index + 1));
  23803. faceVertices.push(extractDecalVector3(index + 2));
  23804. // Clip
  23805. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  23806. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  23807. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  23808. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  23809. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  23810. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  23811. if (faceVertices.length === 0) {
  23812. continue;
  23813. }
  23814. // Add UVs and get back to world
  23815. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  23816. var vertex = faceVertices[vIndex];
  23817. //TODO check for Int32Array
  23818. vertexData.indices.push(currentVertexDataIndex);
  23819. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  23820. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  23821. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  23822. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  23823. currentVertexDataIndex++;
  23824. }
  23825. }
  23826. // Return mesh
  23827. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  23828. vertexData.applyToMesh(decal);
  23829. decal.position = position.clone();
  23830. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  23831. return decal;
  23832. };
  23833. // Privates
  23834. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV) {
  23835. // extrusion geometry
  23836. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  23837. var tangents = path3D.getTangents();
  23838. var normals = path3D.getNormals();
  23839. var binormals = path3D.getBinormals();
  23840. var distances = path3D.getDistances();
  23841. var angle = 0;
  23842. var returnScale = function () { return scale; };
  23843. var returnRotation = function () { return rotation; };
  23844. var rotate = custom ? rotateFunction : returnRotation;
  23845. var scl = custom ? scaleFunction : returnScale;
  23846. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  23847. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  23848. for (var i = 0; i < curve.length; i++) {
  23849. var shapePath = new Array();
  23850. var angleStep = rotate(i, distances[i]);
  23851. var scaleRatio = scl(i, distances[i]);
  23852. for (var p = 0; p < shape.length; p++) {
  23853. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  23854. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  23855. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  23856. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  23857. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  23858. shapePath[p] = rotated;
  23859. }
  23860. shapePaths[index] = shapePath;
  23861. angle += angleStep;
  23862. index++;
  23863. }
  23864. // cap
  23865. var capPath = function (shapePath) {
  23866. var pointCap = Array();
  23867. var barycenter = BABYLON.Vector3.Zero();
  23868. var i;
  23869. for (i = 0; i < shapePath.length; i++) {
  23870. barycenter.addInPlace(shapePath[i]);
  23871. }
  23872. barycenter.scaleInPlace(1.0 / shapePath.length);
  23873. for (i = 0; i < shapePath.length; i++) {
  23874. pointCap.push(barycenter);
  23875. }
  23876. return pointCap;
  23877. };
  23878. switch (cap) {
  23879. case BABYLON.Mesh.NO_CAP:
  23880. break;
  23881. case BABYLON.Mesh.CAP_START:
  23882. shapePaths[0] = capPath(shapePaths[2]);
  23883. shapePaths[1] = shapePaths[2];
  23884. break;
  23885. case BABYLON.Mesh.CAP_END:
  23886. shapePaths[index] = shapePaths[index - 1];
  23887. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  23888. break;
  23889. case BABYLON.Mesh.CAP_ALL:
  23890. shapePaths[0] = capPath(shapePaths[2]);
  23891. shapePaths[1] = shapePaths[2];
  23892. shapePaths[index] = shapePaths[index - 1];
  23893. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  23894. break;
  23895. default:
  23896. break;
  23897. }
  23898. return shapePaths;
  23899. };
  23900. var path3D;
  23901. var pathArray;
  23902. if (instance) {
  23903. path3D = (instance.path3D).update(curve);
  23904. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  23905. instance = BABYLON.Mesh.CreateRibbon(null, pathArray, null, null, null, scene, null, null, instance);
  23906. return instance;
  23907. }
  23908. // extruded shape creation
  23909. path3D = new BABYLON.Path3D(curve);
  23910. var newShapePaths = new Array();
  23911. cap = (cap < 0 || cap > 3) ? 0 : cap;
  23912. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  23913. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV }, scene);
  23914. extrudedGeneric.pathArray = pathArray;
  23915. extrudedGeneric.path3D = path3D;
  23916. extrudedGeneric.cap = cap;
  23917. return extrudedGeneric;
  23918. };
  23919. return MeshBuilder;
  23920. }());
  23921. BABYLON.MeshBuilder = MeshBuilder;
  23922. })(BABYLON || (BABYLON = {}));
  23923. //# sourceMappingURL=babylon.meshBuilder.js.map
  23924. var BABYLON;
  23925. (function (BABYLON) {
  23926. var BaseTexture = (function () {
  23927. function BaseTexture(scene) {
  23928. this.hasAlpha = false;
  23929. this.getAlphaFromRGB = false;
  23930. this.level = 1;
  23931. this.coordinatesIndex = 0;
  23932. this.coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  23933. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  23934. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  23935. this.anisotropicFilteringLevel = 4;
  23936. this.isCube = false;
  23937. this.isRenderTarget = false;
  23938. this.animations = new Array();
  23939. /**
  23940. * An event triggered when the texture is disposed.
  23941. * @type {BABYLON.Observable}
  23942. */
  23943. this.onDisposeObservable = new BABYLON.Observable();
  23944. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  23945. this._scene = scene;
  23946. this._scene.textures.push(this);
  23947. this._uid = null;
  23948. }
  23949. Object.defineProperty(BaseTexture.prototype, "uid", {
  23950. get: function () {
  23951. if (!this._uid) {
  23952. this._uid = BABYLON.Tools.RandomId();
  23953. }
  23954. return this._uid;
  23955. },
  23956. enumerable: true,
  23957. configurable: true
  23958. });
  23959. BaseTexture.prototype.toString = function () {
  23960. return this.name;
  23961. };
  23962. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  23963. set: function (callback) {
  23964. if (this._onDisposeObserver) {
  23965. this.onDisposeObservable.remove(this._onDisposeObserver);
  23966. }
  23967. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  23968. },
  23969. enumerable: true,
  23970. configurable: true
  23971. });
  23972. BaseTexture.prototype.getScene = function () {
  23973. return this._scene;
  23974. };
  23975. BaseTexture.prototype.getTextureMatrix = function () {
  23976. return null;
  23977. };
  23978. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  23979. return null;
  23980. };
  23981. BaseTexture.prototype.getInternalTexture = function () {
  23982. return this._texture;
  23983. };
  23984. BaseTexture.prototype.isReady = function () {
  23985. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  23986. return true;
  23987. }
  23988. if (this._texture) {
  23989. return this._texture.isReady;
  23990. }
  23991. return false;
  23992. };
  23993. BaseTexture.prototype.getSize = function () {
  23994. if (this._texture._width) {
  23995. return new BABYLON.Size(this._texture._width, this._texture._height);
  23996. }
  23997. if (this._texture._size) {
  23998. return new BABYLON.Size(this._texture._size, this._texture._size);
  23999. }
  24000. return BABYLON.Size.Zero();
  24001. };
  24002. BaseTexture.prototype.getBaseSize = function () {
  24003. if (!this.isReady() || !this._texture)
  24004. return BABYLON.Size.Zero();
  24005. if (this._texture._size) {
  24006. return new BABYLON.Size(this._texture._size, this._texture._size);
  24007. }
  24008. return new BABYLON.Size(this._texture._baseWidth, this._texture._baseHeight);
  24009. };
  24010. BaseTexture.prototype.scale = function (ratio) {
  24011. };
  24012. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  24013. get: function () {
  24014. return false;
  24015. },
  24016. enumerable: true,
  24017. configurable: true
  24018. });
  24019. BaseTexture.prototype._removeFromCache = function (url, noMipmap) {
  24020. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  24021. for (var index = 0; index < texturesCache.length; index++) {
  24022. var texturesCacheEntry = texturesCache[index];
  24023. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  24024. texturesCache.splice(index, 1);
  24025. return;
  24026. }
  24027. }
  24028. };
  24029. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  24030. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  24031. for (var index = 0; index < texturesCache.length; index++) {
  24032. var texturesCacheEntry = texturesCache[index];
  24033. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  24034. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  24035. texturesCacheEntry.references++;
  24036. return texturesCacheEntry;
  24037. }
  24038. }
  24039. }
  24040. return null;
  24041. };
  24042. BaseTexture.prototype.delayLoad = function () {
  24043. };
  24044. BaseTexture.prototype.clone = function () {
  24045. return null;
  24046. };
  24047. BaseTexture.prototype.releaseInternalTexture = function () {
  24048. if (this._texture) {
  24049. this._scene.getEngine().releaseInternalTexture(this._texture);
  24050. delete this._texture;
  24051. }
  24052. };
  24053. BaseTexture.prototype.dispose = function () {
  24054. // Animations
  24055. this.getScene().stopAnimation(this);
  24056. // Remove from scene
  24057. var index = this._scene.textures.indexOf(this);
  24058. if (index >= 0) {
  24059. this._scene.textures.splice(index, 1);
  24060. }
  24061. if (this._texture === undefined) {
  24062. return;
  24063. }
  24064. // Release
  24065. this.releaseInternalTexture();
  24066. // Callback
  24067. this.onDisposeObservable.notifyObservers(this);
  24068. this.onDisposeObservable.clear();
  24069. };
  24070. BaseTexture.prototype.serialize = function () {
  24071. if (!this.name) {
  24072. return null;
  24073. }
  24074. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  24075. // Animations
  24076. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  24077. return serializationObject;
  24078. };
  24079. return BaseTexture;
  24080. }());
  24081. __decorate([
  24082. BABYLON.serialize()
  24083. ], BaseTexture.prototype, "name", void 0);
  24084. __decorate([
  24085. BABYLON.serialize()
  24086. ], BaseTexture.prototype, "hasAlpha", void 0);
  24087. __decorate([
  24088. BABYLON.serialize()
  24089. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  24090. __decorate([
  24091. BABYLON.serialize()
  24092. ], BaseTexture.prototype, "level", void 0);
  24093. __decorate([
  24094. BABYLON.serialize()
  24095. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  24096. __decorate([
  24097. BABYLON.serialize()
  24098. ], BaseTexture.prototype, "coordinatesMode", void 0);
  24099. __decorate([
  24100. BABYLON.serialize()
  24101. ], BaseTexture.prototype, "wrapU", void 0);
  24102. __decorate([
  24103. BABYLON.serialize()
  24104. ], BaseTexture.prototype, "wrapV", void 0);
  24105. __decorate([
  24106. BABYLON.serialize()
  24107. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  24108. __decorate([
  24109. BABYLON.serialize()
  24110. ], BaseTexture.prototype, "isCube", void 0);
  24111. __decorate([
  24112. BABYLON.serialize()
  24113. ], BaseTexture.prototype, "isRenderTarget", void 0);
  24114. BABYLON.BaseTexture = BaseTexture;
  24115. })(BABYLON || (BABYLON = {}));
  24116. //# sourceMappingURL=babylon.baseTexture.js.map
  24117. var BABYLON;
  24118. (function (BABYLON) {
  24119. var Texture = (function (_super) {
  24120. __extends(Texture, _super);
  24121. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer) {
  24122. if (noMipmap === void 0) { noMipmap = false; }
  24123. if (invertY === void 0) { invertY = true; }
  24124. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  24125. if (onLoad === void 0) { onLoad = null; }
  24126. if (onError === void 0) { onError = null; }
  24127. if (buffer === void 0) { buffer = null; }
  24128. if (deleteBuffer === void 0) { deleteBuffer = false; }
  24129. var _this = _super.call(this, scene) || this;
  24130. _this.uOffset = 0;
  24131. _this.vOffset = 0;
  24132. _this.uScale = 1.0;
  24133. _this.vScale = 1.0;
  24134. _this.uAng = 0;
  24135. _this.vAng = 0;
  24136. _this.wAng = 0;
  24137. _this.name = url;
  24138. _this.url = url;
  24139. _this._noMipmap = noMipmap;
  24140. _this._invertY = invertY;
  24141. _this._samplingMode = samplingMode;
  24142. _this._buffer = buffer;
  24143. _this._deleteBuffer = deleteBuffer;
  24144. if (!url) {
  24145. return _this;
  24146. }
  24147. _this._texture = _this._getFromCache(url, noMipmap, samplingMode);
  24148. var load = function () {
  24149. if (_this._onLoadObservarble && _this._onLoadObservarble.hasObservers()) {
  24150. _this.onLoadObservable.notifyObservers(true);
  24151. }
  24152. if (onLoad) {
  24153. onLoad();
  24154. }
  24155. };
  24156. if (!_this._texture) {
  24157. if (!scene.useDelayedTextureLoading) {
  24158. _this._texture = scene.getEngine().createTexture(url, noMipmap, invertY, scene, _this._samplingMode, load, onError, _this._buffer);
  24159. if (deleteBuffer) {
  24160. delete _this._buffer;
  24161. }
  24162. }
  24163. else {
  24164. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  24165. _this._delayedOnLoad = load;
  24166. _this._delayedOnError = onError;
  24167. }
  24168. }
  24169. else {
  24170. if (_this._texture.isReady) {
  24171. BABYLON.Tools.SetImmediate(function () { return load(); });
  24172. }
  24173. else {
  24174. _this._texture.onLoadedCallbacks.push(load);
  24175. }
  24176. }
  24177. return _this;
  24178. }
  24179. Object.defineProperty(Texture.prototype, "noMipmap", {
  24180. get: function () {
  24181. return this._noMipmap;
  24182. },
  24183. enumerable: true,
  24184. configurable: true
  24185. });
  24186. Texture.prototype.delayLoad = function () {
  24187. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  24188. return;
  24189. }
  24190. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  24191. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  24192. if (!this._texture) {
  24193. this._texture = this.getScene().getEngine().createTexture(this.url, this._noMipmap, this._invertY, this.getScene(), this._samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer);
  24194. if (this._deleteBuffer) {
  24195. delete this._buffer;
  24196. }
  24197. }
  24198. };
  24199. Texture.prototype.updateSamplingMode = function (samplingMode) {
  24200. if (!this._texture) {
  24201. return;
  24202. }
  24203. this._samplingMode = samplingMode;
  24204. this.getScene().getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  24205. };
  24206. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  24207. x *= this.uScale;
  24208. y *= this.vScale;
  24209. x -= 0.5 * this.uScale;
  24210. y -= 0.5 * this.vScale;
  24211. z -= 0.5;
  24212. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  24213. t.x += 0.5 * this.uScale + this.uOffset;
  24214. t.y += 0.5 * this.vScale + this.vOffset;
  24215. t.z += 0.5;
  24216. };
  24217. Texture.prototype.getTextureMatrix = function () {
  24218. if (this.uOffset === this._cachedUOffset &&
  24219. this.vOffset === this._cachedVOffset &&
  24220. this.uScale === this._cachedUScale &&
  24221. this.vScale === this._cachedVScale &&
  24222. this.uAng === this._cachedUAng &&
  24223. this.vAng === this._cachedVAng &&
  24224. this.wAng === this._cachedWAng) {
  24225. return this._cachedTextureMatrix;
  24226. }
  24227. this._cachedUOffset = this.uOffset;
  24228. this._cachedVOffset = this.vOffset;
  24229. this._cachedUScale = this.uScale;
  24230. this._cachedVScale = this.vScale;
  24231. this._cachedUAng = this.uAng;
  24232. this._cachedVAng = this.vAng;
  24233. this._cachedWAng = this.wAng;
  24234. if (!this._cachedTextureMatrix) {
  24235. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  24236. this._rowGenerationMatrix = new BABYLON.Matrix();
  24237. this._t0 = BABYLON.Vector3.Zero();
  24238. this._t1 = BABYLON.Vector3.Zero();
  24239. this._t2 = BABYLON.Vector3.Zero();
  24240. }
  24241. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  24242. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  24243. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  24244. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  24245. this._t1.subtractInPlace(this._t0);
  24246. this._t2.subtractInPlace(this._t0);
  24247. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  24248. this._cachedTextureMatrix.m[0] = this._t1.x;
  24249. this._cachedTextureMatrix.m[1] = this._t1.y;
  24250. this._cachedTextureMatrix.m[2] = this._t1.z;
  24251. this._cachedTextureMatrix.m[4] = this._t2.x;
  24252. this._cachedTextureMatrix.m[5] = this._t2.y;
  24253. this._cachedTextureMatrix.m[6] = this._t2.z;
  24254. this._cachedTextureMatrix.m[8] = this._t0.x;
  24255. this._cachedTextureMatrix.m[9] = this._t0.y;
  24256. this._cachedTextureMatrix.m[10] = this._t0.z;
  24257. return this._cachedTextureMatrix;
  24258. };
  24259. Texture.prototype.getReflectionTextureMatrix = function () {
  24260. if (this.uOffset === this._cachedUOffset &&
  24261. this.vOffset === this._cachedVOffset &&
  24262. this.uScale === this._cachedUScale &&
  24263. this.vScale === this._cachedVScale &&
  24264. this.coordinatesMode === this._cachedCoordinatesMode) {
  24265. return this._cachedTextureMatrix;
  24266. }
  24267. if (!this._cachedTextureMatrix) {
  24268. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  24269. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  24270. }
  24271. this._cachedCoordinatesMode = this.coordinatesMode;
  24272. switch (this.coordinatesMode) {
  24273. case Texture.PLANAR_MODE:
  24274. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  24275. this._cachedTextureMatrix[0] = this.uScale;
  24276. this._cachedTextureMatrix[5] = this.vScale;
  24277. this._cachedTextureMatrix[12] = this.uOffset;
  24278. this._cachedTextureMatrix[13] = this.vOffset;
  24279. break;
  24280. case Texture.PROJECTION_MODE:
  24281. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  24282. this._projectionModeMatrix.m[0] = 0.5;
  24283. this._projectionModeMatrix.m[5] = -0.5;
  24284. this._projectionModeMatrix.m[10] = 0.0;
  24285. this._projectionModeMatrix.m[12] = 0.5;
  24286. this._projectionModeMatrix.m[13] = 0.5;
  24287. this._projectionModeMatrix.m[14] = 1.0;
  24288. this._projectionModeMatrix.m[15] = 1.0;
  24289. this.getScene().getProjectionMatrix().multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  24290. break;
  24291. default:
  24292. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  24293. break;
  24294. }
  24295. return this._cachedTextureMatrix;
  24296. };
  24297. Texture.prototype.clone = function () {
  24298. var _this = this;
  24299. return BABYLON.SerializationHelper.Clone(function () {
  24300. return new Texture(_this._texture.url, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  24301. }, this);
  24302. };
  24303. Object.defineProperty(Texture.prototype, "onLoadObservable", {
  24304. get: function () {
  24305. if (!this._onLoadObservarble) {
  24306. this._onLoadObservarble = new BABYLON.Observable();
  24307. }
  24308. return this._onLoadObservarble;
  24309. },
  24310. enumerable: true,
  24311. configurable: true
  24312. });
  24313. // Statics
  24314. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError) {
  24315. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  24316. if (onLoad === void 0) { onLoad = null; }
  24317. if (onError === void 0) { onError = null; }
  24318. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data);
  24319. };
  24320. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  24321. if (parsedTexture.customType) {
  24322. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  24323. return customTexture.Parse(parsedTexture, scene, rootUrl);
  24324. }
  24325. if (parsedTexture.isCube) {
  24326. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  24327. }
  24328. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  24329. return null;
  24330. }
  24331. var texture = BABYLON.SerializationHelper.Parse(function () {
  24332. if (parsedTexture.mirrorPlane) {
  24333. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  24334. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  24335. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  24336. return mirrorTexture;
  24337. }
  24338. else if (parsedTexture.isRenderTarget) {
  24339. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  24340. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  24341. return renderTargetTexture;
  24342. }
  24343. else {
  24344. var texture;
  24345. if (parsedTexture.base64String) {
  24346. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene);
  24347. }
  24348. else {
  24349. texture = new Texture(rootUrl + parsedTexture.name, scene);
  24350. }
  24351. return texture;
  24352. }
  24353. }, parsedTexture, scene);
  24354. // Animations
  24355. if (parsedTexture.animations) {
  24356. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  24357. var parsedAnimation = parsedTexture.animations[animationIndex];
  24358. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  24359. }
  24360. }
  24361. return texture;
  24362. };
  24363. Texture.LoadFromDataString = function (name, buffer, scene, deleteBuffer, noMipmap, invertY, samplingMode, onLoad, onError) {
  24364. if (deleteBuffer === void 0) { deleteBuffer = false; }
  24365. if (noMipmap === void 0) { noMipmap = false; }
  24366. if (invertY === void 0) { invertY = true; }
  24367. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  24368. if (onLoad === void 0) { onLoad = null; }
  24369. if (onError === void 0) { onError = null; }
  24370. if (name.substr(0, 5) !== "data:") {
  24371. name = "data:" + name;
  24372. }
  24373. return new Texture(name, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer);
  24374. };
  24375. return Texture;
  24376. }(BABYLON.BaseTexture));
  24377. // Constants
  24378. Texture.NEAREST_SAMPLINGMODE = 1;
  24379. Texture.BILINEAR_SAMPLINGMODE = 2;
  24380. Texture.TRILINEAR_SAMPLINGMODE = 3;
  24381. Texture.EXPLICIT_MODE = 0;
  24382. Texture.SPHERICAL_MODE = 1;
  24383. Texture.PLANAR_MODE = 2;
  24384. Texture.CUBIC_MODE = 3;
  24385. Texture.PROJECTION_MODE = 4;
  24386. Texture.SKYBOX_MODE = 5;
  24387. Texture.INVCUBIC_MODE = 6;
  24388. Texture.EQUIRECTANGULAR_MODE = 7;
  24389. Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
  24390. Texture.CLAMP_ADDRESSMODE = 0;
  24391. Texture.WRAP_ADDRESSMODE = 1;
  24392. Texture.MIRROR_ADDRESSMODE = 2;
  24393. __decorate([
  24394. BABYLON.serialize()
  24395. ], Texture.prototype, "url", void 0);
  24396. __decorate([
  24397. BABYLON.serialize()
  24398. ], Texture.prototype, "uOffset", void 0);
  24399. __decorate([
  24400. BABYLON.serialize()
  24401. ], Texture.prototype, "vOffset", void 0);
  24402. __decorate([
  24403. BABYLON.serialize()
  24404. ], Texture.prototype, "uScale", void 0);
  24405. __decorate([
  24406. BABYLON.serialize()
  24407. ], Texture.prototype, "vScale", void 0);
  24408. __decorate([
  24409. BABYLON.serialize()
  24410. ], Texture.prototype, "uAng", void 0);
  24411. __decorate([
  24412. BABYLON.serialize()
  24413. ], Texture.prototype, "vAng", void 0);
  24414. __decorate([
  24415. BABYLON.serialize()
  24416. ], Texture.prototype, "wAng", void 0);
  24417. BABYLON.Texture = Texture;
  24418. })(BABYLON || (BABYLON = {}));
  24419. //# sourceMappingURL=babylon.texture.js.map
  24420. var BABYLON;
  24421. (function (BABYLON) {
  24422. var CubeTexture = (function (_super) {
  24423. __extends(CubeTexture, _super);
  24424. function CubeTexture(rootUrl, scene, extensions, noMipmap, files, onLoad, onError) {
  24425. if (onLoad === void 0) { onLoad = null; }
  24426. if (onError === void 0) { onError = null; }
  24427. var _this = _super.call(this, scene) || this;
  24428. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  24429. _this.name = rootUrl;
  24430. _this.url = rootUrl;
  24431. _this._noMipmap = noMipmap;
  24432. _this.hasAlpha = false;
  24433. if (!rootUrl && !files) {
  24434. return _this;
  24435. }
  24436. _this._texture = _this._getFromCache(rootUrl, noMipmap);
  24437. if (!files) {
  24438. if (!extensions) {
  24439. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  24440. }
  24441. files = [];
  24442. for (var index = 0; index < extensions.length; index++) {
  24443. files.push(rootUrl + extensions[index]);
  24444. }
  24445. _this._extensions = extensions;
  24446. }
  24447. _this._files = files;
  24448. if (!_this._texture) {
  24449. if (!scene.useDelayedTextureLoading) {
  24450. _this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap, onLoad, onError);
  24451. }
  24452. else {
  24453. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  24454. }
  24455. }
  24456. else if (onLoad) {
  24457. if (_this._texture.isReady) {
  24458. BABYLON.Tools.SetImmediate(function () { return onLoad(); });
  24459. }
  24460. else {
  24461. _this._texture.onLoadedCallbacks.push(onLoad);
  24462. }
  24463. }
  24464. _this.isCube = true;
  24465. _this._textureMatrix = BABYLON.Matrix.Identity();
  24466. return _this;
  24467. }
  24468. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  24469. return new CubeTexture("", scene, null, noMipmap, files);
  24470. };
  24471. // Methods
  24472. CubeTexture.prototype.delayLoad = function () {
  24473. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  24474. return;
  24475. }
  24476. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  24477. this._texture = this._getFromCache(this.url, this._noMipmap);
  24478. if (!this._texture) {
  24479. this._texture = this.getScene().getEngine().createCubeTexture(this.url, this.getScene(), this._files, this._noMipmap);
  24480. }
  24481. };
  24482. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  24483. return this._textureMatrix;
  24484. };
  24485. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  24486. var texture = BABYLON.SerializationHelper.Parse(function () {
  24487. return new BABYLON.CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions);
  24488. }, parsedTexture, scene);
  24489. // Animations
  24490. if (parsedTexture.animations) {
  24491. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  24492. var parsedAnimation = parsedTexture.animations[animationIndex];
  24493. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  24494. }
  24495. }
  24496. return texture;
  24497. };
  24498. CubeTexture.prototype.clone = function () {
  24499. var _this = this;
  24500. return BABYLON.SerializationHelper.Clone(function () {
  24501. return new CubeTexture(_this.url, _this.getScene(), _this._extensions, _this._noMipmap, _this._files);
  24502. }, this);
  24503. };
  24504. return CubeTexture;
  24505. }(BABYLON.BaseTexture));
  24506. BABYLON.CubeTexture = CubeTexture;
  24507. })(BABYLON || (BABYLON = {}));
  24508. //# sourceMappingURL=babylon.cubeTexture.js.map
  24509. var BABYLON;
  24510. (function (BABYLON) {
  24511. var RenderTargetTexture = (function (_super) {
  24512. __extends(RenderTargetTexture, _super);
  24513. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer) {
  24514. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  24515. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  24516. if (isCube === void 0) { isCube = false; }
  24517. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  24518. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  24519. if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
  24520. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  24521. _this.isCube = isCube;
  24522. /**
  24523. * Use this list to define the list of mesh you want to render.
  24524. */
  24525. _this.renderList = new Array();
  24526. _this.renderParticles = true;
  24527. _this.renderSprites = false;
  24528. _this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  24529. // Events
  24530. /**
  24531. * An event triggered when the texture is unbind.
  24532. * @type {BABYLON.Observable}
  24533. */
  24534. _this.onAfterUnbindObservable = new BABYLON.Observable();
  24535. /**
  24536. * An event triggered before rendering the texture
  24537. * @type {BABYLON.Observable}
  24538. */
  24539. _this.onBeforeRenderObservable = new BABYLON.Observable();
  24540. /**
  24541. * An event triggered after rendering the texture
  24542. * @type {BABYLON.Observable}
  24543. */
  24544. _this.onAfterRenderObservable = new BABYLON.Observable();
  24545. /**
  24546. * An event triggered after the texture clear
  24547. * @type {BABYLON.Observable}
  24548. */
  24549. _this.onClearObservable = new BABYLON.Observable();
  24550. _this._currentRefreshId = -1;
  24551. _this._refreshRate = 1;
  24552. _this.name = name;
  24553. _this.isRenderTarget = true;
  24554. _this._size = size;
  24555. _this._generateMipMaps = generateMipMaps;
  24556. _this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  24557. _this._renderTargetOptions = {
  24558. generateMipMaps: generateMipMaps,
  24559. type: type,
  24560. samplingMode: samplingMode,
  24561. generateDepthBuffer: generateDepthBuffer,
  24562. generateStencilBuffer: generateStencilBuffer
  24563. };
  24564. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  24565. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  24566. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  24567. }
  24568. if (isCube) {
  24569. _this._texture = scene.getEngine().createRenderTargetCubeTexture(size, _this._renderTargetOptions);
  24570. _this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  24571. _this._textureMatrix = BABYLON.Matrix.Identity();
  24572. }
  24573. else {
  24574. _this._texture = scene.getEngine().createRenderTargetTexture(size, _this._renderTargetOptions);
  24575. }
  24576. // Rendering groups
  24577. _this._renderingManager = new BABYLON.RenderingManager(scene);
  24578. return _this;
  24579. }
  24580. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  24581. get: function () {
  24582. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  24583. },
  24584. enumerable: true,
  24585. configurable: true
  24586. });
  24587. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  24588. get: function () {
  24589. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  24590. },
  24591. enumerable: true,
  24592. configurable: true
  24593. });
  24594. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  24595. get: function () {
  24596. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  24597. },
  24598. enumerable: true,
  24599. configurable: true
  24600. });
  24601. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  24602. set: function (callback) {
  24603. if (this._onAfterUnbindObserver) {
  24604. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  24605. }
  24606. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  24607. },
  24608. enumerable: true,
  24609. configurable: true
  24610. });
  24611. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  24612. set: function (callback) {
  24613. if (this._onBeforeRenderObserver) {
  24614. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  24615. }
  24616. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  24617. },
  24618. enumerable: true,
  24619. configurable: true
  24620. });
  24621. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  24622. set: function (callback) {
  24623. if (this._onAfterRenderObserver) {
  24624. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  24625. }
  24626. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  24627. },
  24628. enumerable: true,
  24629. configurable: true
  24630. });
  24631. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  24632. set: function (callback) {
  24633. if (this._onClearObserver) {
  24634. this.onClearObservable.remove(this._onClearObserver);
  24635. }
  24636. this._onClearObserver = this.onClearObservable.add(callback);
  24637. },
  24638. enumerable: true,
  24639. configurable: true
  24640. });
  24641. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  24642. this._currentRefreshId = -1;
  24643. };
  24644. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  24645. get: function () {
  24646. return this._refreshRate;
  24647. },
  24648. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  24649. set: function (value) {
  24650. this._refreshRate = value;
  24651. this.resetRefreshCounter();
  24652. },
  24653. enumerable: true,
  24654. configurable: true
  24655. });
  24656. RenderTargetTexture.prototype._shouldRender = function () {
  24657. if (this._currentRefreshId === -1) {
  24658. this._currentRefreshId = 1;
  24659. return true;
  24660. }
  24661. if (this.refreshRate === this._currentRefreshId) {
  24662. this._currentRefreshId = 1;
  24663. return true;
  24664. }
  24665. this._currentRefreshId++;
  24666. return false;
  24667. };
  24668. RenderTargetTexture.prototype.isReady = function () {
  24669. if (!this.getScene().renderTargetsEnabled) {
  24670. return false;
  24671. }
  24672. return _super.prototype.isReady.call(this);
  24673. };
  24674. RenderTargetTexture.prototype.getRenderSize = function () {
  24675. return this._size;
  24676. };
  24677. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  24678. get: function () {
  24679. return true;
  24680. },
  24681. enumerable: true,
  24682. configurable: true
  24683. });
  24684. RenderTargetTexture.prototype.scale = function (ratio) {
  24685. var newSize = this._size * ratio;
  24686. this.resize(newSize);
  24687. };
  24688. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  24689. if (this.isCube) {
  24690. return this._textureMatrix;
  24691. }
  24692. return _super.prototype.getReflectionTextureMatrix.call(this);
  24693. };
  24694. RenderTargetTexture.prototype.resize = function (size) {
  24695. this.releaseInternalTexture();
  24696. if (this.isCube) {
  24697. this._texture = this.getScene().getEngine().createRenderTargetCubeTexture(size, this._renderTargetOptions);
  24698. }
  24699. else {
  24700. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, this._renderTargetOptions);
  24701. }
  24702. };
  24703. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  24704. var scene = this.getScene();
  24705. var engine = scene.getEngine();
  24706. if (this.useCameraPostProcesses !== undefined) {
  24707. useCameraPostProcess = this.useCameraPostProcesses;
  24708. }
  24709. if (this._waitingRenderList) {
  24710. this.renderList = [];
  24711. for (var index = 0; index < this._waitingRenderList.length; index++) {
  24712. var id = this._waitingRenderList[index];
  24713. this.renderList.push(scene.getMeshByID(id));
  24714. }
  24715. delete this._waitingRenderList;
  24716. }
  24717. // Is predicate defined?
  24718. if (this.renderListPredicate) {
  24719. this.renderList.splice(0); // Clear previous renderList
  24720. var sceneMeshes = this.getScene().meshes;
  24721. for (var index = 0; index < sceneMeshes.length; index++) {
  24722. var mesh = sceneMeshes[index];
  24723. if (this.renderListPredicate(mesh)) {
  24724. this.renderList.push(mesh);
  24725. }
  24726. }
  24727. }
  24728. if (this.renderList && this.renderList.length === 0) {
  24729. return;
  24730. }
  24731. // Set custom projection.
  24732. // Needs to be before binding to prevent changing the aspect ratio.
  24733. if (this.activeCamera) {
  24734. engine.setViewport(this.activeCamera.viewport);
  24735. if (this.activeCamera !== scene.activeCamera) {
  24736. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  24737. }
  24738. }
  24739. else {
  24740. engine.setViewport(scene.activeCamera.viewport);
  24741. }
  24742. // Prepare renderingManager
  24743. this._renderingManager.reset();
  24744. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  24745. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  24746. var sceneRenderId = scene.getRenderId();
  24747. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  24748. var mesh = currentRenderList[meshIndex];
  24749. if (mesh) {
  24750. if (!mesh.isReady()) {
  24751. // Reset _currentRefreshId
  24752. this.resetRefreshCounter();
  24753. continue;
  24754. }
  24755. mesh._preActivateForIntermediateRendering(sceneRenderId);
  24756. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && ((mesh.layerMask & scene.activeCamera.layerMask) !== 0)) {
  24757. mesh._activate(sceneRenderId);
  24758. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  24759. var subMesh = mesh.subMeshes[subIndex];
  24760. scene._activeIndices.addCount(subMesh.indexCount, false);
  24761. this._renderingManager.dispatch(subMesh);
  24762. }
  24763. }
  24764. }
  24765. }
  24766. if (this.isCube) {
  24767. for (var face = 0; face < 6; face++) {
  24768. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  24769. scene.incrementRenderId();
  24770. scene.resetCachedMaterial();
  24771. }
  24772. }
  24773. else {
  24774. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  24775. }
  24776. this.onAfterUnbindObservable.notifyObservers(this);
  24777. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  24778. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  24779. }
  24780. engine.setViewport(scene.activeCamera.viewport);
  24781. scene.resetCachedMaterial();
  24782. };
  24783. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  24784. var scene = this.getScene();
  24785. var engine = scene.getEngine();
  24786. // Bind
  24787. if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  24788. if (this.isCube) {
  24789. engine.bindFramebuffer(this._texture, faceIndex);
  24790. }
  24791. else {
  24792. engine.bindFramebuffer(this._texture);
  24793. }
  24794. }
  24795. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  24796. // Clear
  24797. if (this.onClearObservable.hasObservers()) {
  24798. this.onClearObservable.notifyObservers(engine);
  24799. }
  24800. else {
  24801. engine.clear(scene.clearColor, true, true, true);
  24802. }
  24803. if (!this._doNotChangeAspectRatio) {
  24804. scene.updateTransformMatrix(true);
  24805. }
  24806. // Render
  24807. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  24808. if (useCameraPostProcess) {
  24809. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  24810. }
  24811. if (!this._doNotChangeAspectRatio) {
  24812. scene.updateTransformMatrix(true);
  24813. }
  24814. this.onAfterRenderObservable.notifyObservers(faceIndex);
  24815. // Dump ?
  24816. if (dumpForDebug) {
  24817. BABYLON.Tools.DumpFramebuffer(this._size, this._size, engine);
  24818. }
  24819. // Unbind
  24820. if (!this.isCube || faceIndex === 5) {
  24821. if (this.isCube) {
  24822. if (faceIndex === 5) {
  24823. engine.generateMipMapsForCubemap(this._texture);
  24824. }
  24825. }
  24826. engine.unBindFramebuffer(this._texture, this.isCube);
  24827. }
  24828. };
  24829. /**
  24830. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  24831. * This allowed control for front to back rendering or reversly depending of the special needs.
  24832. *
  24833. * @param renderingGroupId The rendering group id corresponding to its index
  24834. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  24835. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  24836. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  24837. */
  24838. RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  24839. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  24840. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  24841. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  24842. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  24843. };
  24844. /**
  24845. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  24846. *
  24847. * @param renderingGroupId The rendering group id corresponding to its index
  24848. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  24849. */
  24850. RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  24851. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  24852. };
  24853. RenderTargetTexture.prototype.clone = function () {
  24854. var textureSize = this.getSize();
  24855. 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);
  24856. // Base texture
  24857. newTexture.hasAlpha = this.hasAlpha;
  24858. newTexture.level = this.level;
  24859. // RenderTarget Texture
  24860. newTexture.coordinatesMode = this.coordinatesMode;
  24861. newTexture.renderList = this.renderList.slice(0);
  24862. return newTexture;
  24863. };
  24864. RenderTargetTexture.prototype.serialize = function () {
  24865. if (!this.name) {
  24866. return null;
  24867. }
  24868. var serializationObject = _super.prototype.serialize.call(this);
  24869. serializationObject.renderTargetSize = this.getRenderSize();
  24870. serializationObject.renderList = [];
  24871. for (var index = 0; index < this.renderList.length; index++) {
  24872. serializationObject.renderList.push(this.renderList[index].id);
  24873. }
  24874. return serializationObject;
  24875. };
  24876. return RenderTargetTexture;
  24877. }(BABYLON.Texture));
  24878. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  24879. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  24880. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  24881. BABYLON.RenderTargetTexture = RenderTargetTexture;
  24882. })(BABYLON || (BABYLON = {}));
  24883. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  24884. var BABYLON;
  24885. (function (BABYLON) {
  24886. var ProceduralTexture = (function (_super) {
  24887. __extends(ProceduralTexture, _super);
  24888. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  24889. if (generateMipMaps === void 0) { generateMipMaps = true; }
  24890. if (isCube === void 0) { isCube = false; }
  24891. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  24892. _this.isCube = isCube;
  24893. _this.isEnabled = true;
  24894. _this._currentRefreshId = -1;
  24895. _this._refreshRate = 1;
  24896. _this._vertexBuffers = {};
  24897. _this._uniforms = new Array();
  24898. _this._samplers = new Array();
  24899. _this._textures = new Array();
  24900. _this._floats = new Array();
  24901. _this._floatsArrays = {};
  24902. _this._colors3 = new Array();
  24903. _this._colors4 = new Array();
  24904. _this._vectors2 = new Array();
  24905. _this._vectors3 = new Array();
  24906. _this._matrices = new Array();
  24907. _this._fallbackTextureUsed = false;
  24908. scene._proceduralTextures.push(_this);
  24909. _this.name = name;
  24910. _this.isRenderTarget = true;
  24911. _this._size = size;
  24912. _this._generateMipMaps = generateMipMaps;
  24913. _this.setFragment(fragment);
  24914. _this._fallbackTexture = fallbackTexture;
  24915. var engine = scene.getEngine();
  24916. if (isCube) {
  24917. _this._texture = engine.createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  24918. _this.setFloat("face", 0);
  24919. }
  24920. else {
  24921. _this._texture = engine.createRenderTargetTexture(size, generateMipMaps);
  24922. }
  24923. // VBO
  24924. var vertices = [];
  24925. vertices.push(1, 1);
  24926. vertices.push(-1, 1);
  24927. vertices.push(-1, -1);
  24928. vertices.push(1, -1);
  24929. _this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  24930. // Indices
  24931. var indices = [];
  24932. indices.push(0);
  24933. indices.push(1);
  24934. indices.push(2);
  24935. indices.push(0);
  24936. indices.push(2);
  24937. indices.push(3);
  24938. _this._indexBuffer = engine.createIndexBuffer(indices);
  24939. return _this;
  24940. }
  24941. ProceduralTexture.prototype.reset = function () {
  24942. if (this._effect === undefined) {
  24943. return;
  24944. }
  24945. var engine = this.getScene().getEngine();
  24946. engine._releaseEffect(this._effect);
  24947. };
  24948. ProceduralTexture.prototype.isReady = function () {
  24949. var _this = this;
  24950. var engine = this.getScene().getEngine();
  24951. var shaders;
  24952. if (!this._fragment) {
  24953. return false;
  24954. }
  24955. if (this._fallbackTextureUsed) {
  24956. return true;
  24957. }
  24958. if (this._fragment.fragmentElement !== undefined) {
  24959. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  24960. }
  24961. else {
  24962. shaders = { vertex: "procedural", fragment: this._fragment };
  24963. }
  24964. this._effect = engine.createEffect(shaders, [BABYLON.VertexBuffer.PositionKind], this._uniforms, this._samplers, "", null, null, function () {
  24965. _this.releaseInternalTexture();
  24966. if (_this._fallbackTexture) {
  24967. _this._texture = _this._fallbackTexture._texture;
  24968. _this._texture.references++;
  24969. }
  24970. _this._fallbackTextureUsed = true;
  24971. });
  24972. return this._effect.isReady();
  24973. };
  24974. ProceduralTexture.prototype.resetRefreshCounter = function () {
  24975. this._currentRefreshId = -1;
  24976. };
  24977. ProceduralTexture.prototype.setFragment = function (fragment) {
  24978. this._fragment = fragment;
  24979. };
  24980. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  24981. get: function () {
  24982. return this._refreshRate;
  24983. },
  24984. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  24985. set: function (value) {
  24986. this._refreshRate = value;
  24987. this.resetRefreshCounter();
  24988. },
  24989. enumerable: true,
  24990. configurable: true
  24991. });
  24992. ProceduralTexture.prototype._shouldRender = function () {
  24993. if (!this.isEnabled || !this.isReady() || !this._texture) {
  24994. return false;
  24995. }
  24996. if (this._fallbackTextureUsed) {
  24997. return false;
  24998. }
  24999. if (this._currentRefreshId === -1) {
  25000. this._currentRefreshId = 1;
  25001. return true;
  25002. }
  25003. if (this.refreshRate === this._currentRefreshId) {
  25004. this._currentRefreshId = 1;
  25005. return true;
  25006. }
  25007. this._currentRefreshId++;
  25008. return false;
  25009. };
  25010. ProceduralTexture.prototype.getRenderSize = function () {
  25011. return this._size;
  25012. };
  25013. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  25014. if (this._fallbackTextureUsed) {
  25015. return;
  25016. }
  25017. this.releaseInternalTexture();
  25018. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  25019. };
  25020. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  25021. if (this._uniforms.indexOf(uniformName) === -1) {
  25022. this._uniforms.push(uniformName);
  25023. }
  25024. };
  25025. ProceduralTexture.prototype.setTexture = function (name, texture) {
  25026. if (this._samplers.indexOf(name) === -1) {
  25027. this._samplers.push(name);
  25028. }
  25029. this._textures[name] = texture;
  25030. return this;
  25031. };
  25032. ProceduralTexture.prototype.setFloat = function (name, value) {
  25033. this._checkUniform(name);
  25034. this._floats[name] = value;
  25035. return this;
  25036. };
  25037. ProceduralTexture.prototype.setFloats = function (name, value) {
  25038. this._checkUniform(name);
  25039. this._floatsArrays[name] = value;
  25040. return this;
  25041. };
  25042. ProceduralTexture.prototype.setColor3 = function (name, value) {
  25043. this._checkUniform(name);
  25044. this._colors3[name] = value;
  25045. return this;
  25046. };
  25047. ProceduralTexture.prototype.setColor4 = function (name, value) {
  25048. this._checkUniform(name);
  25049. this._colors4[name] = value;
  25050. return this;
  25051. };
  25052. ProceduralTexture.prototype.setVector2 = function (name, value) {
  25053. this._checkUniform(name);
  25054. this._vectors2[name] = value;
  25055. return this;
  25056. };
  25057. ProceduralTexture.prototype.setVector3 = function (name, value) {
  25058. this._checkUniform(name);
  25059. this._vectors3[name] = value;
  25060. return this;
  25061. };
  25062. ProceduralTexture.prototype.setMatrix = function (name, value) {
  25063. this._checkUniform(name);
  25064. this._matrices[name] = value;
  25065. return this;
  25066. };
  25067. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  25068. var scene = this.getScene();
  25069. var engine = scene.getEngine();
  25070. // Render
  25071. engine.enableEffect(this._effect);
  25072. engine.setState(false);
  25073. // Texture
  25074. for (var name in this._textures) {
  25075. this._effect.setTexture(name, this._textures[name]);
  25076. }
  25077. // Float
  25078. for (name in this._floats) {
  25079. this._effect.setFloat(name, this._floats[name]);
  25080. }
  25081. // Floats
  25082. for (name in this._floatsArrays) {
  25083. this._effect.setArray(name, this._floatsArrays[name]);
  25084. }
  25085. // Color3
  25086. for (name in this._colors3) {
  25087. this._effect.setColor3(name, this._colors3[name]);
  25088. }
  25089. // Color4
  25090. for (name in this._colors4) {
  25091. var color = this._colors4[name];
  25092. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  25093. }
  25094. // Vector2
  25095. for (name in this._vectors2) {
  25096. this._effect.setVector2(name, this._vectors2[name]);
  25097. }
  25098. // Vector3
  25099. for (name in this._vectors3) {
  25100. this._effect.setVector3(name, this._vectors3[name]);
  25101. }
  25102. // Matrix
  25103. for (name in this._matrices) {
  25104. this._effect.setMatrix(name, this._matrices[name]);
  25105. }
  25106. // VBOs
  25107. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  25108. if (this.isCube) {
  25109. for (var face = 0; face < 6; face++) {
  25110. engine.bindFramebuffer(this._texture, face);
  25111. this._effect.setFloat("face", face);
  25112. // Clear
  25113. engine.clear(scene.clearColor, true, true, true);
  25114. // Draw order
  25115. engine.draw(true, 0, 6);
  25116. // Mipmaps
  25117. if (face === 5) {
  25118. engine.generateMipMapsForCubemap(this._texture);
  25119. }
  25120. }
  25121. }
  25122. else {
  25123. engine.bindFramebuffer(this._texture);
  25124. // Clear
  25125. engine.clear(scene.clearColor, true, true, true);
  25126. // Draw order
  25127. engine.draw(true, 0, 6);
  25128. }
  25129. // Unbind
  25130. engine.unBindFramebuffer(this._texture, this.isCube);
  25131. if (this.onGenerated) {
  25132. this.onGenerated();
  25133. }
  25134. };
  25135. ProceduralTexture.prototype.clone = function () {
  25136. var textureSize = this.getSize();
  25137. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  25138. // Base texture
  25139. newTexture.hasAlpha = this.hasAlpha;
  25140. newTexture.level = this.level;
  25141. // RenderTarget Texture
  25142. newTexture.coordinatesMode = this.coordinatesMode;
  25143. return newTexture;
  25144. };
  25145. ProceduralTexture.prototype.dispose = function () {
  25146. var index = this.getScene()._proceduralTextures.indexOf(this);
  25147. if (index >= 0) {
  25148. this.getScene()._proceduralTextures.splice(index, 1);
  25149. }
  25150. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  25151. if (vertexBuffer) {
  25152. vertexBuffer.dispose();
  25153. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  25154. }
  25155. if (this._indexBuffer && this.getScene().getEngine()._releaseBuffer(this._indexBuffer)) {
  25156. this._indexBuffer = null;
  25157. }
  25158. _super.prototype.dispose.call(this);
  25159. };
  25160. return ProceduralTexture;
  25161. }(BABYLON.Texture));
  25162. BABYLON.ProceduralTexture = ProceduralTexture;
  25163. })(BABYLON || (BABYLON = {}));
  25164. //# sourceMappingURL=babylon.proceduralTexture.js.map
  25165. var BABYLON;
  25166. (function (BABYLON) {
  25167. var MirrorTexture = (function (_super) {
  25168. __extends(MirrorTexture, _super);
  25169. function MirrorTexture(name, size, scene, generateMipMaps, type, samplingMode, generateDepthBuffer) {
  25170. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  25171. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  25172. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  25173. var _this = _super.call(this, name, size, scene, generateMipMaps, true, type, false, samplingMode, generateDepthBuffer) || this;
  25174. _this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  25175. _this._transformMatrix = BABYLON.Matrix.Zero();
  25176. _this._mirrorMatrix = BABYLON.Matrix.Zero();
  25177. _this.onBeforeRenderObservable.add(function () {
  25178. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  25179. _this._savedViewMatrix = scene.getViewMatrix();
  25180. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  25181. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  25182. scene.clipPlane = _this.mirrorPlane;
  25183. scene.getEngine().cullBackFaces = false;
  25184. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.position, _this._mirrorMatrix);
  25185. });
  25186. _this.onAfterRenderObservable.add(function () {
  25187. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  25188. scene.getEngine().cullBackFaces = true;
  25189. scene._mirroredCameraPosition = null;
  25190. delete scene.clipPlane;
  25191. });
  25192. return _this;
  25193. }
  25194. MirrorTexture.prototype.clone = function () {
  25195. var textureSize = this.getSize();
  25196. var newTexture = new MirrorTexture(this.name, textureSize.width, this.getScene(), this._renderTargetOptions.generateMipMaps, this._renderTargetOptions.type, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer);
  25197. // Base texture
  25198. newTexture.hasAlpha = this.hasAlpha;
  25199. newTexture.level = this.level;
  25200. // Mirror Texture
  25201. newTexture.mirrorPlane = this.mirrorPlane.clone();
  25202. newTexture.renderList = this.renderList.slice(0);
  25203. return newTexture;
  25204. };
  25205. MirrorTexture.prototype.serialize = function () {
  25206. if (!this.name) {
  25207. return null;
  25208. }
  25209. var serializationObject = _super.prototype.serialize.call(this);
  25210. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  25211. return serializationObject;
  25212. };
  25213. return MirrorTexture;
  25214. }(BABYLON.RenderTargetTexture));
  25215. BABYLON.MirrorTexture = MirrorTexture;
  25216. })(BABYLON || (BABYLON = {}));
  25217. //# sourceMappingURL=babylon.mirrorTexture.js.map
  25218. var BABYLON;
  25219. (function (BABYLON) {
  25220. /**
  25221. * Creates a refraction texture used by refraction channel of the standard material.
  25222. * @param name the texture name
  25223. * @param size size of the underlying texture
  25224. * @param scene root scene
  25225. */
  25226. var RefractionTexture = (function (_super) {
  25227. __extends(RefractionTexture, _super);
  25228. function RefractionTexture(name, size, scene, generateMipMaps) {
  25229. var _this = _super.call(this, name, size, scene, generateMipMaps, true) || this;
  25230. _this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  25231. _this.depth = 2.0;
  25232. _this.onBeforeRenderObservable.add(function () {
  25233. scene.clipPlane = _this.refractionPlane;
  25234. });
  25235. _this.onAfterRenderObservable.add(function () {
  25236. delete scene.clipPlane;
  25237. });
  25238. return _this;
  25239. }
  25240. RefractionTexture.prototype.clone = function () {
  25241. var textureSize = this.getSize();
  25242. var newTexture = new RefractionTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  25243. // Base texture
  25244. newTexture.hasAlpha = this.hasAlpha;
  25245. newTexture.level = this.level;
  25246. // Refraction Texture
  25247. newTexture.refractionPlane = this.refractionPlane.clone();
  25248. newTexture.renderList = this.renderList.slice(0);
  25249. newTexture.depth = this.depth;
  25250. return newTexture;
  25251. };
  25252. RefractionTexture.prototype.serialize = function () {
  25253. if (!this.name) {
  25254. return null;
  25255. }
  25256. var serializationObject = _super.prototype.serialize.call(this);
  25257. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  25258. serializationObject.depth = this.depth;
  25259. return serializationObject;
  25260. };
  25261. return RefractionTexture;
  25262. }(BABYLON.RenderTargetTexture));
  25263. BABYLON.RefractionTexture = RefractionTexture;
  25264. })(BABYLON || (BABYLON = {}));
  25265. //# sourceMappingURL=babylon.refractionTexture.js.map
  25266. var BABYLON;
  25267. (function (BABYLON) {
  25268. var DynamicTexture = (function (_super) {
  25269. __extends(DynamicTexture, _super);
  25270. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode) {
  25271. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  25272. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  25273. _this.name = name;
  25274. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  25275. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  25276. _this._generateMipMaps = generateMipMaps;
  25277. if (options.getContext) {
  25278. _this._canvas = options;
  25279. _this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  25280. }
  25281. else {
  25282. _this._canvas = document.createElement("canvas");
  25283. if (options.width) {
  25284. _this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  25285. }
  25286. else {
  25287. _this._texture = scene.getEngine().createDynamicTexture(options, options, generateMipMaps, samplingMode);
  25288. }
  25289. }
  25290. var textureSize = _this.getSize();
  25291. _this._canvas.width = textureSize.width;
  25292. _this._canvas.height = textureSize.height;
  25293. _this._context = _this._canvas.getContext("2d");
  25294. return _this;
  25295. }
  25296. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  25297. get: function () {
  25298. return true;
  25299. },
  25300. enumerable: true,
  25301. configurable: true
  25302. });
  25303. DynamicTexture.prototype.scale = function (ratio) {
  25304. var textureSize = this.getSize();
  25305. textureSize.width *= ratio;
  25306. textureSize.height *= ratio;
  25307. this._canvas.width = textureSize.width;
  25308. this._canvas.height = textureSize.height;
  25309. this.releaseInternalTexture();
  25310. this._texture = this.getScene().getEngine().createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  25311. };
  25312. DynamicTexture.prototype.getContext = function () {
  25313. return this._context;
  25314. };
  25315. DynamicTexture.prototype.clear = function () {
  25316. var size = this.getSize();
  25317. this._context.fillRect(0, 0, size.width, size.height);
  25318. };
  25319. DynamicTexture.prototype.update = function (invertY) {
  25320. this.getScene().getEngine().updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY);
  25321. };
  25322. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  25323. if (update === void 0) { update = true; }
  25324. var size = this.getSize();
  25325. if (clearColor) {
  25326. this._context.fillStyle = clearColor;
  25327. this._context.fillRect(0, 0, size.width, size.height);
  25328. }
  25329. this._context.font = font;
  25330. if (x === null) {
  25331. var textSize = this._context.measureText(text);
  25332. x = (size.width - textSize.width) / 2;
  25333. }
  25334. this._context.fillStyle = color;
  25335. this._context.fillText(text, x, y);
  25336. if (update) {
  25337. this.update(invertY);
  25338. }
  25339. };
  25340. DynamicTexture.prototype.clone = function () {
  25341. var textureSize = this.getSize();
  25342. var newTexture = new DynamicTexture(this.name, textureSize, this.getScene(), this._generateMipMaps);
  25343. // Base texture
  25344. newTexture.hasAlpha = this.hasAlpha;
  25345. newTexture.level = this.level;
  25346. // Dynamic Texture
  25347. newTexture.wrapU = this.wrapU;
  25348. newTexture.wrapV = this.wrapV;
  25349. return newTexture;
  25350. };
  25351. return DynamicTexture;
  25352. }(BABYLON.Texture));
  25353. BABYLON.DynamicTexture = DynamicTexture;
  25354. })(BABYLON || (BABYLON = {}));
  25355. //# sourceMappingURL=babylon.dynamicTexture.js.map
  25356. var BABYLON;
  25357. (function (BABYLON) {
  25358. var VideoTexture = (function (_super) {
  25359. __extends(VideoTexture, _super);
  25360. /**
  25361. * Creates a video texture.
  25362. * Sample : https://doc.babylonjs.com/tutorials/01._Advanced_Texturing
  25363. * @param {Array} urlsOrVideo can be used to provide an array of urls or an already setup HTML video element.
  25364. * @param {BABYLON.Scene} scene is obviously the current scene.
  25365. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  25366. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  25367. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  25368. */
  25369. function VideoTexture(name, urlsOrVideo, scene, generateMipMaps, invertY, samplingMode) {
  25370. if (generateMipMaps === void 0) { generateMipMaps = false; }
  25371. if (invertY === void 0) { invertY = false; }
  25372. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  25373. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  25374. _this._autoLaunch = true;
  25375. var urls;
  25376. _this.name = name;
  25377. if (urlsOrVideo instanceof HTMLVideoElement) {
  25378. _this.video = urlsOrVideo;
  25379. }
  25380. else {
  25381. urls = urlsOrVideo;
  25382. _this.video = document.createElement("video");
  25383. _this.video.autoplay = false;
  25384. _this.video.loop = true;
  25385. }
  25386. _this._generateMipMaps = generateMipMaps;
  25387. _this._samplingMode = samplingMode;
  25388. if (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight)) {
  25389. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  25390. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  25391. }
  25392. else {
  25393. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  25394. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  25395. _this._generateMipMaps = false;
  25396. }
  25397. if (urls) {
  25398. _this.video.addEventListener("canplaythrough", function () {
  25399. _this._createTexture();
  25400. });
  25401. urls.forEach(function (url) {
  25402. var source = document.createElement("source");
  25403. source.src = url;
  25404. _this.video.appendChild(source);
  25405. });
  25406. }
  25407. else {
  25408. _this._createTexture();
  25409. }
  25410. _this._lastUpdate = BABYLON.Tools.Now;
  25411. return _this;
  25412. }
  25413. VideoTexture.prototype._createTexture = function () {
  25414. this._texture = this.getScene().getEngine().createDynamicTexture(this.video.videoWidth, this.video.videoHeight, this._generateMipMaps, this._samplingMode);
  25415. this._texture.isReady = true;
  25416. };
  25417. VideoTexture.prototype.update = function () {
  25418. if (this._autoLaunch) {
  25419. this._autoLaunch = false;
  25420. this.video.play();
  25421. }
  25422. var now = BABYLON.Tools.Now;
  25423. if (now - this._lastUpdate < 15 || this.video.readyState !== this.video.HAVE_ENOUGH_DATA) {
  25424. return false;
  25425. }
  25426. this._lastUpdate = now;
  25427. this.getScene().getEngine().updateVideoTexture(this._texture, this.video, this._invertY);
  25428. return true;
  25429. };
  25430. VideoTexture.CreateFromWebCam = function (scene, onReady, constraints) {
  25431. var video = document.createElement("video");
  25432. navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia;
  25433. window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
  25434. if (navigator.getUserMedia) {
  25435. navigator.getUserMedia({
  25436. video: {
  25437. width: {
  25438. min: (constraints && constraints.minWidth) || 256,
  25439. max: (constraints && constraints.maxWidth) || 640
  25440. },
  25441. height: {
  25442. min: (constraints && constraints.minHeight) || 256,
  25443. max: (constraints && constraints.maxHeight) || 480
  25444. }
  25445. }
  25446. }, function (stream) {
  25447. if (video.mozSrcObject !== undefined) {
  25448. video.mozSrcObject = stream;
  25449. }
  25450. else {
  25451. video.src = (window.URL && window.URL.createObjectURL(stream)) || stream;
  25452. }
  25453. video.play();
  25454. if (onReady) {
  25455. onReady(new BABYLON.VideoTexture("video", video, scene, true, true));
  25456. }
  25457. }, function (e) {
  25458. BABYLON.Tools.Error(e.name);
  25459. });
  25460. }
  25461. };
  25462. return VideoTexture;
  25463. }(BABYLON.Texture));
  25464. BABYLON.VideoTexture = VideoTexture;
  25465. })(BABYLON || (BABYLON = {}));
  25466. //# sourceMappingURL=babylon.videoTexture.js.map
  25467. var BABYLON;
  25468. (function (BABYLON) {
  25469. var CustomProceduralTexture = (function (_super) {
  25470. __extends(CustomProceduralTexture, _super);
  25471. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  25472. var _this = _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps) || this;
  25473. _this._animate = true;
  25474. _this._time = 0;
  25475. _this._texturePath = texturePath;
  25476. //Try to load json
  25477. _this.loadJson(texturePath);
  25478. _this.refreshRate = 1;
  25479. return _this;
  25480. }
  25481. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  25482. var _this = this;
  25483. var that = this;
  25484. function noConfigFile() {
  25485. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  25486. try {
  25487. that.setFragment(that._texturePath);
  25488. }
  25489. catch (ex) {
  25490. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  25491. }
  25492. }
  25493. var configFileUrl = jsonUrl + "/config.json";
  25494. var xhr = new XMLHttpRequest();
  25495. xhr.open("GET", configFileUrl, true);
  25496. xhr.addEventListener("load", function () {
  25497. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  25498. try {
  25499. _this._config = JSON.parse(xhr.response);
  25500. _this.updateShaderUniforms();
  25501. _this.updateTextures();
  25502. _this.setFragment(_this._texturePath + "/custom");
  25503. _this._animate = _this._config.animate;
  25504. _this.refreshRate = _this._config.refreshrate;
  25505. }
  25506. catch (ex) {
  25507. noConfigFile();
  25508. }
  25509. }
  25510. else {
  25511. noConfigFile();
  25512. }
  25513. }, false);
  25514. xhr.addEventListener("error", function () {
  25515. noConfigFile();
  25516. }, false);
  25517. try {
  25518. xhr.send();
  25519. }
  25520. catch (ex) {
  25521. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  25522. }
  25523. };
  25524. CustomProceduralTexture.prototype.isReady = function () {
  25525. if (!_super.prototype.isReady.call(this)) {
  25526. return false;
  25527. }
  25528. for (var name in this._textures) {
  25529. var texture = this._textures[name];
  25530. if (!texture.isReady()) {
  25531. return false;
  25532. }
  25533. }
  25534. return true;
  25535. };
  25536. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  25537. if (this._animate) {
  25538. this._time += this.getScene().getAnimationRatio() * 0.03;
  25539. this.updateShaderUniforms();
  25540. }
  25541. _super.prototype.render.call(this, useCameraPostProcess);
  25542. };
  25543. CustomProceduralTexture.prototype.updateTextures = function () {
  25544. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  25545. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  25546. }
  25547. };
  25548. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  25549. if (this._config) {
  25550. for (var j = 0; j < this._config.uniforms.length; j++) {
  25551. var uniform = this._config.uniforms[j];
  25552. switch (uniform.type) {
  25553. case "float":
  25554. this.setFloat(uniform.name, uniform.value);
  25555. break;
  25556. case "color3":
  25557. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  25558. break;
  25559. case "color4":
  25560. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  25561. break;
  25562. case "vector2":
  25563. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  25564. break;
  25565. case "vector3":
  25566. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  25567. break;
  25568. }
  25569. }
  25570. }
  25571. this.setFloat("time", this._time);
  25572. };
  25573. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  25574. get: function () {
  25575. return this._animate;
  25576. },
  25577. set: function (value) {
  25578. this._animate = value;
  25579. },
  25580. enumerable: true,
  25581. configurable: true
  25582. });
  25583. return CustomProceduralTexture;
  25584. }(BABYLON.ProceduralTexture));
  25585. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  25586. })(BABYLON || (BABYLON = {}));
  25587. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  25588. var BABYLON;
  25589. (function (BABYLON) {
  25590. var EffectFallbacks = (function () {
  25591. function EffectFallbacks() {
  25592. this._defines = {};
  25593. this._currentRank = 32;
  25594. this._maxRank = -1;
  25595. }
  25596. EffectFallbacks.prototype.addFallback = function (rank, define) {
  25597. if (!this._defines[rank]) {
  25598. if (rank < this._currentRank) {
  25599. this._currentRank = rank;
  25600. }
  25601. if (rank > this._maxRank) {
  25602. this._maxRank = rank;
  25603. }
  25604. this._defines[rank] = new Array();
  25605. }
  25606. this._defines[rank].push(define);
  25607. };
  25608. EffectFallbacks.prototype.addCPUSkinningFallback = function (rank, mesh) {
  25609. this._meshRank = rank;
  25610. this._mesh = mesh;
  25611. if (rank > this._maxRank) {
  25612. this._maxRank = rank;
  25613. }
  25614. };
  25615. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  25616. get: function () {
  25617. return this._currentRank <= this._maxRank;
  25618. },
  25619. enumerable: true,
  25620. configurable: true
  25621. });
  25622. EffectFallbacks.prototype.reduce = function (currentDefines) {
  25623. var currentFallbacks = this._defines[this._currentRank];
  25624. for (var index = 0; index < currentFallbacks.length; index++) {
  25625. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  25626. }
  25627. if (this._mesh && this._currentRank === this._meshRank) {
  25628. this._mesh.computeBonesUsingShaders = false;
  25629. currentDefines = currentDefines.replace("#define NUM_BONE_INFLUENCERS " + this._mesh.numBoneInfluencers, "#define NUM_BONE_INFLUENCERS 0");
  25630. BABYLON.Tools.Log("Falling back to CPU skinning for " + this._mesh.name);
  25631. }
  25632. this._currentRank++;
  25633. return currentDefines;
  25634. };
  25635. return EffectFallbacks;
  25636. }());
  25637. BABYLON.EffectFallbacks = EffectFallbacks;
  25638. var Effect = (function () {
  25639. function Effect(baseName, attributesNames, uniformsNames, samplers, engine, defines, fallbacks, onCompiled, onError, indexParameters) {
  25640. var _this = this;
  25641. this.uniqueId = 0;
  25642. this._isReady = false;
  25643. this._compilationError = "";
  25644. this._valueCache = {};
  25645. this._engine = engine;
  25646. this.name = baseName;
  25647. this.defines = defines;
  25648. this._uniformsNames = uniformsNames.concat(samplers);
  25649. this._samplers = samplers;
  25650. this._attributesNames = attributesNames;
  25651. this.onError = onError;
  25652. this.onCompiled = onCompiled;
  25653. this._indexParameters = indexParameters;
  25654. this.uniqueId = Effect._uniqueIdSeed++;
  25655. var vertexSource;
  25656. var fragmentSource;
  25657. if (baseName.vertexElement) {
  25658. vertexSource = document.getElementById(baseName.vertexElement);
  25659. if (!vertexSource) {
  25660. vertexSource = baseName.vertexElement;
  25661. }
  25662. }
  25663. else {
  25664. vertexSource = baseName.vertex || baseName;
  25665. }
  25666. if (baseName.fragmentElement) {
  25667. fragmentSource = document.getElementById(baseName.fragmentElement);
  25668. if (!fragmentSource) {
  25669. fragmentSource = baseName.fragmentElement;
  25670. }
  25671. }
  25672. else {
  25673. fragmentSource = baseName.fragment || baseName;
  25674. }
  25675. this._loadVertexShader(vertexSource, function (vertexCode) {
  25676. _this._processIncludes(vertexCode, function (vertexCodeWithIncludes) {
  25677. _this._processShaderConversion(vertexCodeWithIncludes, false, function (migratedVertexCode) {
  25678. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  25679. _this._processIncludes(fragmentCode, function (fragmentCodeWithIncludes) {
  25680. _this._processShaderConversion(fragmentCodeWithIncludes, true, function (migratedFragmentCode) {
  25681. _this._prepareEffect(migratedVertexCode, migratedFragmentCode, attributesNames, defines, fallbacks);
  25682. });
  25683. });
  25684. });
  25685. });
  25686. });
  25687. });
  25688. }
  25689. Object.defineProperty(Effect.prototype, "key", {
  25690. get: function () {
  25691. return this._key;
  25692. },
  25693. enumerable: true,
  25694. configurable: true
  25695. });
  25696. // Properties
  25697. Effect.prototype.isReady = function () {
  25698. return this._isReady;
  25699. };
  25700. Effect.prototype.getProgram = function () {
  25701. return this._program;
  25702. };
  25703. Effect.prototype.getAttributesNames = function () {
  25704. return this._attributesNames;
  25705. };
  25706. Effect.prototype.getAttributeLocation = function (index) {
  25707. return this._attributes[index];
  25708. };
  25709. Effect.prototype.getAttributeLocationByName = function (name) {
  25710. var index = this._attributesNames.indexOf(name);
  25711. return this._attributes[index];
  25712. };
  25713. Effect.prototype.getAttributesCount = function () {
  25714. return this._attributes.length;
  25715. };
  25716. Effect.prototype.getUniformIndex = function (uniformName) {
  25717. return this._uniformsNames.indexOf(uniformName);
  25718. };
  25719. Effect.prototype.getUniform = function (uniformName) {
  25720. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  25721. };
  25722. Effect.prototype.getSamplers = function () {
  25723. return this._samplers;
  25724. };
  25725. Effect.prototype.getCompilationError = function () {
  25726. return this._compilationError;
  25727. };
  25728. Effect.prototype.getVertexShaderSource = function () {
  25729. return this._evaluateDefinesOnString(this._engine.getVertexShaderSource(this._program));
  25730. };
  25731. Effect.prototype.getFragmentShaderSource = function () {
  25732. return this._evaluateDefinesOnString(this._engine.getFragmentShaderSource(this._program));
  25733. };
  25734. // Methods
  25735. Effect.prototype._loadVertexShader = function (vertex, callback) {
  25736. // DOM element ?
  25737. if (vertex instanceof HTMLElement) {
  25738. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  25739. callback(vertexCode);
  25740. return;
  25741. }
  25742. // Base64 encoded ?
  25743. if (vertex.substr(0, 7) === "base64:") {
  25744. var vertexBinary = window.atob(vertex.substr(7));
  25745. callback(vertexBinary);
  25746. return;
  25747. }
  25748. // Is in local store ?
  25749. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  25750. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  25751. return;
  25752. }
  25753. var vertexShaderUrl;
  25754. if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
  25755. vertexShaderUrl = vertex;
  25756. }
  25757. else {
  25758. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  25759. }
  25760. // Vertex shader
  25761. BABYLON.Tools.LoadFile(vertexShaderUrl + ".vertex.fx", callback);
  25762. };
  25763. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  25764. // DOM element ?
  25765. if (fragment instanceof HTMLElement) {
  25766. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  25767. callback(fragmentCode);
  25768. return;
  25769. }
  25770. // Base64 encoded ?
  25771. if (fragment.substr(0, 7) === "base64:") {
  25772. var fragmentBinary = window.atob(fragment.substr(7));
  25773. callback(fragmentBinary);
  25774. return;
  25775. }
  25776. // Is in local store ?
  25777. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  25778. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  25779. return;
  25780. }
  25781. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  25782. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  25783. return;
  25784. }
  25785. var fragmentShaderUrl;
  25786. if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
  25787. fragmentShaderUrl = fragment;
  25788. }
  25789. else {
  25790. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  25791. }
  25792. // Fragment shader
  25793. BABYLON.Tools.LoadFile(fragmentShaderUrl + ".fragment.fx", callback);
  25794. };
  25795. Effect.prototype._dumpShadersName = function () {
  25796. if (this.name.vertexElement) {
  25797. BABYLON.Tools.Error("Vertex shader:" + this.name.vertexElement);
  25798. BABYLON.Tools.Error("Fragment shader:" + this.name.fragmentElement);
  25799. }
  25800. else if (this.name.vertex) {
  25801. BABYLON.Tools.Error("Vertex shader:" + this.name.vertex);
  25802. BABYLON.Tools.Error("Fragment shader:" + this.name.fragment);
  25803. }
  25804. else {
  25805. BABYLON.Tools.Error("Vertex shader:" + this.name);
  25806. BABYLON.Tools.Error("Fragment shader:" + this.name);
  25807. }
  25808. };
  25809. Effect.prototype._processShaderConversion = function (sourceCode, isFragment, callback) {
  25810. var preparedSourceCode = this._processPrecision(sourceCode);
  25811. if (this._engine.webGLVersion == 1) {
  25812. callback(preparedSourceCode);
  25813. return;
  25814. }
  25815. // Already converted
  25816. if (preparedSourceCode.indexOf("#version 3") !== -1) {
  25817. callback(preparedSourceCode);
  25818. return;
  25819. }
  25820. // Remove extensions
  25821. // #extension GL_OES_standard_derivatives : enable
  25822. // #extension GL_EXT_shader_texture_lod : enable
  25823. // #extension GL_EXT_frag_depth : enable
  25824. var regex = /#extension.+(GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_frag_depth).+enable/g;
  25825. var result = preparedSourceCode.replace(regex, "");
  25826. // Migrate to GLSL v300
  25827. result = result.replace(/varying\s/g, isFragment ? "in " : "out ");
  25828. result = result.replace(/attribute[ \t]/g, "in ");
  25829. result = result.replace(/[ \t]attribute/g, " in");
  25830. if (isFragment) {
  25831. result = result.replace(/textureCubeLodEXT\(/g, "textureLod(");
  25832. result = result.replace(/texture2D\(/g, "texture(");
  25833. result = result.replace(/textureCube\(/g, "texture(");
  25834. result = result.replace(/gl_FragDepthEXT/g, "gl_FragDepth");
  25835. result = result.replace(/gl_FragColor/g, "glFragColor");
  25836. result = result.replace(/void\s+?main\(/g, "out vec4 glFragColor;\nvoid main(");
  25837. }
  25838. callback(result);
  25839. };
  25840. Effect.prototype._processIncludes = function (sourceCode, callback) {
  25841. var _this = this;
  25842. var regex = /#include<(.+)>(\((.*)\))*(\[(.*)\])*/g;
  25843. var match = regex.exec(sourceCode);
  25844. var returnValue = new String(sourceCode);
  25845. while (match != null) {
  25846. var includeFile = match[1];
  25847. if (Effect.IncludesShadersStore[includeFile]) {
  25848. // Substitution
  25849. var includeContent = Effect.IncludesShadersStore[includeFile];
  25850. if (match[2]) {
  25851. var splits = match[3].split(",");
  25852. for (var index = 0; index < splits.length; index += 2) {
  25853. var source = new RegExp(splits[index], "g");
  25854. var dest = splits[index + 1];
  25855. includeContent = includeContent.replace(source, dest);
  25856. }
  25857. }
  25858. if (match[4]) {
  25859. var indexString = match[5];
  25860. if (indexString.indexOf("..") !== -1) {
  25861. var indexSplits = indexString.split("..");
  25862. var minIndex = parseInt(indexSplits[0]);
  25863. var maxIndex = parseInt(indexSplits[1]);
  25864. var sourceIncludeContent = includeContent.slice(0);
  25865. includeContent = "";
  25866. if (isNaN(maxIndex)) {
  25867. maxIndex = this._indexParameters[indexSplits[1]];
  25868. }
  25869. for (var i = minIndex; i <= maxIndex; i++) {
  25870. includeContent += sourceIncludeContent.replace(/\{X\}/g, i) + "\n";
  25871. }
  25872. }
  25873. else {
  25874. includeContent = includeContent.replace(/\{X\}/g, indexString);
  25875. }
  25876. }
  25877. // Replace
  25878. returnValue = returnValue.replace(match[0], includeContent);
  25879. }
  25880. else {
  25881. var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
  25882. BABYLON.Tools.LoadFile(includeShaderUrl, function (fileContent) {
  25883. Effect.IncludesShadersStore[includeFile] = fileContent;
  25884. _this._processIncludes(returnValue, callback);
  25885. });
  25886. return;
  25887. }
  25888. match = regex.exec(sourceCode);
  25889. }
  25890. callback(returnValue);
  25891. };
  25892. Effect.prototype._processPrecision = function (source) {
  25893. if (source.indexOf("precision highp float") === -1) {
  25894. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  25895. source = "precision mediump float;\n" + source;
  25896. }
  25897. else {
  25898. source = "precision highp float;\n" + source;
  25899. }
  25900. }
  25901. else {
  25902. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  25903. source = source.replace("precision highp float", "precision mediump float");
  25904. }
  25905. }
  25906. return source;
  25907. };
  25908. Effect.prototype._prepareEffect = function (vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks) {
  25909. try {
  25910. var engine = this._engine;
  25911. this._program = engine.createShaderProgram(vertexSourceCode, fragmentSourceCode, defines);
  25912. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  25913. this._attributes = engine.getAttributes(this._program, attributesNames);
  25914. var index;
  25915. for (index = 0; index < this._samplers.length; index++) {
  25916. var sampler = this.getUniform(this._samplers[index]);
  25917. if (sampler == null) {
  25918. this._samplers.splice(index, 1);
  25919. index--;
  25920. }
  25921. }
  25922. engine.bindSamplers(this);
  25923. this._compilationError = "";
  25924. this._isReady = true;
  25925. if (this.onCompiled) {
  25926. this.onCompiled(this);
  25927. }
  25928. }
  25929. catch (e) {
  25930. this._compilationError = e.message;
  25931. // Let's go through fallbacks then
  25932. BABYLON.Tools.Error("Unable to compile effect: ");
  25933. BABYLON.Tools.Error("Defines: " + defines);
  25934. BABYLON.Tools.Error("Error: " + this._compilationError);
  25935. this._dumpShadersName();
  25936. if (fallbacks && fallbacks.isMoreFallbacks) {
  25937. BABYLON.Tools.Error("Trying next fallback.");
  25938. defines = fallbacks.reduce(defines);
  25939. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  25940. }
  25941. else {
  25942. if (this.onError) {
  25943. this.onError(this, this._compilationError);
  25944. }
  25945. }
  25946. }
  25947. };
  25948. Object.defineProperty(Effect.prototype, "isSupported", {
  25949. get: function () {
  25950. return this._compilationError === "";
  25951. },
  25952. enumerable: true,
  25953. configurable: true
  25954. });
  25955. Effect.prototype._bindTexture = function (channel, texture) {
  25956. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  25957. };
  25958. Effect.prototype.setTexture = function (channel, texture) {
  25959. this._engine.setTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  25960. };
  25961. Effect.prototype.setTextureArray = function (channel, textures) {
  25962. if (this._samplers.indexOf(channel + "Ex") === -1) {
  25963. var initialPos = this._samplers.indexOf(channel);
  25964. for (var index = 1; index < textures.length; index++) {
  25965. this._samplers.splice(initialPos + index, 0, channel + "Ex");
  25966. }
  25967. }
  25968. this._engine.setTextureArray(this._samplers.indexOf(channel), this.getUniform(channel), textures);
  25969. };
  25970. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  25971. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  25972. };
  25973. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  25974. var changed = false;
  25975. var cache = this._valueCache[uniformName];
  25976. if (!cache || !(cache instanceof BABYLON.Matrix)) {
  25977. changed = true;
  25978. cache = new BABYLON.Matrix();
  25979. }
  25980. var tm = cache.m;
  25981. var om = matrix.m;
  25982. for (var index = 0; index < 16; index++) {
  25983. if (tm[index] !== om[index]) {
  25984. tm[index] = om[index];
  25985. changed = true;
  25986. }
  25987. }
  25988. this._valueCache[uniformName] = cache;
  25989. return changed;
  25990. };
  25991. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  25992. var cache = this._valueCache[uniformName];
  25993. if (!cache) {
  25994. cache = [x, y];
  25995. this._valueCache[uniformName] = cache;
  25996. return true;
  25997. }
  25998. var changed = false;
  25999. if (cache[0] !== x) {
  26000. cache[0] = x;
  26001. changed = true;
  26002. }
  26003. if (cache[1] !== y) {
  26004. cache[1] = y;
  26005. changed = true;
  26006. }
  26007. return changed;
  26008. };
  26009. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  26010. var cache = this._valueCache[uniformName];
  26011. if (!cache) {
  26012. cache = [x, y, z];
  26013. this._valueCache[uniformName] = cache;
  26014. return true;
  26015. }
  26016. var changed = false;
  26017. if (cache[0] !== x) {
  26018. cache[0] = x;
  26019. changed = true;
  26020. }
  26021. if (cache[1] !== y) {
  26022. cache[1] = y;
  26023. changed = true;
  26024. }
  26025. if (cache[2] !== z) {
  26026. cache[2] = z;
  26027. changed = true;
  26028. }
  26029. return changed;
  26030. };
  26031. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  26032. var cache = this._valueCache[uniformName];
  26033. if (!cache) {
  26034. cache = [x, y, z, w];
  26035. this._valueCache[uniformName] = cache;
  26036. return true;
  26037. }
  26038. var changed = false;
  26039. if (cache[0] !== x) {
  26040. cache[0] = x;
  26041. changed = true;
  26042. }
  26043. if (cache[1] !== y) {
  26044. cache[1] = y;
  26045. changed = true;
  26046. }
  26047. if (cache[2] !== z) {
  26048. cache[2] = z;
  26049. changed = true;
  26050. }
  26051. if (cache[3] !== w) {
  26052. cache[3] = w;
  26053. changed = true;
  26054. }
  26055. return changed;
  26056. };
  26057. Effect.prototype.setIntArray = function (uniformName, array) {
  26058. this._valueCache[uniformName] = null;
  26059. this._engine.setIntArray(this.getUniform(uniformName), array);
  26060. return this;
  26061. };
  26062. Effect.prototype.setIntArray2 = function (uniformName, array) {
  26063. this._valueCache[uniformName] = null;
  26064. this._engine.setIntArray2(this.getUniform(uniformName), array);
  26065. return this;
  26066. };
  26067. Effect.prototype.setIntArray3 = function (uniformName, array) {
  26068. this._valueCache[uniformName] = null;
  26069. this._engine.setIntArray3(this.getUniform(uniformName), array);
  26070. return this;
  26071. };
  26072. Effect.prototype.setIntArray4 = function (uniformName, array) {
  26073. this._valueCache[uniformName] = null;
  26074. this._engine.setIntArray4(this.getUniform(uniformName), array);
  26075. return this;
  26076. };
  26077. Effect.prototype.setFloatArray = function (uniformName, array) {
  26078. this._valueCache[uniformName] = null;
  26079. this._engine.setFloatArray(this.getUniform(uniformName), array);
  26080. return this;
  26081. };
  26082. Effect.prototype.setFloatArray2 = function (uniformName, array) {
  26083. this._valueCache[uniformName] = null;
  26084. this._engine.setFloatArray2(this.getUniform(uniformName), array);
  26085. return this;
  26086. };
  26087. Effect.prototype.setFloatArray3 = function (uniformName, array) {
  26088. this._valueCache[uniformName] = null;
  26089. this._engine.setFloatArray3(this.getUniform(uniformName), array);
  26090. return this;
  26091. };
  26092. Effect.prototype.setFloatArray4 = function (uniformName, array) {
  26093. this._valueCache[uniformName] = null;
  26094. this._engine.setFloatArray4(this.getUniform(uniformName), array);
  26095. return this;
  26096. };
  26097. Effect.prototype.setArray = function (uniformName, array) {
  26098. this._valueCache[uniformName] = null;
  26099. this._engine.setArray(this.getUniform(uniformName), array);
  26100. return this;
  26101. };
  26102. Effect.prototype.setArray2 = function (uniformName, array) {
  26103. this._valueCache[uniformName] = null;
  26104. this._engine.setArray2(this.getUniform(uniformName), array);
  26105. return this;
  26106. };
  26107. Effect.prototype.setArray3 = function (uniformName, array) {
  26108. this._valueCache[uniformName] = null;
  26109. this._engine.setArray3(this.getUniform(uniformName), array);
  26110. return this;
  26111. };
  26112. Effect.prototype.setArray4 = function (uniformName, array) {
  26113. this._valueCache[uniformName] = null;
  26114. this._engine.setArray4(this.getUniform(uniformName), array);
  26115. return this;
  26116. };
  26117. Effect.prototype.setMatrices = function (uniformName, matrices) {
  26118. this._valueCache[uniformName] = null;
  26119. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  26120. return this;
  26121. };
  26122. Effect.prototype.setMatrix = function (uniformName, matrix) {
  26123. if (this._cacheMatrix(uniformName, matrix)) {
  26124. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  26125. }
  26126. return this;
  26127. };
  26128. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  26129. this._valueCache[uniformName] = null;
  26130. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  26131. return this;
  26132. };
  26133. Effect.prototype.setMatrix2x2 = function (uniformName, matrix) {
  26134. this._valueCache[uniformName] = null;
  26135. this._engine.setMatrix2x2(this.getUniform(uniformName), matrix);
  26136. return this;
  26137. };
  26138. Effect.prototype.setFloat = function (uniformName, value) {
  26139. var cache = this._valueCache[uniformName];
  26140. if (cache !== undefined && cache === value)
  26141. return this;
  26142. this._valueCache[uniformName] = value;
  26143. this._engine.setFloat(this.getUniform(uniformName), value);
  26144. return this;
  26145. };
  26146. Effect.prototype.setBool = function (uniformName, bool) {
  26147. var cache = this._valueCache[uniformName];
  26148. if (cache !== undefined && cache === bool)
  26149. return this;
  26150. this._valueCache[uniformName] = bool;
  26151. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  26152. return this;
  26153. };
  26154. Effect.prototype.setVector2 = function (uniformName, vector2) {
  26155. if (this._cacheFloat2(uniformName, vector2.x, vector2.y)) {
  26156. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  26157. }
  26158. return this;
  26159. };
  26160. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  26161. if (this._cacheFloat2(uniformName, x, y)) {
  26162. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  26163. }
  26164. return this;
  26165. };
  26166. Effect.prototype.setVector3 = function (uniformName, vector3) {
  26167. if (this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z)) {
  26168. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  26169. }
  26170. return this;
  26171. };
  26172. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  26173. if (this._cacheFloat3(uniformName, x, y, z)) {
  26174. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  26175. }
  26176. return this;
  26177. };
  26178. Effect.prototype.setVector4 = function (uniformName, vector4) {
  26179. if (this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w)) {
  26180. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  26181. }
  26182. return this;
  26183. };
  26184. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  26185. if (this._cacheFloat4(uniformName, x, y, z, w)) {
  26186. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  26187. }
  26188. return this;
  26189. };
  26190. Effect.prototype.setColor3 = function (uniformName, color3) {
  26191. if (this._cacheFloat3(uniformName, color3.r, color3.g, color3.b)) {
  26192. this._engine.setColor3(this.getUniform(uniformName), color3);
  26193. }
  26194. return this;
  26195. };
  26196. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  26197. if (this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha)) {
  26198. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  26199. }
  26200. return this;
  26201. };
  26202. Effect.prototype._recombineShader = function (node) {
  26203. if (node.define) {
  26204. if (node.condition) {
  26205. var defineIndex = this.defines.indexOf("#define " + node.define);
  26206. if (defineIndex === -1) {
  26207. return null;
  26208. }
  26209. var nextComma = this.defines.indexOf("\n", defineIndex);
  26210. var defineValue = this.defines.substr(defineIndex + 7, nextComma - defineIndex - 7).replace(node.define, "").trim();
  26211. var condition = defineValue + node.condition;
  26212. if (!eval(condition)) {
  26213. return null;
  26214. }
  26215. }
  26216. else if (node.ndef) {
  26217. if (this.defines.indexOf("#define " + node.define) !== -1) {
  26218. return null;
  26219. }
  26220. }
  26221. else if (this.defines.indexOf("#define " + node.define) === -1) {
  26222. return null;
  26223. }
  26224. }
  26225. var result = "";
  26226. for (var index = 0; index < node.children.length; index++) {
  26227. var line = node.children[index];
  26228. if (line.children) {
  26229. var combined = this._recombineShader(line);
  26230. if (combined !== null) {
  26231. result += combined + "\r\n";
  26232. }
  26233. continue;
  26234. }
  26235. if (line.length > 0) {
  26236. result += line + "\r\n";
  26237. }
  26238. }
  26239. return result;
  26240. };
  26241. Effect.prototype._evaluateDefinesOnString = function (shaderString) {
  26242. var root = {
  26243. children: []
  26244. };
  26245. var currentNode = root;
  26246. var lines = shaderString.split("\n");
  26247. for (var index = 0; index < lines.length; index++) {
  26248. var line = lines[index].trim();
  26249. // #ifdef
  26250. var pos = line.indexOf("#ifdef ");
  26251. if (pos !== -1) {
  26252. var define = line.substr(pos + 7);
  26253. var newNode = {
  26254. condition: null,
  26255. ndef: false,
  26256. define: define,
  26257. children: [],
  26258. parent: currentNode
  26259. };
  26260. currentNode.children.push(newNode);
  26261. currentNode = newNode;
  26262. continue;
  26263. }
  26264. // #ifndef
  26265. var pos = line.indexOf("#ifndef ");
  26266. if (pos !== -1) {
  26267. var define = line.substr(pos + 8);
  26268. newNode = {
  26269. condition: null,
  26270. define: define,
  26271. ndef: true,
  26272. children: [],
  26273. parent: currentNode
  26274. };
  26275. currentNode.children.push(newNode);
  26276. currentNode = newNode;
  26277. continue;
  26278. }
  26279. // #if
  26280. var pos = line.indexOf("#if ");
  26281. if (pos !== -1) {
  26282. var define = line.substr(pos + 4).trim();
  26283. var conditionPos = define.indexOf(" ");
  26284. newNode = {
  26285. condition: define.substr(conditionPos + 1),
  26286. define: define.substr(0, conditionPos),
  26287. ndef: false,
  26288. children: [],
  26289. parent: currentNode
  26290. };
  26291. currentNode.children.push(newNode);
  26292. currentNode = newNode;
  26293. continue;
  26294. }
  26295. // #endif
  26296. pos = line.indexOf("#endif");
  26297. if (pos !== -1) {
  26298. currentNode = currentNode.parent;
  26299. continue;
  26300. }
  26301. currentNode.children.push(line);
  26302. }
  26303. // Recombine
  26304. return this._recombineShader(root);
  26305. };
  26306. return Effect;
  26307. }());
  26308. Effect._uniqueIdSeed = 0;
  26309. // Statics
  26310. Effect.ShadersStore = {};
  26311. Effect.IncludesShadersStore = {};
  26312. BABYLON.Effect = Effect;
  26313. })(BABYLON || (BABYLON = {}));
  26314. //# sourceMappingURL=babylon.effect.js.map
  26315. var BABYLON;
  26316. (function (BABYLON) {
  26317. var MaterialHelper = (function () {
  26318. function MaterialHelper() {
  26319. }
  26320. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, maxSimultaneousLights) {
  26321. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  26322. var lightIndex = 0;
  26323. var needNormals = false;
  26324. var needRebuild = false;
  26325. var needShadows = false;
  26326. var lightmapMode = false;
  26327. for (var index = 0; index < scene.lights.length; index++) {
  26328. var light = scene.lights[index];
  26329. if (!light.isEnabled()) {
  26330. continue;
  26331. }
  26332. // Excluded check
  26333. if (light._excludedMeshesIds.length > 0) {
  26334. for (var excludedIndex = 0; excludedIndex < light._excludedMeshesIds.length; excludedIndex++) {
  26335. var excludedMesh = scene.getMeshByID(light._excludedMeshesIds[excludedIndex]);
  26336. if (excludedMesh) {
  26337. light.excludedMeshes.push(excludedMesh);
  26338. }
  26339. }
  26340. light._excludedMeshesIds = [];
  26341. }
  26342. // Included check
  26343. if (light._includedOnlyMeshesIds.length > 0) {
  26344. for (var includedOnlyIndex = 0; includedOnlyIndex < light._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  26345. var includedOnlyMesh = scene.getMeshByID(light._includedOnlyMeshesIds[includedOnlyIndex]);
  26346. if (includedOnlyMesh) {
  26347. light.includedOnlyMeshes.push(includedOnlyMesh);
  26348. }
  26349. }
  26350. light._includedOnlyMeshesIds = [];
  26351. }
  26352. if (!light.canAffectMesh(mesh)) {
  26353. continue;
  26354. }
  26355. needNormals = true;
  26356. if (defines["LIGHT" + lightIndex] === undefined) {
  26357. needRebuild = true;
  26358. }
  26359. defines["LIGHT" + lightIndex] = true;
  26360. var type;
  26361. if (light instanceof BABYLON.SpotLight) {
  26362. type = "SPOTLIGHT" + lightIndex;
  26363. }
  26364. else if (light instanceof BABYLON.HemisphericLight) {
  26365. type = "HEMILIGHT" + lightIndex;
  26366. }
  26367. else if (light instanceof BABYLON.PointLight) {
  26368. type = "POINTLIGHT" + lightIndex;
  26369. }
  26370. else {
  26371. type = "DIRLIGHT" + lightIndex;
  26372. }
  26373. if (defines[type] === undefined) {
  26374. needRebuild = true;
  26375. }
  26376. defines[type] = true;
  26377. // Specular
  26378. if (!light.specular.equalsFloats(0, 0, 0) && defines["SPECULARTERM"] !== undefined) {
  26379. defines["SPECULARTERM"] = true;
  26380. }
  26381. // Shadows
  26382. if (scene.shadowsEnabled) {
  26383. var shadowGenerator = light.getShadowGenerator();
  26384. if (mesh && mesh.receiveShadows && shadowGenerator) {
  26385. if (defines["SHADOW" + lightIndex] === undefined) {
  26386. needRebuild = true;
  26387. }
  26388. defines["SHADOW" + lightIndex] = true;
  26389. defines["SHADOWS"] = true;
  26390. if (shadowGenerator.useVarianceShadowMap || shadowGenerator.useBlurVarianceShadowMap) {
  26391. if (defines["SHADOWVSM" + lightIndex] === undefined) {
  26392. needRebuild = true;
  26393. }
  26394. defines["SHADOWVSM" + lightIndex] = true;
  26395. }
  26396. if (shadowGenerator.usePoissonSampling) {
  26397. if (defines["SHADOWPCF" + lightIndex] === undefined) {
  26398. needRebuild = true;
  26399. }
  26400. defines["SHADOWPCF" + lightIndex] = true;
  26401. }
  26402. needShadows = true;
  26403. }
  26404. }
  26405. if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
  26406. lightmapMode = true;
  26407. if (defines["LIGHTMAPEXCLUDED" + lightIndex] === undefined) {
  26408. needRebuild = true;
  26409. }
  26410. if (defines["LIGHTMAPNOSPECULAR" + lightIndex] === undefined) {
  26411. needRebuild = true;
  26412. }
  26413. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  26414. if (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY) {
  26415. defines["LIGHTMAPNOSPECULAR" + lightIndex] = true;
  26416. }
  26417. }
  26418. lightIndex++;
  26419. if (lightIndex === maxSimultaneousLights)
  26420. break;
  26421. }
  26422. var caps = scene.getEngine().getCaps();
  26423. if (needShadows && caps.textureFloat && caps.textureFloatLinearFiltering && caps.textureFloatRender) {
  26424. if (defines["SHADOWFULLFLOAT"] === undefined) {
  26425. needRebuild = true;
  26426. }
  26427. defines["SHADOWFULLFLOAT"] = true;
  26428. }
  26429. if (defines["LIGHTMAPEXCLUDED"] === undefined) {
  26430. needRebuild = true;
  26431. }
  26432. if (lightmapMode) {
  26433. defines["LIGHTMAPEXCLUDED"] = true;
  26434. }
  26435. if (needRebuild) {
  26436. defines.rebuild();
  26437. }
  26438. return needNormals;
  26439. };
  26440. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsList, samplersList, defines, maxSimultaneousLights) {
  26441. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  26442. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  26443. if (!defines["LIGHT" + lightIndex]) {
  26444. break;
  26445. }
  26446. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex);
  26447. samplersList.push("shadowSampler" + lightIndex);
  26448. }
  26449. };
  26450. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights) {
  26451. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  26452. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  26453. if (!defines["LIGHT" + lightIndex]) {
  26454. break;
  26455. }
  26456. if (lightIndex > 0) {
  26457. fallbacks.addFallback(lightIndex, "LIGHT" + lightIndex);
  26458. }
  26459. if (defines["SHADOW" + lightIndex]) {
  26460. fallbacks.addFallback(0, "SHADOW" + lightIndex);
  26461. }
  26462. if (defines["SHADOWPCF" + lightIndex]) {
  26463. fallbacks.addFallback(0, "SHADOWPCF" + lightIndex);
  26464. }
  26465. if (defines["SHADOWVSM" + lightIndex]) {
  26466. fallbacks.addFallback(0, "SHADOWVSM" + lightIndex);
  26467. }
  26468. }
  26469. };
  26470. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  26471. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  26472. fallbacks.addCPUSkinningFallback(0, mesh);
  26473. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  26474. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  26475. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  26476. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  26477. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  26478. }
  26479. }
  26480. };
  26481. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  26482. if (defines["INSTANCES"]) {
  26483. attribs.push("world0");
  26484. attribs.push("world1");
  26485. attribs.push("world2");
  26486. attribs.push("world3");
  26487. }
  26488. };
  26489. // Bindings
  26490. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect, depthValuesAlreadySet) {
  26491. var shadowGenerator = light.getShadowGenerator();
  26492. if (mesh.receiveShadows && shadowGenerator) {
  26493. if (!light.needCube()) {
  26494. effect.setMatrix("lightMatrix" + lightIndex, shadowGenerator.getTransformMatrix());
  26495. }
  26496. else {
  26497. if (!depthValuesAlreadySet) {
  26498. depthValuesAlreadySet = true;
  26499. effect.setFloat2("depthValues", scene.activeCamera.minZ, scene.activeCamera.maxZ);
  26500. }
  26501. }
  26502. effect.setTexture("shadowSampler" + lightIndex, shadowGenerator.getShadowMapForRendering());
  26503. effect.setFloat3("shadowsInfo" + lightIndex, shadowGenerator.getDarkness(), shadowGenerator.blurScale / shadowGenerator.getShadowMap().getSize().width, shadowGenerator.bias);
  26504. }
  26505. return depthValuesAlreadySet;
  26506. };
  26507. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  26508. if (light instanceof BABYLON.PointLight) {
  26509. // Point Light
  26510. light.transferToEffect(effect, "vLightData" + lightIndex);
  26511. }
  26512. else if (light instanceof BABYLON.DirectionalLight) {
  26513. // Directional Light
  26514. light.transferToEffect(effect, "vLightData" + lightIndex);
  26515. }
  26516. else if (light instanceof BABYLON.SpotLight) {
  26517. // Spot Light
  26518. light.transferToEffect(effect, "vLightData" + lightIndex, "vLightDirection" + lightIndex);
  26519. }
  26520. else if (light instanceof BABYLON.HemisphericLight) {
  26521. // Hemispheric Light
  26522. light.transferToEffect(effect, "vLightData" + lightIndex, "vLightGround" + lightIndex);
  26523. }
  26524. };
  26525. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights) {
  26526. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  26527. var lightIndex = 0;
  26528. var depthValuesAlreadySet = false;
  26529. for (var index = 0; index < scene.lights.length; index++) {
  26530. var light = scene.lights[index];
  26531. if (!light.isEnabled()) {
  26532. continue;
  26533. }
  26534. if (!light.canAffectMesh(mesh)) {
  26535. continue;
  26536. }
  26537. MaterialHelper.BindLightProperties(light, effect, lightIndex);
  26538. light.diffuse.scaleToRef(light.intensity, BABYLON.Tmp.Color3[0]);
  26539. effect.setColor4("vLightDiffuse" + lightIndex, BABYLON.Tmp.Color3[0], light.range);
  26540. if (defines["SPECULARTERM"]) {
  26541. light.specular.scaleToRef(light.intensity, BABYLON.Tmp.Color3[1]);
  26542. effect.setColor3("vLightSpecular" + lightIndex, BABYLON.Tmp.Color3[1]);
  26543. }
  26544. // Shadows
  26545. if (scene.shadowsEnabled) {
  26546. depthValuesAlreadySet = this.BindLightShadow(light, scene, mesh, lightIndex, effect, depthValuesAlreadySet);
  26547. }
  26548. lightIndex++;
  26549. if (lightIndex === maxSimultaneousLights)
  26550. break;
  26551. }
  26552. };
  26553. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  26554. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  26555. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  26556. effect.setColor3("vFogColor", scene.fogColor);
  26557. }
  26558. };
  26559. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  26560. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  26561. var matrices = mesh.skeleton.getTransformMatrices(mesh);
  26562. if (matrices) {
  26563. effect.setMatrices("mBones", matrices);
  26564. }
  26565. }
  26566. };
  26567. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  26568. if (defines["LOGARITHMICDEPTH"]) {
  26569. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  26570. }
  26571. };
  26572. MaterialHelper.BindClipPlane = function (effect, scene) {
  26573. if (scene.clipPlane) {
  26574. var clipPlane = scene.clipPlane;
  26575. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  26576. }
  26577. };
  26578. return MaterialHelper;
  26579. }());
  26580. BABYLON.MaterialHelper = MaterialHelper;
  26581. })(BABYLON || (BABYLON = {}));
  26582. //# sourceMappingURL=babylon.materialHelper.js.map
  26583. var BABYLON;
  26584. (function (BABYLON) {
  26585. var FresnelParameters = (function () {
  26586. function FresnelParameters() {
  26587. this.isEnabled = true;
  26588. this.leftColor = BABYLON.Color3.White();
  26589. this.rightColor = BABYLON.Color3.Black();
  26590. this.bias = 0;
  26591. this.power = 1;
  26592. }
  26593. FresnelParameters.prototype.clone = function () {
  26594. var newFresnelParameters = new FresnelParameters();
  26595. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  26596. return newFresnelParameters;
  26597. };
  26598. FresnelParameters.prototype.serialize = function () {
  26599. var serializationObject = {};
  26600. serializationObject.isEnabled = this.isEnabled;
  26601. serializationObject.leftColor = this.leftColor;
  26602. serializationObject.rightColor = this.rightColor;
  26603. serializationObject.bias = this.bias;
  26604. serializationObject.power = this.power;
  26605. return serializationObject;
  26606. };
  26607. FresnelParameters.Parse = function (parsedFresnelParameters) {
  26608. var fresnelParameters = new FresnelParameters();
  26609. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  26610. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  26611. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  26612. fresnelParameters.bias = parsedFresnelParameters.bias;
  26613. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  26614. return fresnelParameters;
  26615. };
  26616. return FresnelParameters;
  26617. }());
  26618. BABYLON.FresnelParameters = FresnelParameters;
  26619. })(BABYLON || (BABYLON = {}));
  26620. //# sourceMappingURL=babylon.fresnelParameters.js.map
  26621. var BABYLON;
  26622. (function (BABYLON) {
  26623. var MaterialDefines = (function () {
  26624. function MaterialDefines() {
  26625. }
  26626. MaterialDefines.prototype.rebuild = function () {
  26627. if (this._keys) {
  26628. delete this._keys;
  26629. }
  26630. this._keys = Object.keys(this);
  26631. };
  26632. MaterialDefines.prototype.isEqual = function (other) {
  26633. if (this._keys.length !== other._keys.length) {
  26634. return false;
  26635. }
  26636. for (var index = 0; index < this._keys.length; index++) {
  26637. var prop = this._keys[index];
  26638. if (this[prop] !== other[prop]) {
  26639. return false;
  26640. }
  26641. }
  26642. return true;
  26643. };
  26644. MaterialDefines.prototype.cloneTo = function (other) {
  26645. if (this._keys.length !== other._keys.length) {
  26646. other._keys = this._keys.slice(0);
  26647. }
  26648. for (var index = 0; index < this._keys.length; index++) {
  26649. var prop = this._keys[index];
  26650. other[prop] = this[prop];
  26651. }
  26652. };
  26653. MaterialDefines.prototype.reset = function () {
  26654. for (var index = 0; index < this._keys.length; index++) {
  26655. var prop = this._keys[index];
  26656. if (typeof (this[prop]) === "number") {
  26657. this[prop] = 0;
  26658. }
  26659. else {
  26660. this[prop] = false;
  26661. }
  26662. }
  26663. };
  26664. MaterialDefines.prototype.toString = function () {
  26665. var result = "";
  26666. for (var index = 0; index < this._keys.length; index++) {
  26667. var prop = this._keys[index];
  26668. if (typeof (this[prop]) === "number") {
  26669. result += "#define " + prop + " " + this[prop] + "\n";
  26670. }
  26671. else if (this[prop]) {
  26672. result += "#define " + prop + "\n";
  26673. }
  26674. }
  26675. return result;
  26676. };
  26677. return MaterialDefines;
  26678. }());
  26679. BABYLON.MaterialDefines = MaterialDefines;
  26680. var Material = (function () {
  26681. function Material(name, scene, doNotAdd) {
  26682. this.checkReadyOnEveryCall = false;
  26683. this.checkReadyOnlyOnce = false;
  26684. this.state = "";
  26685. this.alpha = 1.0;
  26686. this.backFaceCulling = true;
  26687. this.doNotSerialize = false;
  26688. /**
  26689. * An event triggered when the material is disposed.
  26690. * @type {BABYLON.Observable}
  26691. */
  26692. this.onDisposeObservable = new BABYLON.Observable();
  26693. /**
  26694. * An event triggered when the material is bound.
  26695. * @type {BABYLON.Observable}
  26696. */
  26697. this.onBindObservable = new BABYLON.Observable();
  26698. /**
  26699. * An event triggered when the material is unbound.
  26700. * @type {BABYLON.Observable}
  26701. */
  26702. this.onUnBindObservable = new BABYLON.Observable();
  26703. this.alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  26704. this.disableDepthWrite = false;
  26705. this.fogEnabled = true;
  26706. this.pointSize = 1.0;
  26707. this.zOffset = 0;
  26708. this._wasPreviouslyReady = false;
  26709. this._fillMode = Material.TriangleFillMode;
  26710. this.name = name;
  26711. this.id = name;
  26712. this._scene = scene;
  26713. if (scene.useRightHandedSystem) {
  26714. this.sideOrientation = Material.ClockWiseSideOrientation;
  26715. }
  26716. else {
  26717. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  26718. }
  26719. if (!doNotAdd) {
  26720. scene.materials.push(this);
  26721. }
  26722. }
  26723. Object.defineProperty(Material, "TriangleFillMode", {
  26724. get: function () {
  26725. return Material._TriangleFillMode;
  26726. },
  26727. enumerable: true,
  26728. configurable: true
  26729. });
  26730. Object.defineProperty(Material, "WireFrameFillMode", {
  26731. get: function () {
  26732. return Material._WireFrameFillMode;
  26733. },
  26734. enumerable: true,
  26735. configurable: true
  26736. });
  26737. Object.defineProperty(Material, "PointFillMode", {
  26738. get: function () {
  26739. return Material._PointFillMode;
  26740. },
  26741. enumerable: true,
  26742. configurable: true
  26743. });
  26744. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  26745. get: function () {
  26746. return Material._ClockWiseSideOrientation;
  26747. },
  26748. enumerable: true,
  26749. configurable: true
  26750. });
  26751. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  26752. get: function () {
  26753. return Material._CounterClockWiseSideOrientation;
  26754. },
  26755. enumerable: true,
  26756. configurable: true
  26757. });
  26758. Object.defineProperty(Material.prototype, "onDispose", {
  26759. set: function (callback) {
  26760. if (this._onDisposeObserver) {
  26761. this.onDisposeObservable.remove(this._onDisposeObserver);
  26762. }
  26763. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  26764. },
  26765. enumerable: true,
  26766. configurable: true
  26767. });
  26768. Object.defineProperty(Material.prototype, "onBind", {
  26769. set: function (callback) {
  26770. if (this._onBindObserver) {
  26771. this.onBindObservable.remove(this._onBindObserver);
  26772. }
  26773. this._onBindObserver = this.onBindObservable.add(callback);
  26774. },
  26775. enumerable: true,
  26776. configurable: true
  26777. });
  26778. Object.defineProperty(Material.prototype, "wireframe", {
  26779. get: function () {
  26780. return this._fillMode === Material.WireFrameFillMode;
  26781. },
  26782. set: function (value) {
  26783. this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  26784. },
  26785. enumerable: true,
  26786. configurable: true
  26787. });
  26788. Object.defineProperty(Material.prototype, "pointsCloud", {
  26789. get: function () {
  26790. return this._fillMode === Material.PointFillMode;
  26791. },
  26792. set: function (value) {
  26793. this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  26794. },
  26795. enumerable: true,
  26796. configurable: true
  26797. });
  26798. Object.defineProperty(Material.prototype, "fillMode", {
  26799. get: function () {
  26800. return this._fillMode;
  26801. },
  26802. set: function (value) {
  26803. this._fillMode = value;
  26804. },
  26805. enumerable: true,
  26806. configurable: true
  26807. });
  26808. /**
  26809. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  26810. * subclasses should override adding information pertainent to themselves
  26811. */
  26812. Material.prototype.toString = function (fullDetails) {
  26813. var ret = "Name: " + this.name;
  26814. if (fullDetails) {
  26815. }
  26816. return ret;
  26817. };
  26818. Material.prototype.getClassName = function () {
  26819. return "Material";
  26820. };
  26821. Object.defineProperty(Material.prototype, "isFrozen", {
  26822. get: function () {
  26823. return this.checkReadyOnlyOnce;
  26824. },
  26825. enumerable: true,
  26826. configurable: true
  26827. });
  26828. Material.prototype.freeze = function () {
  26829. this.checkReadyOnlyOnce = true;
  26830. };
  26831. Material.prototype.unfreeze = function () {
  26832. this.checkReadyOnlyOnce = false;
  26833. };
  26834. Material.prototype.isReady = function (mesh, useInstances) {
  26835. return true;
  26836. };
  26837. Material.prototype.getEffect = function () {
  26838. return this._effect;
  26839. };
  26840. Material.prototype.getScene = function () {
  26841. return this._scene;
  26842. };
  26843. Material.prototype.needAlphaBlending = function () {
  26844. return (this.alpha < 1.0);
  26845. };
  26846. Material.prototype.needAlphaTesting = function () {
  26847. return false;
  26848. };
  26849. Material.prototype.getAlphaTestTexture = function () {
  26850. return null;
  26851. };
  26852. Material.prototype.markDirty = function () {
  26853. this._wasPreviouslyReady = false;
  26854. };
  26855. Material.prototype._preBind = function () {
  26856. var engine = this._scene.getEngine();
  26857. var reverse = this.sideOrientation === Material.ClockWiseSideOrientation;
  26858. engine.enableEffect(this._effect);
  26859. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  26860. };
  26861. Material.prototype.bind = function (world, mesh) {
  26862. this._scene._cachedMaterial = this;
  26863. this.onBindObservable.notifyObservers(mesh);
  26864. if (this.disableDepthWrite) {
  26865. var engine = this._scene.getEngine();
  26866. this._cachedDepthWriteState = engine.getDepthWrite();
  26867. engine.setDepthWrite(false);
  26868. }
  26869. };
  26870. Material.prototype.bindOnlyWorldMatrix = function (world) {
  26871. };
  26872. Material.prototype.unbind = function () {
  26873. this.onUnBindObservable.notifyObservers(this);
  26874. if (this.disableDepthWrite) {
  26875. var engine = this._scene.getEngine();
  26876. engine.setDepthWrite(this._cachedDepthWriteState);
  26877. }
  26878. };
  26879. Material.prototype.clone = function (name) {
  26880. return null;
  26881. };
  26882. Material.prototype.getBindedMeshes = function () {
  26883. var result = new Array();
  26884. for (var index = 0; index < this._scene.meshes.length; index++) {
  26885. var mesh = this._scene.meshes[index];
  26886. if (mesh.material === this) {
  26887. result.push(mesh);
  26888. }
  26889. }
  26890. return result;
  26891. };
  26892. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  26893. // Animations
  26894. this.getScene().stopAnimation(this);
  26895. // Remove from scene
  26896. var index = this._scene.materials.indexOf(this);
  26897. if (index >= 0) {
  26898. this._scene.materials.splice(index, 1);
  26899. }
  26900. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  26901. if (forceDisposeEffect && this._effect) {
  26902. this._scene.getEngine()._releaseEffect(this._effect);
  26903. this._effect = null;
  26904. }
  26905. // Remove from meshes
  26906. for (index = 0; index < this._scene.meshes.length; index++) {
  26907. var mesh = this._scene.meshes[index];
  26908. if (mesh.material === this) {
  26909. mesh.material = null;
  26910. }
  26911. }
  26912. // Callback
  26913. this.onDisposeObservable.notifyObservers(this);
  26914. this.onDisposeObservable.clear();
  26915. this.onBindObservable.clear();
  26916. this.onUnBindObservable.clear();
  26917. };
  26918. Material.prototype.serialize = function () {
  26919. return BABYLON.SerializationHelper.Serialize(this);
  26920. };
  26921. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  26922. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  26923. multiMaterial.id = parsedMultiMaterial.id;
  26924. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  26925. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  26926. var subMatId = parsedMultiMaterial.materials[matIndex];
  26927. if (subMatId) {
  26928. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  26929. }
  26930. else {
  26931. multiMaterial.subMaterials.push(null);
  26932. }
  26933. }
  26934. return multiMaterial;
  26935. };
  26936. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  26937. if (!parsedMaterial.customType) {
  26938. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  26939. }
  26940. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  26941. return materialType.Parse(parsedMaterial, scene, rootUrl);
  26942. ;
  26943. };
  26944. return Material;
  26945. }());
  26946. Material._TriangleFillMode = 0;
  26947. Material._WireFrameFillMode = 1;
  26948. Material._PointFillMode = 2;
  26949. Material._ClockWiseSideOrientation = 0;
  26950. Material._CounterClockWiseSideOrientation = 1;
  26951. __decorate([
  26952. BABYLON.serialize()
  26953. ], Material.prototype, "id", void 0);
  26954. __decorate([
  26955. BABYLON.serialize()
  26956. ], Material.prototype, "name", void 0);
  26957. __decorate([
  26958. BABYLON.serialize()
  26959. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  26960. __decorate([
  26961. BABYLON.serialize()
  26962. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  26963. __decorate([
  26964. BABYLON.serialize()
  26965. ], Material.prototype, "state", void 0);
  26966. __decorate([
  26967. BABYLON.serialize()
  26968. ], Material.prototype, "alpha", void 0);
  26969. __decorate([
  26970. BABYLON.serialize()
  26971. ], Material.prototype, "backFaceCulling", void 0);
  26972. __decorate([
  26973. BABYLON.serialize()
  26974. ], Material.prototype, "sideOrientation", void 0);
  26975. __decorate([
  26976. BABYLON.serialize()
  26977. ], Material.prototype, "alphaMode", void 0);
  26978. __decorate([
  26979. BABYLON.serialize()
  26980. ], Material.prototype, "disableDepthWrite", void 0);
  26981. __decorate([
  26982. BABYLON.serialize()
  26983. ], Material.prototype, "fogEnabled", void 0);
  26984. __decorate([
  26985. BABYLON.serialize()
  26986. ], Material.prototype, "pointSize", void 0);
  26987. __decorate([
  26988. BABYLON.serialize()
  26989. ], Material.prototype, "zOffset", void 0);
  26990. __decorate([
  26991. BABYLON.serialize()
  26992. ], Material.prototype, "wireframe", null);
  26993. __decorate([
  26994. BABYLON.serialize()
  26995. ], Material.prototype, "pointsCloud", null);
  26996. __decorate([
  26997. BABYLON.serialize()
  26998. ], Material.prototype, "fillMode", null);
  26999. BABYLON.Material = Material;
  27000. })(BABYLON || (BABYLON = {}));
  27001. //# sourceMappingURL=babylon.material.js.map
  27002. var BABYLON;
  27003. (function (BABYLON) {
  27004. var StandardMaterialDefines = (function (_super) {
  27005. __extends(StandardMaterialDefines, _super);
  27006. function StandardMaterialDefines() {
  27007. var _this = _super.call(this) || this;
  27008. _this.DIFFUSE = false;
  27009. _this.AMBIENT = false;
  27010. _this.OPACITY = false;
  27011. _this.OPACITYRGB = false;
  27012. _this.REFLECTION = false;
  27013. _this.EMISSIVE = false;
  27014. _this.SPECULAR = false;
  27015. _this.BUMP = false;
  27016. _this.PARALLAX = false;
  27017. _this.PARALLAXOCCLUSION = false;
  27018. _this.SPECULAROVERALPHA = false;
  27019. _this.CLIPPLANE = false;
  27020. _this.ALPHATEST = false;
  27021. _this.ALPHAFROMDIFFUSE = false;
  27022. _this.POINTSIZE = false;
  27023. _this.FOG = false;
  27024. _this.SPECULARTERM = false;
  27025. _this.DIFFUSEFRESNEL = false;
  27026. _this.OPACITYFRESNEL = false;
  27027. _this.REFLECTIONFRESNEL = false;
  27028. _this.REFRACTIONFRESNEL = false;
  27029. _this.EMISSIVEFRESNEL = false;
  27030. _this.FRESNEL = false;
  27031. _this.NORMAL = false;
  27032. _this.UV1 = false;
  27033. _this.UV2 = false;
  27034. _this.VERTEXCOLOR = false;
  27035. _this.VERTEXALPHA = false;
  27036. _this.NUM_BONE_INFLUENCERS = 0;
  27037. _this.BonesPerMesh = 0;
  27038. _this.INSTANCES = false;
  27039. _this.GLOSSINESS = false;
  27040. _this.ROUGHNESS = false;
  27041. _this.EMISSIVEASILLUMINATION = false;
  27042. _this.LINKEMISSIVEWITHDIFFUSE = false;
  27043. _this.REFLECTIONFRESNELFROMSPECULAR = false;
  27044. _this.LIGHTMAP = false;
  27045. _this.USELIGHTMAPASSHADOWMAP = false;
  27046. _this.REFLECTIONMAP_3D = false;
  27047. _this.REFLECTIONMAP_SPHERICAL = false;
  27048. _this.REFLECTIONMAP_PLANAR = false;
  27049. _this.REFLECTIONMAP_CUBIC = false;
  27050. _this.REFLECTIONMAP_PROJECTION = false;
  27051. _this.REFLECTIONMAP_SKYBOX = false;
  27052. _this.REFLECTIONMAP_EXPLICIT = false;
  27053. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  27054. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  27055. _this.INVERTCUBICMAP = false;
  27056. _this.LOGARITHMICDEPTH = false;
  27057. _this.REFRACTION = false;
  27058. _this.REFRACTIONMAP_3D = false;
  27059. _this.REFLECTIONOVERALPHA = false;
  27060. _this.INVERTNORMALMAPX = false;
  27061. _this.INVERTNORMALMAPY = false;
  27062. _this.SHADOWFULLFLOAT = false;
  27063. _this.CAMERACOLORGRADING = false;
  27064. _this.CAMERACOLORCURVES = false;
  27065. _this.rebuild();
  27066. return _this;
  27067. }
  27068. return StandardMaterialDefines;
  27069. }(BABYLON.MaterialDefines));
  27070. var StandardMaterial = (function (_super) {
  27071. __extends(StandardMaterial, _super);
  27072. function StandardMaterial(name, scene) {
  27073. var _this = _super.call(this, name, scene) || this;
  27074. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  27075. _this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  27076. _this.specularColor = new BABYLON.Color3(1, 1, 1);
  27077. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  27078. _this.specularPower = 64;
  27079. _this.useAlphaFromDiffuseTexture = false;
  27080. _this.useEmissiveAsIllumination = false;
  27081. _this.linkEmissiveWithDiffuse = false;
  27082. _this.useReflectionFresnelFromSpecular = false;
  27083. _this.useSpecularOverAlpha = false;
  27084. _this.useReflectionOverAlpha = false;
  27085. _this.disableLighting = false;
  27086. _this.useParallax = false;
  27087. _this.useParallaxOcclusion = false;
  27088. _this.parallaxScaleBias = 0.05;
  27089. _this.roughness = 0;
  27090. _this.indexOfRefraction = 0.98;
  27091. _this.invertRefractionY = true;
  27092. _this.useLightmapAsShadowmap = false;
  27093. _this.useGlossinessFromSpecularMapAlpha = false;
  27094. _this.maxSimultaneousLights = 4;
  27095. /**
  27096. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  27097. */
  27098. _this.invertNormalMapX = false;
  27099. /**
  27100. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  27101. */
  27102. _this.invertNormalMapY = false;
  27103. /**
  27104. * Color Grading 2D Lookup Texture.
  27105. * This allows special effects like sepia, black and white to sixties rendering style.
  27106. */
  27107. _this.cameraColorGradingTexture = null;
  27108. /**
  27109. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  27110. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  27111. * 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;
  27112. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  27113. */
  27114. _this.cameraColorCurves = null;
  27115. _this._renderTargets = new BABYLON.SmartArray(16);
  27116. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  27117. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  27118. _this._defines = new StandardMaterialDefines();
  27119. _this._cachedDefines = new StandardMaterialDefines();
  27120. _this._cachedDefines.BonesPerMesh = -1;
  27121. _this.getRenderTargetTextures = function () {
  27122. _this._renderTargets.reset();
  27123. if (_this.reflectionTexture && _this.reflectionTexture.isRenderTarget) {
  27124. _this._renderTargets.push(_this.reflectionTexture);
  27125. }
  27126. if (_this.refractionTexture && _this.refractionTexture.isRenderTarget) {
  27127. _this._renderTargets.push(_this.refractionTexture);
  27128. }
  27129. return _this._renderTargets;
  27130. };
  27131. return _this;
  27132. }
  27133. StandardMaterial.prototype.getClassName = function () {
  27134. return "StandardMaterial";
  27135. };
  27136. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  27137. get: function () {
  27138. return this._useLogarithmicDepth;
  27139. },
  27140. set: function (value) {
  27141. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  27142. },
  27143. enumerable: true,
  27144. configurable: true
  27145. });
  27146. StandardMaterial.prototype.needAlphaBlending = function () {
  27147. return (this.alpha < 1.0) || (this.opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled;
  27148. };
  27149. StandardMaterial.prototype.needAlphaTesting = function () {
  27150. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha;
  27151. };
  27152. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  27153. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha && this.useAlphaFromDiffuseTexture;
  27154. };
  27155. StandardMaterial.prototype.getAlphaTestTexture = function () {
  27156. return this.diffuseTexture;
  27157. };
  27158. // Methods
  27159. StandardMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  27160. if (!mesh) {
  27161. return true;
  27162. }
  27163. if (this._defines.INSTANCES !== useInstances) {
  27164. return false;
  27165. }
  27166. if (mesh._materialDefines && mesh._materialDefines.isEqual(this._defines)) {
  27167. return true;
  27168. }
  27169. return false;
  27170. };
  27171. StandardMaterial.prototype.isReady = function (mesh, useInstances) {
  27172. if (this.isFrozen) {
  27173. if (this._wasPreviouslyReady) {
  27174. return true;
  27175. }
  27176. }
  27177. var scene = this.getScene();
  27178. var engine = scene.getEngine();
  27179. var needUVs = false;
  27180. var needNormals = false;
  27181. this._defines.reset();
  27182. // Lights
  27183. if (scene.lightsEnabled && !this.disableLighting) {
  27184. needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, this._defines, this.maxSimultaneousLights);
  27185. }
  27186. if (!this.checkReadyOnEveryCall) {
  27187. if (this._renderId === scene.getRenderId()) {
  27188. if (this._checkCache(scene, mesh, useInstances)) {
  27189. return true;
  27190. }
  27191. }
  27192. }
  27193. // Textures
  27194. if (scene.texturesEnabled) {
  27195. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  27196. if (!this.diffuseTexture.isReady()) {
  27197. return false;
  27198. }
  27199. else {
  27200. needUVs = true;
  27201. this._defines.DIFFUSE = true;
  27202. }
  27203. }
  27204. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  27205. if (!this.ambientTexture.isReady()) {
  27206. return false;
  27207. }
  27208. else {
  27209. needUVs = true;
  27210. this._defines.AMBIENT = true;
  27211. }
  27212. }
  27213. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  27214. if (!this.opacityTexture.isReady()) {
  27215. return false;
  27216. }
  27217. else {
  27218. needUVs = true;
  27219. this._defines.OPACITY = true;
  27220. if (this.opacityTexture.getAlphaFromRGB) {
  27221. this._defines.OPACITYRGB = true;
  27222. }
  27223. }
  27224. }
  27225. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  27226. if (!this.reflectionTexture.isReady()) {
  27227. return false;
  27228. }
  27229. else {
  27230. needNormals = true;
  27231. this._defines.REFLECTION = true;
  27232. if (this.roughness > 0) {
  27233. this._defines.ROUGHNESS = true;
  27234. }
  27235. if (this.useReflectionOverAlpha) {
  27236. this._defines.REFLECTIONOVERALPHA = true;
  27237. }
  27238. if (this.reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  27239. this._defines.INVERTCUBICMAP = true;
  27240. }
  27241. this._defines.REFLECTIONMAP_3D = this.reflectionTexture.isCube;
  27242. switch (this.reflectionTexture.coordinatesMode) {
  27243. case BABYLON.Texture.CUBIC_MODE:
  27244. case BABYLON.Texture.INVCUBIC_MODE:
  27245. this._defines.REFLECTIONMAP_CUBIC = true;
  27246. break;
  27247. case BABYLON.Texture.EXPLICIT_MODE:
  27248. this._defines.REFLECTIONMAP_EXPLICIT = true;
  27249. break;
  27250. case BABYLON.Texture.PLANAR_MODE:
  27251. this._defines.REFLECTIONMAP_PLANAR = true;
  27252. break;
  27253. case BABYLON.Texture.PROJECTION_MODE:
  27254. this._defines.REFLECTIONMAP_PROJECTION = true;
  27255. break;
  27256. case BABYLON.Texture.SKYBOX_MODE:
  27257. this._defines.REFLECTIONMAP_SKYBOX = true;
  27258. break;
  27259. case BABYLON.Texture.SPHERICAL_MODE:
  27260. this._defines.REFLECTIONMAP_SPHERICAL = true;
  27261. break;
  27262. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  27263. this._defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  27264. break;
  27265. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  27266. this._defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  27267. break;
  27268. }
  27269. }
  27270. }
  27271. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  27272. if (!this.emissiveTexture.isReady()) {
  27273. return false;
  27274. }
  27275. else {
  27276. needUVs = true;
  27277. this._defines.EMISSIVE = true;
  27278. }
  27279. }
  27280. if (this.lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  27281. if (!this.lightmapTexture.isReady()) {
  27282. return false;
  27283. }
  27284. else {
  27285. needUVs = true;
  27286. this._defines.LIGHTMAP = true;
  27287. this._defines.USELIGHTMAPASSHADOWMAP = this.useLightmapAsShadowmap;
  27288. }
  27289. }
  27290. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  27291. if (!this.specularTexture.isReady()) {
  27292. return false;
  27293. }
  27294. else {
  27295. needUVs = true;
  27296. this._defines.SPECULAR = true;
  27297. this._defines.GLOSSINESS = this.useGlossinessFromSpecularMapAlpha;
  27298. }
  27299. }
  27300. if (scene.getEngine().getCaps().standardDerivatives && this.bumpTexture && StandardMaterial.BumpTextureEnabled) {
  27301. if (!this.bumpTexture.isReady()) {
  27302. return false;
  27303. }
  27304. else {
  27305. needUVs = true;
  27306. this._defines.BUMP = true;
  27307. if (this.useParallax) {
  27308. this._defines.PARALLAX = true;
  27309. if (this.useParallaxOcclusion) {
  27310. this._defines.PARALLAXOCCLUSION = true;
  27311. }
  27312. }
  27313. if (this.invertNormalMapX) {
  27314. this._defines.INVERTNORMALMAPX = true;
  27315. }
  27316. if (this.invertNormalMapY) {
  27317. this._defines.INVERTNORMALMAPY = true;
  27318. }
  27319. if (scene._mirroredCameraPosition) {
  27320. this._defines.INVERTNORMALMAPX = !this._defines.INVERTNORMALMAPX;
  27321. this._defines.INVERTNORMALMAPY = !this._defines.INVERTNORMALMAPY;
  27322. }
  27323. }
  27324. }
  27325. if (this.refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  27326. if (!this.refractionTexture.isReady()) {
  27327. return false;
  27328. }
  27329. else {
  27330. needUVs = true;
  27331. this._defines.REFRACTION = true;
  27332. this._defines.REFRACTIONMAP_3D = this.refractionTexture.isCube;
  27333. }
  27334. }
  27335. if (this.cameraColorGradingTexture && StandardMaterial.ColorGradingTextureEnabled) {
  27336. if (!this.cameraColorGradingTexture.isReady()) {
  27337. return false;
  27338. }
  27339. else {
  27340. this._defines.CAMERACOLORGRADING = true;
  27341. }
  27342. }
  27343. }
  27344. // Effect
  27345. if (scene.clipPlane) {
  27346. this._defines.CLIPPLANE = true;
  27347. }
  27348. if (engine.getAlphaTesting()) {
  27349. this._defines.ALPHATEST = true;
  27350. }
  27351. if (this._shouldUseAlphaFromDiffuseTexture()) {
  27352. this._defines.ALPHAFROMDIFFUSE = true;
  27353. }
  27354. if (this.useEmissiveAsIllumination) {
  27355. this._defines.EMISSIVEASILLUMINATION = true;
  27356. }
  27357. if (this.linkEmissiveWithDiffuse) {
  27358. this._defines.LINKEMISSIVEWITHDIFFUSE = true;
  27359. }
  27360. if (this.useLogarithmicDepth) {
  27361. this._defines.LOGARITHMICDEPTH = true;
  27362. }
  27363. if (this.cameraColorCurves) {
  27364. this._defines.CAMERACOLORCURVES = true;
  27365. }
  27366. // Point size
  27367. if (this.pointsCloud || scene.forcePointsCloud) {
  27368. this._defines.POINTSIZE = true;
  27369. }
  27370. // Fog
  27371. if (scene.fogEnabled && mesh && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  27372. this._defines.FOG = true;
  27373. }
  27374. if (StandardMaterial.FresnelEnabled) {
  27375. // Fresnel
  27376. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled ||
  27377. this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled ||
  27378. this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled ||
  27379. this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled ||
  27380. this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  27381. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  27382. this._defines.DIFFUSEFRESNEL = true;
  27383. }
  27384. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  27385. this._defines.OPACITYFRESNEL = true;
  27386. }
  27387. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  27388. this._defines.REFLECTIONFRESNEL = true;
  27389. if (this.useReflectionFresnelFromSpecular) {
  27390. this._defines.REFLECTIONFRESNELFROMSPECULAR = true;
  27391. }
  27392. }
  27393. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  27394. this._defines.REFRACTIONFRESNEL = true;
  27395. }
  27396. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  27397. this._defines.EMISSIVEFRESNEL = true;
  27398. }
  27399. needNormals = true;
  27400. this._defines.FRESNEL = true;
  27401. }
  27402. }
  27403. if (this._defines.SPECULARTERM && this.useSpecularOverAlpha) {
  27404. this._defines.SPECULAROVERALPHA = true;
  27405. }
  27406. // Attribs
  27407. if (mesh) {
  27408. if (needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  27409. this._defines.NORMAL = true;
  27410. }
  27411. if (needUVs) {
  27412. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  27413. this._defines.UV1 = true;
  27414. }
  27415. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  27416. this._defines.UV2 = true;
  27417. }
  27418. }
  27419. if (mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  27420. this._defines.VERTEXCOLOR = true;
  27421. if (mesh.hasVertexAlpha) {
  27422. this._defines.VERTEXALPHA = true;
  27423. }
  27424. }
  27425. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  27426. this._defines.NUM_BONE_INFLUENCERS = mesh.numBoneInfluencers;
  27427. this._defines.BonesPerMesh = (mesh.skeleton.bones.length + 1);
  27428. }
  27429. // Instances
  27430. if (useInstances) {
  27431. this._defines.INSTANCES = true;
  27432. }
  27433. }
  27434. // Get correct effect
  27435. if (!this._defines.isEqual(this._cachedDefines)) {
  27436. this._defines.cloneTo(this._cachedDefines);
  27437. scene.resetCachedMaterial();
  27438. // Fallbacks
  27439. var fallbacks = new BABYLON.EffectFallbacks();
  27440. if (this._defines.REFLECTION) {
  27441. fallbacks.addFallback(0, "REFLECTION");
  27442. }
  27443. if (this._defines.SPECULAR) {
  27444. fallbacks.addFallback(0, "SPECULAR");
  27445. }
  27446. if (this._defines.BUMP) {
  27447. fallbacks.addFallback(0, "BUMP");
  27448. }
  27449. if (this._defines.PARALLAX) {
  27450. fallbacks.addFallback(1, "PARALLAX");
  27451. }
  27452. if (this._defines.PARALLAXOCCLUSION) {
  27453. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  27454. }
  27455. if (this._defines.SPECULAROVERALPHA) {
  27456. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  27457. }
  27458. if (this._defines.FOG) {
  27459. fallbacks.addFallback(1, "FOG");
  27460. }
  27461. if (this._defines.POINTSIZE) {
  27462. fallbacks.addFallback(0, "POINTSIZE");
  27463. }
  27464. if (this._defines.LOGARITHMICDEPTH) {
  27465. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  27466. }
  27467. BABYLON.MaterialHelper.HandleFallbacksForShadows(this._defines, fallbacks, this.maxSimultaneousLights);
  27468. if (this._defines.SPECULARTERM) {
  27469. fallbacks.addFallback(0, "SPECULARTERM");
  27470. }
  27471. if (this._defines.DIFFUSEFRESNEL) {
  27472. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  27473. }
  27474. if (this._defines.OPACITYFRESNEL) {
  27475. fallbacks.addFallback(2, "OPACITYFRESNEL");
  27476. }
  27477. if (this._defines.REFLECTIONFRESNEL) {
  27478. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  27479. }
  27480. if (this._defines.EMISSIVEFRESNEL) {
  27481. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  27482. }
  27483. if (this._defines.FRESNEL) {
  27484. fallbacks.addFallback(4, "FRESNEL");
  27485. }
  27486. //Attributes
  27487. var attribs = [BABYLON.VertexBuffer.PositionKind];
  27488. if (this._defines.NORMAL) {
  27489. attribs.push(BABYLON.VertexBuffer.NormalKind);
  27490. }
  27491. if (this._defines.UV1) {
  27492. attribs.push(BABYLON.VertexBuffer.UVKind);
  27493. }
  27494. if (this._defines.UV2) {
  27495. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  27496. }
  27497. if (this._defines.VERTEXCOLOR) {
  27498. attribs.push(BABYLON.VertexBuffer.ColorKind);
  27499. }
  27500. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, this._defines, fallbacks);
  27501. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, this._defines);
  27502. var shaderName = "default";
  27503. var join = this._defines.toString();
  27504. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  27505. "vFogInfos", "vFogColor", "pointSize",
  27506. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  27507. "mBones",
  27508. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  27509. "depthValues",
  27510. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  27511. "logarithmicDepthConstant"
  27512. ];
  27513. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  27514. if (this._defines.CAMERACOLORCURVES) {
  27515. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  27516. }
  27517. if (this._defines.CAMERACOLORGRADING) {
  27518. BABYLON.ColorGradingTexture.PrepareUniformsAndSamplers(uniforms, samplers);
  27519. }
  27520. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList(uniforms, samplers, this._defines, this.maxSimultaneousLights);
  27521. this._effect = scene.getEngine().createEffect(shaderName, attribs, uniforms, samplers, join, fallbacks, this.onCompiled, this.onError, { maxSimultaneousLights: this.maxSimultaneousLights - 1 });
  27522. }
  27523. if (!this._effect.isReady()) {
  27524. return false;
  27525. }
  27526. this._renderId = scene.getRenderId();
  27527. this._wasPreviouslyReady = true;
  27528. if (mesh) {
  27529. if (!mesh._materialDefines) {
  27530. mesh._materialDefines = new StandardMaterialDefines();
  27531. }
  27532. this._defines.cloneTo(mesh._materialDefines);
  27533. }
  27534. return true;
  27535. };
  27536. StandardMaterial.prototype.unbind = function () {
  27537. if (this.reflectionTexture && this.reflectionTexture.isRenderTarget) {
  27538. this._effect.setTexture("reflection2DSampler", null);
  27539. }
  27540. if (this.refractionTexture && this.refractionTexture.isRenderTarget) {
  27541. this._effect.setTexture("refraction2DSampler", null);
  27542. }
  27543. _super.prototype.unbind.call(this);
  27544. };
  27545. StandardMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  27546. this._effect.setMatrix("world", world);
  27547. };
  27548. StandardMaterial.prototype.bind = function (world, mesh) {
  27549. var scene = this.getScene();
  27550. // Matrices
  27551. this.bindOnlyWorldMatrix(world);
  27552. // Bones
  27553. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  27554. if (scene.getCachedMaterial() !== this) {
  27555. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  27556. if (StandardMaterial.FresnelEnabled) {
  27557. // Fresnel
  27558. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  27559. this._effect.setColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  27560. this._effect.setColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  27561. }
  27562. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  27563. this._effect.setColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  27564. }
  27565. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  27566. this._effect.setColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  27567. this._effect.setColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  27568. }
  27569. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  27570. this._effect.setColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  27571. this._effect.setColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  27572. }
  27573. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  27574. this._effect.setColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  27575. this._effect.setColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  27576. }
  27577. }
  27578. // Textures
  27579. if (scene.texturesEnabled) {
  27580. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  27581. this._effect.setTexture("diffuseSampler", this.diffuseTexture);
  27582. this._effect.setFloat2("vDiffuseInfos", this.diffuseTexture.coordinatesIndex, this.diffuseTexture.level);
  27583. this._effect.setMatrix("diffuseMatrix", this.diffuseTexture.getTextureMatrix());
  27584. }
  27585. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  27586. this._effect.setTexture("ambientSampler", this.ambientTexture);
  27587. this._effect.setFloat2("vAmbientInfos", this.ambientTexture.coordinatesIndex, this.ambientTexture.level);
  27588. this._effect.setMatrix("ambientMatrix", this.ambientTexture.getTextureMatrix());
  27589. }
  27590. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  27591. this._effect.setTexture("opacitySampler", this.opacityTexture);
  27592. this._effect.setFloat2("vOpacityInfos", this.opacityTexture.coordinatesIndex, this.opacityTexture.level);
  27593. this._effect.setMatrix("opacityMatrix", this.opacityTexture.getTextureMatrix());
  27594. }
  27595. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  27596. if (this.reflectionTexture.isCube) {
  27597. this._effect.setTexture("reflectionCubeSampler", this.reflectionTexture);
  27598. }
  27599. else {
  27600. this._effect.setTexture("reflection2DSampler", this.reflectionTexture);
  27601. }
  27602. this._effect.setMatrix("reflectionMatrix", this.reflectionTexture.getReflectionTextureMatrix());
  27603. this._effect.setFloat2("vReflectionInfos", this.reflectionTexture.level, this.roughness);
  27604. }
  27605. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  27606. this._effect.setTexture("emissiveSampler", this.emissiveTexture);
  27607. this._effect.setFloat2("vEmissiveInfos", this.emissiveTexture.coordinatesIndex, this.emissiveTexture.level);
  27608. this._effect.setMatrix("emissiveMatrix", this.emissiveTexture.getTextureMatrix());
  27609. }
  27610. if (this.lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  27611. this._effect.setTexture("lightmapSampler", this.lightmapTexture);
  27612. this._effect.setFloat2("vLightmapInfos", this.lightmapTexture.coordinatesIndex, this.lightmapTexture.level);
  27613. this._effect.setMatrix("lightmapMatrix", this.lightmapTexture.getTextureMatrix());
  27614. }
  27615. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  27616. this._effect.setTexture("specularSampler", this.specularTexture);
  27617. this._effect.setFloat2("vSpecularInfos", this.specularTexture.coordinatesIndex, this.specularTexture.level);
  27618. this._effect.setMatrix("specularMatrix", this.specularTexture.getTextureMatrix());
  27619. }
  27620. if (this.bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  27621. this._effect.setTexture("bumpSampler", this.bumpTexture);
  27622. this._effect.setFloat3("vBumpInfos", this.bumpTexture.coordinatesIndex, 1.0 / this.bumpTexture.level, this.parallaxScaleBias);
  27623. this._effect.setMatrix("bumpMatrix", this.bumpTexture.getTextureMatrix());
  27624. }
  27625. if (this.refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  27626. var depth = 1.0;
  27627. if (this.refractionTexture.isCube) {
  27628. this._effect.setTexture("refractionCubeSampler", this.refractionTexture);
  27629. }
  27630. else {
  27631. this._effect.setTexture("refraction2DSampler", this.refractionTexture);
  27632. this._effect.setMatrix("refractionMatrix", this.refractionTexture.getReflectionTextureMatrix());
  27633. if (this.refractionTexture.depth) {
  27634. depth = this.refractionTexture.depth;
  27635. }
  27636. }
  27637. this._effect.setFloat4("vRefractionInfos", this.refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  27638. }
  27639. if (this.cameraColorGradingTexture && StandardMaterial.ColorGradingTextureEnabled) {
  27640. BABYLON.ColorGradingTexture.Bind(this.cameraColorGradingTexture, this._effect);
  27641. }
  27642. }
  27643. // Clip plane
  27644. BABYLON.MaterialHelper.BindClipPlane(this._effect, scene);
  27645. // Point size
  27646. if (this.pointsCloud) {
  27647. this._effect.setFloat("pointSize", this.pointSize);
  27648. }
  27649. // Colors
  27650. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  27651. this._effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.position);
  27652. this._effect.setColor3("vAmbientColor", this._globalAmbientColor);
  27653. if (this._defines.SPECULARTERM) {
  27654. this._effect.setColor4("vSpecularColor", this.specularColor, this.specularPower);
  27655. }
  27656. this._effect.setColor3("vEmissiveColor", this.emissiveColor);
  27657. }
  27658. if (scene.getCachedMaterial() !== this || !this.isFrozen) {
  27659. // Diffuse
  27660. this._effect.setColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  27661. // Lights
  27662. if (scene.lightsEnabled && !this.disableLighting) {
  27663. BABYLON.MaterialHelper.BindLights(scene, mesh, this._effect, this._defines, this.maxSimultaneousLights);
  27664. }
  27665. // View
  27666. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this.reflectionTexture || this.refractionTexture) {
  27667. this._effect.setMatrix("view", scene.getViewMatrix());
  27668. }
  27669. // Fog
  27670. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._effect);
  27671. // Log. depth
  27672. BABYLON.MaterialHelper.BindLogDepth(this._defines, this._effect, scene);
  27673. // Color Curves
  27674. if (this.cameraColorCurves) {
  27675. BABYLON.ColorCurves.Bind(this.cameraColorCurves, this._effect);
  27676. }
  27677. }
  27678. _super.prototype.bind.call(this, world, mesh);
  27679. };
  27680. StandardMaterial.prototype.getAnimatables = function () {
  27681. var results = [];
  27682. if (this.diffuseTexture && this.diffuseTexture.animations && this.diffuseTexture.animations.length > 0) {
  27683. results.push(this.diffuseTexture);
  27684. }
  27685. if (this.ambientTexture && this.ambientTexture.animations && this.ambientTexture.animations.length > 0) {
  27686. results.push(this.ambientTexture);
  27687. }
  27688. if (this.opacityTexture && this.opacityTexture.animations && this.opacityTexture.animations.length > 0) {
  27689. results.push(this.opacityTexture);
  27690. }
  27691. if (this.reflectionTexture && this.reflectionTexture.animations && this.reflectionTexture.animations.length > 0) {
  27692. results.push(this.reflectionTexture);
  27693. }
  27694. if (this.emissiveTexture && this.emissiveTexture.animations && this.emissiveTexture.animations.length > 0) {
  27695. results.push(this.emissiveTexture);
  27696. }
  27697. if (this.specularTexture && this.specularTexture.animations && this.specularTexture.animations.length > 0) {
  27698. results.push(this.specularTexture);
  27699. }
  27700. if (this.bumpTexture && this.bumpTexture.animations && this.bumpTexture.animations.length > 0) {
  27701. results.push(this.bumpTexture);
  27702. }
  27703. if (this.lightmapTexture && this.lightmapTexture.animations && this.lightmapTexture.animations.length > 0) {
  27704. results.push(this.lightmapTexture);
  27705. }
  27706. if (this.refractionTexture && this.refractionTexture.animations && this.refractionTexture.animations.length > 0) {
  27707. results.push(this.refractionTexture);
  27708. }
  27709. if (this.cameraColorGradingTexture && this.cameraColorGradingTexture.animations && this.cameraColorGradingTexture.animations.length > 0) {
  27710. results.push(this.cameraColorGradingTexture);
  27711. }
  27712. return results;
  27713. };
  27714. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  27715. if (forceDisposeTextures) {
  27716. if (this.diffuseTexture) {
  27717. this.diffuseTexture.dispose();
  27718. }
  27719. if (this.ambientTexture) {
  27720. this.ambientTexture.dispose();
  27721. }
  27722. if (this.opacityTexture) {
  27723. this.opacityTexture.dispose();
  27724. }
  27725. if (this.reflectionTexture) {
  27726. this.reflectionTexture.dispose();
  27727. }
  27728. if (this.emissiveTexture) {
  27729. this.emissiveTexture.dispose();
  27730. }
  27731. if (this.specularTexture) {
  27732. this.specularTexture.dispose();
  27733. }
  27734. if (this.bumpTexture) {
  27735. this.bumpTexture.dispose();
  27736. }
  27737. if (this.lightmapTexture) {
  27738. this.lightmapTexture.dispose();
  27739. }
  27740. if (this.refractionTexture) {
  27741. this.refractionTexture.dispose();
  27742. }
  27743. if (this.cameraColorGradingTexture) {
  27744. this.cameraColorGradingTexture.dispose();
  27745. }
  27746. }
  27747. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  27748. };
  27749. StandardMaterial.prototype.clone = function (name) {
  27750. var _this = this;
  27751. return BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  27752. };
  27753. StandardMaterial.prototype.serialize = function () {
  27754. return BABYLON.SerializationHelper.Serialize(this);
  27755. };
  27756. // Statics
  27757. StandardMaterial.Parse = function (source, scene, rootUrl) {
  27758. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  27759. };
  27760. return StandardMaterial;
  27761. }(BABYLON.Material));
  27762. // Flags used to enable or disable a type of texture for all Standard Materials
  27763. StandardMaterial.DiffuseTextureEnabled = true;
  27764. StandardMaterial.AmbientTextureEnabled = true;
  27765. StandardMaterial.OpacityTextureEnabled = true;
  27766. StandardMaterial.ReflectionTextureEnabled = true;
  27767. StandardMaterial.EmissiveTextureEnabled = true;
  27768. StandardMaterial.SpecularTextureEnabled = true;
  27769. StandardMaterial.BumpTextureEnabled = true;
  27770. StandardMaterial.FresnelEnabled = true;
  27771. StandardMaterial.LightmapTextureEnabled = true;
  27772. StandardMaterial.RefractionTextureEnabled = true;
  27773. StandardMaterial.ColorGradingTextureEnabled = true;
  27774. __decorate([
  27775. BABYLON.serializeAsTexture()
  27776. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  27777. __decorate([
  27778. BABYLON.serializeAsTexture()
  27779. ], StandardMaterial.prototype, "ambientTexture", void 0);
  27780. __decorate([
  27781. BABYLON.serializeAsTexture()
  27782. ], StandardMaterial.prototype, "opacityTexture", void 0);
  27783. __decorate([
  27784. BABYLON.serializeAsTexture()
  27785. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  27786. __decorate([
  27787. BABYLON.serializeAsTexture()
  27788. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  27789. __decorate([
  27790. BABYLON.serializeAsTexture()
  27791. ], StandardMaterial.prototype, "specularTexture", void 0);
  27792. __decorate([
  27793. BABYLON.serializeAsTexture()
  27794. ], StandardMaterial.prototype, "bumpTexture", void 0);
  27795. __decorate([
  27796. BABYLON.serializeAsTexture()
  27797. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  27798. __decorate([
  27799. BABYLON.serializeAsTexture()
  27800. ], StandardMaterial.prototype, "refractionTexture", void 0);
  27801. __decorate([
  27802. BABYLON.serializeAsColor3("ambient")
  27803. ], StandardMaterial.prototype, "ambientColor", void 0);
  27804. __decorate([
  27805. BABYLON.serializeAsColor3("diffuse")
  27806. ], StandardMaterial.prototype, "diffuseColor", void 0);
  27807. __decorate([
  27808. BABYLON.serializeAsColor3("specular")
  27809. ], StandardMaterial.prototype, "specularColor", void 0);
  27810. __decorate([
  27811. BABYLON.serializeAsColor3("emissive")
  27812. ], StandardMaterial.prototype, "emissiveColor", void 0);
  27813. __decorate([
  27814. BABYLON.serialize()
  27815. ], StandardMaterial.prototype, "specularPower", void 0);
  27816. __decorate([
  27817. BABYLON.serialize()
  27818. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  27819. __decorate([
  27820. BABYLON.serialize()
  27821. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  27822. __decorate([
  27823. BABYLON.serialize()
  27824. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  27825. __decorate([
  27826. BABYLON.serialize()
  27827. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  27828. __decorate([
  27829. BABYLON.serialize()
  27830. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  27831. __decorate([
  27832. BABYLON.serialize()
  27833. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  27834. __decorate([
  27835. BABYLON.serialize()
  27836. ], StandardMaterial.prototype, "disableLighting", void 0);
  27837. __decorate([
  27838. BABYLON.serialize()
  27839. ], StandardMaterial.prototype, "useParallax", void 0);
  27840. __decorate([
  27841. BABYLON.serialize()
  27842. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  27843. __decorate([
  27844. BABYLON.serialize()
  27845. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  27846. __decorate([
  27847. BABYLON.serialize()
  27848. ], StandardMaterial.prototype, "roughness", void 0);
  27849. __decorate([
  27850. BABYLON.serialize()
  27851. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  27852. __decorate([
  27853. BABYLON.serialize()
  27854. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  27855. __decorate([
  27856. BABYLON.serialize()
  27857. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  27858. __decorate([
  27859. BABYLON.serializeAsFresnelParameters()
  27860. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  27861. __decorate([
  27862. BABYLON.serializeAsFresnelParameters()
  27863. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  27864. __decorate([
  27865. BABYLON.serializeAsFresnelParameters()
  27866. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  27867. __decorate([
  27868. BABYLON.serializeAsFresnelParameters()
  27869. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  27870. __decorate([
  27871. BABYLON.serializeAsFresnelParameters()
  27872. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  27873. __decorate([
  27874. BABYLON.serialize()
  27875. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  27876. __decorate([
  27877. BABYLON.serialize()
  27878. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  27879. __decorate([
  27880. BABYLON.serialize()
  27881. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  27882. __decorate([
  27883. BABYLON.serialize()
  27884. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  27885. __decorate([
  27886. BABYLON.serializeAsTexture()
  27887. ], StandardMaterial.prototype, "cameraColorGradingTexture", void 0);
  27888. __decorate([
  27889. BABYLON.serializeAsColorCurves()
  27890. ], StandardMaterial.prototype, "cameraColorCurves", void 0);
  27891. __decorate([
  27892. BABYLON.serialize()
  27893. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  27894. BABYLON.StandardMaterial = StandardMaterial;
  27895. })(BABYLON || (BABYLON = {}));
  27896. //# sourceMappingURL=babylon.standardMaterial.js.map
  27897. var BABYLON;
  27898. (function (BABYLON) {
  27899. var MultiMaterial = (function (_super) {
  27900. __extends(MultiMaterial, _super);
  27901. function MultiMaterial(name, scene) {
  27902. var _this = _super.call(this, name, scene, true) || this;
  27903. _this.subMaterials = new Array();
  27904. scene.multiMaterials.push(_this);
  27905. return _this;
  27906. }
  27907. // Properties
  27908. MultiMaterial.prototype.getSubMaterial = function (index) {
  27909. if (index < 0 || index >= this.subMaterials.length) {
  27910. return this.getScene().defaultMaterial;
  27911. }
  27912. return this.subMaterials[index];
  27913. };
  27914. // Methods
  27915. MultiMaterial.prototype.getClassName = function () {
  27916. return "MultiMaterial";
  27917. };
  27918. MultiMaterial.prototype.isReady = function (mesh) {
  27919. for (var index = 0; index < this.subMaterials.length; index++) {
  27920. var subMaterial = this.subMaterials[index];
  27921. if (subMaterial) {
  27922. if (!this.subMaterials[index].isReady(mesh)) {
  27923. return false;
  27924. }
  27925. }
  27926. }
  27927. return true;
  27928. };
  27929. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  27930. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  27931. for (var index = 0; index < this.subMaterials.length; index++) {
  27932. var subMaterial = null;
  27933. if (cloneChildren) {
  27934. subMaterial = this.subMaterials[index].clone(name + "-" + this.subMaterials[index].name);
  27935. }
  27936. else {
  27937. subMaterial = this.subMaterials[index];
  27938. }
  27939. newMultiMaterial.subMaterials.push(subMaterial);
  27940. }
  27941. return newMultiMaterial;
  27942. };
  27943. MultiMaterial.prototype.serialize = function () {
  27944. var serializationObject = {};
  27945. serializationObject.name = this.name;
  27946. serializationObject.id = this.id;
  27947. serializationObject.tags = BABYLON.Tags.GetTags(this);
  27948. serializationObject.materials = [];
  27949. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  27950. var subMat = this.subMaterials[matIndex];
  27951. if (subMat) {
  27952. serializationObject.materials.push(subMat.id);
  27953. }
  27954. else {
  27955. serializationObject.materials.push(null);
  27956. }
  27957. }
  27958. return serializationObject;
  27959. };
  27960. return MultiMaterial;
  27961. }(BABYLON.Material));
  27962. BABYLON.MultiMaterial = MultiMaterial;
  27963. })(BABYLON || (BABYLON = {}));
  27964. //# sourceMappingURL=babylon.multiMaterial.js.map
  27965. var BABYLON;
  27966. (function (BABYLON) {
  27967. var SceneLoader = (function () {
  27968. function SceneLoader() {
  27969. }
  27970. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  27971. get: function () {
  27972. return 0;
  27973. },
  27974. enumerable: true,
  27975. configurable: true
  27976. });
  27977. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  27978. get: function () {
  27979. return 1;
  27980. },
  27981. enumerable: true,
  27982. configurable: true
  27983. });
  27984. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  27985. get: function () {
  27986. return 2;
  27987. },
  27988. enumerable: true,
  27989. configurable: true
  27990. });
  27991. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  27992. get: function () {
  27993. return 3;
  27994. },
  27995. enumerable: true,
  27996. configurable: true
  27997. });
  27998. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  27999. get: function () {
  28000. return SceneLoader._ForceFullSceneLoadingForIncremental;
  28001. },
  28002. set: function (value) {
  28003. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  28004. },
  28005. enumerable: true,
  28006. configurable: true
  28007. });
  28008. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  28009. get: function () {
  28010. return SceneLoader._ShowLoadingScreen;
  28011. },
  28012. set: function (value) {
  28013. SceneLoader._ShowLoadingScreen = value;
  28014. },
  28015. enumerable: true,
  28016. configurable: true
  28017. });
  28018. Object.defineProperty(SceneLoader, "loggingLevel", {
  28019. get: function () {
  28020. return SceneLoader._loggingLevel;
  28021. },
  28022. set: function (value) {
  28023. SceneLoader._loggingLevel = value;
  28024. },
  28025. enumerable: true,
  28026. configurable: true
  28027. });
  28028. SceneLoader._getDefaultPlugin = function () {
  28029. return SceneLoader._registeredPlugins[".babylon"];
  28030. };
  28031. SceneLoader._getPluginForExtension = function (extension) {
  28032. var registeredPlugin = SceneLoader._registeredPlugins[extension];
  28033. if (registeredPlugin) {
  28034. return registeredPlugin;
  28035. }
  28036. return SceneLoader._getDefaultPlugin();
  28037. };
  28038. SceneLoader._getPluginForFilename = function (sceneFilename) {
  28039. if (sceneFilename.name) {
  28040. sceneFilename = sceneFilename.name;
  28041. }
  28042. var dotPosition = sceneFilename.lastIndexOf(".");
  28043. var queryStringPosition = sceneFilename.indexOf("?");
  28044. if (queryStringPosition === -1) {
  28045. queryStringPosition = sceneFilename.length;
  28046. }
  28047. var extension = sceneFilename.substring(dotPosition, queryStringPosition).toLowerCase();
  28048. return SceneLoader._getPluginForExtension(extension);
  28049. };
  28050. // use babylon file loader directly if sceneFilename is prefixed with "data:"
  28051. SceneLoader._getDirectLoad = function (sceneFilename) {
  28052. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  28053. return sceneFilename.substr(5);
  28054. }
  28055. return null;
  28056. };
  28057. // Public functions
  28058. SceneLoader.GetPluginForExtension = function (extension) {
  28059. return SceneLoader._getPluginForExtension(extension).plugin;
  28060. };
  28061. SceneLoader.RegisterPlugin = function (plugin) {
  28062. if (typeof plugin.extensions === "string") {
  28063. var extension = plugin.extensions;
  28064. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  28065. plugin: plugin,
  28066. isBinary: false
  28067. };
  28068. }
  28069. else {
  28070. var extensions = plugin.extensions;
  28071. Object.keys(extensions).forEach(function (extension) {
  28072. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  28073. plugin: plugin,
  28074. isBinary: extensions[extension].isBinary
  28075. };
  28076. });
  28077. }
  28078. };
  28079. SceneLoader.ImportMesh = function (meshesNames, rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  28080. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  28081. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  28082. return;
  28083. }
  28084. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  28085. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  28086. return;
  28087. }
  28088. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  28089. var loadingToken = {};
  28090. scene._addPendingData(loadingToken);
  28091. var manifestChecked = function (success) {
  28092. scene.database = database;
  28093. var registeredPlugin = directLoad ? SceneLoader._getDefaultPlugin() : SceneLoader._getPluginForFilename(sceneFilename);
  28094. var plugin = registeredPlugin.plugin;
  28095. var useArrayBuffer = registeredPlugin.isBinary;
  28096. var importMeshFromData = function (data) {
  28097. var meshes = [];
  28098. var particleSystems = [];
  28099. var skeletons = [];
  28100. try {
  28101. if (plugin.importMesh) {
  28102. var syncedPlugin = plugin;
  28103. if (!syncedPlugin.importMesh(meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons)) {
  28104. if (onerror) {
  28105. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename);
  28106. }
  28107. scene._removePendingData(loadingToken);
  28108. return;
  28109. }
  28110. if (onsuccess) {
  28111. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  28112. onsuccess(meshes, particleSystems, skeletons);
  28113. scene._removePendingData(loadingToken);
  28114. }
  28115. }
  28116. else {
  28117. var asyncedPlugin = plugin;
  28118. asyncedPlugin.importMeshAsync(meshesNames, scene, data, rootUrl, function (meshes, particleSystems, skeletons) {
  28119. if (onsuccess) {
  28120. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  28121. onsuccess(meshes, particleSystems, skeletons);
  28122. scene._removePendingData(loadingToken);
  28123. }
  28124. }, function () {
  28125. if (onerror) {
  28126. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename);
  28127. }
  28128. scene._removePendingData(loadingToken);
  28129. });
  28130. }
  28131. }
  28132. catch (e) {
  28133. if (onerror) {
  28134. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename, e);
  28135. }
  28136. scene._removePendingData(loadingToken);
  28137. }
  28138. };
  28139. if (directLoad) {
  28140. importMeshFromData(directLoad);
  28141. return;
  28142. }
  28143. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, function (data) {
  28144. importMeshFromData(data);
  28145. }, progressCallBack, database, useArrayBuffer);
  28146. };
  28147. if (scene.getEngine().enableOfflineSupport && !directLoad) {
  28148. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  28149. var database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  28150. }
  28151. else {
  28152. // If the scene is a data stream or offline support is not enabled, it's a direct load
  28153. manifestChecked(true);
  28154. }
  28155. };
  28156. /**
  28157. * Load a scene
  28158. * @param rootUrl a string that defines the root url for scene and resources
  28159. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  28160. * @param engine is the instance of BABYLON.Engine to use to create the scene
  28161. */
  28162. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onsuccess, progressCallBack, onerror) {
  28163. SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onsuccess, progressCallBack, onerror);
  28164. };
  28165. /**
  28166. * Append a scene
  28167. * @param rootUrl a string that defines the root url for scene and resources
  28168. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  28169. * @param scene is the instance of BABYLON.Scene to append to
  28170. */
  28171. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  28172. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  28173. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  28174. return;
  28175. }
  28176. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  28177. var registeredPlugin = directLoad ? SceneLoader._getDefaultPlugin() : SceneLoader._getPluginForFilename(sceneFilename);
  28178. var plugin = registeredPlugin.plugin;
  28179. var useArrayBuffer = registeredPlugin.isBinary;
  28180. var database;
  28181. var loadingToken = {};
  28182. scene._addPendingData(loadingToken);
  28183. if (SceneLoader.ShowLoadingScreen) {
  28184. scene.getEngine().displayLoadingUI();
  28185. }
  28186. var loadSceneFromData = function (data) {
  28187. scene.database = database;
  28188. if (plugin.load) {
  28189. var syncedPlugin = plugin;
  28190. if (!syncedPlugin.load(scene, data, rootUrl)) {
  28191. if (onerror) {
  28192. onerror(scene);
  28193. }
  28194. scene._removePendingData(loadingToken);
  28195. scene.getEngine().hideLoadingUI();
  28196. return;
  28197. }
  28198. if (onsuccess) {
  28199. onsuccess(scene);
  28200. }
  28201. scene._removePendingData(loadingToken);
  28202. }
  28203. else {
  28204. var asyncedPlugin = plugin;
  28205. asyncedPlugin.loadAsync(scene, data, rootUrl, function () {
  28206. if (onsuccess) {
  28207. onsuccess(scene);
  28208. }
  28209. scene._removePendingData(loadingToken);
  28210. }, function () {
  28211. if (onerror) {
  28212. onerror(scene);
  28213. }
  28214. scene._removePendingData(loadingToken);
  28215. scene.getEngine().hideLoadingUI();
  28216. });
  28217. }
  28218. if (SceneLoader.ShowLoadingScreen) {
  28219. scene.executeWhenReady(function () {
  28220. scene.getEngine().hideLoadingUI();
  28221. });
  28222. }
  28223. };
  28224. var manifestChecked = function (success) {
  28225. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, loadSceneFromData, progressCallBack, database, useArrayBuffer);
  28226. };
  28227. if (directLoad) {
  28228. loadSceneFromData(directLoad);
  28229. return;
  28230. }
  28231. if (rootUrl.indexOf("file:") === -1) {
  28232. if (scene.getEngine().enableOfflineSupport) {
  28233. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  28234. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  28235. }
  28236. else {
  28237. manifestChecked(true);
  28238. }
  28239. }
  28240. else {
  28241. BABYLON.Tools.ReadFile(sceneFilename, loadSceneFromData, progressCallBack, useArrayBuffer);
  28242. }
  28243. };
  28244. return SceneLoader;
  28245. }());
  28246. // Flags
  28247. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  28248. SceneLoader._ShowLoadingScreen = true;
  28249. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  28250. // Members
  28251. SceneLoader._registeredPlugins = {};
  28252. BABYLON.SceneLoader = SceneLoader;
  28253. ;
  28254. })(BABYLON || (BABYLON = {}));
  28255. //# sourceMappingURL=babylon.sceneLoader.js.map
  28256. var BABYLON;
  28257. (function (BABYLON) {
  28258. var Internals;
  28259. (function (Internals) {
  28260. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  28261. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  28262. var parsedMaterial = parsedData.materials[index];
  28263. if (parsedMaterial.id === id) {
  28264. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  28265. }
  28266. }
  28267. return null;
  28268. };
  28269. var isDescendantOf = function (mesh, names, hierarchyIds) {
  28270. names = (names instanceof Array) ? names : [names];
  28271. for (var i in names) {
  28272. if (mesh.name === names[i]) {
  28273. hierarchyIds.push(mesh.id);
  28274. return true;
  28275. }
  28276. }
  28277. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  28278. hierarchyIds.push(mesh.id);
  28279. return true;
  28280. }
  28281. return false;
  28282. };
  28283. var logOperation = function (operation, producer) {
  28284. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  28285. };
  28286. BABYLON.SceneLoader.RegisterPlugin({
  28287. extensions: ".babylon",
  28288. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
  28289. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  28290. // when SceneLoader.debugLogging = true (default), or exception encountered.
  28291. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  28292. // and avoid problems with multiple concurrent .babylon loads.
  28293. var log = "importMesh has failed JSON parse";
  28294. try {
  28295. var parsedData = JSON.parse(data);
  28296. log = "";
  28297. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  28298. var loadedSkeletonsIds = [];
  28299. var loadedMaterialsIds = [];
  28300. var hierarchyIds = [];
  28301. var index;
  28302. var cache;
  28303. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  28304. var parsedMesh = parsedData.meshes[index];
  28305. if (!meshesNames || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  28306. if (meshesNames instanceof Array) {
  28307. // Remove found mesh name from list.
  28308. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  28309. }
  28310. //Geometry?
  28311. if (parsedMesh.geometryId) {
  28312. //does the file contain geometries?
  28313. if (parsedData.geometries) {
  28314. //find the correct geometry and add it to the scene
  28315. var found = false;
  28316. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  28317. if (found || !parsedData.geometries[geometryType] || !(parsedData.geometries[geometryType] instanceof Array)) {
  28318. return;
  28319. }
  28320. else {
  28321. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  28322. if (parsedGeometryData.id === parsedMesh.geometryId) {
  28323. switch (geometryType) {
  28324. case "boxes":
  28325. BABYLON.Geometry.Primitives.Box.Parse(parsedGeometryData, scene);
  28326. break;
  28327. case "spheres":
  28328. BABYLON.Geometry.Primitives.Sphere.Parse(parsedGeometryData, scene);
  28329. break;
  28330. case "cylinders":
  28331. BABYLON.Geometry.Primitives.Cylinder.Parse(parsedGeometryData, scene);
  28332. break;
  28333. case "toruses":
  28334. BABYLON.Geometry.Primitives.Torus.Parse(parsedGeometryData, scene);
  28335. break;
  28336. case "grounds":
  28337. BABYLON.Geometry.Primitives.Ground.Parse(parsedGeometryData, scene);
  28338. break;
  28339. case "planes":
  28340. BABYLON.Geometry.Primitives.Plane.Parse(parsedGeometryData, scene);
  28341. break;
  28342. case "torusKnots":
  28343. BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedGeometryData, scene);
  28344. break;
  28345. case "vertexData":
  28346. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  28347. break;
  28348. }
  28349. found = true;
  28350. }
  28351. });
  28352. }
  28353. });
  28354. if (!found) {
  28355. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  28356. }
  28357. }
  28358. }
  28359. // Material ?
  28360. if (parsedMesh.materialId) {
  28361. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  28362. if (!materialFound && parsedData.multiMaterials) {
  28363. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  28364. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  28365. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  28366. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  28367. var subMatId = parsedMultiMaterial.materials[matIndex];
  28368. loadedMaterialsIds.push(subMatId);
  28369. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  28370. log += "\n\tMaterial " + mat.toString(fullDetails);
  28371. }
  28372. loadedMaterialsIds.push(parsedMultiMaterial.id);
  28373. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  28374. materialFound = true;
  28375. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  28376. break;
  28377. }
  28378. }
  28379. }
  28380. if (!materialFound) {
  28381. loadedMaterialsIds.push(parsedMesh.materialId);
  28382. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  28383. if (!mat) {
  28384. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  28385. }
  28386. else {
  28387. log += "\n\tMaterial " + mat.toString(fullDetails);
  28388. }
  28389. }
  28390. }
  28391. // Skeleton ?
  28392. if (parsedMesh.skeletonId > -1 && scene.skeletons) {
  28393. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  28394. if (!skeletonAlreadyLoaded) {
  28395. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  28396. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  28397. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  28398. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  28399. skeletons.push(skeleton);
  28400. loadedSkeletonsIds.push(parsedSkeleton.id);
  28401. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  28402. }
  28403. }
  28404. }
  28405. }
  28406. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  28407. meshes.push(mesh);
  28408. log += "\n\tMesh " + mesh.toString(fullDetails);
  28409. }
  28410. }
  28411. // Connecting parents
  28412. var currentMesh;
  28413. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  28414. currentMesh = scene.meshes[index];
  28415. if (currentMesh._waitingParentId) {
  28416. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  28417. currentMesh._waitingParentId = undefined;
  28418. }
  28419. }
  28420. // freeze and compute world matrix application
  28421. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  28422. currentMesh = scene.meshes[index];
  28423. if (currentMesh._waitingFreezeWorldMatrix) {
  28424. currentMesh.freezeWorldMatrix();
  28425. currentMesh._waitingFreezeWorldMatrix = undefined;
  28426. }
  28427. else {
  28428. currentMesh.computeWorldMatrix(true);
  28429. }
  28430. }
  28431. // Particles
  28432. if (parsedData.particleSystems) {
  28433. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  28434. var parsedParticleSystem = parsedData.particleSystems[index];
  28435. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  28436. particleSystems.push(BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl));
  28437. }
  28438. }
  28439. }
  28440. return true;
  28441. }
  28442. catch (err) {
  28443. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log);
  28444. log = null;
  28445. throw err;
  28446. }
  28447. finally {
  28448. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  28449. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  28450. }
  28451. }
  28452. },
  28453. load: function (scene, data, rootUrl) {
  28454. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  28455. // when SceneLoader.debugLogging = true (default), or exception encountered.
  28456. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  28457. // and avoid problems with multiple concurrent .babylon loads.
  28458. var log = "importScene has failed JSON parse";
  28459. try {
  28460. var parsedData = JSON.parse(data);
  28461. log = "";
  28462. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  28463. // Scene
  28464. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  28465. scene.autoClear = parsedData.autoClear;
  28466. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  28467. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  28468. if (parsedData.gravity) {
  28469. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  28470. }
  28471. // Fog
  28472. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  28473. scene.fogMode = parsedData.fogMode;
  28474. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  28475. scene.fogStart = parsedData.fogStart;
  28476. scene.fogEnd = parsedData.fogEnd;
  28477. scene.fogDensity = parsedData.fogDensity;
  28478. log += "\tFog mode for scene: ";
  28479. switch (scene.fogMode) {
  28480. // getters not compiling, so using hardcoded
  28481. case 1:
  28482. log += "exp\n";
  28483. break;
  28484. case 2:
  28485. log += "exp2\n";
  28486. break;
  28487. case 3:
  28488. log += "linear\n";
  28489. break;
  28490. }
  28491. }
  28492. //Physics
  28493. if (parsedData.physicsEnabled) {
  28494. var physicsPlugin;
  28495. if (parsedData.physicsEngine === "cannon") {
  28496. physicsPlugin = new BABYLON.CannonJSPlugin();
  28497. }
  28498. else if (parsedData.physicsEngine === "oimo") {
  28499. physicsPlugin = new BABYLON.OimoJSPlugin();
  28500. }
  28501. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  28502. //else - default engine, which is currently oimo
  28503. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  28504. scene.enablePhysics(physicsGravity, physicsPlugin);
  28505. }
  28506. // Metadata
  28507. if (parsedData.metadata !== undefined) {
  28508. scene.metadata = parsedData.metadata;
  28509. }
  28510. //collisions, if defined. otherwise, default is true
  28511. if (parsedData.collisionsEnabled != undefined) {
  28512. scene.collisionsEnabled = parsedData.collisionsEnabled;
  28513. }
  28514. scene.workerCollisions = !!parsedData.workerCollisions;
  28515. var index;
  28516. var cache;
  28517. // Lights
  28518. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  28519. var parsedLight = parsedData.lights[index];
  28520. var light = BABYLON.Light.Parse(parsedLight, scene);
  28521. log += (index === 0 ? "\n\tLights:" : "");
  28522. log += "\n\t\t" + light.toString(fullDetails);
  28523. }
  28524. // Animations
  28525. if (parsedData.animations) {
  28526. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  28527. var parsedAnimation = parsedData.animations[index];
  28528. var animation = BABYLON.Animation.Parse(parsedAnimation);
  28529. scene.animations.push(animation);
  28530. log += (index === 0 ? "\n\tAnimations:" : "");
  28531. log += "\n\t\t" + animation.toString(fullDetails);
  28532. }
  28533. }
  28534. if (parsedData.autoAnimate) {
  28535. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  28536. }
  28537. // Materials
  28538. if (parsedData.materials) {
  28539. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  28540. var parsedMaterial = parsedData.materials[index];
  28541. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  28542. log += (index === 0 ? "\n\tMaterials:" : "");
  28543. log += "\n\t\t" + mat.toString(fullDetails);
  28544. }
  28545. }
  28546. if (parsedData.multiMaterials) {
  28547. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  28548. var parsedMultiMaterial = parsedData.multiMaterials[index];
  28549. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  28550. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  28551. log += "\n\t\t" + mmat.toString(fullDetails);
  28552. }
  28553. }
  28554. // Skeletons
  28555. if (parsedData.skeletons) {
  28556. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  28557. var parsedSkeleton = parsedData.skeletons[index];
  28558. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  28559. log += (index === 0 ? "\n\tSkeletons:" : "");
  28560. log += "\n\t\t" + skeleton.toString(fullDetails);
  28561. }
  28562. }
  28563. // Geometries
  28564. var geometries = parsedData.geometries;
  28565. if (geometries) {
  28566. // Boxes
  28567. var boxes = geometries.boxes;
  28568. if (boxes) {
  28569. for (index = 0, cache = boxes.length; index < cache; index++) {
  28570. var parsedBox = boxes[index];
  28571. BABYLON.Geometry.Primitives.Box.Parse(parsedBox, scene);
  28572. }
  28573. }
  28574. // Spheres
  28575. var spheres = geometries.spheres;
  28576. if (spheres) {
  28577. for (index = 0, cache = spheres.length; index < cache; index++) {
  28578. var parsedSphere = spheres[index];
  28579. BABYLON.Geometry.Primitives.Sphere.Parse(parsedSphere, scene);
  28580. }
  28581. }
  28582. // Cylinders
  28583. var cylinders = geometries.cylinders;
  28584. if (cylinders) {
  28585. for (index = 0, cache = cylinders.length; index < cache; index++) {
  28586. var parsedCylinder = cylinders[index];
  28587. BABYLON.Geometry.Primitives.Cylinder.Parse(parsedCylinder, scene);
  28588. }
  28589. }
  28590. // Toruses
  28591. var toruses = geometries.toruses;
  28592. if (toruses) {
  28593. for (index = 0, cache = toruses.length; index < cache; index++) {
  28594. var parsedTorus = toruses[index];
  28595. BABYLON.Geometry.Primitives.Torus.Parse(parsedTorus, scene);
  28596. }
  28597. }
  28598. // Grounds
  28599. var grounds = geometries.grounds;
  28600. if (grounds) {
  28601. for (index = 0, cache = grounds.length; index < cache; index++) {
  28602. var parsedGround = grounds[index];
  28603. BABYLON.Geometry.Primitives.Ground.Parse(parsedGround, scene);
  28604. }
  28605. }
  28606. // Planes
  28607. var planes = geometries.planes;
  28608. if (planes) {
  28609. for (index = 0, cache = planes.length; index < cache; index++) {
  28610. var parsedPlane = planes[index];
  28611. BABYLON.Geometry.Primitives.Plane.Parse(parsedPlane, scene);
  28612. }
  28613. }
  28614. // TorusKnots
  28615. var torusKnots = geometries.torusKnots;
  28616. if (torusKnots) {
  28617. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  28618. var parsedTorusKnot = torusKnots[index];
  28619. BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedTorusKnot, scene);
  28620. }
  28621. }
  28622. // VertexData
  28623. var vertexData = geometries.vertexData;
  28624. if (vertexData) {
  28625. for (index = 0, cache = vertexData.length; index < cache; index++) {
  28626. var parsedVertexData = vertexData[index];
  28627. BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl);
  28628. }
  28629. }
  28630. }
  28631. // Meshes
  28632. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  28633. var parsedMesh = parsedData.meshes[index];
  28634. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  28635. log += (index === 0 ? "\n\tMeshes:" : "");
  28636. log += "\n\t\t" + mesh.toString(fullDetails);
  28637. }
  28638. // Cameras
  28639. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  28640. var parsedCamera = parsedData.cameras[index];
  28641. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  28642. log += (index === 0 ? "\n\tCameras:" : "");
  28643. log += "\n\t\t" + camera.toString(fullDetails);
  28644. }
  28645. if (parsedData.activeCameraID) {
  28646. scene.setActiveCameraByID(parsedData.activeCameraID);
  28647. }
  28648. // Browsing all the graph to connect the dots
  28649. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  28650. var camera = scene.cameras[index];
  28651. if (camera._waitingParentId) {
  28652. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  28653. camera._waitingParentId = undefined;
  28654. }
  28655. }
  28656. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  28657. var light = scene.lights[index];
  28658. if (light._waitingParentId) {
  28659. light.parent = scene.getLastEntryByID(light._waitingParentId);
  28660. light._waitingParentId = undefined;
  28661. }
  28662. }
  28663. // Sounds
  28664. var loadedSounds = [];
  28665. var loadedSound;
  28666. if (BABYLON.AudioEngine && parsedData.sounds) {
  28667. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  28668. var parsedSound = parsedData.sounds[index];
  28669. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  28670. if (!parsedSound.url)
  28671. parsedSound.url = parsedSound.name;
  28672. if (!loadedSounds[parsedSound.url]) {
  28673. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  28674. loadedSounds[parsedSound.url] = loadedSound;
  28675. }
  28676. else {
  28677. BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]);
  28678. }
  28679. }
  28680. else {
  28681. var emptySound = new BABYLON.Sound(parsedSound.name, null, scene);
  28682. }
  28683. }
  28684. }
  28685. loadedSounds = [];
  28686. // Connect parents & children and parse actions
  28687. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  28688. var mesh = scene.meshes[index];
  28689. if (mesh._waitingParentId) {
  28690. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  28691. mesh._waitingParentId = undefined;
  28692. }
  28693. if (mesh._waitingActions) {
  28694. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  28695. mesh._waitingActions = undefined;
  28696. }
  28697. }
  28698. // freeze world matrix application
  28699. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  28700. var currentMesh = scene.meshes[index];
  28701. if (currentMesh._waitingFreezeWorldMatrix) {
  28702. currentMesh.freezeWorldMatrix();
  28703. currentMesh._waitingFreezeWorldMatrix = undefined;
  28704. }
  28705. else {
  28706. currentMesh.computeWorldMatrix(true);
  28707. }
  28708. }
  28709. // Particles Systems
  28710. if (parsedData.particleSystems) {
  28711. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  28712. var parsedParticleSystem = parsedData.particleSystems[index];
  28713. BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  28714. }
  28715. }
  28716. // Lens flares
  28717. if (parsedData.lensFlareSystems) {
  28718. for (index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  28719. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  28720. BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  28721. }
  28722. }
  28723. // Shadows
  28724. if (parsedData.shadowGenerators) {
  28725. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  28726. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  28727. BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  28728. }
  28729. }
  28730. // Actions (scene)
  28731. if (parsedData.actions) {
  28732. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  28733. }
  28734. // Finish
  28735. return true;
  28736. }
  28737. catch (err) {
  28738. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log);
  28739. log = null;
  28740. throw err;
  28741. }
  28742. finally {
  28743. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  28744. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  28745. }
  28746. }
  28747. }
  28748. });
  28749. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  28750. })(BABYLON || (BABYLON = {}));
  28751. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  28752. var BABYLON;
  28753. (function (BABYLON) {
  28754. var SpriteManager = (function () {
  28755. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  28756. if (epsilon === void 0) { epsilon = 0.01; }
  28757. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  28758. this.name = name;
  28759. this.sprites = new Array();
  28760. this.renderingGroupId = 0;
  28761. this.layerMask = 0x0FFFFFFF;
  28762. this.fogEnabled = true;
  28763. this.isPickable = false;
  28764. /**
  28765. * An event triggered when the manager is disposed.
  28766. * @type {BABYLON.Observable}
  28767. */
  28768. this.onDisposeObservable = new BABYLON.Observable();
  28769. this._vertexBuffers = {};
  28770. this._capacity = capacity;
  28771. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  28772. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  28773. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  28774. if (cellSize.width && cellSize.height) {
  28775. this.cellWidth = cellSize.width;
  28776. this.cellHeight = cellSize.height;
  28777. }
  28778. else if (cellSize !== undefined) {
  28779. this.cellWidth = cellSize;
  28780. this.cellHeight = cellSize;
  28781. }
  28782. else {
  28783. return;
  28784. }
  28785. this._epsilon = epsilon;
  28786. this._scene = scene;
  28787. this._scene.spriteManagers.push(this);
  28788. var indices = [];
  28789. var index = 0;
  28790. for (var count = 0; count < capacity; count++) {
  28791. indices.push(index);
  28792. indices.push(index + 1);
  28793. indices.push(index + 2);
  28794. indices.push(index);
  28795. indices.push(index + 2);
  28796. indices.push(index + 3);
  28797. index += 4;
  28798. }
  28799. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  28800. // VBO
  28801. // 16 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color r, color g, color b, color a)
  28802. this._vertexData = new Float32Array(capacity * 16 * 4);
  28803. this._buffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 16);
  28804. var positions = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 4);
  28805. var options = this._buffer.createVertexBuffer("options", 4, 4);
  28806. var cellInfo = this._buffer.createVertexBuffer("cellInfo", 8, 4);
  28807. var colors = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 12, 4);
  28808. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  28809. this._vertexBuffers["options"] = options;
  28810. this._vertexBuffers["cellInfo"] = cellInfo;
  28811. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  28812. // Effects
  28813. this._effectBase = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  28814. this._effectFog = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  28815. }
  28816. Object.defineProperty(SpriteManager.prototype, "onDispose", {
  28817. set: function (callback) {
  28818. if (this._onDisposeObserver) {
  28819. this.onDisposeObservable.remove(this._onDisposeObserver);
  28820. }
  28821. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  28822. },
  28823. enumerable: true,
  28824. configurable: true
  28825. });
  28826. Object.defineProperty(SpriteManager.prototype, "texture", {
  28827. get: function () {
  28828. return this._spriteTexture;
  28829. },
  28830. set: function (value) {
  28831. this._spriteTexture = value;
  28832. },
  28833. enumerable: true,
  28834. configurable: true
  28835. });
  28836. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  28837. var arrayOffset = index * 16;
  28838. if (offsetX === 0)
  28839. offsetX = this._epsilon;
  28840. else if (offsetX === 1)
  28841. offsetX = 1 - this._epsilon;
  28842. if (offsetY === 0)
  28843. offsetY = this._epsilon;
  28844. else if (offsetY === 1)
  28845. offsetY = 1 - this._epsilon;
  28846. this._vertexData[arrayOffset] = sprite.position.x;
  28847. this._vertexData[arrayOffset + 1] = sprite.position.y;
  28848. this._vertexData[arrayOffset + 2] = sprite.position.z;
  28849. this._vertexData[arrayOffset + 3] = sprite.angle;
  28850. this._vertexData[arrayOffset + 4] = sprite.width;
  28851. this._vertexData[arrayOffset + 5] = sprite.height;
  28852. this._vertexData[arrayOffset + 6] = offsetX;
  28853. this._vertexData[arrayOffset + 7] = offsetY;
  28854. this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  28855. this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  28856. var offset = (sprite.cellIndex / rowSize) >> 0;
  28857. this._vertexData[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  28858. this._vertexData[arrayOffset + 11] = offset;
  28859. // Color
  28860. this._vertexData[arrayOffset + 12] = sprite.color.r;
  28861. this._vertexData[arrayOffset + 13] = sprite.color.g;
  28862. this._vertexData[arrayOffset + 14] = sprite.color.b;
  28863. this._vertexData[arrayOffset + 15] = sprite.color.a;
  28864. };
  28865. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  28866. var count = Math.min(this._capacity, this.sprites.length);
  28867. var min = BABYLON.Vector3.Zero();
  28868. var max = BABYLON.Vector3.Zero();
  28869. var distance = Number.MAX_VALUE;
  28870. var currentSprite;
  28871. var cameraSpacePosition = BABYLON.Vector3.Zero();
  28872. var cameraView = camera.getViewMatrix();
  28873. for (var index = 0; index < count; index++) {
  28874. var sprite = this.sprites[index];
  28875. if (!sprite) {
  28876. continue;
  28877. }
  28878. if (predicate) {
  28879. if (!predicate(sprite)) {
  28880. continue;
  28881. }
  28882. }
  28883. else if (!sprite.isPickable) {
  28884. continue;
  28885. }
  28886. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  28887. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  28888. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  28889. if (ray.intersectsBoxMinMax(min, max)) {
  28890. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  28891. if (distance > currentDistance) {
  28892. distance = currentDistance;
  28893. currentSprite = sprite;
  28894. if (fastCheck) {
  28895. break;
  28896. }
  28897. }
  28898. }
  28899. }
  28900. if (currentSprite) {
  28901. var result = new BABYLON.PickingInfo();
  28902. result.hit = true;
  28903. result.pickedSprite = currentSprite;
  28904. result.distance = distance;
  28905. return result;
  28906. }
  28907. return null;
  28908. };
  28909. SpriteManager.prototype.render = function () {
  28910. // Check
  28911. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  28912. return;
  28913. var engine = this._scene.getEngine();
  28914. var baseSize = this._spriteTexture.getBaseSize();
  28915. // Sprites
  28916. var deltaTime = engine.getDeltaTime();
  28917. var max = Math.min(this._capacity, this.sprites.length);
  28918. var rowSize = baseSize.width / this.cellWidth;
  28919. var offset = 0;
  28920. for (var index = 0; index < max; index++) {
  28921. var sprite = this.sprites[index];
  28922. if (!sprite) {
  28923. continue;
  28924. }
  28925. sprite._animate(deltaTime);
  28926. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  28927. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  28928. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  28929. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  28930. }
  28931. this._buffer.update(this._vertexData);
  28932. // Render
  28933. var effect = this._effectBase;
  28934. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  28935. effect = this._effectFog;
  28936. }
  28937. engine.enableEffect(effect);
  28938. var viewMatrix = this._scene.getViewMatrix();
  28939. effect.setTexture("diffuseSampler", this._spriteTexture);
  28940. effect.setMatrix("view", viewMatrix);
  28941. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  28942. effect.setFloat2("textureInfos", this.cellWidth / baseSize.width, this.cellHeight / baseSize.height);
  28943. // Fog
  28944. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  28945. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  28946. effect.setColor3("vFogColor", this._scene.fogColor);
  28947. }
  28948. // VBOs
  28949. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  28950. // Draw order
  28951. engine.setDepthFunctionToLessOrEqual();
  28952. effect.setBool("alphaTest", true);
  28953. engine.setColorWrite(false);
  28954. engine.draw(true, 0, max * 6);
  28955. engine.setColorWrite(true);
  28956. effect.setBool("alphaTest", false);
  28957. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  28958. engine.draw(true, 0, max * 6);
  28959. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  28960. };
  28961. SpriteManager.prototype.dispose = function () {
  28962. if (this._buffer) {
  28963. this._buffer.dispose();
  28964. this._buffer = null;
  28965. }
  28966. if (this._indexBuffer) {
  28967. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  28968. this._indexBuffer = null;
  28969. }
  28970. if (this._spriteTexture) {
  28971. this._spriteTexture.dispose();
  28972. this._spriteTexture = null;
  28973. }
  28974. // Remove from scene
  28975. var index = this._scene.spriteManagers.indexOf(this);
  28976. this._scene.spriteManagers.splice(index, 1);
  28977. // Callback
  28978. this.onDisposeObservable.notifyObservers(this);
  28979. this.onDisposeObservable.clear();
  28980. };
  28981. return SpriteManager;
  28982. }());
  28983. BABYLON.SpriteManager = SpriteManager;
  28984. })(BABYLON || (BABYLON = {}));
  28985. //# sourceMappingURL=babylon.spriteManager.js.map
  28986. var BABYLON;
  28987. (function (BABYLON) {
  28988. var Sprite = (function () {
  28989. function Sprite(name, manager) {
  28990. this.name = name;
  28991. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  28992. this.width = 1.0;
  28993. this.height = 1.0;
  28994. this.angle = 0;
  28995. this.cellIndex = 0;
  28996. this.invertU = 0;
  28997. this.invertV = 0;
  28998. this.animations = new Array();
  28999. this.isPickable = false;
  29000. this._animationStarted = false;
  29001. this._loopAnimation = false;
  29002. this._fromIndex = 0;
  29003. this._toIndex = 0;
  29004. this._delay = 0;
  29005. this._direction = 1;
  29006. this._frameCount = 0;
  29007. this._time = 0;
  29008. this._manager = manager;
  29009. this._manager.sprites.push(this);
  29010. this.position = BABYLON.Vector3.Zero();
  29011. }
  29012. Object.defineProperty(Sprite.prototype, "size", {
  29013. get: function () {
  29014. return this.width;
  29015. },
  29016. set: function (value) {
  29017. this.width = value;
  29018. this.height = value;
  29019. },
  29020. enumerable: true,
  29021. configurable: true
  29022. });
  29023. Sprite.prototype.playAnimation = function (from, to, loop, delay, onAnimationEnd) {
  29024. this._fromIndex = from;
  29025. this._toIndex = to;
  29026. this._loopAnimation = loop;
  29027. this._delay = delay;
  29028. this._animationStarted = true;
  29029. this._direction = from < to ? 1 : -1;
  29030. this.cellIndex = from;
  29031. this._time = 0;
  29032. this._onAnimationEnd = onAnimationEnd;
  29033. };
  29034. Sprite.prototype.stopAnimation = function () {
  29035. this._animationStarted = false;
  29036. };
  29037. Sprite.prototype._animate = function (deltaTime) {
  29038. if (!this._animationStarted)
  29039. return;
  29040. this._time += deltaTime;
  29041. if (this._time > this._delay) {
  29042. this._time = this._time % this._delay;
  29043. this.cellIndex += this._direction;
  29044. if (this.cellIndex === this._toIndex) {
  29045. if (this._loopAnimation) {
  29046. this.cellIndex = this._fromIndex;
  29047. }
  29048. else {
  29049. this._animationStarted = false;
  29050. if (this._onAnimationEnd) {
  29051. this._onAnimationEnd();
  29052. }
  29053. if (this.disposeWhenFinishedAnimating) {
  29054. this.dispose();
  29055. }
  29056. }
  29057. }
  29058. }
  29059. };
  29060. Sprite.prototype.dispose = function () {
  29061. for (var i = 0; i < this._manager.sprites.length; i++) {
  29062. if (this._manager.sprites[i] == this) {
  29063. this._manager.sprites.splice(i, 1);
  29064. }
  29065. }
  29066. };
  29067. return Sprite;
  29068. }());
  29069. BABYLON.Sprite = Sprite;
  29070. })(BABYLON || (BABYLON = {}));
  29071. //# sourceMappingURL=babylon.sprite.js.map
  29072. var BABYLON;
  29073. (function (BABYLON) {
  29074. var Layer = (function () {
  29075. function Layer(name, imgUrl, scene, isBackground, color) {
  29076. this.name = name;
  29077. this.scale = new BABYLON.Vector2(1, 1);
  29078. this.offset = new BABYLON.Vector2(0, 0);
  29079. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  29080. this._vertexBuffers = {};
  29081. // Events
  29082. /**
  29083. * An event triggered when the layer is disposed.
  29084. * @type {BABYLON.Observable}
  29085. */
  29086. this.onDisposeObservable = new BABYLON.Observable();
  29087. /**
  29088. * An event triggered before rendering the scene
  29089. * @type {BABYLON.Observable}
  29090. */
  29091. this.onBeforeRenderObservable = new BABYLON.Observable();
  29092. /**
  29093. * An event triggered after rendering the scene
  29094. * @type {BABYLON.Observable}
  29095. */
  29096. this.onAfterRenderObservable = new BABYLON.Observable();
  29097. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  29098. this.isBackground = isBackground === undefined ? true : isBackground;
  29099. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  29100. this._scene = scene;
  29101. this._scene.layers.push(this);
  29102. var engine = scene.getEngine();
  29103. // VBO
  29104. var vertices = [];
  29105. vertices.push(1, 1);
  29106. vertices.push(-1, 1);
  29107. vertices.push(-1, -1);
  29108. vertices.push(1, -1);
  29109. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  29110. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  29111. // Indices
  29112. var indices = [];
  29113. indices.push(0);
  29114. indices.push(1);
  29115. indices.push(2);
  29116. indices.push(0);
  29117. indices.push(2);
  29118. indices.push(3);
  29119. this._indexBuffer = engine.createIndexBuffer(indices);
  29120. // Effects
  29121. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  29122. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  29123. }
  29124. Object.defineProperty(Layer.prototype, "onDispose", {
  29125. set: function (callback) {
  29126. if (this._onDisposeObserver) {
  29127. this.onDisposeObservable.remove(this._onDisposeObserver);
  29128. }
  29129. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  29130. },
  29131. enumerable: true,
  29132. configurable: true
  29133. });
  29134. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  29135. set: function (callback) {
  29136. if (this._onBeforeRenderObserver) {
  29137. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  29138. }
  29139. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  29140. },
  29141. enumerable: true,
  29142. configurable: true
  29143. });
  29144. Object.defineProperty(Layer.prototype, "onAfterRender", {
  29145. set: function (callback) {
  29146. if (this._onAfterRenderObserver) {
  29147. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  29148. }
  29149. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  29150. },
  29151. enumerable: true,
  29152. configurable: true
  29153. });
  29154. Layer.prototype.render = function () {
  29155. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  29156. // Check
  29157. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  29158. return;
  29159. var engine = this._scene.getEngine();
  29160. this.onBeforeRenderObservable.notifyObservers(this);
  29161. // Render
  29162. engine.enableEffect(currentEffect);
  29163. engine.setState(false);
  29164. // Texture
  29165. currentEffect.setTexture("textureSampler", this.texture);
  29166. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  29167. // Color
  29168. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  29169. // Scale / offset
  29170. currentEffect.setVector2("offset", this.offset);
  29171. currentEffect.setVector2("scale", this.scale);
  29172. // VBOs
  29173. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  29174. // Draw order
  29175. if (!this.alphaTest) {
  29176. engine.setAlphaMode(this.alphaBlendingMode);
  29177. engine.draw(true, 0, 6);
  29178. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  29179. }
  29180. else {
  29181. engine.draw(true, 0, 6);
  29182. }
  29183. this.onAfterRenderObservable.notifyObservers(this);
  29184. };
  29185. Layer.prototype.dispose = function () {
  29186. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  29187. if (vertexBuffer) {
  29188. vertexBuffer.dispose();
  29189. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  29190. }
  29191. if (this._indexBuffer) {
  29192. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  29193. this._indexBuffer = null;
  29194. }
  29195. if (this.texture) {
  29196. this.texture.dispose();
  29197. this.texture = null;
  29198. }
  29199. // Remove from scene
  29200. var index = this._scene.layers.indexOf(this);
  29201. this._scene.layers.splice(index, 1);
  29202. // Callback
  29203. this.onDisposeObservable.notifyObservers(this);
  29204. this.onDisposeObservable.clear();
  29205. this.onAfterRenderObservable.clear();
  29206. this.onBeforeRenderObservable.clear();
  29207. };
  29208. return Layer;
  29209. }());
  29210. BABYLON.Layer = Layer;
  29211. })(BABYLON || (BABYLON = {}));
  29212. //# sourceMappingURL=babylon.layer.js.map
  29213. var BABYLON;
  29214. (function (BABYLON) {
  29215. var Particle = (function () {
  29216. function Particle() {
  29217. this.position = BABYLON.Vector3.Zero();
  29218. this.direction = BABYLON.Vector3.Zero();
  29219. this.color = new BABYLON.Color4(0, 0, 0, 0);
  29220. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  29221. this.lifeTime = 1.0;
  29222. this.age = 0;
  29223. this.size = 0;
  29224. this.angle = 0;
  29225. this.angularSpeed = 0;
  29226. }
  29227. Particle.prototype.copyTo = function (other) {
  29228. other.position.copyFrom(this.position);
  29229. other.direction.copyFrom(this.direction);
  29230. other.color.copyFrom(this.color);
  29231. other.colorStep.copyFrom(this.colorStep);
  29232. other.lifeTime = this.lifeTime;
  29233. other.age = this.age;
  29234. other.size = this.size;
  29235. other.angle = this.angle;
  29236. other.angularSpeed = this.angularSpeed;
  29237. };
  29238. return Particle;
  29239. }());
  29240. BABYLON.Particle = Particle;
  29241. })(BABYLON || (BABYLON = {}));
  29242. //# sourceMappingURL=babylon.particle.js.map
  29243. var BABYLON;
  29244. (function (BABYLON) {
  29245. var randomNumber = function (min, max) {
  29246. if (min === max) {
  29247. return (min);
  29248. }
  29249. var random = Math.random();
  29250. return ((random * (max - min)) + min);
  29251. };
  29252. var ParticleSystem = (function () {
  29253. function ParticleSystem(name, capacity, scene, customEffect) {
  29254. var _this = this;
  29255. this.name = name;
  29256. // Members
  29257. this.animations = [];
  29258. this.renderingGroupId = 0;
  29259. this.emitter = null;
  29260. this.emitRate = 10;
  29261. this.manualEmitCount = -1;
  29262. this.updateSpeed = 0.01;
  29263. this.targetStopDuration = 0;
  29264. this.disposeOnStop = false;
  29265. this.minEmitPower = 1;
  29266. this.maxEmitPower = 1;
  29267. this.minLifeTime = 1;
  29268. this.maxLifeTime = 1;
  29269. this.minSize = 1;
  29270. this.maxSize = 1;
  29271. this.minAngularSpeed = 0;
  29272. this.maxAngularSpeed = 0;
  29273. this.layerMask = 0x0FFFFFFF;
  29274. this.customShader = null;
  29275. this.preventAutoStart = false;
  29276. /**
  29277. * An event triggered when the system is disposed.
  29278. * @type {BABYLON.Observable}
  29279. */
  29280. this.onDisposeObservable = new BABYLON.Observable();
  29281. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  29282. this.forceDepthWrite = false;
  29283. this.gravity = BABYLON.Vector3.Zero();
  29284. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  29285. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  29286. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  29287. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  29288. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  29289. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  29290. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  29291. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  29292. this.particles = new Array();
  29293. this._stockParticles = new Array();
  29294. this._newPartsExcess = 0;
  29295. this._vertexBuffers = {};
  29296. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  29297. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  29298. this._scaledDirection = BABYLON.Vector3.Zero();
  29299. this._scaledGravity = BABYLON.Vector3.Zero();
  29300. this._currentRenderId = -1;
  29301. this._started = false;
  29302. this._stopped = false;
  29303. this._actualFrame = 0;
  29304. this.id = name;
  29305. this._capacity = capacity;
  29306. this._scene = scene;
  29307. this._customEffect = customEffect;
  29308. scene.particleSystems.push(this);
  29309. var indices = [];
  29310. var index = 0;
  29311. for (var count = 0; count < capacity; count++) {
  29312. indices.push(index);
  29313. indices.push(index + 1);
  29314. indices.push(index + 2);
  29315. indices.push(index);
  29316. indices.push(index + 2);
  29317. indices.push(index + 3);
  29318. index += 4;
  29319. }
  29320. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  29321. // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY) + 1 filler
  29322. this._vertexData = new Float32Array(capacity * 11 * 4);
  29323. this._vertexBuffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 11);
  29324. var positions = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 3);
  29325. var colors = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 3, 4);
  29326. var options = this._vertexBuffer.createVertexBuffer("options", 7, 4);
  29327. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  29328. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  29329. this._vertexBuffers["options"] = options;
  29330. // Default behaviors
  29331. this.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  29332. var randX = randomNumber(_this.direction1.x, _this.direction2.x);
  29333. var randY = randomNumber(_this.direction1.y, _this.direction2.y);
  29334. var randZ = randomNumber(_this.direction1.z, _this.direction2.z);
  29335. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  29336. };
  29337. this.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  29338. var randX = randomNumber(_this.minEmitBox.x, _this.maxEmitBox.x);
  29339. var randY = randomNumber(_this.minEmitBox.y, _this.maxEmitBox.y);
  29340. var randZ = randomNumber(_this.minEmitBox.z, _this.maxEmitBox.z);
  29341. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  29342. };
  29343. this.updateFunction = function (particles) {
  29344. for (var index = 0; index < particles.length; index++) {
  29345. var particle = particles[index];
  29346. particle.age += _this._scaledUpdateSpeed;
  29347. if (particle.age >= particle.lifeTime) {
  29348. _this.recycleParticle(particle);
  29349. index--;
  29350. continue;
  29351. }
  29352. else {
  29353. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  29354. particle.color.addInPlace(_this._scaledColorStep);
  29355. if (particle.color.a < 0)
  29356. particle.color.a = 0;
  29357. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  29358. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  29359. particle.position.addInPlace(_this._scaledDirection);
  29360. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  29361. particle.direction.addInPlace(_this._scaledGravity);
  29362. }
  29363. }
  29364. };
  29365. }
  29366. Object.defineProperty(ParticleSystem.prototype, "onDispose", {
  29367. set: function (callback) {
  29368. if (this._onDisposeObserver) {
  29369. this.onDisposeObservable.remove(this._onDisposeObserver);
  29370. }
  29371. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  29372. },
  29373. enumerable: true,
  29374. configurable: true
  29375. });
  29376. ParticleSystem.prototype.recycleParticle = function (particle) {
  29377. var lastParticle = this.particles.pop();
  29378. if (lastParticle !== particle) {
  29379. lastParticle.copyTo(particle);
  29380. this._stockParticles.push(lastParticle);
  29381. }
  29382. };
  29383. ParticleSystem.prototype.getCapacity = function () {
  29384. return this._capacity;
  29385. };
  29386. ParticleSystem.prototype.isAlive = function () {
  29387. return this._alive;
  29388. };
  29389. ParticleSystem.prototype.isStarted = function () {
  29390. return this._started;
  29391. };
  29392. ParticleSystem.prototype.start = function () {
  29393. this._started = true;
  29394. this._stopped = false;
  29395. this._actualFrame = 0;
  29396. };
  29397. ParticleSystem.prototype.stop = function () {
  29398. this._stopped = true;
  29399. };
  29400. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  29401. var offset = index * 11;
  29402. this._vertexData[offset] = particle.position.x;
  29403. this._vertexData[offset + 1] = particle.position.y;
  29404. this._vertexData[offset + 2] = particle.position.z;
  29405. this._vertexData[offset + 3] = particle.color.r;
  29406. this._vertexData[offset + 4] = particle.color.g;
  29407. this._vertexData[offset + 5] = particle.color.b;
  29408. this._vertexData[offset + 6] = particle.color.a;
  29409. this._vertexData[offset + 7] = particle.angle;
  29410. this._vertexData[offset + 8] = particle.size;
  29411. this._vertexData[offset + 9] = offsetX;
  29412. this._vertexData[offset + 10] = offsetY;
  29413. };
  29414. ParticleSystem.prototype._update = function (newParticles) {
  29415. // Update current
  29416. this._alive = this.particles.length > 0;
  29417. this.updateFunction(this.particles);
  29418. // Add new ones
  29419. var worldMatrix;
  29420. if (this.emitter.position) {
  29421. worldMatrix = this.emitter.getWorldMatrix();
  29422. }
  29423. else {
  29424. worldMatrix = BABYLON.Matrix.Translation(this.emitter.x, this.emitter.y, this.emitter.z);
  29425. }
  29426. var particle;
  29427. for (var index = 0; index < newParticles; index++) {
  29428. if (this.particles.length === this._capacity) {
  29429. break;
  29430. }
  29431. if (this._stockParticles.length !== 0) {
  29432. particle = this._stockParticles.pop();
  29433. particle.age = 0;
  29434. }
  29435. else {
  29436. particle = new BABYLON.Particle();
  29437. }
  29438. this.particles.push(particle);
  29439. var emitPower = randomNumber(this.minEmitPower, this.maxEmitPower);
  29440. this.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  29441. particle.lifeTime = randomNumber(this.minLifeTime, this.maxLifeTime);
  29442. particle.size = randomNumber(this.minSize, this.maxSize);
  29443. particle.angularSpeed = randomNumber(this.minAngularSpeed, this.maxAngularSpeed);
  29444. this.startPositionFunction(worldMatrix, particle.position, particle);
  29445. var step = randomNumber(0, 1.0);
  29446. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  29447. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  29448. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  29449. }
  29450. };
  29451. ParticleSystem.prototype._getEffect = function () {
  29452. if (this._customEffect) {
  29453. return this._customEffect;
  29454. }
  29455. ;
  29456. var defines = [];
  29457. if (this._scene.clipPlane) {
  29458. defines.push("#define CLIPPLANE");
  29459. }
  29460. // Effect
  29461. var join = defines.join("\n");
  29462. if (this._cachedDefines !== join) {
  29463. this._cachedDefines = join;
  29464. this._effect = this._scene.getEngine().createEffect("particles", [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options"], ["invView", "view", "projection", "vClipPlane", "textureMask"], ["diffuseSampler"], join);
  29465. }
  29466. return this._effect;
  29467. };
  29468. ParticleSystem.prototype.animate = function () {
  29469. if (!this._started)
  29470. return;
  29471. var effect = this._getEffect();
  29472. // Check
  29473. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  29474. return;
  29475. if (this._currentRenderId === this._scene.getRenderId()) {
  29476. return;
  29477. }
  29478. this._currentRenderId = this._scene.getRenderId();
  29479. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  29480. // determine the number of particles we need to create
  29481. var newParticles;
  29482. if (this.manualEmitCount > -1) {
  29483. newParticles = this.manualEmitCount;
  29484. this._newPartsExcess = 0;
  29485. this.manualEmitCount = 0;
  29486. }
  29487. else {
  29488. newParticles = ((this.emitRate * this._scaledUpdateSpeed) >> 0);
  29489. this._newPartsExcess += this.emitRate * this._scaledUpdateSpeed - newParticles;
  29490. }
  29491. if (this._newPartsExcess > 1.0) {
  29492. newParticles += this._newPartsExcess >> 0;
  29493. this._newPartsExcess -= this._newPartsExcess >> 0;
  29494. }
  29495. this._alive = false;
  29496. if (!this._stopped) {
  29497. this._actualFrame += this._scaledUpdateSpeed;
  29498. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  29499. this.stop();
  29500. }
  29501. else {
  29502. newParticles = 0;
  29503. }
  29504. this._update(newParticles);
  29505. // Stopped?
  29506. if (this._stopped) {
  29507. if (!this._alive) {
  29508. this._started = false;
  29509. if (this.disposeOnStop) {
  29510. this._scene._toBeDisposed.push(this);
  29511. }
  29512. }
  29513. }
  29514. // Update VBO
  29515. var offset = 0;
  29516. for (var index = 0; index < this.particles.length; index++) {
  29517. var particle = this.particles[index];
  29518. this._appendParticleVertex(offset++, particle, 0, 0);
  29519. this._appendParticleVertex(offset++, particle, 1, 0);
  29520. this._appendParticleVertex(offset++, particle, 1, 1);
  29521. this._appendParticleVertex(offset++, particle, 0, 1);
  29522. }
  29523. this._vertexBuffer.update(this._vertexData);
  29524. };
  29525. ParticleSystem.prototype.render = function () {
  29526. var effect = this._getEffect();
  29527. // Check
  29528. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this.particles.length)
  29529. return 0;
  29530. var engine = this._scene.getEngine();
  29531. // Render
  29532. engine.enableEffect(effect);
  29533. engine.setState(false);
  29534. var viewMatrix = this._scene.getViewMatrix();
  29535. effect.setTexture("diffuseSampler", this.particleTexture);
  29536. effect.setMatrix("view", viewMatrix);
  29537. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  29538. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  29539. if (this._scene.clipPlane) {
  29540. var clipPlane = this._scene.clipPlane;
  29541. var invView = viewMatrix.clone();
  29542. invView.invert();
  29543. effect.setMatrix("invView", invView);
  29544. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  29545. }
  29546. // VBOs
  29547. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  29548. // Draw order
  29549. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  29550. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  29551. }
  29552. else {
  29553. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  29554. }
  29555. if (this.forceDepthWrite) {
  29556. engine.setDepthWrite(true);
  29557. }
  29558. engine.draw(true, 0, this.particles.length * 6);
  29559. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  29560. return this.particles.length;
  29561. };
  29562. ParticleSystem.prototype.dispose = function () {
  29563. if (this._vertexBuffer) {
  29564. this._vertexBuffer.dispose();
  29565. this._vertexBuffer = null;
  29566. }
  29567. if (this._indexBuffer) {
  29568. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  29569. this._indexBuffer = null;
  29570. }
  29571. if (this.particleTexture) {
  29572. this.particleTexture.dispose();
  29573. this.particleTexture = null;
  29574. }
  29575. // Remove from scene
  29576. var index = this._scene.particleSystems.indexOf(this);
  29577. this._scene.particleSystems.splice(index, 1);
  29578. // Callback
  29579. this.onDisposeObservable.notifyObservers(this);
  29580. this.onDisposeObservable.clear();
  29581. };
  29582. // Clone
  29583. ParticleSystem.prototype.clone = function (name, newEmitter) {
  29584. var custom = null;
  29585. var program = null;
  29586. if (this.customShader != null) {
  29587. program = this.customShader;
  29588. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  29589. custom = this._scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  29590. }
  29591. var result = new ParticleSystem(name, this._capacity, this._scene, custom);
  29592. result.customShader = program;
  29593. BABYLON.Tools.DeepCopy(this, result, ["particles", "customShader"]);
  29594. if (newEmitter === undefined) {
  29595. newEmitter = this.emitter;
  29596. }
  29597. result.emitter = newEmitter;
  29598. if (this.particleTexture) {
  29599. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  29600. }
  29601. if (!this.preventAutoStart) {
  29602. result.start();
  29603. }
  29604. return result;
  29605. };
  29606. ParticleSystem.prototype.serialize = function () {
  29607. var serializationObject = {};
  29608. serializationObject.name = this.name;
  29609. serializationObject.id = this.id;
  29610. // Emitter
  29611. if (this.emitter.position) {
  29612. serializationObject.emitterId = this.emitter.id;
  29613. }
  29614. else {
  29615. serializationObject.emitter = this.emitter.asArray();
  29616. }
  29617. serializationObject.capacity = this.getCapacity();
  29618. if (this.particleTexture) {
  29619. serializationObject.textureName = this.particleTexture.name;
  29620. }
  29621. // Animations
  29622. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  29623. // Particle system
  29624. serializationObject.minAngularSpeed = this.minAngularSpeed;
  29625. serializationObject.maxAngularSpeed = this.maxAngularSpeed;
  29626. serializationObject.minSize = this.minSize;
  29627. serializationObject.maxSize = this.maxSize;
  29628. serializationObject.minEmitPower = this.minEmitPower;
  29629. serializationObject.maxEmitPower = this.maxEmitPower;
  29630. serializationObject.minLifeTime = this.minLifeTime;
  29631. serializationObject.maxLifeTime = this.maxLifeTime;
  29632. serializationObject.emitRate = this.emitRate;
  29633. serializationObject.minEmitBox = this.minEmitBox.asArray();
  29634. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  29635. serializationObject.gravity = this.gravity.asArray();
  29636. serializationObject.direction1 = this.direction1.asArray();
  29637. serializationObject.direction2 = this.direction2.asArray();
  29638. serializationObject.color1 = this.color1.asArray();
  29639. serializationObject.color2 = this.color2.asArray();
  29640. serializationObject.colorDead = this.colorDead.asArray();
  29641. serializationObject.updateSpeed = this.updateSpeed;
  29642. serializationObject.targetStopDuration = this.targetStopDuration;
  29643. serializationObject.textureMask = this.textureMask.asArray();
  29644. serializationObject.blendMode = this.blendMode;
  29645. serializationObject.customShader = this.customShader;
  29646. serializationObject.preventAutoStart = this.preventAutoStart;
  29647. return serializationObject;
  29648. };
  29649. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  29650. var name = parsedParticleSystem.name;
  29651. var custom = null;
  29652. var program = null;
  29653. if (parsedParticleSystem.customShader) {
  29654. program = parsedParticleSystem.customShader;
  29655. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  29656. custom = scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  29657. }
  29658. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene, custom);
  29659. particleSystem.customShader = program;
  29660. if (parsedParticleSystem.id) {
  29661. particleSystem.id = parsedParticleSystem.id;
  29662. }
  29663. // Auto start
  29664. if (parsedParticleSystem.preventAutoStart) {
  29665. particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;
  29666. }
  29667. // Texture
  29668. if (parsedParticleSystem.textureName) {
  29669. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  29670. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  29671. }
  29672. // Emitter
  29673. if (parsedParticleSystem.emitterId) {
  29674. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  29675. }
  29676. else {
  29677. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  29678. }
  29679. // Animations
  29680. if (parsedParticleSystem.animations) {
  29681. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  29682. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  29683. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  29684. }
  29685. }
  29686. if (parsedParticleSystem.autoAnimate) {
  29687. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  29688. }
  29689. // Particle system
  29690. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  29691. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  29692. particleSystem.minSize = parsedParticleSystem.minSize;
  29693. particleSystem.maxSize = parsedParticleSystem.maxSize;
  29694. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  29695. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  29696. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  29697. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  29698. particleSystem.emitRate = parsedParticleSystem.emitRate;
  29699. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  29700. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  29701. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  29702. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  29703. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  29704. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  29705. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  29706. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  29707. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  29708. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  29709. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  29710. particleSystem.blendMode = parsedParticleSystem.blendMode;
  29711. if (!particleSystem.preventAutoStart) {
  29712. particleSystem.start();
  29713. }
  29714. return particleSystem;
  29715. };
  29716. return ParticleSystem;
  29717. }());
  29718. // Statics
  29719. ParticleSystem.BLENDMODE_ONEONE = 0;
  29720. ParticleSystem.BLENDMODE_STANDARD = 1;
  29721. BABYLON.ParticleSystem = ParticleSystem;
  29722. })(BABYLON || (BABYLON = {}));
  29723. //# sourceMappingURL=babylon.particleSystem.js.map
  29724. var BABYLON;
  29725. (function (BABYLON) {
  29726. var AnimationRange = (function () {
  29727. function AnimationRange(name, from, to) {
  29728. this.name = name;
  29729. this.from = from;
  29730. this.to = to;
  29731. }
  29732. AnimationRange.prototype.clone = function () {
  29733. return new AnimationRange(this.name, this.from, this.to);
  29734. };
  29735. return AnimationRange;
  29736. }());
  29737. BABYLON.AnimationRange = AnimationRange;
  29738. /**
  29739. * Composed of a frame, and an action function
  29740. */
  29741. var AnimationEvent = (function () {
  29742. function AnimationEvent(frame, action, onlyOnce) {
  29743. this.frame = frame;
  29744. this.action = action;
  29745. this.onlyOnce = onlyOnce;
  29746. this.isDone = false;
  29747. }
  29748. return AnimationEvent;
  29749. }());
  29750. BABYLON.AnimationEvent = AnimationEvent;
  29751. var PathCursor = (function () {
  29752. function PathCursor(path) {
  29753. this.path = path;
  29754. this._onchange = new Array();
  29755. this.value = 0;
  29756. this.animations = new Array();
  29757. }
  29758. PathCursor.prototype.getPoint = function () {
  29759. var point = this.path.getPointAtLengthPosition(this.value);
  29760. return new BABYLON.Vector3(point.x, 0, point.y);
  29761. };
  29762. PathCursor.prototype.moveAhead = function (step) {
  29763. if (step === void 0) { step = 0.002; }
  29764. this.move(step);
  29765. return this;
  29766. };
  29767. PathCursor.prototype.moveBack = function (step) {
  29768. if (step === void 0) { step = 0.002; }
  29769. this.move(-step);
  29770. return this;
  29771. };
  29772. PathCursor.prototype.move = function (step) {
  29773. if (Math.abs(step) > 1) {
  29774. throw "step size should be less than 1.";
  29775. }
  29776. this.value += step;
  29777. this.ensureLimits();
  29778. this.raiseOnChange();
  29779. return this;
  29780. };
  29781. PathCursor.prototype.ensureLimits = function () {
  29782. while (this.value > 1) {
  29783. this.value -= 1;
  29784. }
  29785. while (this.value < 0) {
  29786. this.value += 1;
  29787. }
  29788. return this;
  29789. };
  29790. // used by animation engine
  29791. PathCursor.prototype.markAsDirty = function (propertyName) {
  29792. this.ensureLimits();
  29793. this.raiseOnChange();
  29794. return this;
  29795. };
  29796. PathCursor.prototype.raiseOnChange = function () {
  29797. var _this = this;
  29798. this._onchange.forEach(function (f) { return f(_this); });
  29799. return this;
  29800. };
  29801. PathCursor.prototype.onchange = function (f) {
  29802. this._onchange.push(f);
  29803. return this;
  29804. };
  29805. return PathCursor;
  29806. }());
  29807. BABYLON.PathCursor = PathCursor;
  29808. var Animation = (function () {
  29809. function Animation(name, targetProperty, framePerSecond, dataType, loopMode, enableBlending) {
  29810. this.name = name;
  29811. this.targetProperty = targetProperty;
  29812. this.framePerSecond = framePerSecond;
  29813. this.dataType = dataType;
  29814. this.loopMode = loopMode;
  29815. this.enableBlending = enableBlending;
  29816. this._offsetsCache = {};
  29817. this._highLimitsCache = {};
  29818. this._stopped = false;
  29819. this._blendingFactor = 0;
  29820. // The set of event that will be linked to this animation
  29821. this._events = new Array();
  29822. this.allowMatricesInterpolation = false;
  29823. this.blendingSpeed = 0.01;
  29824. this._ranges = {};
  29825. this.targetPropertyPath = targetProperty.split(".");
  29826. this.dataType = dataType;
  29827. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  29828. }
  29829. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  29830. var dataType = undefined;
  29831. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  29832. dataType = Animation.ANIMATIONTYPE_FLOAT;
  29833. }
  29834. else if (from instanceof BABYLON.Quaternion) {
  29835. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  29836. }
  29837. else if (from instanceof BABYLON.Vector3) {
  29838. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  29839. }
  29840. else if (from instanceof BABYLON.Vector2) {
  29841. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  29842. }
  29843. else if (from instanceof BABYLON.Color3) {
  29844. dataType = Animation.ANIMATIONTYPE_COLOR3;
  29845. }
  29846. else if (from instanceof BABYLON.Size) {
  29847. dataType = Animation.ANIMATIONTYPE_SIZE;
  29848. }
  29849. if (dataType == undefined) {
  29850. return null;
  29851. }
  29852. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  29853. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  29854. animation.setKeys(keys);
  29855. if (easingFunction !== undefined) {
  29856. animation.setEasingFunction(easingFunction);
  29857. }
  29858. return animation;
  29859. };
  29860. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  29861. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  29862. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  29863. };
  29864. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  29865. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  29866. node.animations.push(animation);
  29867. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  29868. };
  29869. // Methods
  29870. /**
  29871. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  29872. */
  29873. Animation.prototype.toString = function (fullDetails) {
  29874. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  29875. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  29876. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  29877. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  29878. if (fullDetails) {
  29879. ret += ", Ranges: {";
  29880. var first = true;
  29881. for (var name in this._ranges) {
  29882. if (first) {
  29883. ret += ", ";
  29884. first = false;
  29885. }
  29886. ret += name;
  29887. }
  29888. ret += "}";
  29889. }
  29890. return ret;
  29891. };
  29892. /**
  29893. * Add an event to this animation.
  29894. */
  29895. Animation.prototype.addEvent = function (event) {
  29896. this._events.push(event);
  29897. };
  29898. /**
  29899. * Remove all events found at the given frame
  29900. * @param frame
  29901. */
  29902. Animation.prototype.removeEvents = function (frame) {
  29903. for (var index = 0; index < this._events.length; index++) {
  29904. if (this._events[index].frame === frame) {
  29905. this._events.splice(index, 1);
  29906. index--;
  29907. }
  29908. }
  29909. };
  29910. Animation.prototype.createRange = function (name, from, to) {
  29911. // check name not already in use; could happen for bones after serialized
  29912. if (!this._ranges[name]) {
  29913. this._ranges[name] = new AnimationRange(name, from, to);
  29914. }
  29915. };
  29916. Animation.prototype.deleteRange = function (name, deleteFrames) {
  29917. if (deleteFrames === void 0) { deleteFrames = true; }
  29918. if (this._ranges[name]) {
  29919. if (deleteFrames) {
  29920. var from = this._ranges[name].from;
  29921. var to = this._ranges[name].to;
  29922. // this loop MUST go high to low for multiple splices to work
  29923. for (var key = this._keys.length - 1; key >= 0; key--) {
  29924. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  29925. this._keys.splice(key, 1);
  29926. }
  29927. }
  29928. }
  29929. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  29930. }
  29931. };
  29932. Animation.prototype.getRange = function (name) {
  29933. return this._ranges[name];
  29934. };
  29935. Animation.prototype.reset = function () {
  29936. this._offsetsCache = {};
  29937. this._highLimitsCache = {};
  29938. this.currentFrame = 0;
  29939. this._blendingFactor = 0;
  29940. this._originalBlendValue = null;
  29941. };
  29942. Animation.prototype.isStopped = function () {
  29943. return this._stopped;
  29944. };
  29945. Animation.prototype.getKeys = function () {
  29946. return this._keys;
  29947. };
  29948. Animation.prototype.getHighestFrame = function () {
  29949. var ret = 0;
  29950. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  29951. if (ret < this._keys[key].frame) {
  29952. ret = this._keys[key].frame;
  29953. }
  29954. }
  29955. return ret;
  29956. };
  29957. Animation.prototype.getEasingFunction = function () {
  29958. return this._easingFunction;
  29959. };
  29960. Animation.prototype.setEasingFunction = function (easingFunction) {
  29961. this._easingFunction = easingFunction;
  29962. };
  29963. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  29964. return startValue + (endValue - startValue) * gradient;
  29965. };
  29966. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  29967. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  29968. };
  29969. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  29970. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  29971. };
  29972. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  29973. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  29974. };
  29975. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  29976. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  29977. };
  29978. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  29979. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  29980. };
  29981. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  29982. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  29983. };
  29984. Animation.prototype.clone = function () {
  29985. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  29986. clone.enableBlending = this.enableBlending;
  29987. clone.blendingSpeed = this.blendingSpeed;
  29988. if (this._keys) {
  29989. clone.setKeys(this._keys);
  29990. }
  29991. if (this._ranges) {
  29992. clone._ranges = {};
  29993. for (var name in this._ranges) {
  29994. clone._ranges[name] = this._ranges[name].clone();
  29995. }
  29996. }
  29997. return clone;
  29998. };
  29999. Animation.prototype.setKeys = function (values) {
  30000. this._keys = values.slice(0);
  30001. this._offsetsCache = {};
  30002. this._highLimitsCache = {};
  30003. };
  30004. Animation.prototype._getKeyValue = function (value) {
  30005. if (typeof value === "function") {
  30006. return value();
  30007. }
  30008. return value;
  30009. };
  30010. Animation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  30011. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  30012. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  30013. }
  30014. this.currentFrame = currentFrame;
  30015. // Try to get a hash to find the right key
  30016. 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));
  30017. if (this._keys[startKey].frame >= currentFrame) {
  30018. while (startKey - 1 >= 0 && this._keys[startKey].frame >= currentFrame) {
  30019. startKey--;
  30020. }
  30021. }
  30022. for (var key = startKey; key < this._keys.length; key++) {
  30023. if (this._keys[key + 1].frame >= currentFrame) {
  30024. var startValue = this._getKeyValue(this._keys[key].value);
  30025. var endValue = this._getKeyValue(this._keys[key + 1].value);
  30026. // gradient : percent of currentFrame between the frame inf and the frame sup
  30027. var gradient = (currentFrame - this._keys[key].frame) / (this._keys[key + 1].frame - this._keys[key].frame);
  30028. // check for easingFunction and correction of gradient
  30029. if (this._easingFunction != null) {
  30030. gradient = this._easingFunction.ease(gradient);
  30031. }
  30032. switch (this.dataType) {
  30033. // Float
  30034. case Animation.ANIMATIONTYPE_FLOAT:
  30035. switch (loopMode) {
  30036. case Animation.ANIMATIONLOOPMODE_CYCLE:
  30037. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  30038. return this.floatInterpolateFunction(startValue, endValue, gradient);
  30039. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  30040. return offsetValue * repeatCount + this.floatInterpolateFunction(startValue, endValue, gradient);
  30041. }
  30042. break;
  30043. // Quaternion
  30044. case Animation.ANIMATIONTYPE_QUATERNION:
  30045. var quaternion = null;
  30046. switch (loopMode) {
  30047. case Animation.ANIMATIONLOOPMODE_CYCLE:
  30048. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  30049. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient);
  30050. break;
  30051. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  30052. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  30053. break;
  30054. }
  30055. return quaternion;
  30056. // Vector3
  30057. case Animation.ANIMATIONTYPE_VECTOR3:
  30058. switch (loopMode) {
  30059. case Animation.ANIMATIONLOOPMODE_CYCLE:
  30060. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  30061. return this.vector3InterpolateFunction(startValue, endValue, gradient);
  30062. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  30063. return this.vector3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  30064. }
  30065. // Vector2
  30066. case Animation.ANIMATIONTYPE_VECTOR2:
  30067. switch (loopMode) {
  30068. case Animation.ANIMATIONLOOPMODE_CYCLE:
  30069. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  30070. return this.vector2InterpolateFunction(startValue, endValue, gradient);
  30071. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  30072. return this.vector2InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  30073. }
  30074. // Size
  30075. case Animation.ANIMATIONTYPE_SIZE:
  30076. switch (loopMode) {
  30077. case Animation.ANIMATIONLOOPMODE_CYCLE:
  30078. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  30079. return this.sizeInterpolateFunction(startValue, endValue, gradient);
  30080. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  30081. return this.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  30082. }
  30083. // Color3
  30084. case Animation.ANIMATIONTYPE_COLOR3:
  30085. switch (loopMode) {
  30086. case Animation.ANIMATIONLOOPMODE_CYCLE:
  30087. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  30088. return this.color3InterpolateFunction(startValue, endValue, gradient);
  30089. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  30090. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  30091. }
  30092. // Matrix
  30093. case Animation.ANIMATIONTYPE_MATRIX:
  30094. switch (loopMode) {
  30095. case Animation.ANIMATIONLOOPMODE_CYCLE:
  30096. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  30097. if (this.allowMatricesInterpolation) {
  30098. return this.matrixInterpolateFunction(startValue, endValue, gradient);
  30099. }
  30100. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  30101. return startValue;
  30102. }
  30103. default:
  30104. break;
  30105. }
  30106. break;
  30107. }
  30108. }
  30109. return this._getKeyValue(this._keys[this._keys.length - 1].value);
  30110. };
  30111. Animation.prototype.setValue = function (currentValue, blend) {
  30112. if (blend === void 0) { blend = false; }
  30113. // Set value
  30114. var path;
  30115. var destination;
  30116. if (this.targetPropertyPath.length > 1) {
  30117. var property = this._target[this.targetPropertyPath[0]];
  30118. for (var index = 1; index < this.targetPropertyPath.length - 1; index++) {
  30119. property = property[this.targetPropertyPath[index]];
  30120. }
  30121. path = this.targetPropertyPath[this.targetPropertyPath.length - 1];
  30122. destination = property;
  30123. }
  30124. else {
  30125. path = this.targetPropertyPath[0];
  30126. destination = this._target;
  30127. }
  30128. // Blending
  30129. if (this.enableBlending && this._blendingFactor <= 1.0) {
  30130. if (!this._originalBlendValue) {
  30131. if (destination[path].clone) {
  30132. this._originalBlendValue = destination[path].clone();
  30133. }
  30134. else {
  30135. this._originalBlendValue = destination[path];
  30136. }
  30137. }
  30138. if (this._originalBlendValue.prototype) {
  30139. if (this._originalBlendValue.prototype.Lerp) {
  30140. destination[path] = this._originalBlendValue.construtor.prototype.Lerp(currentValue, this._originalBlendValue, this._blendingFactor);
  30141. }
  30142. else {
  30143. destination[path] = currentValue;
  30144. }
  30145. }
  30146. else if (this._originalBlendValue.m) {
  30147. destination[path] = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  30148. }
  30149. else {
  30150. destination[path] = this._originalBlendValue * (1.0 - this._blendingFactor) + this._blendingFactor * currentValue;
  30151. }
  30152. this._blendingFactor += this.blendingSpeed;
  30153. }
  30154. else {
  30155. destination[path] = currentValue;
  30156. }
  30157. if (this._target.markAsDirty) {
  30158. this._target.markAsDirty(this.targetProperty);
  30159. }
  30160. };
  30161. Animation.prototype.goToFrame = function (frame) {
  30162. if (frame < this._keys[0].frame) {
  30163. frame = this._keys[0].frame;
  30164. }
  30165. else if (frame > this._keys[this._keys.length - 1].frame) {
  30166. frame = this._keys[this._keys.length - 1].frame;
  30167. }
  30168. var currentValue = this._interpolate(frame, 0, this.loopMode);
  30169. this.setValue(currentValue);
  30170. };
  30171. Animation.prototype.animate = function (delay, from, to, loop, speedRatio, blend) {
  30172. if (blend === void 0) { blend = false; }
  30173. if (!this.targetPropertyPath || this.targetPropertyPath.length < 1) {
  30174. this._stopped = true;
  30175. return false;
  30176. }
  30177. var returnValue = true;
  30178. // Adding a start key at frame 0 if missing
  30179. if (this._keys[0].frame !== 0) {
  30180. var newKey = { frame: 0, value: this._keys[0].value };
  30181. this._keys.splice(0, 0, newKey);
  30182. }
  30183. // Check limits
  30184. if (from < this._keys[0].frame || from > this._keys[this._keys.length - 1].frame) {
  30185. from = this._keys[0].frame;
  30186. }
  30187. if (to < this._keys[0].frame || to > this._keys[this._keys.length - 1].frame) {
  30188. to = this._keys[this._keys.length - 1].frame;
  30189. }
  30190. //to and from cannot be the same key
  30191. if (from === to) {
  30192. from++;
  30193. }
  30194. // Compute ratio
  30195. var range = to - from;
  30196. var offsetValue;
  30197. // ratio represents the frame delta between from and to
  30198. var ratio = delay * (this.framePerSecond * speedRatio) / 1000.0;
  30199. var highLimitValue = 0;
  30200. if (ratio > range && !loop) {
  30201. returnValue = false;
  30202. highLimitValue = this._getKeyValue(this._keys[this._keys.length - 1].value);
  30203. }
  30204. else {
  30205. // Get max value if required
  30206. if (this.loopMode !== Animation.ANIMATIONLOOPMODE_CYCLE) {
  30207. var keyOffset = to.toString() + from.toString();
  30208. if (!this._offsetsCache[keyOffset]) {
  30209. var fromValue = this._interpolate(from, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  30210. var toValue = this._interpolate(to, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  30211. switch (this.dataType) {
  30212. // Float
  30213. case Animation.ANIMATIONTYPE_FLOAT:
  30214. this._offsetsCache[keyOffset] = toValue - fromValue;
  30215. break;
  30216. // Quaternion
  30217. case Animation.ANIMATIONTYPE_QUATERNION:
  30218. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  30219. break;
  30220. // Vector3
  30221. case Animation.ANIMATIONTYPE_VECTOR3:
  30222. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  30223. // Vector2
  30224. case Animation.ANIMATIONTYPE_VECTOR2:
  30225. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  30226. // Size
  30227. case Animation.ANIMATIONTYPE_SIZE:
  30228. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  30229. // Color3
  30230. case Animation.ANIMATIONTYPE_COLOR3:
  30231. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  30232. default:
  30233. break;
  30234. }
  30235. this._highLimitsCache[keyOffset] = toValue;
  30236. }
  30237. highLimitValue = this._highLimitsCache[keyOffset];
  30238. offsetValue = this._offsetsCache[keyOffset];
  30239. }
  30240. }
  30241. if (offsetValue === undefined) {
  30242. switch (this.dataType) {
  30243. // Float
  30244. case Animation.ANIMATIONTYPE_FLOAT:
  30245. offsetValue = 0;
  30246. break;
  30247. // Quaternion
  30248. case Animation.ANIMATIONTYPE_QUATERNION:
  30249. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  30250. break;
  30251. // Vector3
  30252. case Animation.ANIMATIONTYPE_VECTOR3:
  30253. offsetValue = BABYLON.Vector3.Zero();
  30254. break;
  30255. // Vector2
  30256. case Animation.ANIMATIONTYPE_VECTOR2:
  30257. offsetValue = BABYLON.Vector2.Zero();
  30258. break;
  30259. // Size
  30260. case Animation.ANIMATIONTYPE_SIZE:
  30261. offsetValue = BABYLON.Size.Zero();
  30262. break;
  30263. // Color3
  30264. case Animation.ANIMATIONTYPE_COLOR3:
  30265. offsetValue = BABYLON.Color3.Black();
  30266. }
  30267. }
  30268. // Compute value
  30269. var repeatCount = (ratio / range) >> 0;
  30270. var currentFrame = returnValue ? from + ratio % range : to;
  30271. var currentValue = this._interpolate(currentFrame, repeatCount, this.loopMode, offsetValue, highLimitValue);
  30272. // Set value
  30273. this.setValue(currentValue);
  30274. // Check events
  30275. for (var index = 0; index < this._events.length; index++) {
  30276. if (currentFrame >= this._events[index].frame) {
  30277. var event = this._events[index];
  30278. if (!event.isDone) {
  30279. // If event should be done only once, remove it.
  30280. if (event.onlyOnce) {
  30281. this._events.splice(index, 1);
  30282. index--;
  30283. }
  30284. event.isDone = true;
  30285. event.action();
  30286. } // Don't do anything if the event has already be done.
  30287. }
  30288. else if (this._events[index].isDone && !this._events[index].onlyOnce) {
  30289. // reset event, the animation is looping
  30290. this._events[index].isDone = false;
  30291. }
  30292. }
  30293. if (!returnValue) {
  30294. this._stopped = true;
  30295. }
  30296. return returnValue;
  30297. };
  30298. Animation.prototype.serialize = function () {
  30299. var serializationObject = {};
  30300. serializationObject.name = this.name;
  30301. serializationObject.property = this.targetProperty;
  30302. serializationObject.framePerSecond = this.framePerSecond;
  30303. serializationObject.dataType = this.dataType;
  30304. serializationObject.loopBehavior = this.loopMode;
  30305. serializationObject.enableBlending = this.enableBlending;
  30306. serializationObject.blendingSpeed = this.blendingSpeed;
  30307. var dataType = this.dataType;
  30308. serializationObject.keys = [];
  30309. var keys = this.getKeys();
  30310. for (var index = 0; index < keys.length; index++) {
  30311. var animationKey = keys[index];
  30312. var key = {};
  30313. key.frame = animationKey.frame;
  30314. switch (dataType) {
  30315. case Animation.ANIMATIONTYPE_FLOAT:
  30316. key.values = [animationKey.value];
  30317. break;
  30318. case Animation.ANIMATIONTYPE_QUATERNION:
  30319. case Animation.ANIMATIONTYPE_MATRIX:
  30320. case Animation.ANIMATIONTYPE_VECTOR3:
  30321. case Animation.ANIMATIONTYPE_COLOR3:
  30322. key.values = animationKey.value.asArray();
  30323. break;
  30324. }
  30325. serializationObject.keys.push(key);
  30326. }
  30327. serializationObject.ranges = [];
  30328. for (var name in this._ranges) {
  30329. var range = {};
  30330. range.name = name;
  30331. range.from = this._ranges[name].from;
  30332. range.to = this._ranges[name].to;
  30333. serializationObject.ranges.push(range);
  30334. }
  30335. return serializationObject;
  30336. };
  30337. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  30338. get: function () {
  30339. return Animation._ANIMATIONTYPE_FLOAT;
  30340. },
  30341. enumerable: true,
  30342. configurable: true
  30343. });
  30344. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  30345. get: function () {
  30346. return Animation._ANIMATIONTYPE_VECTOR3;
  30347. },
  30348. enumerable: true,
  30349. configurable: true
  30350. });
  30351. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  30352. get: function () {
  30353. return Animation._ANIMATIONTYPE_VECTOR2;
  30354. },
  30355. enumerable: true,
  30356. configurable: true
  30357. });
  30358. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  30359. get: function () {
  30360. return Animation._ANIMATIONTYPE_SIZE;
  30361. },
  30362. enumerable: true,
  30363. configurable: true
  30364. });
  30365. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  30366. get: function () {
  30367. return Animation._ANIMATIONTYPE_QUATERNION;
  30368. },
  30369. enumerable: true,
  30370. configurable: true
  30371. });
  30372. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  30373. get: function () {
  30374. return Animation._ANIMATIONTYPE_MATRIX;
  30375. },
  30376. enumerable: true,
  30377. configurable: true
  30378. });
  30379. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  30380. get: function () {
  30381. return Animation._ANIMATIONTYPE_COLOR3;
  30382. },
  30383. enumerable: true,
  30384. configurable: true
  30385. });
  30386. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  30387. get: function () {
  30388. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  30389. },
  30390. enumerable: true,
  30391. configurable: true
  30392. });
  30393. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  30394. get: function () {
  30395. return Animation._ANIMATIONLOOPMODE_CYCLE;
  30396. },
  30397. enumerable: true,
  30398. configurable: true
  30399. });
  30400. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  30401. get: function () {
  30402. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  30403. },
  30404. enumerable: true,
  30405. configurable: true
  30406. });
  30407. Animation.Parse = function (parsedAnimation) {
  30408. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  30409. var dataType = parsedAnimation.dataType;
  30410. var keys = [];
  30411. var data;
  30412. var index;
  30413. if (parsedAnimation.enableBlending) {
  30414. animation.enableBlending = parsedAnimation.enableBlending;
  30415. }
  30416. if (parsedAnimation.blendingSpeed) {
  30417. animation.blendingSpeed = parsedAnimation.blendingSpeed;
  30418. }
  30419. for (index = 0; index < parsedAnimation.keys.length; index++) {
  30420. var key = parsedAnimation.keys[index];
  30421. switch (dataType) {
  30422. case Animation.ANIMATIONTYPE_FLOAT:
  30423. data = key.values[0];
  30424. break;
  30425. case Animation.ANIMATIONTYPE_QUATERNION:
  30426. data = BABYLON.Quaternion.FromArray(key.values);
  30427. break;
  30428. case Animation.ANIMATIONTYPE_MATRIX:
  30429. data = BABYLON.Matrix.FromArray(key.values);
  30430. break;
  30431. case Animation.ANIMATIONTYPE_COLOR3:
  30432. data = BABYLON.Color3.FromArray(key.values);
  30433. break;
  30434. case Animation.ANIMATIONTYPE_VECTOR3:
  30435. default:
  30436. data = BABYLON.Vector3.FromArray(key.values);
  30437. break;
  30438. }
  30439. keys.push({
  30440. frame: key.frame,
  30441. value: data
  30442. });
  30443. }
  30444. animation.setKeys(keys);
  30445. if (parsedAnimation.ranges) {
  30446. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  30447. data = parsedAnimation.ranges[index];
  30448. animation.createRange(data.name, data.from, data.to);
  30449. }
  30450. }
  30451. return animation;
  30452. };
  30453. Animation.AppendSerializedAnimations = function (source, destination) {
  30454. if (source.animations) {
  30455. destination.animations = [];
  30456. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  30457. var animation = source.animations[animationIndex];
  30458. destination.animations.push(animation.serialize());
  30459. }
  30460. }
  30461. };
  30462. return Animation;
  30463. }());
  30464. // Statics
  30465. Animation._ANIMATIONTYPE_FLOAT = 0;
  30466. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  30467. Animation._ANIMATIONTYPE_QUATERNION = 2;
  30468. Animation._ANIMATIONTYPE_MATRIX = 3;
  30469. Animation._ANIMATIONTYPE_COLOR3 = 4;
  30470. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  30471. Animation._ANIMATIONTYPE_SIZE = 6;
  30472. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  30473. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  30474. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  30475. BABYLON.Animation = Animation;
  30476. })(BABYLON || (BABYLON = {}));
  30477. //# sourceMappingURL=babylon.animation.js.map
  30478. var BABYLON;
  30479. (function (BABYLON) {
  30480. var Animatable = (function () {
  30481. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  30482. if (fromFrame === void 0) { fromFrame = 0; }
  30483. if (toFrame === void 0) { toFrame = 100; }
  30484. if (loopAnimation === void 0) { loopAnimation = false; }
  30485. if (speedRatio === void 0) { speedRatio = 1.0; }
  30486. this.target = target;
  30487. this.fromFrame = fromFrame;
  30488. this.toFrame = toFrame;
  30489. this.loopAnimation = loopAnimation;
  30490. this.speedRatio = speedRatio;
  30491. this.onAnimationEnd = onAnimationEnd;
  30492. this._animations = new Array();
  30493. this._paused = false;
  30494. this.animationStarted = false;
  30495. if (animations) {
  30496. this.appendAnimations(target, animations);
  30497. }
  30498. this._scene = scene;
  30499. scene._activeAnimatables.push(this);
  30500. }
  30501. // Methods
  30502. Animatable.prototype.getAnimations = function () {
  30503. return this._animations;
  30504. };
  30505. Animatable.prototype.appendAnimations = function (target, animations) {
  30506. for (var index = 0; index < animations.length; index++) {
  30507. var animation = animations[index];
  30508. animation._target = target;
  30509. this._animations.push(animation);
  30510. }
  30511. };
  30512. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  30513. var animations = this._animations;
  30514. for (var index = 0; index < animations.length; index++) {
  30515. if (animations[index].targetProperty === property) {
  30516. return animations[index];
  30517. }
  30518. }
  30519. return null;
  30520. };
  30521. Animatable.prototype.reset = function () {
  30522. var animations = this._animations;
  30523. for (var index = 0; index < animations.length; index++) {
  30524. animations[index].reset();
  30525. }
  30526. this._localDelayOffset = null;
  30527. this._pausedDelay = null;
  30528. };
  30529. Animatable.prototype.enableBlending = function (blendingSpeed) {
  30530. var animations = this._animations;
  30531. for (var index = 0; index < animations.length; index++) {
  30532. animations[index].enableBlending = true;
  30533. animations[index].blendingSpeed = blendingSpeed;
  30534. }
  30535. };
  30536. Animatable.prototype.disableBlending = function () {
  30537. var animations = this._animations;
  30538. for (var index = 0; index < animations.length; index++) {
  30539. animations[index].enableBlending = false;
  30540. }
  30541. };
  30542. Animatable.prototype.goToFrame = function (frame) {
  30543. var animations = this._animations;
  30544. if (animations[0]) {
  30545. var fps = animations[0].framePerSecond;
  30546. var currentFrame = animations[0].currentFrame;
  30547. var adjustTime = frame - currentFrame;
  30548. var delay = adjustTime * 1000 / fps;
  30549. this._localDelayOffset -= delay;
  30550. }
  30551. for (var index = 0; index < animations.length; index++) {
  30552. animations[index].goToFrame(frame);
  30553. }
  30554. };
  30555. Animatable.prototype.pause = function () {
  30556. if (this._paused) {
  30557. return;
  30558. }
  30559. this._paused = true;
  30560. };
  30561. Animatable.prototype.restart = function () {
  30562. this._paused = false;
  30563. };
  30564. Animatable.prototype.stop = function (animationName) {
  30565. if (animationName) {
  30566. var idx = this._scene._activeAnimatables.indexOf(this);
  30567. if (idx > -1) {
  30568. var animations = this._animations;
  30569. var numberOfAnimationsStopped = 0;
  30570. for (var index = animations.length - 1; index >= 0; index--) {
  30571. if (typeof animationName === "string" && animations[index].name != animationName) {
  30572. continue;
  30573. }
  30574. animations[index].reset();
  30575. animations.splice(index, 1);
  30576. numberOfAnimationsStopped++;
  30577. }
  30578. if (animations.length == numberOfAnimationsStopped) {
  30579. this._scene._activeAnimatables.splice(idx, 1);
  30580. if (this.onAnimationEnd) {
  30581. this.onAnimationEnd();
  30582. }
  30583. }
  30584. }
  30585. }
  30586. else {
  30587. var index = this._scene._activeAnimatables.indexOf(this);
  30588. if (index > -1) {
  30589. this._scene._activeAnimatables.splice(index, 1);
  30590. var animations = this._animations;
  30591. for (var index = 0; index < animations.length; index++) {
  30592. animations[index].reset();
  30593. }
  30594. if (this.onAnimationEnd) {
  30595. this.onAnimationEnd();
  30596. }
  30597. }
  30598. }
  30599. };
  30600. Animatable.prototype._animate = function (delay) {
  30601. if (this._paused) {
  30602. this.animationStarted = false;
  30603. if (!this._pausedDelay) {
  30604. this._pausedDelay = delay;
  30605. }
  30606. return true;
  30607. }
  30608. if (!this._localDelayOffset) {
  30609. this._localDelayOffset = delay;
  30610. }
  30611. else if (this._pausedDelay) {
  30612. this._localDelayOffset += delay - this._pausedDelay;
  30613. this._pausedDelay = null;
  30614. }
  30615. // Animating
  30616. var running = false;
  30617. var animations = this._animations;
  30618. var index;
  30619. for (index = 0; index < animations.length; index++) {
  30620. var animation = animations[index];
  30621. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this.speedRatio);
  30622. running = running || isRunning;
  30623. }
  30624. this.animationStarted = running;
  30625. if (!running) {
  30626. // Remove from active animatables
  30627. index = this._scene._activeAnimatables.indexOf(this);
  30628. this._scene._activeAnimatables.splice(index, 1);
  30629. }
  30630. if (!running && this.onAnimationEnd) {
  30631. this.onAnimationEnd();
  30632. this.onAnimationEnd = null;
  30633. }
  30634. return running;
  30635. };
  30636. return Animatable;
  30637. }());
  30638. BABYLON.Animatable = Animatable;
  30639. })(BABYLON || (BABYLON = {}));
  30640. //# sourceMappingURL=babylon.animatable.js.map
  30641. var BABYLON;
  30642. (function (BABYLON) {
  30643. var EasingFunction = (function () {
  30644. function EasingFunction() {
  30645. // Properties
  30646. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  30647. }
  30648. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  30649. get: function () {
  30650. return EasingFunction._EASINGMODE_EASEIN;
  30651. },
  30652. enumerable: true,
  30653. configurable: true
  30654. });
  30655. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  30656. get: function () {
  30657. return EasingFunction._EASINGMODE_EASEOUT;
  30658. },
  30659. enumerable: true,
  30660. configurable: true
  30661. });
  30662. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  30663. get: function () {
  30664. return EasingFunction._EASINGMODE_EASEINOUT;
  30665. },
  30666. enumerable: true,
  30667. configurable: true
  30668. });
  30669. EasingFunction.prototype.setEasingMode = function (easingMode) {
  30670. var n = Math.min(Math.max(easingMode, 0), 2);
  30671. this._easingMode = n;
  30672. };
  30673. EasingFunction.prototype.getEasingMode = function () {
  30674. return this._easingMode;
  30675. };
  30676. EasingFunction.prototype.easeInCore = function (gradient) {
  30677. throw new Error('You must implement this method');
  30678. };
  30679. EasingFunction.prototype.ease = function (gradient) {
  30680. switch (this._easingMode) {
  30681. case EasingFunction.EASINGMODE_EASEIN:
  30682. return this.easeInCore(gradient);
  30683. case EasingFunction.EASINGMODE_EASEOUT:
  30684. return (1 - this.easeInCore(1 - gradient));
  30685. }
  30686. if (gradient >= 0.5) {
  30687. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  30688. }
  30689. return (this.easeInCore(gradient * 2) * 0.5);
  30690. };
  30691. return EasingFunction;
  30692. }());
  30693. //Statics
  30694. EasingFunction._EASINGMODE_EASEIN = 0;
  30695. EasingFunction._EASINGMODE_EASEOUT = 1;
  30696. EasingFunction._EASINGMODE_EASEINOUT = 2;
  30697. BABYLON.EasingFunction = EasingFunction;
  30698. var CircleEase = (function (_super) {
  30699. __extends(CircleEase, _super);
  30700. function CircleEase() {
  30701. return _super.apply(this, arguments) || this;
  30702. }
  30703. CircleEase.prototype.easeInCore = function (gradient) {
  30704. gradient = Math.max(0, Math.min(1, gradient));
  30705. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  30706. };
  30707. return CircleEase;
  30708. }(EasingFunction));
  30709. BABYLON.CircleEase = CircleEase;
  30710. var BackEase = (function (_super) {
  30711. __extends(BackEase, _super);
  30712. function BackEase(amplitude) {
  30713. if (amplitude === void 0) { amplitude = 1; }
  30714. var _this = _super.call(this) || this;
  30715. _this.amplitude = amplitude;
  30716. return _this;
  30717. }
  30718. BackEase.prototype.easeInCore = function (gradient) {
  30719. var num = Math.max(0, this.amplitude);
  30720. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  30721. };
  30722. return BackEase;
  30723. }(EasingFunction));
  30724. BABYLON.BackEase = BackEase;
  30725. var BounceEase = (function (_super) {
  30726. __extends(BounceEase, _super);
  30727. function BounceEase(bounces, bounciness) {
  30728. if (bounces === void 0) { bounces = 3; }
  30729. if (bounciness === void 0) { bounciness = 2; }
  30730. var _this = _super.call(this) || this;
  30731. _this.bounces = bounces;
  30732. _this.bounciness = bounciness;
  30733. return _this;
  30734. }
  30735. BounceEase.prototype.easeInCore = function (gradient) {
  30736. var y = Math.max(0.0, this.bounces);
  30737. var bounciness = this.bounciness;
  30738. if (bounciness <= 1.0) {
  30739. bounciness = 1.001;
  30740. }
  30741. var num9 = Math.pow(bounciness, y);
  30742. var num5 = 1.0 - bounciness;
  30743. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  30744. var num15 = gradient * num4;
  30745. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  30746. var num3 = Math.floor(num65);
  30747. var num13 = num3 + 1.0;
  30748. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  30749. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  30750. var num7 = (num8 + num12) * 0.5;
  30751. var num6 = gradient - num7;
  30752. var num2 = num7 - num8;
  30753. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  30754. };
  30755. return BounceEase;
  30756. }(EasingFunction));
  30757. BABYLON.BounceEase = BounceEase;
  30758. var CubicEase = (function (_super) {
  30759. __extends(CubicEase, _super);
  30760. function CubicEase() {
  30761. return _super.apply(this, arguments) || this;
  30762. }
  30763. CubicEase.prototype.easeInCore = function (gradient) {
  30764. return (gradient * gradient * gradient);
  30765. };
  30766. return CubicEase;
  30767. }(EasingFunction));
  30768. BABYLON.CubicEase = CubicEase;
  30769. var ElasticEase = (function (_super) {
  30770. __extends(ElasticEase, _super);
  30771. function ElasticEase(oscillations, springiness) {
  30772. if (oscillations === void 0) { oscillations = 3; }
  30773. if (springiness === void 0) { springiness = 3; }
  30774. var _this = _super.call(this) || this;
  30775. _this.oscillations = oscillations;
  30776. _this.springiness = springiness;
  30777. return _this;
  30778. }
  30779. ElasticEase.prototype.easeInCore = function (gradient) {
  30780. var num2;
  30781. var num3 = Math.max(0.0, this.oscillations);
  30782. var num = Math.max(0.0, this.springiness);
  30783. if (num == 0) {
  30784. num2 = gradient;
  30785. }
  30786. else {
  30787. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  30788. }
  30789. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  30790. };
  30791. return ElasticEase;
  30792. }(EasingFunction));
  30793. BABYLON.ElasticEase = ElasticEase;
  30794. var ExponentialEase = (function (_super) {
  30795. __extends(ExponentialEase, _super);
  30796. function ExponentialEase(exponent) {
  30797. if (exponent === void 0) { exponent = 2; }
  30798. var _this = _super.call(this) || this;
  30799. _this.exponent = exponent;
  30800. return _this;
  30801. }
  30802. ExponentialEase.prototype.easeInCore = function (gradient) {
  30803. if (this.exponent <= 0) {
  30804. return gradient;
  30805. }
  30806. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  30807. };
  30808. return ExponentialEase;
  30809. }(EasingFunction));
  30810. BABYLON.ExponentialEase = ExponentialEase;
  30811. var PowerEase = (function (_super) {
  30812. __extends(PowerEase, _super);
  30813. function PowerEase(power) {
  30814. if (power === void 0) { power = 2; }
  30815. var _this = _super.call(this) || this;
  30816. _this.power = power;
  30817. return _this;
  30818. }
  30819. PowerEase.prototype.easeInCore = function (gradient) {
  30820. var y = Math.max(0.0, this.power);
  30821. return Math.pow(gradient, y);
  30822. };
  30823. return PowerEase;
  30824. }(EasingFunction));
  30825. BABYLON.PowerEase = PowerEase;
  30826. var QuadraticEase = (function (_super) {
  30827. __extends(QuadraticEase, _super);
  30828. function QuadraticEase() {
  30829. return _super.apply(this, arguments) || this;
  30830. }
  30831. QuadraticEase.prototype.easeInCore = function (gradient) {
  30832. return (gradient * gradient);
  30833. };
  30834. return QuadraticEase;
  30835. }(EasingFunction));
  30836. BABYLON.QuadraticEase = QuadraticEase;
  30837. var QuarticEase = (function (_super) {
  30838. __extends(QuarticEase, _super);
  30839. function QuarticEase() {
  30840. return _super.apply(this, arguments) || this;
  30841. }
  30842. QuarticEase.prototype.easeInCore = function (gradient) {
  30843. return (gradient * gradient * gradient * gradient);
  30844. };
  30845. return QuarticEase;
  30846. }(EasingFunction));
  30847. BABYLON.QuarticEase = QuarticEase;
  30848. var QuinticEase = (function (_super) {
  30849. __extends(QuinticEase, _super);
  30850. function QuinticEase() {
  30851. return _super.apply(this, arguments) || this;
  30852. }
  30853. QuinticEase.prototype.easeInCore = function (gradient) {
  30854. return (gradient * gradient * gradient * gradient * gradient);
  30855. };
  30856. return QuinticEase;
  30857. }(EasingFunction));
  30858. BABYLON.QuinticEase = QuinticEase;
  30859. var SineEase = (function (_super) {
  30860. __extends(SineEase, _super);
  30861. function SineEase() {
  30862. return _super.apply(this, arguments) || this;
  30863. }
  30864. SineEase.prototype.easeInCore = function (gradient) {
  30865. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  30866. };
  30867. return SineEase;
  30868. }(EasingFunction));
  30869. BABYLON.SineEase = SineEase;
  30870. var BezierCurveEase = (function (_super) {
  30871. __extends(BezierCurveEase, _super);
  30872. function BezierCurveEase(x1, y1, x2, y2) {
  30873. if (x1 === void 0) { x1 = 0; }
  30874. if (y1 === void 0) { y1 = 0; }
  30875. if (x2 === void 0) { x2 = 1; }
  30876. if (y2 === void 0) { y2 = 1; }
  30877. var _this = _super.call(this) || this;
  30878. _this.x1 = x1;
  30879. _this.y1 = y1;
  30880. _this.x2 = x2;
  30881. _this.y2 = y2;
  30882. return _this;
  30883. }
  30884. BezierCurveEase.prototype.easeInCore = function (gradient) {
  30885. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  30886. };
  30887. return BezierCurveEase;
  30888. }(EasingFunction));
  30889. BABYLON.BezierCurveEase = BezierCurveEase;
  30890. })(BABYLON || (BABYLON = {}));
  30891. //# sourceMappingURL=babylon.easing.js.map
  30892. var BABYLON;
  30893. (function (BABYLON) {
  30894. var Bone = (function (_super) {
  30895. __extends(Bone, _super);
  30896. function Bone(name, skeleton, parentBone, matrix, restPose) {
  30897. var _this = _super.call(this, name, skeleton.getScene()) || this;
  30898. _this.name = name;
  30899. _this.children = new Array();
  30900. _this.animations = new Array();
  30901. _this._worldTransform = new BABYLON.Matrix();
  30902. _this._absoluteTransform = new BABYLON.Matrix();
  30903. _this._invertedAbsoluteTransform = new BABYLON.Matrix();
  30904. _this._scaleMatrix = BABYLON.Matrix.Identity();
  30905. _this._scaleVector = new BABYLON.Vector3(1, 1, 1);
  30906. _this._negateScaleChildren = new BABYLON.Vector3(1, 1, 1);
  30907. _this._scalingDeterminant = 1;
  30908. _this._syncScaleVector = function () {
  30909. var lm = this.getLocalMatrix();
  30910. var xsq = (lm.m[0] * lm.m[0] + lm.m[1] * lm.m[1] + lm.m[2] * lm.m[2]);
  30911. var ysq = (lm.m[4] * lm.m[4] + lm.m[5] * lm.m[5] + lm.m[6] * lm.m[6]);
  30912. var zsq = (lm.m[8] * lm.m[8] + lm.m[9] * lm.m[9] + lm.m[10] * lm.m[10]);
  30913. var xs = lm.m[0] * lm.m[1] * lm.m[2] * lm.m[3] < 0 ? -1 : 1;
  30914. var ys = lm.m[4] * lm.m[5] * lm.m[6] * lm.m[7] < 0 ? -1 : 1;
  30915. var zs = lm.m[8] * lm.m[9] * lm.m[10] * lm.m[11] < 0 ? -1 : 1;
  30916. this._scaleVector.x = xs * Math.sqrt(xsq);
  30917. this._scaleVector.y = ys * Math.sqrt(ysq);
  30918. this._scaleVector.z = zs * Math.sqrt(zsq);
  30919. if (this._parent) {
  30920. this._scaleVector.x /= this._parent._negateScaleChildren.x;
  30921. this._scaleVector.y /= this._parent._negateScaleChildren.y;
  30922. this._scaleVector.z /= this._parent._negateScaleChildren.z;
  30923. }
  30924. 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);
  30925. };
  30926. _this._skeleton = skeleton;
  30927. _this._matrix = matrix;
  30928. _this._baseMatrix = matrix;
  30929. _this._restPose = restPose ? restPose : matrix.clone();
  30930. skeleton.bones.push(_this);
  30931. if (parentBone) {
  30932. _this._parent = parentBone;
  30933. parentBone.children.push(_this);
  30934. }
  30935. else {
  30936. _this._parent = null;
  30937. }
  30938. _this._updateDifferenceMatrix();
  30939. if (_this.getAbsoluteTransform().determinant() < 0) {
  30940. _this._scalingDeterminant *= -1;
  30941. }
  30942. return _this;
  30943. }
  30944. // Members
  30945. Bone.prototype.getParent = function () {
  30946. return this._parent;
  30947. };
  30948. Bone.prototype.getLocalMatrix = function () {
  30949. return this._matrix;
  30950. };
  30951. Bone.prototype.getBaseMatrix = function () {
  30952. return this._baseMatrix;
  30953. };
  30954. Bone.prototype.getRestPose = function () {
  30955. return this._restPose;
  30956. };
  30957. Bone.prototype.returnToRest = function () {
  30958. this.updateMatrix(this._restPose.clone());
  30959. };
  30960. Bone.prototype.getWorldMatrix = function () {
  30961. return this._worldTransform;
  30962. };
  30963. Bone.prototype.getInvertedAbsoluteTransform = function () {
  30964. return this._invertedAbsoluteTransform;
  30965. };
  30966. Bone.prototype.getAbsoluteTransform = function () {
  30967. return this._absoluteTransform;
  30968. };
  30969. // Methods
  30970. Bone.prototype.updateMatrix = function (matrix, updateDifferenceMatrix) {
  30971. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  30972. this._baseMatrix = matrix.clone();
  30973. this._matrix = matrix.clone();
  30974. this._skeleton._markAsDirty();
  30975. if (updateDifferenceMatrix) {
  30976. this._updateDifferenceMatrix();
  30977. }
  30978. };
  30979. Bone.prototype._updateDifferenceMatrix = function (rootMatrix) {
  30980. if (!rootMatrix) {
  30981. rootMatrix = this._baseMatrix;
  30982. }
  30983. if (this._parent) {
  30984. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  30985. }
  30986. else {
  30987. this._absoluteTransform.copyFrom(rootMatrix);
  30988. }
  30989. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  30990. for (var index = 0; index < this.children.length; index++) {
  30991. this.children[index]._updateDifferenceMatrix();
  30992. }
  30993. };
  30994. Bone.prototype.markAsDirty = function () {
  30995. this._currentRenderId++;
  30996. this._skeleton._markAsDirty();
  30997. };
  30998. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) {
  30999. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  31000. if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; }
  31001. // all animation may be coming from a library skeleton, so may need to create animation
  31002. if (this.animations.length === 0) {
  31003. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  31004. this.animations[0].setKeys([]);
  31005. }
  31006. // get animation info / verify there is such a range from the source bone
  31007. var sourceRange = source.animations[0].getRange(rangeName);
  31008. if (!sourceRange) {
  31009. return false;
  31010. }
  31011. var from = sourceRange.from;
  31012. var to = sourceRange.to;
  31013. var sourceKeys = source.animations[0].getKeys();
  31014. // rescaling prep
  31015. var sourceBoneLength = source.length;
  31016. var sourceParent = source.getParent();
  31017. var parent = this.getParent();
  31018. var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  31019. var parentRatio = parentScalingReqd ? parent.length / sourceParent.length : null;
  31020. var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);
  31021. var destKeys = this.animations[0].getKeys();
  31022. // loop vars declaration
  31023. var orig;
  31024. var origTranslation;
  31025. var mat;
  31026. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  31027. orig = sourceKeys[key];
  31028. if (orig.frame >= from && orig.frame <= to) {
  31029. if (rescaleAsRequired) {
  31030. mat = orig.value.clone();
  31031. // scale based on parent ratio, when bone has parent
  31032. if (parentScalingReqd) {
  31033. origTranslation = mat.getTranslation();
  31034. mat.setTranslation(origTranslation.scaleInPlace(parentRatio));
  31035. }
  31036. else if (dimensionsScalingReqd) {
  31037. origTranslation = mat.getTranslation();
  31038. mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));
  31039. }
  31040. else {
  31041. mat = orig.value;
  31042. }
  31043. }
  31044. else {
  31045. mat = orig.value;
  31046. }
  31047. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  31048. }
  31049. }
  31050. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  31051. return true;
  31052. };
  31053. Bone.prototype.translate = function (vec, space, mesh) {
  31054. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  31055. var lm = this.getLocalMatrix();
  31056. if (space == BABYLON.Space.LOCAL) {
  31057. lm.m[12] += vec.x;
  31058. lm.m[13] += vec.y;
  31059. lm.m[14] += vec.z;
  31060. }
  31061. else {
  31062. this._skeleton.computeAbsoluteTransforms();
  31063. var tmat = BABYLON.Tmp.Matrix[0];
  31064. var tvec = BABYLON.Tmp.Vector3[0];
  31065. if (mesh) {
  31066. tmat.copyFrom(this._parent.getAbsoluteTransform());
  31067. tmat.multiplyToRef(mesh.getWorldMatrix(), tmat);
  31068. }
  31069. else {
  31070. tmat.copyFrom(this._parent.getAbsoluteTransform());
  31071. }
  31072. tmat.m[12] = 0;
  31073. tmat.m[13] = 0;
  31074. tmat.m[14] = 0;
  31075. tmat.invert();
  31076. BABYLON.Vector3.TransformCoordinatesToRef(vec, tmat, tvec);
  31077. lm.m[12] += tvec.x;
  31078. lm.m[13] += tvec.y;
  31079. lm.m[14] += tvec.z;
  31080. }
  31081. this.markAsDirty();
  31082. };
  31083. Bone.prototype.setPosition = function (position, space, mesh) {
  31084. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  31085. var lm = this.getLocalMatrix();
  31086. if (space == BABYLON.Space.LOCAL) {
  31087. lm.m[12] = position.x;
  31088. lm.m[13] = position.y;
  31089. lm.m[14] = position.z;
  31090. }
  31091. else {
  31092. this._skeleton.computeAbsoluteTransforms();
  31093. var tmat = BABYLON.Tmp.Matrix[0];
  31094. var vec = BABYLON.Tmp.Vector3[0];
  31095. if (mesh) {
  31096. tmat.copyFrom(this._parent.getAbsoluteTransform());
  31097. tmat.multiplyToRef(mesh.getWorldMatrix(), tmat);
  31098. }
  31099. else {
  31100. tmat.copyFrom(this._parent.getAbsoluteTransform());
  31101. }
  31102. tmat.invert();
  31103. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, vec);
  31104. lm.m[12] = vec.x;
  31105. lm.m[13] = vec.y;
  31106. lm.m[14] = vec.z;
  31107. }
  31108. this.markAsDirty();
  31109. };
  31110. Bone.prototype.setAbsolutePosition = function (position, mesh) {
  31111. this.setPosition(position, BABYLON.Space.WORLD, mesh);
  31112. };
  31113. Bone.prototype.setScale = function (x, y, z, scaleChildren) {
  31114. if (scaleChildren === void 0) { scaleChildren = false; }
  31115. if (this.animations[0] && !this.animations[0].isStopped()) {
  31116. if (!scaleChildren) {
  31117. this._negateScaleChildren.x = 1 / x;
  31118. this._negateScaleChildren.y = 1 / y;
  31119. this._negateScaleChildren.z = 1 / z;
  31120. }
  31121. this._syncScaleVector();
  31122. }
  31123. this.scale(x / this._scaleVector.x, y / this._scaleVector.y, z / this._scaleVector.z, scaleChildren);
  31124. };
  31125. Bone.prototype.scale = function (x, y, z, scaleChildren) {
  31126. if (scaleChildren === void 0) { scaleChildren = false; }
  31127. var locMat = this.getLocalMatrix();
  31128. var origLocMat = BABYLON.Tmp.Matrix[0];
  31129. origLocMat.copyFrom(locMat);
  31130. var origLocMatInv = BABYLON.Tmp.Matrix[1];
  31131. origLocMatInv.copyFrom(origLocMat);
  31132. origLocMatInv.invert();
  31133. var scaleMat = BABYLON.Tmp.Matrix[2];
  31134. BABYLON.Matrix.FromValuesToRef(x, 0, 0, 0, 0, y, 0, 0, 0, 0, z, 0, 0, 0, 0, 1, scaleMat);
  31135. this._scaleMatrix.multiplyToRef(scaleMat, this._scaleMatrix);
  31136. this._scaleVector.x *= x;
  31137. this._scaleVector.y *= y;
  31138. this._scaleVector.z *= z;
  31139. locMat.multiplyToRef(origLocMatInv, locMat);
  31140. locMat.multiplyToRef(scaleMat, locMat);
  31141. locMat.multiplyToRef(origLocMat, locMat);
  31142. var parent = this.getParent();
  31143. if (parent) {
  31144. locMat.multiplyToRef(parent.getAbsoluteTransform(), this.getAbsoluteTransform());
  31145. }
  31146. else {
  31147. this.getAbsoluteTransform().copyFrom(locMat);
  31148. }
  31149. var len = this.children.length;
  31150. scaleMat.invert();
  31151. for (var i = 0; i < len; i++) {
  31152. var child = this.children[i];
  31153. var cm = child.getLocalMatrix();
  31154. cm.multiplyToRef(scaleMat, cm);
  31155. var lm = child.getLocalMatrix();
  31156. lm.m[12] *= x;
  31157. lm.m[13] *= y;
  31158. lm.m[14] *= z;
  31159. }
  31160. this.computeAbsoluteTransforms();
  31161. if (scaleChildren) {
  31162. for (var i = 0; i < len; i++) {
  31163. this.children[i].scale(x, y, z, scaleChildren);
  31164. }
  31165. }
  31166. this.markAsDirty();
  31167. };
  31168. Bone.prototype.setYawPitchRoll = function (yaw, pitch, roll, space, mesh) {
  31169. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  31170. var rotMat = BABYLON.Tmp.Matrix[0];
  31171. BABYLON.Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, rotMat);
  31172. var rotMatInv = BABYLON.Tmp.Matrix[1];
  31173. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  31174. rotMatInv.multiplyToRef(rotMat, rotMat);
  31175. this._rotateWithMatrix(rotMat, space, mesh);
  31176. };
  31177. Bone.prototype.rotate = function (axis, amount, space, mesh) {
  31178. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  31179. var rmat = BABYLON.Tmp.Matrix[0];
  31180. rmat.m[12] = 0;
  31181. rmat.m[13] = 0;
  31182. rmat.m[14] = 0;
  31183. BABYLON.Matrix.RotationAxisToRef(axis, amount, rmat);
  31184. this._rotateWithMatrix(rmat, space, mesh);
  31185. };
  31186. Bone.prototype.setAxisAngle = function (axis, angle, space, mesh) {
  31187. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  31188. var rotMat = BABYLON.Tmp.Matrix[0];
  31189. BABYLON.Matrix.RotationAxisToRef(axis, angle, rotMat);
  31190. var rotMatInv = BABYLON.Tmp.Matrix[1];
  31191. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  31192. rotMatInv.multiplyToRef(rotMat, rotMat);
  31193. this._rotateWithMatrix(rotMat, space, mesh);
  31194. };
  31195. Bone.prototype.setRotation = function (rotation, space, mesh) {
  31196. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  31197. this.setYawPitchRoll(rotation.y, rotation.x, rotation.z, space, mesh);
  31198. };
  31199. Bone.prototype.setRotationQuaternion = function (quat, space, mesh) {
  31200. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  31201. var rotMatInv = BABYLON.Tmp.Matrix[0];
  31202. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  31203. var rotMat = BABYLON.Tmp.Matrix[1];
  31204. BABYLON.Matrix.FromQuaternionToRef(quat, rotMat);
  31205. rotMatInv.multiplyToRef(rotMat, rotMat);
  31206. this._rotateWithMatrix(rotMat, space, mesh);
  31207. };
  31208. Bone.prototype.setRotationMatrix = function (rotMat, space, mesh) {
  31209. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  31210. var rotMatInv = BABYLON.Tmp.Matrix[0];
  31211. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  31212. var rotMat2 = BABYLON.Tmp.Matrix[1];
  31213. rotMat2.copyFrom(rotMat);
  31214. rotMatInv.multiplyToRef(rotMat, rotMat2);
  31215. this._rotateWithMatrix(rotMat2, space, mesh);
  31216. };
  31217. Bone.prototype._rotateWithMatrix = function (rmat, space, mesh) {
  31218. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  31219. var lmat = this.getLocalMatrix();
  31220. var lx = lmat.m[12];
  31221. var ly = lmat.m[13];
  31222. var lz = lmat.m[14];
  31223. var parent = this.getParent();
  31224. var parentScale = BABYLON.Tmp.Matrix[3];
  31225. var parentScaleInv = BABYLON.Tmp.Matrix[4];
  31226. if (parent) {
  31227. if (space == BABYLON.Space.WORLD) {
  31228. if (mesh) {
  31229. parentScale.copyFrom(mesh.getWorldMatrix());
  31230. parent.getAbsoluteTransform().multiplyToRef(parentScale, parentScale);
  31231. }
  31232. else {
  31233. parentScale.copyFrom(parent.getAbsoluteTransform());
  31234. }
  31235. }
  31236. else {
  31237. parentScale = parent._scaleMatrix;
  31238. }
  31239. parentScaleInv.copyFrom(parentScale);
  31240. parentScaleInv.invert();
  31241. lmat.multiplyToRef(parentScale, lmat);
  31242. lmat.multiplyToRef(rmat, lmat);
  31243. lmat.multiplyToRef(parentScaleInv, lmat);
  31244. }
  31245. else {
  31246. if (space == BABYLON.Space.WORLD && mesh) {
  31247. parentScale.copyFrom(mesh.getWorldMatrix());
  31248. parentScaleInv.copyFrom(parentScale);
  31249. parentScaleInv.invert();
  31250. lmat.multiplyToRef(parentScale, lmat);
  31251. lmat.multiplyToRef(rmat, lmat);
  31252. lmat.multiplyToRef(parentScaleInv, lmat);
  31253. }
  31254. else {
  31255. lmat.multiplyToRef(rmat, lmat);
  31256. }
  31257. }
  31258. lmat.m[12] = lx;
  31259. lmat.m[13] = ly;
  31260. lmat.m[14] = lz;
  31261. this.computeAbsoluteTransforms();
  31262. this.markAsDirty();
  31263. };
  31264. Bone.prototype._getNegativeRotationToRef = function (rotMatInv, space, mesh) {
  31265. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  31266. if (space == BABYLON.Space.WORLD) {
  31267. var scaleMatrix = BABYLON.Tmp.Matrix[2];
  31268. scaleMatrix.copyFrom(this._scaleMatrix);
  31269. rotMatInv.copyFrom(this.getAbsoluteTransform());
  31270. if (mesh) {
  31271. rotMatInv.multiplyToRef(mesh.getWorldMatrix(), rotMatInv);
  31272. var meshScale = BABYLON.Tmp.Matrix[3];
  31273. BABYLON.Matrix.ScalingToRef(mesh.scaling.x, mesh.scaling.y, mesh.scaling.z, meshScale);
  31274. scaleMatrix.multiplyToRef(meshScale, scaleMatrix);
  31275. }
  31276. rotMatInv.invert();
  31277. scaleMatrix.m[0] *= this._scalingDeterminant;
  31278. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  31279. }
  31280. else {
  31281. rotMatInv.copyFrom(this.getLocalMatrix());
  31282. rotMatInv.invert();
  31283. var scaleMatrix = BABYLON.Tmp.Matrix[2];
  31284. scaleMatrix.copyFrom(this._scaleMatrix);
  31285. if (this._parent) {
  31286. var pscaleMatrix = BABYLON.Tmp.Matrix[3];
  31287. pscaleMatrix.copyFrom(this._parent._scaleMatrix);
  31288. pscaleMatrix.invert();
  31289. pscaleMatrix.multiplyToRef(rotMatInv, rotMatInv);
  31290. }
  31291. else {
  31292. scaleMatrix.m[0] *= this._scalingDeterminant;
  31293. }
  31294. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  31295. }
  31296. };
  31297. Bone.prototype.getScale = function () {
  31298. return this._scaleVector.clone();
  31299. };
  31300. Bone.prototype.getScaleToRef = function (result) {
  31301. result.copyFrom(this._scaleVector);
  31302. };
  31303. Bone.prototype.getPosition = function (space, mesh) {
  31304. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  31305. var pos = BABYLON.Vector3.Zero();
  31306. this.getPositionToRef(space, mesh, pos);
  31307. return pos;
  31308. };
  31309. Bone.prototype.getPositionToRef = function (space, mesh, result) {
  31310. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  31311. if (space == BABYLON.Space.LOCAL) {
  31312. var lm = this.getLocalMatrix();
  31313. result.x = lm.m[12];
  31314. result.y = lm.m[13];
  31315. result.z = lm.m[14];
  31316. }
  31317. else {
  31318. this._skeleton.computeAbsoluteTransforms();
  31319. var tmat = BABYLON.Tmp.Matrix[0];
  31320. if (mesh) {
  31321. tmat.copyFrom(this.getAbsoluteTransform());
  31322. tmat.multiplyToRef(mesh.getWorldMatrix(), tmat);
  31323. }
  31324. else {
  31325. tmat = this.getAbsoluteTransform();
  31326. }
  31327. result.x = tmat.m[12];
  31328. result.y = tmat.m[13];
  31329. result.z = tmat.m[14];
  31330. }
  31331. };
  31332. Bone.prototype.getAbsolutePosition = function (mesh) {
  31333. var pos = BABYLON.Vector3.Zero();
  31334. this.getPositionToRef(BABYLON.Space.WORLD, mesh, pos);
  31335. return pos;
  31336. };
  31337. Bone.prototype.getAbsolutePositionToRef = function (mesh, result) {
  31338. this.getPositionToRef(BABYLON.Space.WORLD, mesh, result);
  31339. };
  31340. Bone.prototype.computeAbsoluteTransforms = function () {
  31341. if (this._parent) {
  31342. this._matrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  31343. }
  31344. else {
  31345. this._absoluteTransform.copyFrom(this._matrix);
  31346. var poseMatrix = this._skeleton.getPoseMatrix();
  31347. if (poseMatrix) {
  31348. this._absoluteTransform.multiplyToRef(poseMatrix, this._absoluteTransform);
  31349. }
  31350. }
  31351. var children = this.children;
  31352. var len = children.length;
  31353. for (var i = 0; i < len; i++) {
  31354. children[i].computeAbsoluteTransforms();
  31355. }
  31356. };
  31357. Bone.prototype.getDirection = function (localAxis, mesh) {
  31358. var result = BABYLON.Vector3.Zero();
  31359. this.getDirectionToRef(localAxis, mesh, result);
  31360. return result;
  31361. };
  31362. Bone.prototype.getDirectionToRef = function (localAxis, mesh, result) {
  31363. this._skeleton.computeAbsoluteTransforms();
  31364. var mat = BABYLON.Tmp.Matrix[0];
  31365. mat.copyFrom(this.getAbsoluteTransform());
  31366. if (mesh) {
  31367. mat.multiplyToRef(mesh.getWorldMatrix(), mat);
  31368. }
  31369. BABYLON.Vector3.TransformNormalToRef(localAxis, mat, result);
  31370. result.normalize();
  31371. };
  31372. Bone.prototype.getRotation = function (space, mesh) {
  31373. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  31374. var result = BABYLON.Vector3.Zero();
  31375. this.getRotationToRef(space, mesh, result);
  31376. return result;
  31377. };
  31378. Bone.prototype.getRotationToRef = function (space, mesh, result) {
  31379. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  31380. var quat = BABYLON.Tmp.Quaternion[0];
  31381. this.getRotationQuaternionToRef(space, mesh, quat);
  31382. quat.toEulerAnglesToRef(result);
  31383. };
  31384. Bone.prototype.getRotationQuaternion = function (space, mesh) {
  31385. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  31386. var result = BABYLON.Quaternion.Identity();
  31387. this.getRotationQuaternionToRef(space, mesh, result);
  31388. return result;
  31389. };
  31390. Bone.prototype.getRotationQuaternionToRef = function (space, mesh, result) {
  31391. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  31392. if (space == BABYLON.Space.LOCAL) {
  31393. this.getLocalMatrix().decompose(BABYLON.Tmp.Vector3[0], result, BABYLON.Tmp.Vector3[1]);
  31394. }
  31395. else {
  31396. var mat = BABYLON.Tmp.Matrix[0];
  31397. var amat = this.getAbsoluteTransform();
  31398. if (mesh) {
  31399. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  31400. }
  31401. else {
  31402. mat.copyFrom(amat);
  31403. }
  31404. mat.m[0] *= this._scalingDeterminant;
  31405. mat.m[1] *= this._scalingDeterminant;
  31406. mat.m[2] *= this._scalingDeterminant;
  31407. mat.decompose(BABYLON.Tmp.Vector3[0], result, BABYLON.Tmp.Vector3[1]);
  31408. }
  31409. };
  31410. Bone.prototype.getRotationMatrix = function (space, mesh) {
  31411. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  31412. var result = BABYLON.Matrix.Identity();
  31413. this.getRotationMatrixToRef(space, mesh, result);
  31414. return result;
  31415. };
  31416. Bone.prototype.getRotationMatrixToRef = function (space, mesh, result) {
  31417. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  31418. if (space == BABYLON.Space.LOCAL) {
  31419. this.getLocalMatrix().getRotationMatrixToRef(result);
  31420. }
  31421. else {
  31422. var mat = BABYLON.Tmp.Matrix[0];
  31423. var amat = this.getAbsoluteTransform();
  31424. if (mesh) {
  31425. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  31426. }
  31427. else {
  31428. mat.copyFrom(amat);
  31429. }
  31430. mat.m[0] *= this._scalingDeterminant;
  31431. mat.m[1] *= this._scalingDeterminant;
  31432. mat.m[2] *= this._scalingDeterminant;
  31433. mat.getRotationMatrixToRef(result);
  31434. }
  31435. };
  31436. Bone.prototype.getAbsolutePositionFromLocal = function (position, mesh) {
  31437. var result = BABYLON.Vector3.Zero();
  31438. this.getAbsolutePositionFromLocalToRef(position, mesh, result);
  31439. return result;
  31440. };
  31441. Bone.prototype.getAbsolutePositionFromLocalToRef = function (position, mesh, result) {
  31442. this._skeleton.computeAbsoluteTransforms();
  31443. var tmat = BABYLON.Tmp.Matrix[0];
  31444. if (mesh) {
  31445. tmat.copyFrom(this.getAbsoluteTransform());
  31446. tmat.multiplyToRef(mesh.getWorldMatrix(), tmat);
  31447. }
  31448. else {
  31449. tmat = this.getAbsoluteTransform();
  31450. }
  31451. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  31452. };
  31453. Bone.prototype.getLocalPositionFromAbsolute = function (position, mesh) {
  31454. var result = BABYLON.Vector3.Zero();
  31455. this.getLocalPositionFromAbsoluteToRef(position, mesh, result);
  31456. return result;
  31457. };
  31458. Bone.prototype.getLocalPositionFromAbsoluteToRef = function (position, mesh, result) {
  31459. this._skeleton.computeAbsoluteTransforms();
  31460. var tmat = BABYLON.Tmp.Matrix[0];
  31461. tmat.copyFrom(this.getAbsoluteTransform());
  31462. if (mesh) {
  31463. tmat.multiplyToRef(mesh.getWorldMatrix(), tmat);
  31464. }
  31465. tmat.invert();
  31466. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  31467. };
  31468. return Bone;
  31469. }(BABYLON.Node));
  31470. BABYLON.Bone = Bone;
  31471. })(BABYLON || (BABYLON = {}));
  31472. //# sourceMappingURL=babylon.bone.js.map
  31473. var BABYLON;
  31474. (function (BABYLON) {
  31475. var BoneIKController = (function () {
  31476. function BoneIKController(mesh, bone, options) {
  31477. this.targetPosition = BABYLON.Vector3.Zero();
  31478. this.poleTargetPosition = BABYLON.Vector3.Zero();
  31479. this.poleTargetLocalOffset = BABYLON.Vector3.Zero();
  31480. this.poleAngle = 0;
  31481. this.slerpAmount = 1;
  31482. this._bone1Quat = BABYLON.Quaternion.Identity();
  31483. this._bone1Mat = BABYLON.Matrix.Identity();
  31484. this._bone2Ang = Math.PI;
  31485. this._maxAngle = Math.PI;
  31486. this._tmpVec1 = BABYLON.Vector3.Zero();
  31487. this._tmpVec2 = BABYLON.Vector3.Zero();
  31488. this._tmpVec3 = BABYLON.Vector3.Zero();
  31489. this._tmpVec4 = BABYLON.Vector3.Zero();
  31490. this._tmpVec5 = BABYLON.Vector3.Zero();
  31491. this._tmpMat1 = BABYLON.Matrix.Identity();
  31492. this._tmpMat2 = BABYLON.Matrix.Identity();
  31493. this._tmpQuat1 = BABYLON.Quaternion.Identity();
  31494. this._rightHandedSystem = false;
  31495. this._bendAxis = BABYLON.Vector3.Right();
  31496. this._slerping = false;
  31497. this._bone2 = bone;
  31498. this._bone1 = bone.getParent();
  31499. this.mesh = mesh;
  31500. if (bone.getAbsoluteTransform().determinant() > 0) {
  31501. this._rightHandedSystem = true;
  31502. this._bendAxis.x = 0;
  31503. this._bendAxis.y = 0;
  31504. this._bendAxis.z = 1;
  31505. }
  31506. if (this._bone1.length) {
  31507. var boneScale1 = this._bone1.getScale();
  31508. var boneScale2 = this._bone2.getScale();
  31509. this._bone1Length = this._bone1.length * boneScale1.y * this.mesh.scaling.y;
  31510. this._bone2Length = this._bone2.length * boneScale2.y * this.mesh.scaling.y;
  31511. }
  31512. else if (this._bone1.children[0]) {
  31513. mesh.computeWorldMatrix(true);
  31514. var pos1 = this._bone2.children[0].getAbsolutePosition(mesh);
  31515. var pos2 = this._bone2.getAbsolutePosition(mesh);
  31516. var pos3 = this._bone1.getAbsolutePosition(mesh);
  31517. this._bone1Length = BABYLON.Vector3.Distance(pos1, pos2);
  31518. this._bone2Length = BABYLON.Vector3.Distance(pos2, pos3);
  31519. }
  31520. this._bone1.getRotationMatrixToRef(BABYLON.Space.WORLD, mesh, this._bone1Mat);
  31521. this.maxAngle = Math.PI;
  31522. if (options) {
  31523. if (options.targetMesh) {
  31524. this.targetMesh = options.targetMesh;
  31525. this.targetMesh.computeWorldMatrix(true);
  31526. }
  31527. if (options.poleTargetMesh) {
  31528. this.poleTargetMesh = options.poleTargetMesh;
  31529. this.poleTargetMesh.computeWorldMatrix(true);
  31530. }
  31531. else if (options.poleTargetBone) {
  31532. this.poleTargetBone = options.poleTargetBone;
  31533. }
  31534. else if (this._bone1.getParent()) {
  31535. this.poleTargetBone = this._bone1.getParent();
  31536. }
  31537. if (options.poleTargetLocalOffset) {
  31538. this.poleTargetLocalOffset.copyFrom(options.poleTargetLocalOffset);
  31539. }
  31540. if (options.poleAngle) {
  31541. this.poleAngle = options.poleAngle;
  31542. }
  31543. if (options.bendAxis) {
  31544. this._bendAxis.copyFrom(options.bendAxis);
  31545. }
  31546. if (options.maxAngle) {
  31547. this.maxAngle = options.maxAngle;
  31548. }
  31549. if (options.slerpAmount) {
  31550. this.slerpAmount = options.slerpAmount;
  31551. }
  31552. }
  31553. }
  31554. Object.defineProperty(BoneIKController.prototype, "maxAngle", {
  31555. get: function () {
  31556. return this._maxAngle;
  31557. },
  31558. set: function (value) {
  31559. this._setMaxAngle(value);
  31560. },
  31561. enumerable: true,
  31562. configurable: true
  31563. });
  31564. BoneIKController.prototype._setMaxAngle = function (ang) {
  31565. if (ang < 0) {
  31566. ang = 0;
  31567. }
  31568. if (ang > Math.PI || ang == undefined) {
  31569. ang = Math.PI;
  31570. }
  31571. this._maxAngle = ang;
  31572. var a = this._bone1Length;
  31573. var b = this._bone2Length;
  31574. this._maxReach = Math.sqrt(a * a + b * b - 2 * a * b * Math.cos(ang));
  31575. };
  31576. BoneIKController.prototype.update = function () {
  31577. var bone1 = this._bone1;
  31578. var target = this.targetPosition;
  31579. var poleTarget = this.poleTargetPosition;
  31580. var mat1 = this._tmpMat1;
  31581. var mat2 = this._tmpMat2;
  31582. if (this.targetMesh) {
  31583. target.copyFrom(this.targetMesh.getAbsolutePosition());
  31584. }
  31585. if (this.poleTargetBone) {
  31586. this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset, this.mesh, poleTarget);
  31587. }
  31588. else if (this.poleTargetMesh) {
  31589. BABYLON.Vector3.TransformCoordinatesToRef(this.poleTargetLocalOffset, this.poleTargetMesh.getWorldMatrix(), poleTarget);
  31590. }
  31591. var bonePos = this._tmpVec1;
  31592. var zaxis = this._tmpVec2;
  31593. var xaxis = this._tmpVec3;
  31594. var yaxis = this._tmpVec4;
  31595. var upAxis = this._tmpVec5;
  31596. bone1.getAbsolutePositionToRef(this.mesh, bonePos);
  31597. poleTarget.subtractToRef(bonePos, upAxis);
  31598. if (upAxis.x == 0 && upAxis.y == 0 && upAxis.z == 0) {
  31599. upAxis.y = 1;
  31600. }
  31601. else {
  31602. upAxis.normalize();
  31603. }
  31604. target.subtractToRef(bonePos, yaxis);
  31605. yaxis.normalize();
  31606. BABYLON.Vector3.CrossToRef(yaxis, upAxis, zaxis);
  31607. zaxis.normalize();
  31608. BABYLON.Vector3.CrossToRef(yaxis, zaxis, xaxis);
  31609. xaxis.normalize();
  31610. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1);
  31611. var a = this._bone1Length;
  31612. var b = this._bone2Length;
  31613. var c = BABYLON.Vector3.Distance(bonePos, target);
  31614. if (this._maxReach > 0) {
  31615. c = Math.min(this._maxReach, c);
  31616. }
  31617. var acosa = (b * b + c * c - a * a) / (2 * b * c);
  31618. var acosb = (c * c + a * a - b * b) / (2 * c * a);
  31619. if (acosa > 1) {
  31620. acosa = 1;
  31621. }
  31622. if (acosb > 1) {
  31623. acosb = 1;
  31624. }
  31625. if (acosa < -1) {
  31626. acosa = -1;
  31627. }
  31628. if (acosb < -1) {
  31629. acosb = -1;
  31630. }
  31631. var angA = Math.acos(acosa);
  31632. var angB = Math.acos(acosb);
  31633. var angC = -angA - angB;
  31634. if (this._rightHandedSystem) {
  31635. BABYLON.Matrix.RotationYawPitchRollToRef(0, 0, Math.PI * .5, mat2);
  31636. mat2.multiplyToRef(mat1, mat1);
  31637. BABYLON.Matrix.RotationAxisToRef(this._bendAxis, angB, mat2);
  31638. mat2.multiplyToRef(mat1, mat1);
  31639. }
  31640. else {
  31641. this._tmpVec1.copyFrom(this._bendAxis);
  31642. this._tmpVec1.x *= -1;
  31643. BABYLON.Matrix.RotationAxisToRef(this._tmpVec1, -angB, mat2);
  31644. mat2.multiplyToRef(mat1, mat1);
  31645. }
  31646. if (this.poleAngle) {
  31647. BABYLON.Matrix.RotationAxisToRef(yaxis, this.poleAngle, mat2);
  31648. mat1.multiplyToRef(mat2, mat1);
  31649. }
  31650. if (this.slerpAmount < 1) {
  31651. if (!this._slerping) {
  31652. BABYLON.Quaternion.FromRotationMatrixToRef(this._bone1Mat, this._bone1Quat);
  31653. }
  31654. BABYLON.Quaternion.FromRotationMatrixToRef(mat1, this._tmpQuat1);
  31655. BABYLON.Quaternion.SlerpToRef(this._bone1Quat, this._tmpQuat1, this.slerpAmount, this._bone1Quat);
  31656. angC = this._bone2Ang * (1.0 - this.slerpAmount) + angC * this.slerpAmount;
  31657. this._bone1.setRotationQuaternion(this._bone1Quat, BABYLON.Space.WORLD, this.mesh);
  31658. this._slerping = true;
  31659. }
  31660. else {
  31661. this._bone1.setRotationMatrix(mat1, BABYLON.Space.WORLD, this.mesh);
  31662. this._bone1Mat.copyFrom(mat1);
  31663. this._slerping = false;
  31664. }
  31665. this._bone2.setAxisAngle(this._bendAxis, angC, BABYLON.Space.LOCAL);
  31666. this._bone2Ang = angC;
  31667. };
  31668. return BoneIKController;
  31669. }());
  31670. BABYLON.BoneIKController = BoneIKController;
  31671. })(BABYLON || (BABYLON = {}));
  31672. //# sourceMappingURL=babylon.boneIKController.js.map
  31673. var BABYLON;
  31674. (function (BABYLON) {
  31675. var BoneLookController = (function () {
  31676. function BoneLookController(mesh, bone, target, options) {
  31677. this.upAxis = BABYLON.Vector3.Up();
  31678. this.adjustYaw = 0;
  31679. this.adjustPitch = 0;
  31680. this.adjustRoll = 0;
  31681. this._tmpVec1 = BABYLON.Vector3.Zero();
  31682. this._tmpVec2 = BABYLON.Vector3.Zero();
  31683. this._tmpVec3 = BABYLON.Vector3.Zero();
  31684. this._tmpVec4 = BABYLON.Vector3.Zero();
  31685. this._tmpMat1 = BABYLON.Matrix.Identity();
  31686. this._tmpMat2 = BABYLON.Matrix.Identity();
  31687. this.mesh = mesh;
  31688. this.bone = bone;
  31689. this.target = target;
  31690. if (options) {
  31691. if (options.adjustYaw) {
  31692. this.adjustYaw = options.adjustYaw;
  31693. }
  31694. if (options.adjustPitch) {
  31695. this.adjustPitch = options.adjustPitch;
  31696. }
  31697. if (options.adjustRoll) {
  31698. this.adjustRoll = options.adjustRoll;
  31699. }
  31700. }
  31701. }
  31702. BoneLookController.prototype.update = function () {
  31703. var bone = this.bone;
  31704. var target = this.target;
  31705. var bonePos = this._tmpVec1;
  31706. var zaxis = this._tmpVec2;
  31707. var xaxis = this._tmpVec3;
  31708. var yaxis = this._tmpVec4;
  31709. var mat1 = this._tmpMat1;
  31710. var mat2 = this._tmpMat2;
  31711. bone.getAbsolutePositionToRef(this.mesh, bonePos);
  31712. target.subtractToRef(bonePos, zaxis);
  31713. zaxis.normalize();
  31714. BABYLON.Vector3.CrossToRef(this.upAxis, zaxis, xaxis);
  31715. xaxis.normalize();
  31716. BABYLON.Vector3.CrossToRef(zaxis, xaxis, yaxis);
  31717. yaxis.normalize();
  31718. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1);
  31719. if (this.adjustYaw || this.adjustPitch || this.adjustRoll) {
  31720. BABYLON.Matrix.RotationYawPitchRollToRef(this.adjustYaw, this.adjustPitch, this.adjustRoll, mat2);
  31721. mat2.multiplyToRef(mat1, mat1);
  31722. }
  31723. this.bone.setRotationMatrix(mat1, BABYLON.Space.WORLD, this.mesh);
  31724. };
  31725. return BoneLookController;
  31726. }());
  31727. BABYLON.BoneLookController = BoneLookController;
  31728. })(BABYLON || (BABYLON = {}));
  31729. //# sourceMappingURL=babylon.boneLookController.js.map
  31730. var BABYLON;
  31731. (function (BABYLON) {
  31732. var Skeleton = (function () {
  31733. function Skeleton(name, id, scene) {
  31734. this.name = name;
  31735. this.id = id;
  31736. this.bones = new Array();
  31737. this.needInitialSkinMatrix = false;
  31738. this._isDirty = true;
  31739. this._meshesWithPoseMatrix = new Array();
  31740. this._identity = BABYLON.Matrix.Identity();
  31741. this._ranges = {};
  31742. this._lastAbsoluteTransformsUpdateId = -1;
  31743. this.bones = [];
  31744. this._scene = scene;
  31745. scene.skeletons.push(this);
  31746. //make sure it will recalculate the matrix next time prepare is called.
  31747. this._isDirty = true;
  31748. }
  31749. // Members
  31750. Skeleton.prototype.getTransformMatrices = function (mesh) {
  31751. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  31752. return mesh._bonesTransformMatrices;
  31753. }
  31754. if (!this._transformMatrices) {
  31755. this.prepare();
  31756. }
  31757. return this._transformMatrices;
  31758. };
  31759. Skeleton.prototype.getScene = function () {
  31760. return this._scene;
  31761. };
  31762. // Methods
  31763. /**
  31764. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  31765. */
  31766. Skeleton.prototype.toString = function (fullDetails) {
  31767. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  31768. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  31769. if (fullDetails) {
  31770. ret += ", Ranges: {";
  31771. var first = true;
  31772. for (var name_1 in this._ranges) {
  31773. if (first) {
  31774. ret += ", ";
  31775. first = false;
  31776. }
  31777. ret += name_1;
  31778. }
  31779. ret += "}";
  31780. }
  31781. return ret;
  31782. };
  31783. /**
  31784. * Get bone's index searching by name
  31785. * @param {string} name is bone's name to search for
  31786. * @return {number} Indice of the bone. Returns -1 if not found
  31787. */
  31788. Skeleton.prototype.getBoneIndexByName = function (name) {
  31789. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  31790. if (this.bones[boneIndex].name === name) {
  31791. return boneIndex;
  31792. }
  31793. }
  31794. return -1;
  31795. };
  31796. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  31797. // check name not already in use
  31798. if (!this._ranges[name]) {
  31799. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  31800. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  31801. if (this.bones[i].animations[0]) {
  31802. this.bones[i].animations[0].createRange(name, from, to);
  31803. }
  31804. }
  31805. }
  31806. };
  31807. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  31808. if (deleteFrames === void 0) { deleteFrames = true; }
  31809. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  31810. if (this.bones[i].animations[0]) {
  31811. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  31812. }
  31813. }
  31814. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  31815. };
  31816. Skeleton.prototype.getAnimationRange = function (name) {
  31817. return this._ranges[name];
  31818. };
  31819. /**
  31820. * Returns as an Array, all AnimationRanges defined on this skeleton
  31821. */
  31822. Skeleton.prototype.getAnimationRanges = function () {
  31823. var animationRanges = [];
  31824. var name;
  31825. var i = 0;
  31826. for (name in this._ranges) {
  31827. animationRanges[i] = this._ranges[name];
  31828. i++;
  31829. }
  31830. return animationRanges;
  31831. };
  31832. /**
  31833. * note: This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  31834. */
  31835. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  31836. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  31837. if (this._ranges[name] || !source.getAnimationRange(name)) {
  31838. return false;
  31839. }
  31840. var ret = true;
  31841. var frameOffset = this._getHighestAnimationFrame() + 1;
  31842. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  31843. var boneDict = {};
  31844. var sourceBones = source.bones;
  31845. var nBones;
  31846. var i;
  31847. for (i = 0, nBones = sourceBones.length; i < nBones; i++) {
  31848. boneDict[sourceBones[i].name] = sourceBones[i];
  31849. }
  31850. if (this.bones.length !== sourceBones.length) {
  31851. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  31852. ret = false;
  31853. }
  31854. var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;
  31855. for (i = 0, nBones = this.bones.length; i < nBones; i++) {
  31856. var boneName = this.bones[i].name;
  31857. var sourceBone = boneDict[boneName];
  31858. if (sourceBone) {
  31859. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio);
  31860. }
  31861. else {
  31862. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  31863. ret = false;
  31864. }
  31865. }
  31866. // do not call createAnimationRange(), since it also is done to bones, which was already done
  31867. var range = source.getAnimationRange(name);
  31868. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  31869. return ret;
  31870. };
  31871. Skeleton.prototype.returnToRest = function () {
  31872. for (var index = 0; index < this.bones.length; index++) {
  31873. this.bones[index].returnToRest();
  31874. }
  31875. };
  31876. Skeleton.prototype._getHighestAnimationFrame = function () {
  31877. var ret = 0;
  31878. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  31879. if (this.bones[i].animations[0]) {
  31880. var highest = this.bones[i].animations[0].getHighestFrame();
  31881. if (ret < highest) {
  31882. ret = highest;
  31883. }
  31884. }
  31885. }
  31886. return ret;
  31887. };
  31888. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  31889. var range = this.getAnimationRange(name);
  31890. if (!range) {
  31891. return null;
  31892. }
  31893. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  31894. };
  31895. Skeleton.prototype._markAsDirty = function () {
  31896. this._isDirty = true;
  31897. };
  31898. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  31899. this._meshesWithPoseMatrix.push(mesh);
  31900. };
  31901. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  31902. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  31903. if (index > -1) {
  31904. this._meshesWithPoseMatrix.splice(index, 1);
  31905. }
  31906. };
  31907. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  31908. for (var index = 0; index < this.bones.length; index++) {
  31909. var bone = this.bones[index];
  31910. var parentBone = bone.getParent();
  31911. if (parentBone) {
  31912. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  31913. }
  31914. else {
  31915. if (initialSkinMatrix) {
  31916. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  31917. }
  31918. else {
  31919. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  31920. }
  31921. }
  31922. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, index * 16);
  31923. }
  31924. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  31925. };
  31926. Skeleton.prototype.prepare = function () {
  31927. if (!this._isDirty) {
  31928. return;
  31929. }
  31930. if (this.needInitialSkinMatrix) {
  31931. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  31932. var mesh = this._meshesWithPoseMatrix[index];
  31933. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  31934. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  31935. }
  31936. var poseMatrix = mesh.getPoseMatrix();
  31937. // Prepare bones
  31938. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  31939. var bone = this.bones[boneIndex];
  31940. if (!bone.getParent()) {
  31941. var matrix = bone.getBaseMatrix();
  31942. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[0]);
  31943. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[0]);
  31944. }
  31945. }
  31946. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  31947. }
  31948. }
  31949. else {
  31950. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  31951. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  31952. }
  31953. this._computeTransformMatrices(this._transformMatrices, null);
  31954. }
  31955. this._isDirty = false;
  31956. this._scene._activeBones.addCount(this.bones.length, false);
  31957. };
  31958. Skeleton.prototype.getAnimatables = function () {
  31959. if (!this._animatables || this._animatables.length !== this.bones.length) {
  31960. this._animatables = [];
  31961. for (var index = 0; index < this.bones.length; index++) {
  31962. this._animatables.push(this.bones[index]);
  31963. }
  31964. }
  31965. return this._animatables;
  31966. };
  31967. Skeleton.prototype.clone = function (name, id) {
  31968. var result = new Skeleton(name, id || name, this._scene);
  31969. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  31970. for (var index = 0; index < this.bones.length; index++) {
  31971. var source = this.bones[index];
  31972. var parentBone = null;
  31973. if (source.getParent()) {
  31974. var parentIndex = this.bones.indexOf(source.getParent());
  31975. parentBone = result.bones[parentIndex];
  31976. }
  31977. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  31978. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  31979. }
  31980. if (this._ranges) {
  31981. result._ranges = {};
  31982. for (var rangeName in this._ranges) {
  31983. result._ranges[rangeName] = this._ranges[rangeName].clone();
  31984. }
  31985. }
  31986. this._isDirty = true;
  31987. return result;
  31988. };
  31989. Skeleton.prototype.enableBlending = function (blendingSpeed) {
  31990. if (blendingSpeed === void 0) { blendingSpeed = 0.01; }
  31991. this.bones.forEach(function (bone) {
  31992. bone.animations.forEach(function (animation) {
  31993. animation.enableBlending = true;
  31994. animation.blendingSpeed = blendingSpeed;
  31995. });
  31996. });
  31997. };
  31998. Skeleton.prototype.dispose = function () {
  31999. this._meshesWithPoseMatrix = [];
  32000. // Animations
  32001. this.getScene().stopAnimation(this);
  32002. // Remove from scene
  32003. this.getScene().removeSkeleton(this);
  32004. };
  32005. Skeleton.prototype.serialize = function () {
  32006. var serializationObject = {};
  32007. serializationObject.name = this.name;
  32008. serializationObject.id = this.id;
  32009. serializationObject.dimensionsAtRest = this.dimensionsAtRest;
  32010. serializationObject.bones = [];
  32011. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  32012. for (var index = 0; index < this.bones.length; index++) {
  32013. var bone = this.bones[index];
  32014. var serializedBone = {
  32015. parentBoneIndex: bone.getParent() ? this.bones.indexOf(bone.getParent()) : -1,
  32016. name: bone.name,
  32017. matrix: bone.getLocalMatrix().toArray(),
  32018. rest: bone.getRestPose().toArray()
  32019. };
  32020. serializationObject.bones.push(serializedBone);
  32021. if (bone.length) {
  32022. serializedBone.length = bone.length;
  32023. }
  32024. if (bone.animations && bone.animations.length > 0) {
  32025. serializedBone.animation = bone.animations[0].serialize();
  32026. }
  32027. serializationObject.ranges = [];
  32028. for (var name in this._ranges) {
  32029. var range = {};
  32030. range.name = name;
  32031. range.from = this._ranges[name].from;
  32032. range.to = this._ranges[name].to;
  32033. serializationObject.ranges.push(range);
  32034. }
  32035. }
  32036. return serializationObject;
  32037. };
  32038. Skeleton.Parse = function (parsedSkeleton, scene) {
  32039. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  32040. if (parsedSkeleton.dimensionsAtRest) {
  32041. skeleton.dimensionsAtRest = BABYLON.Vector3.FromArray(parsedSkeleton.dimensionsAtRest);
  32042. }
  32043. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  32044. var index;
  32045. for (index = 0; index < parsedSkeleton.bones.length; index++) {
  32046. var parsedBone = parsedSkeleton.bones[index];
  32047. var parentBone = null;
  32048. if (parsedBone.parentBoneIndex > -1) {
  32049. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  32050. }
  32051. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  32052. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  32053. if (parsedBone.length) {
  32054. bone.length = parsedBone.length;
  32055. }
  32056. if (parsedBone.animation) {
  32057. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  32058. }
  32059. }
  32060. // placed after bones, so createAnimationRange can cascade down
  32061. if (parsedSkeleton.ranges) {
  32062. for (index = 0; index < parsedSkeleton.ranges.length; index++) {
  32063. var data = parsedSkeleton.ranges[index];
  32064. skeleton.createAnimationRange(data.name, data.from, data.to);
  32065. }
  32066. }
  32067. return skeleton;
  32068. };
  32069. Skeleton.prototype.computeAbsoluteTransforms = function (forceUpdate) {
  32070. if (forceUpdate === void 0) { forceUpdate = false; }
  32071. var renderId = this._scene.getRenderId();
  32072. if (this._lastAbsoluteTransformsUpdateId != renderId || forceUpdate) {
  32073. this.bones[0].computeAbsoluteTransforms();
  32074. this._lastAbsoluteTransformsUpdateId = renderId;
  32075. }
  32076. };
  32077. Skeleton.prototype.getPoseMatrix = function () {
  32078. var poseMatrix;
  32079. if (this._meshesWithPoseMatrix.length > 0) {
  32080. poseMatrix = this._meshesWithPoseMatrix[0].getPoseMatrix();
  32081. }
  32082. return poseMatrix;
  32083. };
  32084. return Skeleton;
  32085. }());
  32086. BABYLON.Skeleton = Skeleton;
  32087. })(BABYLON || (BABYLON = {}));
  32088. //# sourceMappingURL=babylon.skeleton.js.map
  32089. var BABYLON;
  32090. (function (BABYLON) {
  32091. var PostProcess = (function () {
  32092. function PostProcess(name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType) {
  32093. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  32094. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  32095. this.name = name;
  32096. this.width = -1;
  32097. this.height = -1;
  32098. /*
  32099. Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  32100. Can only be used on a single postprocess or on the last one of a chain.
  32101. */
  32102. this.enablePixelPerfectMode = false;
  32103. this._reusable = false;
  32104. this._textures = new BABYLON.SmartArray(2);
  32105. this._currentRenderTextureInd = 0;
  32106. this._scaleRatio = new BABYLON.Vector2(1, 1);
  32107. // Events
  32108. /**
  32109. * An event triggered when the postprocess is activated.
  32110. * @type {BABYLON.Observable}
  32111. */
  32112. this.onActivateObservable = new BABYLON.Observable();
  32113. /**
  32114. * An event triggered when the postprocess changes its size.
  32115. * @type {BABYLON.Observable}
  32116. */
  32117. this.onSizeChangedObservable = new BABYLON.Observable();
  32118. /**
  32119. * An event triggered when the postprocess applies its effect.
  32120. * @type {BABYLON.Observable}
  32121. */
  32122. this.onApplyObservable = new BABYLON.Observable();
  32123. /**
  32124. * An event triggered before rendering the postprocess
  32125. * @type {BABYLON.Observable}
  32126. */
  32127. this.onBeforeRenderObservable = new BABYLON.Observable();
  32128. /**
  32129. * An event triggered after rendering the postprocess
  32130. * @type {BABYLON.Observable}
  32131. */
  32132. this.onAfterRenderObservable = new BABYLON.Observable();
  32133. if (camera != null) {
  32134. this._camera = camera;
  32135. this._scene = camera.getScene();
  32136. camera.attachPostProcess(this);
  32137. this._engine = this._scene.getEngine();
  32138. }
  32139. else {
  32140. this._engine = engine;
  32141. }
  32142. this._options = options;
  32143. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  32144. this._reusable = reusable || false;
  32145. this._textureType = textureType;
  32146. this._samplers = samplers || [];
  32147. this._samplers.push("textureSampler");
  32148. this._fragmentUrl = fragmentUrl;
  32149. this._parameters = parameters || [];
  32150. this._parameters.push("scale");
  32151. this.updateEffect(defines);
  32152. }
  32153. Object.defineProperty(PostProcess.prototype, "onActivate", {
  32154. set: function (callback) {
  32155. if (this._onActivateObserver) {
  32156. this.onActivateObservable.remove(this._onActivateObserver);
  32157. }
  32158. this._onActivateObserver = this.onActivateObservable.add(callback);
  32159. },
  32160. enumerable: true,
  32161. configurable: true
  32162. });
  32163. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  32164. set: function (callback) {
  32165. if (this._onSizeChangedObserver) {
  32166. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  32167. }
  32168. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  32169. },
  32170. enumerable: true,
  32171. configurable: true
  32172. });
  32173. Object.defineProperty(PostProcess.prototype, "onApply", {
  32174. set: function (callback) {
  32175. if (this._onApplyObserver) {
  32176. this.onApplyObservable.remove(this._onApplyObserver);
  32177. }
  32178. this._onApplyObserver = this.onApplyObservable.add(callback);
  32179. },
  32180. enumerable: true,
  32181. configurable: true
  32182. });
  32183. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  32184. set: function (callback) {
  32185. if (this._onBeforeRenderObserver) {
  32186. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  32187. }
  32188. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  32189. },
  32190. enumerable: true,
  32191. configurable: true
  32192. });
  32193. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  32194. set: function (callback) {
  32195. if (this._onAfterRenderObserver) {
  32196. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  32197. }
  32198. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  32199. },
  32200. enumerable: true,
  32201. configurable: true
  32202. });
  32203. PostProcess.prototype.updateEffect = function (defines) {
  32204. this._effect = this._engine.createEffect({ vertex: "postprocess", fragment: this._fragmentUrl }, ["position"], this._parameters, this._samplers, defines !== undefined ? defines : "");
  32205. };
  32206. PostProcess.prototype.isReusable = function () {
  32207. return this._reusable;
  32208. };
  32209. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  32210. PostProcess.prototype.markTextureDirty = function () {
  32211. this.width = -1;
  32212. };
  32213. PostProcess.prototype.activate = function (camera, sourceTexture) {
  32214. camera = camera || this._camera;
  32215. var scene = camera.getScene();
  32216. var maxSize = camera.getEngine().getCaps().maxTextureSize;
  32217. var requiredWidth = ((sourceTexture ? sourceTexture._width : this._engine.getRenderingCanvas().width) * this._options) | 0;
  32218. var requiredHeight = ((sourceTexture ? sourceTexture._height : this._engine.getRenderingCanvas().height) * this._options) | 0;
  32219. var desiredWidth = this._options.width || requiredWidth;
  32220. var desiredHeight = this._options.height || requiredHeight;
  32221. if (this.renderTargetSamplingMode !== BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  32222. if (!this._options.width) {
  32223. desiredWidth = BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize);
  32224. }
  32225. if (!this._options.height) {
  32226. desiredHeight = BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize);
  32227. }
  32228. }
  32229. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  32230. if (this._textures.length > 0) {
  32231. for (var i = 0; i < this._textures.length; i++) {
  32232. this._engine._releaseTexture(this._textures.data[i]);
  32233. }
  32234. this._textures.reset();
  32235. }
  32236. this.width = desiredWidth;
  32237. this.height = desiredHeight;
  32238. var textureSize = { width: this.width, height: this.height };
  32239. var textureOptions = {
  32240. generateMipMaps: false,
  32241. generateDepthBuffer: camera._postProcesses.indexOf(this) === 0,
  32242. generateStencilBuffer: camera._postProcesses.indexOf(this) === 0 && this._engine.isStencilEnable,
  32243. samplingMode: this.renderTargetSamplingMode,
  32244. type: this._textureType
  32245. };
  32246. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  32247. if (this._reusable) {
  32248. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  32249. }
  32250. this.onSizeChangedObservable.notifyObservers(this);
  32251. }
  32252. if (this.enablePixelPerfectMode) {
  32253. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  32254. this._engine.bindFramebuffer(this._textures.data[this._currentRenderTextureInd], 0, requiredWidth, requiredHeight);
  32255. }
  32256. else {
  32257. this._scaleRatio.copyFromFloats(1, 1);
  32258. this._engine.bindFramebuffer(this._textures.data[this._currentRenderTextureInd]);
  32259. }
  32260. this.onActivateObservable.notifyObservers(camera);
  32261. // Clear
  32262. if (this.clearColor) {
  32263. this._engine.clear(this.clearColor, true, true, true);
  32264. }
  32265. else {
  32266. this._engine.clear(scene.clearColor, scene.autoClear || scene.forceWireframe, true, true);
  32267. }
  32268. if (this._reusable) {
  32269. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  32270. }
  32271. };
  32272. Object.defineProperty(PostProcess.prototype, "isSupported", {
  32273. get: function () {
  32274. return this._effect.isSupported;
  32275. },
  32276. enumerable: true,
  32277. configurable: true
  32278. });
  32279. PostProcess.prototype.apply = function () {
  32280. // Check
  32281. if (!this._effect.isReady())
  32282. return null;
  32283. // States
  32284. this._engine.enableEffect(this._effect);
  32285. this._engine.setState(false);
  32286. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  32287. this._engine.setDepthBuffer(false);
  32288. this._engine.setDepthWrite(false);
  32289. // Texture
  32290. this._effect._bindTexture("textureSampler", this._textures.data[this._currentRenderTextureInd]);
  32291. // Parameters
  32292. this._effect.setVector2("scale", this._scaleRatio);
  32293. this.onApplyObservable.notifyObservers(this._effect);
  32294. return this._effect;
  32295. };
  32296. PostProcess.prototype.dispose = function (camera) {
  32297. camera = camera || this._camera;
  32298. if (this._textures.length > 0) {
  32299. for (var i = 0; i < this._textures.length; i++) {
  32300. this._engine._releaseTexture(this._textures.data[i]);
  32301. }
  32302. this._textures.reset();
  32303. }
  32304. if (!camera) {
  32305. return;
  32306. }
  32307. camera.detachPostProcess(this);
  32308. var index = camera._postProcesses.indexOf(this);
  32309. if (index === 0 && camera._postProcesses.length > 0) {
  32310. this._camera._postProcesses[0].markTextureDirty();
  32311. }
  32312. this.onActivateObservable.clear();
  32313. this.onAfterRenderObservable.clear();
  32314. this.onApplyObservable.clear();
  32315. this.onBeforeRenderObservable.clear();
  32316. this.onSizeChangedObservable.clear();
  32317. };
  32318. return PostProcess;
  32319. }());
  32320. BABYLON.PostProcess = PostProcess;
  32321. })(BABYLON || (BABYLON = {}));
  32322. //# sourceMappingURL=babylon.postProcess.js.map
  32323. var BABYLON;
  32324. (function (BABYLON) {
  32325. var PostProcessManager = (function () {
  32326. function PostProcessManager(scene) {
  32327. this._vertexBuffers = {};
  32328. this._scene = scene;
  32329. }
  32330. PostProcessManager.prototype._prepareBuffers = function () {
  32331. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  32332. return;
  32333. }
  32334. // VBO
  32335. var vertices = [];
  32336. vertices.push(1, 1);
  32337. vertices.push(-1, 1);
  32338. vertices.push(-1, -1);
  32339. vertices.push(1, -1);
  32340. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  32341. // Indices
  32342. var indices = [];
  32343. indices.push(0);
  32344. indices.push(1);
  32345. indices.push(2);
  32346. indices.push(0);
  32347. indices.push(2);
  32348. indices.push(3);
  32349. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  32350. };
  32351. // Methods
  32352. PostProcessManager.prototype._prepareFrame = function (sourceTexture) {
  32353. var postProcesses = this._scene.activeCamera._postProcesses;
  32354. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  32355. return false;
  32356. }
  32357. postProcesses[0].activate(this._scene.activeCamera, sourceTexture);
  32358. return true;
  32359. };
  32360. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture) {
  32361. var engine = this._scene.getEngine();
  32362. for (var index = 0; index < postProcesses.length; index++) {
  32363. if (index < postProcesses.length - 1) {
  32364. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  32365. }
  32366. else {
  32367. if (targetTexture) {
  32368. engine.bindFramebuffer(targetTexture);
  32369. }
  32370. else {
  32371. engine.restoreDefaultFramebuffer();
  32372. }
  32373. }
  32374. var pp = postProcesses[index];
  32375. var effect = pp.apply();
  32376. if (effect) {
  32377. pp.onBeforeRenderObservable.notifyObservers(effect);
  32378. // VBOs
  32379. this._prepareBuffers();
  32380. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  32381. // Draw order
  32382. engine.draw(true, 0, 6);
  32383. pp.onAfterRenderObservable.notifyObservers(effect);
  32384. }
  32385. }
  32386. // Restore depth buffer
  32387. engine.setDepthBuffer(true);
  32388. engine.setDepthWrite(true);
  32389. };
  32390. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses) {
  32391. postProcesses = postProcesses || this._scene.activeCamera._postProcesses;
  32392. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  32393. return;
  32394. }
  32395. var engine = this._scene.getEngine();
  32396. for (var index = 0, len = postProcesses.length; index < len; index++) {
  32397. if (index < len - 1) {
  32398. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  32399. }
  32400. else {
  32401. if (targetTexture) {
  32402. engine.bindFramebuffer(targetTexture, faceIndex);
  32403. }
  32404. else {
  32405. engine.restoreDefaultFramebuffer();
  32406. }
  32407. }
  32408. if (doNotPresent) {
  32409. break;
  32410. }
  32411. var pp = postProcesses[index];
  32412. var effect = pp.apply();
  32413. if (effect) {
  32414. pp.onBeforeRenderObservable.notifyObservers(effect);
  32415. // VBOs
  32416. this._prepareBuffers();
  32417. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  32418. // Draw order
  32419. engine.draw(true, 0, 6);
  32420. pp.onAfterRenderObservable.notifyObservers(effect);
  32421. }
  32422. }
  32423. // Restore depth buffer
  32424. engine.setDepthBuffer(true);
  32425. engine.setDepthWrite(true);
  32426. };
  32427. PostProcessManager.prototype.dispose = function () {
  32428. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  32429. if (buffer) {
  32430. buffer.dispose();
  32431. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  32432. }
  32433. if (this._indexBuffer) {
  32434. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  32435. this._indexBuffer = null;
  32436. }
  32437. };
  32438. return PostProcessManager;
  32439. }());
  32440. BABYLON.PostProcessManager = PostProcessManager;
  32441. })(BABYLON || (BABYLON = {}));
  32442. //# sourceMappingURL=babylon.postProcessManager.js.map
  32443. var BABYLON;
  32444. (function (BABYLON) {
  32445. var PassPostProcess = (function (_super) {
  32446. __extends(PassPostProcess, _super);
  32447. function PassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  32448. return _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable) || this;
  32449. }
  32450. return PassPostProcess;
  32451. }(BABYLON.PostProcess));
  32452. BABYLON.PassPostProcess = PassPostProcess;
  32453. })(BABYLON || (BABYLON = {}));
  32454. //# sourceMappingURL=babylon.passPostProcess.js.map
  32455. var BABYLON;
  32456. (function (BABYLON) {
  32457. /**
  32458. * This is a holder class for the physics joint created by the physics plugin.
  32459. * It holds a set of functions to control the underlying joint.
  32460. */
  32461. var PhysicsJoint = (function () {
  32462. function PhysicsJoint(type, jointData) {
  32463. this.type = type;
  32464. this.jointData = jointData;
  32465. jointData.nativeParams = jointData.nativeParams || {};
  32466. }
  32467. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  32468. get: function () {
  32469. return this._physicsJoint;
  32470. },
  32471. set: function (newJoint) {
  32472. if (this._physicsJoint) {
  32473. }
  32474. this._physicsJoint = newJoint;
  32475. },
  32476. enumerable: true,
  32477. configurable: true
  32478. });
  32479. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  32480. set: function (physicsPlugin) {
  32481. this._physicsPlugin = physicsPlugin;
  32482. },
  32483. enumerable: true,
  32484. configurable: true
  32485. });
  32486. /**
  32487. * Execute a function that is physics-plugin specific.
  32488. * @param {Function} func the function that will be executed.
  32489. * It accepts two parameters: the physics world and the physics joint.
  32490. */
  32491. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  32492. func(this._physicsPlugin.world, this._physicsJoint);
  32493. };
  32494. return PhysicsJoint;
  32495. }());
  32496. //TODO check if the native joints are the same
  32497. //Joint Types
  32498. PhysicsJoint.DistanceJoint = 0;
  32499. PhysicsJoint.HingeJoint = 1;
  32500. PhysicsJoint.BallAndSocketJoint = 2;
  32501. PhysicsJoint.WheelJoint = 3;
  32502. PhysicsJoint.SliderJoint = 4;
  32503. //OIMO
  32504. PhysicsJoint.PrismaticJoint = 5;
  32505. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  32506. PhysicsJoint.UniversalJoint = 6;
  32507. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  32508. //Cannon
  32509. //Similar to a Ball-Joint. Different in params
  32510. PhysicsJoint.PointToPointJoint = 8;
  32511. //Cannon only at the moment
  32512. PhysicsJoint.SpringJoint = 9;
  32513. PhysicsJoint.LockJoint = 10;
  32514. BABYLON.PhysicsJoint = PhysicsJoint;
  32515. /**
  32516. * A class representing a physics distance joint.
  32517. */
  32518. var DistanceJoint = (function (_super) {
  32519. __extends(DistanceJoint, _super);
  32520. function DistanceJoint(jointData) {
  32521. return _super.call(this, PhysicsJoint.DistanceJoint, jointData) || this;
  32522. }
  32523. /**
  32524. * Update the predefined distance.
  32525. */
  32526. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  32527. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  32528. };
  32529. return DistanceJoint;
  32530. }(PhysicsJoint));
  32531. BABYLON.DistanceJoint = DistanceJoint;
  32532. var MotorEnabledJoint = (function (_super) {
  32533. __extends(MotorEnabledJoint, _super);
  32534. function MotorEnabledJoint(type, jointData) {
  32535. return _super.call(this, type, jointData) || this;
  32536. }
  32537. /**
  32538. * Set the motor values.
  32539. * Attention, this function is plugin specific. Engines won't react 100% the same.
  32540. * @param {number} force the force to apply
  32541. * @param {number} maxForce max force for this motor.
  32542. */
  32543. MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
  32544. this._physicsPlugin.setMotor(this, force, maxForce);
  32545. };
  32546. /**
  32547. * Set the motor's limits.
  32548. * Attention, this function is plugin specific. Engines won't react 100% the same.
  32549. */
  32550. MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  32551. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  32552. };
  32553. return MotorEnabledJoint;
  32554. }(PhysicsJoint));
  32555. BABYLON.MotorEnabledJoint = MotorEnabledJoint;
  32556. /**
  32557. * This class represents a single hinge physics joint
  32558. */
  32559. var HingeJoint = (function (_super) {
  32560. __extends(HingeJoint, _super);
  32561. function HingeJoint(jointData) {
  32562. return _super.call(this, PhysicsJoint.HingeJoint, jointData) || this;
  32563. }
  32564. /**
  32565. * Set the motor values.
  32566. * Attention, this function is plugin specific. Engines won't react 100% the same.
  32567. * @param {number} force the force to apply
  32568. * @param {number} maxForce max force for this motor.
  32569. */
  32570. HingeJoint.prototype.setMotor = function (force, maxForce) {
  32571. this._physicsPlugin.setMotor(this, force, maxForce);
  32572. };
  32573. /**
  32574. * Set the motor's limits.
  32575. * Attention, this function is plugin specific. Engines won't react 100% the same.
  32576. */
  32577. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  32578. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  32579. };
  32580. return HingeJoint;
  32581. }(MotorEnabledJoint));
  32582. BABYLON.HingeJoint = HingeJoint;
  32583. /**
  32584. * This class represents a dual hinge physics joint (same as wheel joint)
  32585. */
  32586. var Hinge2Joint = (function (_super) {
  32587. __extends(Hinge2Joint, _super);
  32588. function Hinge2Joint(jointData) {
  32589. return _super.call(this, PhysicsJoint.Hinge2Joint, jointData) || this;
  32590. }
  32591. /**
  32592. * Set the motor values.
  32593. * Attention, this function is plugin specific. Engines won't react 100% the same.
  32594. * @param {number} force the force to apply
  32595. * @param {number} maxForce max force for this motor.
  32596. * @param {motorIndex} the motor's index, 0 or 1.
  32597. */
  32598. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  32599. if (motorIndex === void 0) { motorIndex = 0; }
  32600. this._physicsPlugin.setMotor(this, force, maxForce, motorIndex);
  32601. };
  32602. /**
  32603. * Set the motor limits.
  32604. * Attention, this function is plugin specific. Engines won't react 100% the same.
  32605. * @param {number} upperLimit the upper limit
  32606. * @param {number} lowerLimit lower limit
  32607. * @param {motorIndex} the motor's index, 0 or 1.
  32608. */
  32609. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  32610. if (motorIndex === void 0) { motorIndex = 0; }
  32611. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  32612. };
  32613. return Hinge2Joint;
  32614. }(MotorEnabledJoint));
  32615. BABYLON.Hinge2Joint = Hinge2Joint;
  32616. })(BABYLON || (BABYLON = {}));
  32617. //# sourceMappingURL=babylon.physicsJoint.js.map
  32618. var BABYLON;
  32619. (function (BABYLON) {
  32620. var PhysicsImpostor = (function () {
  32621. function PhysicsImpostor(object, type, _options, _scene) {
  32622. if (_options === void 0) { _options = { mass: 0 }; }
  32623. var _this = this;
  32624. this.object = object;
  32625. this.type = type;
  32626. this._options = _options;
  32627. this._scene = _scene;
  32628. this._bodyUpdateRequired = false;
  32629. this._onBeforePhysicsStepCallbacks = new Array();
  32630. this._onAfterPhysicsStepCallbacks = new Array();
  32631. this._onPhysicsCollideCallbacks = [];
  32632. this._deltaPosition = BABYLON.Vector3.Zero();
  32633. this._tmpPositionWithDelta = BABYLON.Vector3.Zero();
  32634. this._tmpRotationWithDelta = new BABYLON.Quaternion();
  32635. /**
  32636. * this function is executed by the physics engine.
  32637. */
  32638. this.beforeStep = function () {
  32639. _this.object.position.subtractToRef(_this._deltaPosition, _this._tmpPositionWithDelta);
  32640. //conjugate deltaRotation
  32641. if (_this._deltaRotationConjugated) {
  32642. _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this._tmpRotationWithDelta);
  32643. }
  32644. else {
  32645. _this._tmpRotationWithDelta.copyFrom(_this.object.rotationQuaternion);
  32646. }
  32647. _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, _this._tmpPositionWithDelta, _this._tmpRotationWithDelta);
  32648. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  32649. func(_this);
  32650. });
  32651. };
  32652. /**
  32653. * this function is executed by the physics engine.
  32654. */
  32655. this.afterStep = function () {
  32656. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  32657. func(_this);
  32658. });
  32659. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  32660. _this.object.position.addInPlace(_this._deltaPosition);
  32661. if (_this._deltaRotation) {
  32662. _this.object.rotationQuaternion.multiplyInPlace(_this._deltaRotation);
  32663. }
  32664. };
  32665. /**
  32666. * Legacy collision detection event support
  32667. */
  32668. this.onCollideEvent = null;
  32669. //event and body object due to cannon's event-based architecture.
  32670. this.onCollide = function (e) {
  32671. if (!_this._onPhysicsCollideCallbacks.length && !_this.onCollideEvent)
  32672. return;
  32673. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  32674. if (otherImpostor) {
  32675. // Legacy collision detection event support
  32676. if (_this.onCollideEvent) {
  32677. _this.onCollideEvent(_this, otherImpostor);
  32678. }
  32679. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  32680. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  32681. }).forEach(function (obj) {
  32682. obj.callback(_this, otherImpostor);
  32683. });
  32684. }
  32685. };
  32686. //sanity check!
  32687. if (!this.object) {
  32688. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  32689. return;
  32690. }
  32691. //legacy support for old syntax.
  32692. if (!this._scene && object.getScene) {
  32693. this._scene = object.getScene();
  32694. }
  32695. this._physicsEngine = this._scene.getPhysicsEngine();
  32696. if (!this._physicsEngine) {
  32697. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  32698. }
  32699. else {
  32700. //set the object's quaternion, if not set
  32701. if (!this.object.rotationQuaternion) {
  32702. if (this.object.rotation) {
  32703. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  32704. }
  32705. else {
  32706. this.object.rotationQuaternion = new BABYLON.Quaternion();
  32707. }
  32708. }
  32709. //default options params
  32710. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  32711. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  32712. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  32713. this._joints = [];
  32714. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  32715. if (!this.object.parent) {
  32716. this._init();
  32717. }
  32718. }
  32719. }
  32720. /**
  32721. * This function will completly initialize this impostor.
  32722. * It will create a new body - but only if this mesh has no parent.
  32723. * If it has, this impostor will not be used other than to define the impostor
  32724. * of the child mesh.
  32725. */
  32726. PhysicsImpostor.prototype._init = function () {
  32727. this._physicsEngine.removeImpostor(this);
  32728. this.physicsBody = null;
  32729. this._parent = this._parent || this._getPhysicsParent();
  32730. if (!this.parent) {
  32731. this._physicsEngine.addImpostor(this);
  32732. }
  32733. };
  32734. PhysicsImpostor.prototype._getPhysicsParent = function () {
  32735. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  32736. var parentMesh = this.object.parent;
  32737. return parentMesh.physicsImpostor;
  32738. }
  32739. return;
  32740. };
  32741. /**
  32742. * Should a new body be generated.
  32743. */
  32744. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  32745. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  32746. };
  32747. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  32748. this.forceUpdate();
  32749. };
  32750. /**
  32751. * Force a regeneration of this or the parent's impostor's body.
  32752. * Use under cautious - This will remove all joints already implemented.
  32753. */
  32754. PhysicsImpostor.prototype.forceUpdate = function () {
  32755. this._init();
  32756. if (this.parent) {
  32757. this.parent.forceUpdate();
  32758. }
  32759. };
  32760. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  32761. /*public get mesh(): AbstractMesh {
  32762. return this._mesh;
  32763. }*/
  32764. /**
  32765. * Gets the body that holds this impostor. Either its own, or its parent.
  32766. */
  32767. get: function () {
  32768. return this._parent ? this._parent.physicsBody : this._physicsBody;
  32769. },
  32770. /**
  32771. * Set the physics body. Used mainly by the physics engine/plugin
  32772. */
  32773. set: function (physicsBody) {
  32774. if (this._physicsBody) {
  32775. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  32776. }
  32777. this._physicsBody = physicsBody;
  32778. this.resetUpdateFlags();
  32779. },
  32780. enumerable: true,
  32781. configurable: true
  32782. });
  32783. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  32784. get: function () {
  32785. return this._parent;
  32786. },
  32787. set: function (value) {
  32788. this._parent = value;
  32789. },
  32790. enumerable: true,
  32791. configurable: true
  32792. });
  32793. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  32794. this._bodyUpdateRequired = false;
  32795. };
  32796. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  32797. if (this.object.getBoundingInfo) {
  32798. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  32799. return this.object.getBoundingInfo().boundingBox.extendSize.scale(2).multiply(this.object.scaling);
  32800. }
  32801. else {
  32802. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  32803. }
  32804. };
  32805. PhysicsImpostor.prototype.getObjectCenter = function () {
  32806. if (this.object.getBoundingInfo) {
  32807. return this.object.getBoundingInfo().boundingBox.center;
  32808. }
  32809. else {
  32810. return this.object.position;
  32811. }
  32812. };
  32813. /**
  32814. * Get a specific parametes from the options parameter.
  32815. */
  32816. PhysicsImpostor.prototype.getParam = function (paramName) {
  32817. return this._options[paramName];
  32818. };
  32819. /**
  32820. * Sets a specific parameter in the options given to the physics plugin
  32821. */
  32822. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  32823. this._options[paramName] = value;
  32824. this._bodyUpdateRequired = true;
  32825. };
  32826. /**
  32827. * Specifically change the body's mass option. Won't recreate the physics body object
  32828. */
  32829. PhysicsImpostor.prototype.setMass = function (mass) {
  32830. if (this.getParam("mass") !== mass) {
  32831. this.setParam("mass", mass);
  32832. }
  32833. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  32834. };
  32835. PhysicsImpostor.prototype.getLinearVelocity = function () {
  32836. return this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this);
  32837. };
  32838. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  32839. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  32840. };
  32841. PhysicsImpostor.prototype.getAngularVelocity = function () {
  32842. return this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this);
  32843. };
  32844. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  32845. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  32846. };
  32847. /**
  32848. * Execute a function with the physics plugin native code.
  32849. * Provide a function the will have two variables - the world object and the physics body object.
  32850. */
  32851. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  32852. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  32853. };
  32854. /**
  32855. * Register a function that will be executed before the physics world is stepping forward.
  32856. */
  32857. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  32858. this._onBeforePhysicsStepCallbacks.push(func);
  32859. };
  32860. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  32861. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  32862. if (index > -1) {
  32863. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  32864. }
  32865. else {
  32866. BABYLON.Tools.Warn("Function to remove was not found");
  32867. }
  32868. };
  32869. /**
  32870. * Register a function that will be executed after the physics step
  32871. */
  32872. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  32873. this._onAfterPhysicsStepCallbacks.push(func);
  32874. };
  32875. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  32876. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  32877. if (index > -1) {
  32878. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  32879. }
  32880. else {
  32881. BABYLON.Tools.Warn("Function to remove was not found");
  32882. }
  32883. };
  32884. /**
  32885. * register a function that will be executed when this impostor collides against a different body.
  32886. */
  32887. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  32888. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  32889. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  32890. };
  32891. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  32892. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  32893. var index = this._onPhysicsCollideCallbacks.indexOf({ callback: func, otherImpostors: collidedAgainstList });
  32894. if (index > -1) {
  32895. this._onPhysicsCollideCallbacks.splice(index, 1);
  32896. }
  32897. else {
  32898. BABYLON.Tools.Warn("Function to remove was not found");
  32899. }
  32900. };
  32901. /**
  32902. * Apply a force
  32903. */
  32904. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  32905. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  32906. };
  32907. /**
  32908. * Apply an impulse
  32909. */
  32910. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  32911. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  32912. };
  32913. /**
  32914. * A help function to create a joint.
  32915. */
  32916. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  32917. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  32918. this.addJoint(otherImpostor, joint);
  32919. };
  32920. /**
  32921. * Add a joint to this impostor with a different impostor.
  32922. */
  32923. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  32924. this._joints.push({
  32925. otherImpostor: otherImpostor,
  32926. joint: joint
  32927. });
  32928. this._physicsEngine.addJoint(this, otherImpostor, joint);
  32929. };
  32930. /**
  32931. * Will keep this body still, in a sleep mode.
  32932. */
  32933. PhysicsImpostor.prototype.sleep = function () {
  32934. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  32935. };
  32936. /**
  32937. * Wake the body up.
  32938. */
  32939. PhysicsImpostor.prototype.wakeUp = function () {
  32940. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  32941. };
  32942. PhysicsImpostor.prototype.clone = function (newObject) {
  32943. if (!newObject)
  32944. return null;
  32945. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  32946. };
  32947. PhysicsImpostor.prototype.dispose = function () {
  32948. var _this = this;
  32949. //no dispose if no physics engine is available.
  32950. if (!this._physicsEngine) {
  32951. return;
  32952. }
  32953. this._joints.forEach(function (j) {
  32954. _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
  32955. });
  32956. //dispose the physics body
  32957. this._physicsEngine.removeImpostor(this);
  32958. if (this.parent) {
  32959. this.parent.forceUpdate();
  32960. }
  32961. else {
  32962. }
  32963. };
  32964. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  32965. this._deltaPosition.copyFrom(position);
  32966. };
  32967. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  32968. if (!this._deltaRotation) {
  32969. this._deltaRotation = new BABYLON.Quaternion();
  32970. }
  32971. this._deltaRotation.copyFrom(rotation);
  32972. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  32973. };
  32974. return PhysicsImpostor;
  32975. }());
  32976. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  32977. //Impostor types
  32978. PhysicsImpostor.NoImpostor = 0;
  32979. PhysicsImpostor.SphereImpostor = 1;
  32980. PhysicsImpostor.BoxImpostor = 2;
  32981. PhysicsImpostor.PlaneImpostor = 3;
  32982. PhysicsImpostor.MeshImpostor = 4;
  32983. PhysicsImpostor.CylinderImpostor = 7;
  32984. PhysicsImpostor.ParticleImpostor = 8;
  32985. PhysicsImpostor.HeightmapImpostor = 9;
  32986. BABYLON.PhysicsImpostor = PhysicsImpostor;
  32987. })(BABYLON || (BABYLON = {}));
  32988. //# sourceMappingURL=babylon.physicsImpostor.js.map
  32989. var BABYLON;
  32990. (function (BABYLON) {
  32991. var PhysicsEngine = (function () {
  32992. function PhysicsEngine(gravity, _physicsPlugin) {
  32993. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  32994. this._physicsPlugin = _physicsPlugin;
  32995. //new methods and parameters
  32996. this._impostors = [];
  32997. this._joints = [];
  32998. if (!this._physicsPlugin.isSupported()) {
  32999. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  33000. + "Please make sure it is included.");
  33001. }
  33002. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  33003. this.setGravity(gravity);
  33004. this.setTimeStep();
  33005. }
  33006. PhysicsEngine.prototype.setGravity = function (gravity) {
  33007. this.gravity = gravity;
  33008. this._physicsPlugin.setGravity(this.gravity);
  33009. };
  33010. /**
  33011. * Set the time step of the physics engine.
  33012. * default is 1/60.
  33013. * To slow it down, enter 1/600 for example.
  33014. * To speed it up, 1/30
  33015. * @param {number} newTimeStep the new timestep to apply to this world.
  33016. */
  33017. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  33018. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  33019. this._physicsPlugin.setTimeStep(newTimeStep);
  33020. };
  33021. PhysicsEngine.prototype.dispose = function () {
  33022. this._impostors.forEach(function (impostor) {
  33023. impostor.dispose();
  33024. });
  33025. this._physicsPlugin.dispose();
  33026. };
  33027. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  33028. return this._physicsPlugin.name;
  33029. };
  33030. /**
  33031. * Adding a new impostor for the impostor tracking.
  33032. * This will be done by the impostor itself.
  33033. * @param {PhysicsImpostor} impostor the impostor to add
  33034. */
  33035. PhysicsEngine.prototype.addImpostor = function (impostor) {
  33036. impostor.uniqueId = this._impostors.push(impostor);
  33037. //if no parent, generate the body
  33038. if (!impostor.parent) {
  33039. this._physicsPlugin.generatePhysicsBody(impostor);
  33040. }
  33041. };
  33042. /**
  33043. * Remove an impostor from the engine.
  33044. * This impostor and its mesh will not longer be updated by the physics engine.
  33045. * @param {PhysicsImpostor} impostor the impostor to remove
  33046. */
  33047. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  33048. var index = this._impostors.indexOf(impostor);
  33049. if (index > -1) {
  33050. var removed = this._impostors.splice(index, 1);
  33051. //Is it needed?
  33052. if (removed.length) {
  33053. //this will also remove it from the world.
  33054. removed[0].physicsBody = null;
  33055. }
  33056. }
  33057. };
  33058. /**
  33059. * Add a joint to the physics engine
  33060. * @param {PhysicsImpostor} mainImpostor the main impostor to which the joint is added.
  33061. * @param {PhysicsImpostor} connectedImpostor the impostor that is connected to the main impostor using this joint
  33062. * @param {PhysicsJoint} the joint that will connect both impostors.
  33063. */
  33064. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  33065. var impostorJoint = {
  33066. mainImpostor: mainImpostor,
  33067. connectedImpostor: connectedImpostor,
  33068. joint: joint
  33069. };
  33070. joint.physicsPlugin = this._physicsPlugin;
  33071. this._joints.push(impostorJoint);
  33072. this._physicsPlugin.generateJoint(impostorJoint);
  33073. };
  33074. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  33075. var matchingJoints = this._joints.filter(function (impostorJoint) {
  33076. return (impostorJoint.connectedImpostor === connectedImpostor
  33077. && impostorJoint.joint === joint
  33078. && impostorJoint.mainImpostor === mainImpostor);
  33079. });
  33080. if (matchingJoints.length) {
  33081. this._physicsPlugin.removeJoint(matchingJoints[0]);
  33082. }
  33083. };
  33084. /**
  33085. * Called by the scene. no need to call it.
  33086. */
  33087. PhysicsEngine.prototype._step = function (delta) {
  33088. var _this = this;
  33089. //check if any mesh has no body / requires an update
  33090. this._impostors.forEach(function (impostor) {
  33091. if (impostor.isBodyInitRequired()) {
  33092. _this._physicsPlugin.generatePhysicsBody(impostor);
  33093. }
  33094. });
  33095. if (delta > 0.1) {
  33096. delta = 0.1;
  33097. }
  33098. else if (delta <= 0) {
  33099. delta = 1.0 / 60.0;
  33100. }
  33101. this._physicsPlugin.executeStep(delta, this._impostors);
  33102. };
  33103. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  33104. return this._physicsPlugin;
  33105. };
  33106. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  33107. for (var i = 0; i < this._impostors.length; ++i) {
  33108. if (this._impostors[i].object === object) {
  33109. return this._impostors[i];
  33110. }
  33111. }
  33112. };
  33113. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  33114. for (var i = 0; i < this._impostors.length; ++i) {
  33115. if (this._impostors[i].physicsBody === body) {
  33116. return this._impostors[i];
  33117. }
  33118. }
  33119. };
  33120. return PhysicsEngine;
  33121. }());
  33122. // Statics, Legacy support.
  33123. /**
  33124. * @Deprecated
  33125. *
  33126. */
  33127. PhysicsEngine.NoImpostor = BABYLON.PhysicsImpostor.NoImpostor;
  33128. PhysicsEngine.SphereImpostor = BABYLON.PhysicsImpostor.SphereImpostor;
  33129. PhysicsEngine.BoxImpostor = BABYLON.PhysicsImpostor.BoxImpostor;
  33130. PhysicsEngine.PlaneImpostor = BABYLON.PhysicsImpostor.PlaneImpostor;
  33131. PhysicsEngine.MeshImpostor = BABYLON.PhysicsImpostor.MeshImpostor;
  33132. PhysicsEngine.CylinderImpostor = BABYLON.PhysicsImpostor.CylinderImpostor;
  33133. PhysicsEngine.HeightmapImpostor = BABYLON.PhysicsImpostor.HeightmapImpostor;
  33134. PhysicsEngine.CapsuleImpostor = -1;
  33135. PhysicsEngine.ConeImpostor = -1;
  33136. PhysicsEngine.ConvexHullImpostor = -1;
  33137. PhysicsEngine.Epsilon = 0.001;
  33138. BABYLON.PhysicsEngine = PhysicsEngine;
  33139. })(BABYLON || (BABYLON = {}));
  33140. //# sourceMappingURL=babylon.physicsEngine.js.map
  33141. var BABYLON;
  33142. (function (BABYLON) {
  33143. var VertexData = (function () {
  33144. function VertexData() {
  33145. }
  33146. VertexData.prototype.set = function (data, kind) {
  33147. switch (kind) {
  33148. case BABYLON.VertexBuffer.PositionKind:
  33149. this.positions = data;
  33150. break;
  33151. case BABYLON.VertexBuffer.NormalKind:
  33152. this.normals = data;
  33153. break;
  33154. case BABYLON.VertexBuffer.UVKind:
  33155. this.uvs = data;
  33156. break;
  33157. case BABYLON.VertexBuffer.UV2Kind:
  33158. this.uvs2 = data;
  33159. break;
  33160. case BABYLON.VertexBuffer.UV3Kind:
  33161. this.uvs3 = data;
  33162. break;
  33163. case BABYLON.VertexBuffer.UV4Kind:
  33164. this.uvs4 = data;
  33165. break;
  33166. case BABYLON.VertexBuffer.UV5Kind:
  33167. this.uvs5 = data;
  33168. break;
  33169. case BABYLON.VertexBuffer.UV6Kind:
  33170. this.uvs6 = data;
  33171. break;
  33172. case BABYLON.VertexBuffer.ColorKind:
  33173. this.colors = data;
  33174. break;
  33175. case BABYLON.VertexBuffer.MatricesIndicesKind:
  33176. this.matricesIndices = data;
  33177. break;
  33178. case BABYLON.VertexBuffer.MatricesWeightsKind:
  33179. this.matricesWeights = data;
  33180. break;
  33181. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  33182. this.matricesIndicesExtra = data;
  33183. break;
  33184. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  33185. this.matricesWeightsExtra = data;
  33186. break;
  33187. }
  33188. };
  33189. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  33190. this._applyTo(mesh, updatable);
  33191. };
  33192. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  33193. this._applyTo(geometry, updatable);
  33194. };
  33195. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  33196. this._update(mesh);
  33197. };
  33198. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  33199. this._update(geometry);
  33200. };
  33201. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  33202. if (this.positions) {
  33203. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  33204. }
  33205. if (this.normals) {
  33206. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  33207. }
  33208. if (this.uvs) {
  33209. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  33210. }
  33211. if (this.uvs2) {
  33212. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  33213. }
  33214. if (this.uvs3) {
  33215. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  33216. }
  33217. if (this.uvs4) {
  33218. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  33219. }
  33220. if (this.uvs5) {
  33221. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  33222. }
  33223. if (this.uvs6) {
  33224. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  33225. }
  33226. if (this.colors) {
  33227. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  33228. }
  33229. if (this.matricesIndices) {
  33230. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  33231. }
  33232. if (this.matricesWeights) {
  33233. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  33234. }
  33235. if (this.matricesIndicesExtra) {
  33236. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  33237. }
  33238. if (this.matricesWeightsExtra) {
  33239. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  33240. }
  33241. if (this.indices) {
  33242. meshOrGeometry.setIndices(this.indices);
  33243. }
  33244. };
  33245. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  33246. if (this.positions) {
  33247. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  33248. }
  33249. if (this.normals) {
  33250. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  33251. }
  33252. if (this.uvs) {
  33253. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  33254. }
  33255. if (this.uvs2) {
  33256. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  33257. }
  33258. if (this.uvs3) {
  33259. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  33260. }
  33261. if (this.uvs4) {
  33262. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  33263. }
  33264. if (this.uvs5) {
  33265. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  33266. }
  33267. if (this.uvs6) {
  33268. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  33269. }
  33270. if (this.colors) {
  33271. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  33272. }
  33273. if (this.matricesIndices) {
  33274. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  33275. }
  33276. if (this.matricesWeights) {
  33277. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  33278. }
  33279. if (this.matricesIndicesExtra) {
  33280. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  33281. }
  33282. if (this.matricesWeightsExtra) {
  33283. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  33284. }
  33285. if (this.indices) {
  33286. meshOrGeometry.setIndices(this.indices);
  33287. }
  33288. };
  33289. VertexData.prototype.transform = function (matrix) {
  33290. var transformed = BABYLON.Vector3.Zero();
  33291. var index;
  33292. if (this.positions) {
  33293. var position = BABYLON.Vector3.Zero();
  33294. for (index = 0; index < this.positions.length; index += 3) {
  33295. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  33296. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  33297. this.positions[index] = transformed.x;
  33298. this.positions[index + 1] = transformed.y;
  33299. this.positions[index + 2] = transformed.z;
  33300. }
  33301. }
  33302. if (this.normals) {
  33303. var normal = BABYLON.Vector3.Zero();
  33304. for (index = 0; index < this.normals.length; index += 3) {
  33305. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  33306. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  33307. this.normals[index] = transformed.x;
  33308. this.normals[index + 1] = transformed.y;
  33309. this.normals[index + 2] = transformed.z;
  33310. }
  33311. }
  33312. };
  33313. VertexData.prototype.merge = function (other) {
  33314. if (other.indices) {
  33315. if (!this.indices) {
  33316. this.indices = [];
  33317. }
  33318. var offset = this.positions ? this.positions.length / 3 : 0;
  33319. for (var index = 0; index < other.indices.length; index++) {
  33320. //TODO check type - if Int32Array!
  33321. this.indices.push(other.indices[index] + offset);
  33322. }
  33323. }
  33324. this.positions = this._mergeElement(this.positions, other.positions);
  33325. this.normals = this._mergeElement(this.normals, other.normals);
  33326. this.uvs = this._mergeElement(this.uvs, other.uvs);
  33327. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);
  33328. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);
  33329. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);
  33330. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);
  33331. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);
  33332. this.colors = this._mergeElement(this.colors, other.colors);
  33333. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);
  33334. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);
  33335. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);
  33336. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);
  33337. };
  33338. VertexData.prototype._mergeElement = function (source, other) {
  33339. if (!other)
  33340. return source;
  33341. if (!source)
  33342. return other;
  33343. var len = other.length + source.length;
  33344. var isSrcTypedArray = source instanceof Float32Array;
  33345. var isOthTypedArray = other instanceof Float32Array;
  33346. // use non-loop method when the source is Float32Array
  33347. if (isSrcTypedArray) {
  33348. var ret32 = new Float32Array(len);
  33349. ret32.set(source);
  33350. ret32.set(other, source.length);
  33351. return ret32;
  33352. }
  33353. else if (!isOthTypedArray) {
  33354. return source.concat(other);
  33355. }
  33356. else {
  33357. var ret = source.slice(0); // copy source to a separate array
  33358. for (var i = 0, len = other.length; i < len; i++) {
  33359. ret.push(other[i]);
  33360. }
  33361. return ret;
  33362. }
  33363. };
  33364. VertexData.prototype.serialize = function () {
  33365. var serializationObject = this.serialize();
  33366. if (this.positions) {
  33367. serializationObject.positions = this.positions;
  33368. }
  33369. if (this.normals) {
  33370. serializationObject.normals = this.normals;
  33371. }
  33372. if (this.uvs) {
  33373. serializationObject.uvs = this.uvs;
  33374. }
  33375. if (this.uvs2) {
  33376. serializationObject.uvs2 = this.uvs2;
  33377. }
  33378. if (this.uvs3) {
  33379. serializationObject.uvs3 = this.uvs3;
  33380. }
  33381. if (this.uvs4) {
  33382. serializationObject.uvs4 = this.uvs4;
  33383. }
  33384. if (this.uvs5) {
  33385. serializationObject.uvs5 = this.uvs5;
  33386. }
  33387. if (this.uvs6) {
  33388. serializationObject.uvs6 = this.uvs6;
  33389. }
  33390. if (this.colors) {
  33391. serializationObject.colors = this.colors;
  33392. }
  33393. if (this.matricesIndices) {
  33394. serializationObject.matricesIndices = this.matricesIndices;
  33395. serializationObject.matricesIndices._isExpanded = true;
  33396. }
  33397. if (this.matricesWeights) {
  33398. serializationObject.matricesWeights = this.matricesWeights;
  33399. }
  33400. if (this.matricesIndicesExtra) {
  33401. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  33402. serializationObject.matricesIndicesExtra._isExpanded = true;
  33403. }
  33404. if (this.matricesWeightsExtra) {
  33405. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  33406. }
  33407. serializationObject.indices = this.indices;
  33408. return serializationObject;
  33409. };
  33410. // Statics
  33411. VertexData.ExtractFromMesh = function (mesh, copyWhenShared) {
  33412. return VertexData._ExtractFrom(mesh, copyWhenShared);
  33413. };
  33414. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared) {
  33415. return VertexData._ExtractFrom(geometry, copyWhenShared);
  33416. };
  33417. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared) {
  33418. var result = new VertexData();
  33419. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  33420. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared);
  33421. }
  33422. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  33423. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared);
  33424. }
  33425. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  33426. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared);
  33427. }
  33428. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  33429. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared);
  33430. }
  33431. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  33432. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared);
  33433. }
  33434. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  33435. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared);
  33436. }
  33437. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  33438. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared);
  33439. }
  33440. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  33441. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared);
  33442. }
  33443. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  33444. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared);
  33445. }
  33446. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  33447. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared);
  33448. }
  33449. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  33450. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared);
  33451. }
  33452. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  33453. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared);
  33454. }
  33455. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  33456. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared);
  33457. }
  33458. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  33459. return result;
  33460. };
  33461. VertexData.CreateRibbon = function (options) {
  33462. var pathArray = options.pathArray;
  33463. var closeArray = options.closeArray || false;
  33464. var closePath = options.closePath || false;
  33465. var invertUV = options.invertUV || false;
  33466. var defaultOffset = Math.floor(pathArray[0].length / 2);
  33467. var offset = options.offset || defaultOffset;
  33468. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  33469. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33470. var positions = [];
  33471. var indices = [];
  33472. var normals = [];
  33473. var uvs = [];
  33474. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  33475. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  33476. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  33477. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  33478. var minlg; // minimal length among all paths from pathArray
  33479. var lg = []; // array of path lengths : nb of vertex per path
  33480. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  33481. var p; // path iterator
  33482. var i; // point iterator
  33483. var j; // point iterator
  33484. // if single path in pathArray
  33485. if (pathArray.length < 2) {
  33486. var ar1 = [];
  33487. var ar2 = [];
  33488. for (i = 0; i < pathArray[0].length - offset; i++) {
  33489. ar1.push(pathArray[0][i]);
  33490. ar2.push(pathArray[0][i + offset]);
  33491. }
  33492. pathArray = [ar1, ar2];
  33493. }
  33494. // positions and horizontal distances (u)
  33495. var idc = 0;
  33496. var closePathCorr = (closePath) ? 1 : 0;
  33497. var path;
  33498. var l;
  33499. minlg = pathArray[0].length;
  33500. var vectlg;
  33501. var dist;
  33502. for (p = 0; p < pathArray.length; p++) {
  33503. uTotalDistance[p] = 0;
  33504. us[p] = [0];
  33505. path = pathArray[p];
  33506. l = path.length;
  33507. minlg = (minlg < l) ? minlg : l;
  33508. j = 0;
  33509. while (j < l) {
  33510. positions.push(path[j].x, path[j].y, path[j].z);
  33511. if (j > 0) {
  33512. vectlg = path[j].subtract(path[j - 1]).length();
  33513. dist = vectlg + uTotalDistance[p];
  33514. us[p].push(dist);
  33515. uTotalDistance[p] = dist;
  33516. }
  33517. j++;
  33518. }
  33519. if (closePath) {
  33520. j--;
  33521. positions.push(path[0].x, path[0].y, path[0].z);
  33522. vectlg = path[j].subtract(path[0]).length();
  33523. dist = vectlg + uTotalDistance[p];
  33524. us[p].push(dist);
  33525. uTotalDistance[p] = dist;
  33526. }
  33527. lg[p] = l + closePathCorr;
  33528. idx[p] = idc;
  33529. idc += (l + closePathCorr);
  33530. }
  33531. // vertical distances (v)
  33532. var path1;
  33533. var path2;
  33534. var vertex1;
  33535. var vertex2;
  33536. for (i = 0; i < minlg + closePathCorr; i++) {
  33537. vTotalDistance[i] = 0;
  33538. vs[i] = [0];
  33539. for (p = 0; p < pathArray.length - 1; p++) {
  33540. path1 = pathArray[p];
  33541. path2 = pathArray[p + 1];
  33542. if (i === minlg) {
  33543. vertex1 = path1[0];
  33544. vertex2 = path2[0];
  33545. }
  33546. else {
  33547. vertex1 = path1[i];
  33548. vertex2 = path2[i];
  33549. }
  33550. vectlg = vertex2.subtract(vertex1).length();
  33551. dist = vectlg + vTotalDistance[i];
  33552. vs[i].push(dist);
  33553. vTotalDistance[i] = dist;
  33554. }
  33555. if (closeArray) {
  33556. path1 = pathArray[p];
  33557. path2 = pathArray[0];
  33558. if (i === minlg) {
  33559. vertex2 = path2[0];
  33560. }
  33561. vectlg = vertex2.subtract(vertex1).length();
  33562. dist = vectlg + vTotalDistance[i];
  33563. vTotalDistance[i] = dist;
  33564. }
  33565. }
  33566. // uvs
  33567. var u;
  33568. var v;
  33569. for (p = 0; p < pathArray.length; p++) {
  33570. for (i = 0; i < minlg + closePathCorr; i++) {
  33571. u = (uTotalDistance[p] != 0.0) ? us[p][i] / uTotalDistance[p] : 0.0;
  33572. v = (vTotalDistance[i] != 0.0) ? vs[i][p] / vTotalDistance[i] : 0.0;
  33573. if (invertUV) {
  33574. uvs.push(v, u);
  33575. }
  33576. else {
  33577. uvs.push(u, v);
  33578. }
  33579. }
  33580. }
  33581. // indices
  33582. p = 0; // path index
  33583. var pi = 0; // positions array index
  33584. var l1 = lg[p] - 1; // path1 length
  33585. var l2 = lg[p + 1] - 1; // path2 length
  33586. var min = (l1 < l2) ? l1 : l2; // current path stop index
  33587. var shft = idx[1] - idx[0]; // shift
  33588. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  33589. while (pi <= min && p < path1nb) {
  33590. // 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
  33591. indices.push(pi, pi + shft, pi + 1);
  33592. indices.push(pi + shft + 1, pi + 1, pi + shft);
  33593. pi += 1;
  33594. if (pi === min) {
  33595. p++;
  33596. if (p === lg.length - 1) {
  33597. shft = idx[0] - idx[p];
  33598. l1 = lg[p] - 1;
  33599. l2 = lg[0] - 1;
  33600. }
  33601. else {
  33602. shft = idx[p + 1] - idx[p];
  33603. l1 = lg[p] - 1;
  33604. l2 = lg[p + 1] - 1;
  33605. }
  33606. pi = idx[p];
  33607. min = (l1 < l2) ? l1 + pi : l2 + pi;
  33608. }
  33609. }
  33610. // normals
  33611. VertexData.ComputeNormals(positions, indices, normals);
  33612. if (closePath) {
  33613. var indexFirst = 0;
  33614. var indexLast = 0;
  33615. for (p = 0; p < pathArray.length; p++) {
  33616. indexFirst = idx[p] * 3;
  33617. if (p + 1 < pathArray.length) {
  33618. indexLast = (idx[p + 1] - 1) * 3;
  33619. }
  33620. else {
  33621. indexLast = normals.length - 3;
  33622. }
  33623. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  33624. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  33625. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  33626. normals[indexLast] = normals[indexFirst];
  33627. normals[indexLast + 1] = normals[indexFirst + 1];
  33628. normals[indexLast + 2] = normals[indexFirst + 2];
  33629. }
  33630. }
  33631. // sides
  33632. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  33633. // Result
  33634. var vertexData = new VertexData();
  33635. vertexData.indices = indices;
  33636. vertexData.positions = positions;
  33637. vertexData.normals = normals;
  33638. vertexData.uvs = uvs;
  33639. if (closePath) {
  33640. vertexData._idx = idx;
  33641. }
  33642. return vertexData;
  33643. };
  33644. VertexData.CreateBox = function (options) {
  33645. var normalsSource = [
  33646. new BABYLON.Vector3(0, 0, 1),
  33647. new BABYLON.Vector3(0, 0, -1),
  33648. new BABYLON.Vector3(1, 0, 0),
  33649. new BABYLON.Vector3(-1, 0, 0),
  33650. new BABYLON.Vector3(0, 1, 0),
  33651. new BABYLON.Vector3(0, -1, 0)
  33652. ];
  33653. var indices = [];
  33654. var positions = [];
  33655. var normals = [];
  33656. var uvs = [];
  33657. var width = options.width || options.size || 1;
  33658. var height = options.height || options.size || 1;
  33659. var depth = options.depth || options.size || 1;
  33660. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33661. var faceUV = options.faceUV || new Array(6);
  33662. var faceColors = options.faceColors;
  33663. var colors = [];
  33664. // default face colors and UV if undefined
  33665. for (var f = 0; f < 6; f++) {
  33666. if (faceUV[f] === undefined) {
  33667. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  33668. }
  33669. if (faceColors && faceColors[f] === undefined) {
  33670. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  33671. }
  33672. }
  33673. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  33674. // Create each face in turn.
  33675. for (var index = 0; index < normalsSource.length; index++) {
  33676. var normal = normalsSource[index];
  33677. // Get two vectors perpendicular to the face normal and to each other.
  33678. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  33679. var side2 = BABYLON.Vector3.Cross(normal, side1);
  33680. // Six indices (two triangles) per face.
  33681. var verticesLength = positions.length / 3;
  33682. indices.push(verticesLength);
  33683. indices.push(verticesLength + 1);
  33684. indices.push(verticesLength + 2);
  33685. indices.push(verticesLength);
  33686. indices.push(verticesLength + 2);
  33687. indices.push(verticesLength + 3);
  33688. // Four vertices per face.
  33689. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  33690. positions.push(vertex.x, vertex.y, vertex.z);
  33691. normals.push(normal.x, normal.y, normal.z);
  33692. uvs.push(faceUV[index].z, faceUV[index].w);
  33693. if (faceColors) {
  33694. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  33695. }
  33696. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  33697. positions.push(vertex.x, vertex.y, vertex.z);
  33698. normals.push(normal.x, normal.y, normal.z);
  33699. uvs.push(faceUV[index].x, faceUV[index].w);
  33700. if (faceColors) {
  33701. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  33702. }
  33703. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  33704. positions.push(vertex.x, vertex.y, vertex.z);
  33705. normals.push(normal.x, normal.y, normal.z);
  33706. uvs.push(faceUV[index].x, faceUV[index].y);
  33707. if (faceColors) {
  33708. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  33709. }
  33710. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  33711. positions.push(vertex.x, vertex.y, vertex.z);
  33712. normals.push(normal.x, normal.y, normal.z);
  33713. uvs.push(faceUV[index].z, faceUV[index].y);
  33714. if (faceColors) {
  33715. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  33716. }
  33717. }
  33718. // sides
  33719. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  33720. // Result
  33721. var vertexData = new VertexData();
  33722. vertexData.indices = indices;
  33723. vertexData.positions = positions;
  33724. vertexData.normals = normals;
  33725. vertexData.uvs = uvs;
  33726. if (faceColors) {
  33727. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  33728. vertexData.colors = totalColors;
  33729. }
  33730. return vertexData;
  33731. };
  33732. VertexData.CreateSphere = function (options) {
  33733. var segments = options.segments || 32;
  33734. var diameterX = options.diameterX || options.diameter || 1;
  33735. var diameterY = options.diameterY || options.diameter || 1;
  33736. var diameterZ = options.diameterZ || options.diameter || 1;
  33737. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  33738. var slice = (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  33739. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33740. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  33741. var totalZRotationSteps = 2 + segments;
  33742. var totalYRotationSteps = 2 * totalZRotationSteps;
  33743. var indices = [];
  33744. var positions = [];
  33745. var normals = [];
  33746. var uvs = [];
  33747. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  33748. var normalizedZ = zRotationStep / totalZRotationSteps;
  33749. var angleZ = normalizedZ * Math.PI * slice;
  33750. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  33751. var normalizedY = yRotationStep / totalYRotationSteps;
  33752. var angleY = normalizedY * Math.PI * 2 * arc;
  33753. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  33754. var rotationY = BABYLON.Matrix.RotationY(angleY);
  33755. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  33756. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  33757. var vertex = complete.multiply(radius);
  33758. var normal = complete.divide(radius).normalize();
  33759. positions.push(vertex.x, vertex.y, vertex.z);
  33760. normals.push(normal.x, normal.y, normal.z);
  33761. uvs.push(normalizedY, normalizedZ);
  33762. }
  33763. if (zRotationStep > 0) {
  33764. var verticesCount = positions.length / 3;
  33765. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  33766. indices.push((firstIndex));
  33767. indices.push((firstIndex + 1));
  33768. indices.push(firstIndex + totalYRotationSteps + 1);
  33769. indices.push((firstIndex + totalYRotationSteps + 1));
  33770. indices.push((firstIndex + 1));
  33771. indices.push((firstIndex + totalYRotationSteps + 2));
  33772. }
  33773. }
  33774. }
  33775. // Sides
  33776. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  33777. // Result
  33778. var vertexData = new VertexData();
  33779. vertexData.indices = indices;
  33780. vertexData.positions = positions;
  33781. vertexData.normals = normals;
  33782. vertexData.uvs = uvs;
  33783. return vertexData;
  33784. };
  33785. // Cylinder and cone
  33786. VertexData.CreateCylinder = function (options) {
  33787. var height = options.height || 2;
  33788. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  33789. var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;
  33790. var tessellation = options.tessellation || 24;
  33791. var subdivisions = options.subdivisions || 1;
  33792. var hasRings = options.hasRings;
  33793. var enclose = options.enclose;
  33794. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  33795. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33796. var faceUV = options.faceUV || new Array(3);
  33797. var faceColors = options.faceColors;
  33798. // default face colors and UV if undefined
  33799. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  33800. var ringNb = (hasRings) ? subdivisions : 1;
  33801. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  33802. var f;
  33803. for (f = 0; f < surfaceNb; f++) {
  33804. if (faceColors && faceColors[f] === undefined) {
  33805. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  33806. }
  33807. }
  33808. for (f = 0; f < surfaceNb; f++) {
  33809. if (faceUV && faceUV[f] === undefined) {
  33810. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  33811. }
  33812. }
  33813. var indices = [];
  33814. var positions = [];
  33815. var normals = [];
  33816. var uvs = [];
  33817. var colors = [];
  33818. var angle_step = Math.PI * 2 * arc / tessellation;
  33819. var angle;
  33820. var h;
  33821. var radius;
  33822. var tan = (diameterBottom - diameterTop) / 2 / height;
  33823. var ringVertex = BABYLON.Vector3.Zero();
  33824. var ringNormal = BABYLON.Vector3.Zero();
  33825. var ringFirstVertex = BABYLON.Vector3.Zero();
  33826. var ringFirstNormal = BABYLON.Vector3.Zero();
  33827. var quadNormal = BABYLON.Vector3.Zero();
  33828. var Y = BABYLON.Axis.Y;
  33829. // positions, normals, uvs
  33830. var i;
  33831. var j;
  33832. var r;
  33833. var ringIdx = 1;
  33834. var s = 1; // surface index
  33835. var cs = 0;
  33836. var v = 0;
  33837. for (i = 0; i <= subdivisions; i++) {
  33838. h = i / subdivisions;
  33839. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  33840. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  33841. for (r = 0; r < ringIdx; r++) {
  33842. if (hasRings) {
  33843. s += r;
  33844. }
  33845. if (enclose) {
  33846. s += 2 * r;
  33847. }
  33848. for (j = 0; j <= tessellation; j++) {
  33849. angle = j * angle_step;
  33850. // position
  33851. ringVertex.x = Math.cos(-angle) * radius;
  33852. ringVertex.y = -height / 2 + h * height;
  33853. ringVertex.z = Math.sin(-angle) * radius;
  33854. // normal
  33855. if (diameterTop === 0 && i === subdivisions) {
  33856. // if no top cap, reuse former normals
  33857. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  33858. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  33859. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  33860. }
  33861. else {
  33862. ringNormal.x = ringVertex.x;
  33863. ringNormal.z = ringVertex.z;
  33864. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  33865. ringNormal.normalize();
  33866. }
  33867. // keep first ring vertex values for enclose
  33868. if (j === 0) {
  33869. ringFirstVertex.copyFrom(ringVertex);
  33870. ringFirstNormal.copyFrom(ringNormal);
  33871. }
  33872. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  33873. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  33874. if (hasRings) {
  33875. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  33876. }
  33877. else {
  33878. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  33879. }
  33880. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  33881. if (faceColors) {
  33882. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  33883. }
  33884. }
  33885. // if enclose, add four vertices and their dedicated normals
  33886. if (arc !== 1 && enclose) {
  33887. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  33888. positions.push(0, ringVertex.y, 0);
  33889. positions.push(0, ringVertex.y, 0);
  33890. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  33891. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  33892. quadNormal.normalize();
  33893. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  33894. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  33895. quadNormal.normalize();
  33896. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  33897. if (hasRings) {
  33898. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  33899. }
  33900. else {
  33901. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  33902. }
  33903. uvs.push(faceUV[s + 1].x, v);
  33904. uvs.push(faceUV[s + 1].z, v);
  33905. if (hasRings) {
  33906. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  33907. }
  33908. else {
  33909. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  33910. }
  33911. uvs.push(faceUV[s + 2].x, v);
  33912. uvs.push(faceUV[s + 2].z, v);
  33913. if (faceColors) {
  33914. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  33915. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  33916. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  33917. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  33918. }
  33919. }
  33920. if (cs !== s) {
  33921. cs = s;
  33922. }
  33923. }
  33924. }
  33925. // indices
  33926. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  33927. var s;
  33928. i = 0;
  33929. for (s = 0; s < subdivisions; s++) {
  33930. for (j = 0; j < tessellation; j++) {
  33931. var i0 = i * (e + 1) + j;
  33932. var i1 = (i + 1) * (e + 1) + j;
  33933. var i2 = i * (e + 1) + (j + 1);
  33934. var i3 = (i + 1) * (e + 1) + (j + 1);
  33935. indices.push(i0, i1, i2);
  33936. indices.push(i3, i2, i1);
  33937. }
  33938. if (arc !== 1 && enclose) {
  33939. indices.push(i0 + 2, i1 + 2, i2 + 2);
  33940. indices.push(i3 + 2, i2 + 2, i1 + 2);
  33941. indices.push(i0 + 4, i1 + 4, i2 + 4);
  33942. indices.push(i3 + 4, i2 + 4, i1 + 4);
  33943. }
  33944. i = (hasRings) ? (i + 2) : (i + 1);
  33945. }
  33946. // Caps
  33947. var createCylinderCap = function (isTop) {
  33948. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  33949. if (radius === 0) {
  33950. return;
  33951. }
  33952. // Cap positions, normals & uvs
  33953. var angle;
  33954. var circleVector;
  33955. var i;
  33956. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  33957. var c;
  33958. if (faceColors) {
  33959. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  33960. }
  33961. // cap center
  33962. var vbase = positions.length / 3;
  33963. var offset = isTop ? height / 2 : -height / 2;
  33964. var center = new BABYLON.Vector3(0, offset, 0);
  33965. positions.push(center.x, center.y, center.z);
  33966. normals.push(0, isTop ? 1 : -1, 0);
  33967. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  33968. if (faceColors) {
  33969. colors.push(c.r, c.g, c.b, c.a);
  33970. }
  33971. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  33972. for (i = 0; i <= tessellation; i++) {
  33973. angle = Math.PI * 2 * i * arc / tessellation;
  33974. var cos = Math.cos(-angle);
  33975. var sin = Math.sin(-angle);
  33976. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  33977. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  33978. positions.push(circleVector.x, circleVector.y, circleVector.z);
  33979. normals.push(0, isTop ? 1 : -1, 0);
  33980. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  33981. if (faceColors) {
  33982. colors.push(c.r, c.g, c.b, c.a);
  33983. }
  33984. }
  33985. // Cap indices
  33986. for (i = 0; i < tessellation; i++) {
  33987. if (!isTop) {
  33988. indices.push(vbase);
  33989. indices.push(vbase + (i + 1));
  33990. indices.push(vbase + (i + 2));
  33991. }
  33992. else {
  33993. indices.push(vbase);
  33994. indices.push(vbase + (i + 2));
  33995. indices.push(vbase + (i + 1));
  33996. }
  33997. }
  33998. };
  33999. // add caps to geometry
  34000. createCylinderCap(false);
  34001. createCylinderCap(true);
  34002. // Sides
  34003. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  34004. var vertexData = new VertexData();
  34005. vertexData.indices = indices;
  34006. vertexData.positions = positions;
  34007. vertexData.normals = normals;
  34008. vertexData.uvs = uvs;
  34009. if (faceColors) {
  34010. vertexData.colors = colors;
  34011. }
  34012. return vertexData;
  34013. };
  34014. VertexData.CreateTorus = function (options) {
  34015. var indices = [];
  34016. var positions = [];
  34017. var normals = [];
  34018. var uvs = [];
  34019. var diameter = options.diameter || 1;
  34020. var thickness = options.thickness || 0.5;
  34021. var tessellation = options.tessellation || 16;
  34022. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  34023. var stride = tessellation + 1;
  34024. for (var i = 0; i <= tessellation; i++) {
  34025. var u = i / tessellation;
  34026. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  34027. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  34028. for (var j = 0; j <= tessellation; j++) {
  34029. var v = 1 - j / tessellation;
  34030. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  34031. var dx = Math.cos(innerAngle);
  34032. var dy = Math.sin(innerAngle);
  34033. // Create a vertex.
  34034. var normal = new BABYLON.Vector3(dx, dy, 0);
  34035. var position = normal.scale(thickness / 2);
  34036. var textureCoordinate = new BABYLON.Vector2(u, v);
  34037. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  34038. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  34039. positions.push(position.x, position.y, position.z);
  34040. normals.push(normal.x, normal.y, normal.z);
  34041. uvs.push(textureCoordinate.x, textureCoordinate.y);
  34042. // And create indices for two triangles.
  34043. var nextI = (i + 1) % stride;
  34044. var nextJ = (j + 1) % stride;
  34045. indices.push(i * stride + j);
  34046. indices.push(i * stride + nextJ);
  34047. indices.push(nextI * stride + j);
  34048. indices.push(i * stride + nextJ);
  34049. indices.push(nextI * stride + nextJ);
  34050. indices.push(nextI * stride + j);
  34051. }
  34052. }
  34053. // Sides
  34054. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  34055. // Result
  34056. var vertexData = new VertexData();
  34057. vertexData.indices = indices;
  34058. vertexData.positions = positions;
  34059. vertexData.normals = normals;
  34060. vertexData.uvs = uvs;
  34061. return vertexData;
  34062. };
  34063. VertexData.CreateLineSystem = function (options) {
  34064. var indices = [];
  34065. var positions = [];
  34066. var lines = options.lines;
  34067. var idx = 0;
  34068. for (var l = 0; l < lines.length; l++) {
  34069. var points = lines[l];
  34070. for (var index = 0; index < points.length; index++) {
  34071. positions.push(points[index].x, points[index].y, points[index].z);
  34072. if (index > 0) {
  34073. indices.push(idx - 1);
  34074. indices.push(idx);
  34075. }
  34076. idx++;
  34077. }
  34078. }
  34079. var vertexData = new VertexData();
  34080. vertexData.indices = indices;
  34081. vertexData.positions = positions;
  34082. return vertexData;
  34083. };
  34084. VertexData.CreateDashedLines = function (options) {
  34085. var dashSize = options.dashSize || 3;
  34086. var gapSize = options.gapSize || 1;
  34087. var dashNb = options.dashNb || 200;
  34088. var points = options.points;
  34089. var positions = new Array();
  34090. var indices = new Array();
  34091. var curvect = BABYLON.Vector3.Zero();
  34092. var lg = 0;
  34093. var nb = 0;
  34094. var shft = 0;
  34095. var dashshft = 0;
  34096. var curshft = 0;
  34097. var idx = 0;
  34098. var i = 0;
  34099. for (i = 0; i < points.length - 1; i++) {
  34100. points[i + 1].subtractToRef(points[i], curvect);
  34101. lg += curvect.length();
  34102. }
  34103. shft = lg / dashNb;
  34104. dashshft = dashSize * shft / (dashSize + gapSize);
  34105. for (i = 0; i < points.length - 1; i++) {
  34106. points[i + 1].subtractToRef(points[i], curvect);
  34107. nb = Math.floor(curvect.length() / shft);
  34108. curvect.normalize();
  34109. for (var j = 0; j < nb; j++) {
  34110. curshft = shft * j;
  34111. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  34112. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  34113. indices.push(idx, idx + 1);
  34114. idx += 2;
  34115. }
  34116. }
  34117. // Result
  34118. var vertexData = new VertexData();
  34119. vertexData.positions = positions;
  34120. vertexData.indices = indices;
  34121. return vertexData;
  34122. };
  34123. VertexData.CreateGround = function (options) {
  34124. var indices = [];
  34125. var positions = [];
  34126. var normals = [];
  34127. var uvs = [];
  34128. var row, col;
  34129. var width = options.width || 1;
  34130. var height = options.height || 1;
  34131. var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  34132. var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  34133. for (row = 0; row <= subdivisionsY; row++) {
  34134. for (col = 0; col <= subdivisionsX; col++) {
  34135. var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
  34136. var normal = new BABYLON.Vector3(0, 1.0, 0);
  34137. positions.push(position.x, position.y, position.z);
  34138. normals.push(normal.x, normal.y, normal.z);
  34139. uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsY);
  34140. }
  34141. }
  34142. for (row = 0; row < subdivisionsY; row++) {
  34143. for (col = 0; col < subdivisionsX; col++) {
  34144. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  34145. indices.push(col + 1 + row * (subdivisionsX + 1));
  34146. indices.push(col + row * (subdivisionsX + 1));
  34147. indices.push(col + (row + 1) * (subdivisionsX + 1));
  34148. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  34149. indices.push(col + row * (subdivisionsX + 1));
  34150. }
  34151. }
  34152. // Result
  34153. var vertexData = new VertexData();
  34154. vertexData.indices = indices;
  34155. vertexData.positions = positions;
  34156. vertexData.normals = normals;
  34157. vertexData.uvs = uvs;
  34158. return vertexData;
  34159. };
  34160. VertexData.CreateTiledGround = function (options) {
  34161. var xmin = options.xmin || -1.0;
  34162. var zmin = options.zmin || -1.0;
  34163. var xmax = options.xmax || 1.0;
  34164. var zmax = options.zmax || 1.0;
  34165. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  34166. var precision = options.precision || { w: 1, h: 1 };
  34167. var indices = [];
  34168. var positions = [];
  34169. var normals = [];
  34170. var uvs = [];
  34171. var row, col, tileRow, tileCol;
  34172. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  34173. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  34174. precision.w = (precision.w < 1) ? 1 : precision.w;
  34175. precision.h = (precision.h < 1) ? 1 : precision.h;
  34176. var tileSize = {
  34177. 'w': (xmax - xmin) / subdivisions.w,
  34178. 'h': (zmax - zmin) / subdivisions.h
  34179. };
  34180. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  34181. // Indices
  34182. var base = positions.length / 3;
  34183. var rowLength = precision.w + 1;
  34184. for (row = 0; row < precision.h; row++) {
  34185. for (col = 0; col < precision.w; col++) {
  34186. var square = [
  34187. base + col + row * rowLength,
  34188. base + (col + 1) + row * rowLength,
  34189. base + (col + 1) + (row + 1) * rowLength,
  34190. base + col + (row + 1) * rowLength
  34191. ];
  34192. indices.push(square[1]);
  34193. indices.push(square[2]);
  34194. indices.push(square[3]);
  34195. indices.push(square[0]);
  34196. indices.push(square[1]);
  34197. indices.push(square[3]);
  34198. }
  34199. }
  34200. // Position, normals and uvs
  34201. var position = BABYLON.Vector3.Zero();
  34202. var normal = new BABYLON.Vector3(0, 1.0, 0);
  34203. for (row = 0; row <= precision.h; row++) {
  34204. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  34205. for (col = 0; col <= precision.w; col++) {
  34206. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  34207. position.y = 0;
  34208. positions.push(position.x, position.y, position.z);
  34209. normals.push(normal.x, normal.y, normal.z);
  34210. uvs.push(col / precision.w, row / precision.h);
  34211. }
  34212. }
  34213. }
  34214. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  34215. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  34216. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  34217. }
  34218. }
  34219. // Result
  34220. var vertexData = new VertexData();
  34221. vertexData.indices = indices;
  34222. vertexData.positions = positions;
  34223. vertexData.normals = normals;
  34224. vertexData.uvs = uvs;
  34225. return vertexData;
  34226. };
  34227. VertexData.CreateGroundFromHeightMap = function (options) {
  34228. var indices = [];
  34229. var positions = [];
  34230. var normals = [];
  34231. var uvs = [];
  34232. var row, col;
  34233. // Vertices
  34234. for (row = 0; row <= options.subdivisions; row++) {
  34235. for (col = 0; col <= options.subdivisions; col++) {
  34236. 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));
  34237. // Compute height
  34238. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  34239. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  34240. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  34241. var r = options.buffer[pos] / 255.0;
  34242. var g = options.buffer[pos + 1] / 255.0;
  34243. var b = options.buffer[pos + 2] / 255.0;
  34244. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  34245. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  34246. // Add vertex
  34247. positions.push(position.x, position.y, position.z);
  34248. normals.push(0, 0, 0);
  34249. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  34250. }
  34251. }
  34252. // Indices
  34253. for (row = 0; row < options.subdivisions; row++) {
  34254. for (col = 0; col < options.subdivisions; col++) {
  34255. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  34256. indices.push(col + 1 + row * (options.subdivisions + 1));
  34257. indices.push(col + row * (options.subdivisions + 1));
  34258. indices.push(col + (row + 1) * (options.subdivisions + 1));
  34259. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  34260. indices.push(col + row * (options.subdivisions + 1));
  34261. }
  34262. }
  34263. // Normals
  34264. VertexData.ComputeNormals(positions, indices, normals);
  34265. // Result
  34266. var vertexData = new VertexData();
  34267. vertexData.indices = indices;
  34268. vertexData.positions = positions;
  34269. vertexData.normals = normals;
  34270. vertexData.uvs = uvs;
  34271. return vertexData;
  34272. };
  34273. VertexData.CreatePlane = function (options) {
  34274. var indices = [];
  34275. var positions = [];
  34276. var normals = [];
  34277. var uvs = [];
  34278. var width = options.width || options.size || 1;
  34279. var height = options.height || options.size || 1;
  34280. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  34281. // Vertices
  34282. var halfWidth = width / 2.0;
  34283. var halfHeight = height / 2.0;
  34284. positions.push(-halfWidth, -halfHeight, 0);
  34285. normals.push(0, 0, -1.0);
  34286. uvs.push(0.0, 0.0);
  34287. positions.push(halfWidth, -halfHeight, 0);
  34288. normals.push(0, 0, -1.0);
  34289. uvs.push(1.0, 0.0);
  34290. positions.push(halfWidth, halfHeight, 0);
  34291. normals.push(0, 0, -1.0);
  34292. uvs.push(1.0, 1.0);
  34293. positions.push(-halfWidth, halfHeight, 0);
  34294. normals.push(0, 0, -1.0);
  34295. uvs.push(0.0, 1.0);
  34296. // Indices
  34297. indices.push(0);
  34298. indices.push(1);
  34299. indices.push(2);
  34300. indices.push(0);
  34301. indices.push(2);
  34302. indices.push(3);
  34303. // Sides
  34304. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  34305. // Result
  34306. var vertexData = new VertexData();
  34307. vertexData.indices = indices;
  34308. vertexData.positions = positions;
  34309. vertexData.normals = normals;
  34310. vertexData.uvs = uvs;
  34311. return vertexData;
  34312. };
  34313. VertexData.CreateDisc = function (options) {
  34314. var positions = [];
  34315. var indices = [];
  34316. var normals = [];
  34317. var uvs = [];
  34318. var radius = options.radius || 0.5;
  34319. var tessellation = options.tessellation || 64;
  34320. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  34321. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  34322. // positions and uvs
  34323. positions.push(0, 0, 0); // disc center first
  34324. uvs.push(0.5, 0.5);
  34325. var theta = Math.PI * 2 * arc;
  34326. var step = theta / tessellation;
  34327. for (var a = 0; a < theta; a += step) {
  34328. var x = Math.cos(a);
  34329. var y = Math.sin(a);
  34330. var u = (x + 1) / 2;
  34331. var v = (1 - y) / 2;
  34332. positions.push(radius * x, radius * y, 0);
  34333. uvs.push(u, v);
  34334. }
  34335. if (arc === 1) {
  34336. positions.push(positions[3], positions[4], positions[5]); // close the circle
  34337. uvs.push(uvs[2], uvs[3]);
  34338. }
  34339. //indices
  34340. var vertexNb = positions.length / 3;
  34341. for (var i = 1; i < vertexNb - 1; i++) {
  34342. indices.push(i + 1, 0, i);
  34343. }
  34344. // result
  34345. VertexData.ComputeNormals(positions, indices, normals);
  34346. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  34347. var vertexData = new VertexData();
  34348. vertexData.indices = indices;
  34349. vertexData.positions = positions;
  34350. vertexData.normals = normals;
  34351. vertexData.uvs = uvs;
  34352. return vertexData;
  34353. };
  34354. VertexData.CreateIcoSphere = function (options) {
  34355. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  34356. var radius = options.radius || 1;
  34357. var flat = (options.flat === undefined) ? true : options.flat;
  34358. var subdivisions = options.subdivisions || 4;
  34359. var radiusX = options.radiusX || radius;
  34360. var radiusY = options.radiusY || radius;
  34361. var radiusZ = options.radiusZ || radius;
  34362. var t = (1 + Math.sqrt(5)) / 2;
  34363. // 12 vertex x,y,z
  34364. var ico_vertices = [
  34365. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  34366. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  34367. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  34368. ];
  34369. // index of 3 vertex makes a face of icopshere
  34370. var ico_indices = [
  34371. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  34372. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  34373. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  34374. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  34375. ];
  34376. // vertex for uv have aliased position, not for UV
  34377. var vertices_unalias_id = [
  34378. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  34379. // vertex alias
  34380. 0,
  34381. 2,
  34382. 3,
  34383. 3,
  34384. 3,
  34385. 4,
  34386. 7,
  34387. 8,
  34388. 9,
  34389. 9,
  34390. 10,
  34391. 11 // 23: B + 12
  34392. ];
  34393. // uv as integer step (not pixels !)
  34394. var ico_vertexuv = [
  34395. 5, 1, 3, 1, 6, 4, 0, 0,
  34396. 5, 3, 4, 2, 2, 2, 4, 0,
  34397. 2, 0, 1, 1, 6, 0, 6, 2,
  34398. // vertex alias (for same vertex on different faces)
  34399. 0, 4,
  34400. 3, 3,
  34401. 4, 4,
  34402. 3, 1,
  34403. 4, 2,
  34404. 4, 4,
  34405. 0, 2,
  34406. 1, 1,
  34407. 2, 2,
  34408. 3, 3,
  34409. 1, 3,
  34410. 2, 4 // 23: B + 12
  34411. ];
  34412. // Vertices[0, 1, ...9, A, B] : position on UV plane
  34413. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  34414. // First island of uv mapping
  34415. // v = 4h 3+ 2
  34416. // v = 3h 9+ 4
  34417. // v = 2h 9+ 5 B
  34418. // v = 1h 9 1 0
  34419. // v = 0h 3 8 7 A
  34420. // u = 0 1 2 3 4 5 6 *a
  34421. // Second island of uv mapping
  34422. // v = 4h 0+ B+ 4+
  34423. // v = 3h A+ 2+
  34424. // v = 2h 7+ 6 3+
  34425. // v = 1h 8+ 3+
  34426. // v = 0h
  34427. // u = 0 1 2 3 4 5 6 *a
  34428. // Face layout on texture UV mapping
  34429. // ============
  34430. // \ 4 /\ 16 / ======
  34431. // \ / \ / /\ 11 /
  34432. // \/ 7 \/ / \ /
  34433. // ======= / 10 \/
  34434. // /\ 17 /\ =======
  34435. // / \ / \ \ 15 /\
  34436. // / 8 \/ 12 \ \ / \
  34437. // ============ \/ 6 \
  34438. // \ 18 /\ ============
  34439. // \ / \ \ 5 /\ 0 /
  34440. // \/ 13 \ \ / \ /
  34441. // ======= \/ 1 \/
  34442. // =============
  34443. // /\ 19 /\ 2 /\
  34444. // / \ / \ / \
  34445. // / 14 \/ 9 \/ 3 \
  34446. // ===================
  34447. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  34448. var ustep = 138 / 1024;
  34449. var vstep = 239 / 1024;
  34450. var uoffset = 60 / 1024;
  34451. var voffset = 26 / 1024;
  34452. // Second island should have margin, not to touch the first island
  34453. // avoid any borderline artefact in pixel rounding
  34454. var island_u_offset = -40 / 1024;
  34455. var island_v_offset = +20 / 1024;
  34456. // face is either island 0 or 1 :
  34457. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  34458. var island = [
  34459. 0, 0, 0, 0, 1,
  34460. 0, 0, 1, 1, 0,
  34461. 0, 0, 1, 1, 0,
  34462. 0, 1, 1, 1, 0 // 15 - 19
  34463. ];
  34464. var indices = [];
  34465. var positions = [];
  34466. var normals = [];
  34467. var uvs = [];
  34468. var current_indice = 0;
  34469. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  34470. var face_vertex_pos = new Array(3);
  34471. var face_vertex_uv = new Array(3);
  34472. var v012;
  34473. for (v012 = 0; v012 < 3; v012++) {
  34474. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  34475. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  34476. }
  34477. // create all with normals
  34478. for (var face = 0; face < 20; face++) {
  34479. // 3 vertex per face
  34480. for (v012 = 0; v012 < 3; v012++) {
  34481. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  34482. var v_id = ico_indices[3 * face + v012];
  34483. // vertex have 3D position (x,y,z)
  34484. 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]);
  34485. // Normalize to get normal, then scale to radius
  34486. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  34487. // uv Coordinates from vertex ID
  34488. 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);
  34489. }
  34490. // Subdivide the face (interpolate pos, norm, uv)
  34491. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  34492. // - norm is linear interpolation of vertex corner normal
  34493. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  34494. // - uv is linear interpolation
  34495. //
  34496. // Topology is as below for sub-divide by 2
  34497. // vertex shown as v0,v1,v2
  34498. // interp index is i1 to progress in range [v0,v1[
  34499. // interp index is i2 to progress in range [v0,v2[
  34500. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  34501. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  34502. //
  34503. //
  34504. // i2 v2
  34505. // ^ ^
  34506. // / / \
  34507. // / / \
  34508. // / / \
  34509. // / / (0,1) \
  34510. // / #---------\
  34511. // / / \ (0,0)'/ \
  34512. // / / \ / \
  34513. // / / \ / \
  34514. // / / (0,0) \ / (1,0) \
  34515. // / #---------#---------\
  34516. // v0 v1
  34517. //
  34518. // --------------------> i1
  34519. //
  34520. // interp of (i1,i2):
  34521. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  34522. // along i1 : lerp(x0,x1, i1/(S-i2))
  34523. //
  34524. // centroid of triangle is needed to get help normal computation
  34525. // (c1,c2) are used for centroid location
  34526. var interp_vertex = function (i1, i2, c1, c2) {
  34527. // vertex is interpolated from
  34528. // - face_vertex_pos[0..2]
  34529. // - face_vertex_uv[0..2]
  34530. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  34531. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  34532. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  34533. pos_interp.normalize();
  34534. var vertex_normal;
  34535. if (flat) {
  34536. // in flat mode, recalculate normal as face centroid normal
  34537. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  34538. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  34539. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  34540. }
  34541. else {
  34542. // in smooth mode, recalculate normal from each single vertex position
  34543. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  34544. }
  34545. // Vertex normal need correction due to X,Y,Z radius scaling
  34546. vertex_normal.x /= radiusX;
  34547. vertex_normal.y /= radiusY;
  34548. vertex_normal.z /= radiusZ;
  34549. vertex_normal.normalize();
  34550. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  34551. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  34552. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  34553. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  34554. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  34555. uvs.push(uv_interp.x, uv_interp.y);
  34556. // push each vertex has member of a face
  34557. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  34558. indices.push(current_indice);
  34559. current_indice++;
  34560. };
  34561. for (var i2 = 0; i2 < subdivisions; i2++) {
  34562. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  34563. // face : (i1,i2) for /\ :
  34564. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  34565. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  34566. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  34567. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  34568. if (i1 + i2 + 1 < subdivisions) {
  34569. // face : (i1,i2)' for \/ :
  34570. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  34571. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  34572. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  34573. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  34574. }
  34575. }
  34576. }
  34577. }
  34578. // Sides
  34579. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  34580. // Result
  34581. var vertexData = new VertexData();
  34582. vertexData.indices = indices;
  34583. vertexData.positions = positions;
  34584. vertexData.normals = normals;
  34585. vertexData.uvs = uvs;
  34586. return vertexData;
  34587. };
  34588. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  34589. VertexData.CreatePolyhedron = function (options) {
  34590. // provided polyhedron types :
  34591. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  34592. // 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)
  34593. var polyhedra = [];
  34594. 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]] };
  34595. 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]] };
  34596. polyhedra[2] = {
  34597. 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]],
  34598. 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]]
  34599. };
  34600. polyhedra[3] = {
  34601. 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]],
  34602. 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]]
  34603. };
  34604. polyhedra[4] = {
  34605. 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]],
  34606. 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]]
  34607. };
  34608. 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]] };
  34609. 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]] };
  34610. 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]] };
  34611. 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]] };
  34612. 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]] };
  34613. 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]] };
  34614. 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]] };
  34615. 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]] };
  34616. 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]] };
  34617. polyhedra[14] = {
  34618. 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]],
  34619. 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]]
  34620. };
  34621. var type = (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  34622. var size = options.size;
  34623. var sizeX = options.sizeX || size || 1;
  34624. var sizeY = options.sizeY || size || 1;
  34625. var sizeZ = options.sizeZ || size || 1;
  34626. var data = options.custom || polyhedra[type];
  34627. var nbfaces = data.face.length;
  34628. var faceUV = options.faceUV || new Array(nbfaces);
  34629. var faceColors = options.faceColors;
  34630. var flat = (options.flat === undefined) ? true : options.flat;
  34631. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  34632. var positions = [];
  34633. var indices = [];
  34634. var normals = [];
  34635. var uvs = [];
  34636. var colors = [];
  34637. var index = 0;
  34638. var faceIdx = 0; // face cursor in the array "indexes"
  34639. var indexes = [];
  34640. var i = 0;
  34641. var f = 0;
  34642. var u, v, ang, x, y, tmp;
  34643. // default face colors and UV if undefined
  34644. if (flat) {
  34645. for (f = 0; f < nbfaces; f++) {
  34646. if (faceColors && faceColors[f] === undefined) {
  34647. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  34648. }
  34649. if (faceUV && faceUV[f] === undefined) {
  34650. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  34651. }
  34652. }
  34653. }
  34654. if (!flat) {
  34655. for (i = 0; i < data.vertex.length; i++) {
  34656. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  34657. uvs.push(0, 0);
  34658. }
  34659. for (f = 0; f < nbfaces; f++) {
  34660. for (i = 0; i < data.face[f].length - 2; i++) {
  34661. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  34662. }
  34663. }
  34664. }
  34665. else {
  34666. for (f = 0; f < nbfaces; f++) {
  34667. var fl = data.face[f].length; // number of vertices of the current face
  34668. ang = 2 * Math.PI / fl;
  34669. x = 0.5 * Math.tan(ang / 2);
  34670. y = 0.5;
  34671. // positions, uvs, colors
  34672. for (i = 0; i < fl; i++) {
  34673. // positions
  34674. 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);
  34675. indexes.push(index);
  34676. index++;
  34677. // uvs
  34678. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  34679. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  34680. uvs.push(u, v);
  34681. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  34682. y = x * Math.sin(ang) + y * Math.cos(ang);
  34683. x = tmp;
  34684. // colors
  34685. if (faceColors) {
  34686. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  34687. }
  34688. }
  34689. // indices from indexes
  34690. for (i = 0; i < fl - 2; i++) {
  34691. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  34692. }
  34693. faceIdx += fl;
  34694. }
  34695. }
  34696. VertexData.ComputeNormals(positions, indices, normals);
  34697. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  34698. var vertexData = new VertexData();
  34699. vertexData.positions = positions;
  34700. vertexData.indices = indices;
  34701. vertexData.normals = normals;
  34702. vertexData.uvs = uvs;
  34703. if (faceColors && flat) {
  34704. vertexData.colors = colors;
  34705. }
  34706. return vertexData;
  34707. };
  34708. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  34709. VertexData.CreateTorusKnot = function (options) {
  34710. var indices = [];
  34711. var positions = [];
  34712. var normals = [];
  34713. var uvs = [];
  34714. var radius = options.radius || 2;
  34715. var tube = options.tube || 0.5;
  34716. var radialSegments = options.radialSegments || 32;
  34717. var tubularSegments = options.tubularSegments || 32;
  34718. var p = options.p || 2;
  34719. var q = options.q || 3;
  34720. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  34721. // Helper
  34722. var getPos = function (angle) {
  34723. var cu = Math.cos(angle);
  34724. var su = Math.sin(angle);
  34725. var quOverP = q / p * angle;
  34726. var cs = Math.cos(quOverP);
  34727. var tx = radius * (2 + cs) * 0.5 * cu;
  34728. var ty = radius * (2 + cs) * su * 0.5;
  34729. var tz = radius * Math.sin(quOverP) * 0.5;
  34730. return new BABYLON.Vector3(tx, ty, tz);
  34731. };
  34732. // Vertices
  34733. var i;
  34734. var j;
  34735. for (i = 0; i <= radialSegments; i++) {
  34736. var modI = i % radialSegments;
  34737. var u = modI / radialSegments * 2 * p * Math.PI;
  34738. var p1 = getPos(u);
  34739. var p2 = getPos(u + 0.01);
  34740. var tang = p2.subtract(p1);
  34741. var n = p2.add(p1);
  34742. var bitan = BABYLON.Vector3.Cross(tang, n);
  34743. n = BABYLON.Vector3.Cross(bitan, tang);
  34744. bitan.normalize();
  34745. n.normalize();
  34746. for (j = 0; j < tubularSegments; j++) {
  34747. var modJ = j % tubularSegments;
  34748. var v = modJ / tubularSegments * 2 * Math.PI;
  34749. var cx = -tube * Math.cos(v);
  34750. var cy = tube * Math.sin(v);
  34751. positions.push(p1.x + cx * n.x + cy * bitan.x);
  34752. positions.push(p1.y + cx * n.y + cy * bitan.y);
  34753. positions.push(p1.z + cx * n.z + cy * bitan.z);
  34754. uvs.push(i / radialSegments);
  34755. uvs.push(j / tubularSegments);
  34756. }
  34757. }
  34758. for (i = 0; i < radialSegments; i++) {
  34759. for (j = 0; j < tubularSegments; j++) {
  34760. var jNext = (j + 1) % tubularSegments;
  34761. var a = i * tubularSegments + j;
  34762. var b = (i + 1) * tubularSegments + j;
  34763. var c = (i + 1) * tubularSegments + jNext;
  34764. var d = i * tubularSegments + jNext;
  34765. indices.push(d);
  34766. indices.push(b);
  34767. indices.push(a);
  34768. indices.push(d);
  34769. indices.push(c);
  34770. indices.push(b);
  34771. }
  34772. }
  34773. // Normals
  34774. VertexData.ComputeNormals(positions, indices, normals);
  34775. // Sides
  34776. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  34777. // Result
  34778. var vertexData = new VertexData();
  34779. vertexData.indices = indices;
  34780. vertexData.positions = positions;
  34781. vertexData.normals = normals;
  34782. vertexData.uvs = uvs;
  34783. return vertexData;
  34784. };
  34785. // Tools
  34786. /**
  34787. * @param {any} - positions (number[] or Float32Array)
  34788. * @param {any} - indices (number[] or Uint16Array)
  34789. * @param {any} - normals (number[] or Float32Array)
  34790. * options (optional) :
  34791. * facetPositions : optional array of facet positions (vector3)
  34792. * facetNormals : optional array of facet normals (vector3)
  34793. * facetPartitioning : optional partitioning array. facetPositions is required for facetPartitioning computation
  34794. * subDiv : optional partitioning data about subdivsions on each axis (int), required for facetPartitioning computation
  34795. * ratio : optional partitioning ratio / bounding box, required for facetPartitioning computation
  34796. * bbSize : optional bounding box size data, required for facetPartitioning computation
  34797. * bInfo : optional bounding info, required for facetPartitioning computation
  34798. */
  34799. VertexData.ComputeNormals = function (positions, indices, normals, options) {
  34800. // temporary scalar variables
  34801. var index = 0; // facet index
  34802. var p1p2x = 0.0; // p1p2 vector x coordinate
  34803. var p1p2y = 0.0; // p1p2 vector y coordinate
  34804. var p1p2z = 0.0; // p1p2 vector z coordinate
  34805. var p3p2x = 0.0; // p3p2 vector x coordinate
  34806. var p3p2y = 0.0; // p3p2 vector y coordinate
  34807. var p3p2z = 0.0; // p3p2 vector z coordinate
  34808. var faceNormalx = 0.0; // facet normal x coordinate
  34809. var faceNormaly = 0.0; // facet normal y coordinate
  34810. var faceNormalz = 0.0; // facet normal z coordinate
  34811. var length = 0.0; // facet normal length before normalization
  34812. var v1x = 0; // vector1 x index in the positions array
  34813. var v1y = 0; // vector1 y index in the positions array
  34814. var v1z = 0; // vector1 z index in the positions array
  34815. var v2x = 0; // vector2 x index in the positions array
  34816. var v2y = 0; // vector2 y index in the positions array
  34817. var v2z = 0; // vector2 z index in the positions array
  34818. var v3x = 0; // vector3 x index in the positions array
  34819. var v3y = 0; // vector3 y index in the positions array
  34820. var v3z = 0; // vector3 z index in the positions array
  34821. var computeFacetNormals = false;
  34822. var computeFacetPositions = false;
  34823. var computeFacetPartitioning = false;
  34824. if (options) {
  34825. computeFacetNormals = (options.facetNormals) ? true : false;
  34826. computeFacetPositions = (options.facetPositions) ? true : false;
  34827. computeFacetPartitioning = (options.facetPartitioning) ? true : false;
  34828. }
  34829. // facetPartitioning reinit if needed
  34830. if (computeFacetPartitioning) {
  34831. var ox = 0; // X partitioning index for facet position
  34832. var oy = 0; // Y partinioning index for facet position
  34833. var oz = 0; // Z partinioning index for facet position
  34834. var b1x = 0; // X partitioning index for facet v1 vertex
  34835. var b1y = 0; // Y partitioning index for facet v1 vertex
  34836. var b1z = 0; // z partitioning index for facet v1 vertex
  34837. var b2x = 0; // X partitioning index for facet v2 vertex
  34838. var b2y = 0; // Y partitioning index for facet v2 vertex
  34839. var b2z = 0; // Z partitioning index for facet v2 vertex
  34840. var b3x = 0; // X partitioning index for facet v3 vertex
  34841. var b3y = 0; // Y partitioning index for facet v3 vertex
  34842. var b3z = 0; // Z partitioning index for facet v3 vertex
  34843. var block_idx_o = 0; // facet barycenter block index
  34844. var block_idx_v1 = 0; // v1 vertex block index
  34845. var block_idx_v2 = 0; // v2 vertex block index
  34846. var block_idx_v3 = 0; // v3 vertex block index
  34847. var bbSizeMax = (options.bbSize.x > options.bbSize.y) ? options.bbSize.x : options.bbSize.y;
  34848. bbSizeMax = (bbSizeMax > options.bbSize.z) ? bbSizeMax : options.bbSize.z;
  34849. var xSubRatio = options.subDiv.X * options.ratio / options.bbSize.x;
  34850. var ySubRatio = options.subDiv.Y * options.ratio / options.bbSize.y;
  34851. var zSubRatio = options.subDiv.Z * options.ratio / options.bbSize.z;
  34852. var subSq = options.subDiv.max * options.subDiv.max;
  34853. options.facetPartitioning.length = 0;
  34854. }
  34855. // reset the normals
  34856. for (index = 0; index < positions.length; index++) {
  34857. normals[index] = 0.0;
  34858. }
  34859. // Loop : 1 indice triplet = 1 facet
  34860. var nbFaces = indices.length / 3;
  34861. for (index = 0; index < nbFaces; index++) {
  34862. // get the indexes of the coordinates of each vertex of the facet
  34863. v1x = indices[index * 3] * 3;
  34864. v1y = v1x + 1;
  34865. v1z = v1x + 2;
  34866. v2x = indices[index * 3 + 1] * 3;
  34867. v2y = v2x + 1;
  34868. v2z = v2x + 2;
  34869. v3x = indices[index * 3 + 2] * 3;
  34870. v3y = v3x + 1;
  34871. v3z = v3x + 2;
  34872. p1p2x = positions[v1x] - positions[v2x]; // compute two vectors per facet : p1p2 and p3p2
  34873. p1p2y = positions[v1y] - positions[v2y];
  34874. p1p2z = positions[v1z] - positions[v2z];
  34875. p3p2x = positions[v3x] - positions[v2x];
  34876. p3p2y = positions[v3y] - positions[v2y];
  34877. p3p2z = positions[v3z] - positions[v2z];
  34878. // compute the face normal with the cross product
  34879. faceNormalx = p1p2y * p3p2z - p1p2z * p3p2y;
  34880. faceNormaly = p1p2z * p3p2x - p1p2x * p3p2z;
  34881. faceNormalz = p1p2x * p3p2y - p1p2y * p3p2x;
  34882. // normalize this normal and store it in the array facetData
  34883. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  34884. length = (length === 0) ? 1.0 : length;
  34885. faceNormalx /= length;
  34886. faceNormaly /= length;
  34887. faceNormalz /= length;
  34888. if (computeFacetNormals) {
  34889. options.facetNormals[index].x = faceNormalx;
  34890. options.facetNormals[index].y = faceNormaly;
  34891. options.facetNormals[index].z = faceNormalz;
  34892. }
  34893. if (computeFacetPositions) {
  34894. // compute and the facet barycenter coordinates in the array facetPositions
  34895. options.facetPositions[index].x = (positions[v1x] + positions[v2x] + positions[v3x]) / 3.0;
  34896. options.facetPositions[index].y = (positions[v1y] + positions[v2y] + positions[v3y]) / 3.0;
  34897. options.facetPositions[index].z = (positions[v1z] + positions[v2z] + positions[v3z]) / 3.0;
  34898. }
  34899. if (computeFacetPartitioning) {
  34900. // store the facet indexes in arrays in the main facetPartitioning array :
  34901. // compute each facet vertex (+ facet barycenter) index in the partiniong array
  34902. ox = Math.floor((options.facetPositions[index].x - options.bInfo.minimum.x * options.ratio) * xSubRatio);
  34903. oy = Math.floor((options.facetPositions[index].y - options.bInfo.minimum.y * options.ratio) * ySubRatio);
  34904. oz = Math.floor((options.facetPositions[index].z - options.bInfo.minimum.z * options.ratio) * zSubRatio);
  34905. b1x = Math.floor((positions[v1x] - options.bInfo.minimum.x * options.ratio) * xSubRatio);
  34906. b1y = Math.floor((positions[v1y] - options.bInfo.minimum.y * options.ratio) * ySubRatio);
  34907. b1z = Math.floor((positions[v1z] - options.bInfo.minimum.z * options.ratio) * zSubRatio);
  34908. b2x = Math.floor((positions[v2x] - options.bInfo.minimum.x * options.ratio) * xSubRatio);
  34909. b2y = Math.floor((positions[v2y] - options.bInfo.minimum.y * options.ratio) * ySubRatio);
  34910. b2z = Math.floor((positions[v2z] - options.bInfo.minimum.z * options.ratio) * zSubRatio);
  34911. b3x = Math.floor((positions[v3x] - options.bInfo.minimum.x * options.ratio) * xSubRatio);
  34912. b3y = Math.floor((positions[v3y] - options.bInfo.minimum.y * options.ratio) * ySubRatio);
  34913. b3z = Math.floor((positions[v3z] - options.bInfo.minimum.z * options.ratio) * zSubRatio);
  34914. block_idx_v1 = b1x + options.subDiv.max * b1y + subSq * b1z;
  34915. block_idx_v2 = b2x + options.subDiv.max * b2y + subSq * b2z;
  34916. block_idx_v3 = b3x + options.subDiv.max * b3y + subSq * b3z;
  34917. block_idx_o = ox + options.subDiv.max * oy + subSq * oz;
  34918. options.facetPartitioning[block_idx_o] = options.facetPartitioning[block_idx_o] ? options.facetPartitioning[block_idx_o] : new Array();
  34919. options.facetPartitioning[block_idx_v1] = options.facetPartitioning[block_idx_v1] ? options.facetPartitioning[block_idx_v1] : new Array();
  34920. options.facetPartitioning[block_idx_v2] = options.facetPartitioning[block_idx_v2] ? options.facetPartitioning[block_idx_v2] : new Array();
  34921. options.facetPartitioning[block_idx_v3] = options.facetPartitioning[block_idx_v3] ? options.facetPartitioning[block_idx_v3] : new Array();
  34922. // push each facet index in each block containing the vertex
  34923. options.facetPartitioning[block_idx_v1].push(index);
  34924. if (block_idx_v2 != block_idx_v1) {
  34925. options.facetPartitioning[block_idx_v2].push(index);
  34926. }
  34927. if (!(block_idx_v3 == block_idx_v2 || block_idx_v3 == block_idx_v1)) {
  34928. options.facetPartitioning[block_idx_v3].push(index);
  34929. }
  34930. if (!(block_idx_o == block_idx_v1 || block_idx_o == block_idx_v2 || block_idx_o == block_idx_v3)) {
  34931. options.facetPartitioning[block_idx_o].push(index);
  34932. }
  34933. }
  34934. // compute the normals anyway
  34935. normals[v1x] += faceNormalx; // accumulate all the normals per face
  34936. normals[v1y] += faceNormaly;
  34937. normals[v1z] += faceNormalz;
  34938. normals[v2x] += faceNormalx;
  34939. normals[v2y] += faceNormaly;
  34940. normals[v2z] += faceNormalz;
  34941. normals[v3x] += faceNormalx;
  34942. normals[v3y] += faceNormaly;
  34943. normals[v3z] += faceNormalz;
  34944. }
  34945. // last normalization of each normal
  34946. for (index = 0; index < normals.length / 3; index++) {
  34947. faceNormalx = normals[index * 3];
  34948. faceNormaly = normals[index * 3 + 1];
  34949. faceNormalz = normals[index * 3 + 2];
  34950. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  34951. length = (length === 0) ? 1.0 : length;
  34952. faceNormalx /= length;
  34953. faceNormaly /= length;
  34954. faceNormalz /= length;
  34955. normals[index * 3] = faceNormalx;
  34956. normals[index * 3 + 1] = faceNormaly;
  34957. normals[index * 3 + 2] = faceNormalz;
  34958. }
  34959. };
  34960. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs) {
  34961. var li = indices.length;
  34962. var ln = normals.length;
  34963. var i;
  34964. var n;
  34965. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  34966. switch (sideOrientation) {
  34967. case BABYLON.Mesh.FRONTSIDE:
  34968. // nothing changed
  34969. break;
  34970. case BABYLON.Mesh.BACKSIDE:
  34971. var tmp;
  34972. // indices
  34973. for (i = 0; i < li; i += 3) {
  34974. tmp = indices[i];
  34975. indices[i] = indices[i + 2];
  34976. indices[i + 2] = tmp;
  34977. }
  34978. // normals
  34979. for (n = 0; n < ln; n++) {
  34980. normals[n] = -normals[n];
  34981. }
  34982. break;
  34983. case BABYLON.Mesh.DOUBLESIDE:
  34984. // positions
  34985. var lp = positions.length;
  34986. var l = lp / 3;
  34987. for (var p = 0; p < lp; p++) {
  34988. positions[lp + p] = positions[p];
  34989. }
  34990. // indices
  34991. for (i = 0; i < li; i += 3) {
  34992. indices[i + li] = indices[i + 2] + l;
  34993. indices[i + 1 + li] = indices[i + 1] + l;
  34994. indices[i + 2 + li] = indices[i] + l;
  34995. }
  34996. // normals
  34997. for (n = 0; n < ln; n++) {
  34998. normals[ln + n] = -normals[n];
  34999. }
  35000. // uvs
  35001. var lu = uvs.length;
  35002. for (var u = 0; u < lu; u++) {
  35003. uvs[u + lu] = uvs[u];
  35004. }
  35005. break;
  35006. }
  35007. };
  35008. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  35009. var vertexData = new VertexData();
  35010. // positions
  35011. var positions = parsedVertexData.positions;
  35012. if (positions) {
  35013. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  35014. }
  35015. // normals
  35016. var normals = parsedVertexData.normals;
  35017. if (normals) {
  35018. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  35019. }
  35020. // uvs
  35021. var uvs = parsedVertexData.uvs;
  35022. if (uvs) {
  35023. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  35024. }
  35025. // uv2s
  35026. var uv2s = parsedVertexData.uv2s;
  35027. if (uv2s) {
  35028. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  35029. }
  35030. // uv3s
  35031. var uv3s = parsedVertexData.uv3s;
  35032. if (uv3s) {
  35033. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  35034. }
  35035. // uv4s
  35036. var uv4s = parsedVertexData.uv4s;
  35037. if (uv4s) {
  35038. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  35039. }
  35040. // uv5s
  35041. var uv5s = parsedVertexData.uv5s;
  35042. if (uv5s) {
  35043. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  35044. }
  35045. // uv6s
  35046. var uv6s = parsedVertexData.uv6s;
  35047. if (uv6s) {
  35048. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  35049. }
  35050. // colors
  35051. var colors = parsedVertexData.colors;
  35052. if (colors) {
  35053. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  35054. }
  35055. // matricesIndices
  35056. var matricesIndices = parsedVertexData.matricesIndices;
  35057. if (matricesIndices) {
  35058. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  35059. }
  35060. // matricesWeights
  35061. var matricesWeights = parsedVertexData.matricesWeights;
  35062. if (matricesWeights) {
  35063. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  35064. }
  35065. // indices
  35066. var indices = parsedVertexData.indices;
  35067. if (indices) {
  35068. vertexData.indices = indices;
  35069. }
  35070. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  35071. };
  35072. return VertexData;
  35073. }());
  35074. BABYLON.VertexData = VertexData;
  35075. })(BABYLON || (BABYLON = {}));
  35076. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  35077. var BABYLON;
  35078. (function (BABYLON) {
  35079. var Tags = (function () {
  35080. function Tags() {
  35081. }
  35082. Tags.EnableFor = function (obj) {
  35083. obj._tags = obj._tags || {};
  35084. obj.hasTags = function () {
  35085. return Tags.HasTags(obj);
  35086. };
  35087. obj.addTags = function (tagsString) {
  35088. return Tags.AddTagsTo(obj, tagsString);
  35089. };
  35090. obj.removeTags = function (tagsString) {
  35091. return Tags.RemoveTagsFrom(obj, tagsString);
  35092. };
  35093. obj.matchesTagsQuery = function (tagsQuery) {
  35094. return Tags.MatchesQuery(obj, tagsQuery);
  35095. };
  35096. };
  35097. Tags.DisableFor = function (obj) {
  35098. delete obj._tags;
  35099. delete obj.hasTags;
  35100. delete obj.addTags;
  35101. delete obj.removeTags;
  35102. delete obj.matchesTagsQuery;
  35103. };
  35104. Tags.HasTags = function (obj) {
  35105. if (!obj._tags) {
  35106. return false;
  35107. }
  35108. return !BABYLON.Tools.IsEmpty(obj._tags);
  35109. };
  35110. Tags.GetTags = function (obj, asString) {
  35111. if (asString === void 0) { asString = true; }
  35112. if (!obj._tags) {
  35113. return null;
  35114. }
  35115. if (asString) {
  35116. var tagsArray = [];
  35117. for (var tag in obj._tags) {
  35118. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  35119. tagsArray.push(tag);
  35120. }
  35121. }
  35122. return tagsArray.join(" ");
  35123. }
  35124. else {
  35125. return obj._tags;
  35126. }
  35127. };
  35128. // the tags 'true' and 'false' are reserved and cannot be used as tags
  35129. // a tag cannot start with '||', '&&', and '!'
  35130. // it cannot contain whitespaces
  35131. Tags.AddTagsTo = function (obj, tagsString) {
  35132. if (!tagsString) {
  35133. return;
  35134. }
  35135. if (typeof tagsString !== "string") {
  35136. return;
  35137. }
  35138. var tags = tagsString.split(" ");
  35139. tags.forEach(function (tag, index, array) {
  35140. Tags._AddTagTo(obj, tag);
  35141. });
  35142. };
  35143. Tags._AddTagTo = function (obj, tag) {
  35144. tag = tag.trim();
  35145. if (tag === "" || tag === "true" || tag === "false") {
  35146. return;
  35147. }
  35148. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  35149. return;
  35150. }
  35151. Tags.EnableFor(obj);
  35152. obj._tags[tag] = true;
  35153. };
  35154. Tags.RemoveTagsFrom = function (obj, tagsString) {
  35155. if (!Tags.HasTags(obj)) {
  35156. return;
  35157. }
  35158. var tags = tagsString.split(" ");
  35159. for (var t in tags) {
  35160. Tags._RemoveTagFrom(obj, tags[t]);
  35161. }
  35162. };
  35163. Tags._RemoveTagFrom = function (obj, tag) {
  35164. delete obj._tags[tag];
  35165. };
  35166. Tags.MatchesQuery = function (obj, tagsQuery) {
  35167. if (tagsQuery === undefined) {
  35168. return true;
  35169. }
  35170. if (tagsQuery === "") {
  35171. return Tags.HasTags(obj);
  35172. }
  35173. return BABYLON.Internals.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  35174. };
  35175. return Tags;
  35176. }());
  35177. BABYLON.Tags = Tags;
  35178. })(BABYLON || (BABYLON = {}));
  35179. //# sourceMappingURL=babylon.tags.js.map
  35180. var BABYLON;
  35181. (function (BABYLON) {
  35182. var Internals;
  35183. (function (Internals) {
  35184. var AndOrNotEvaluator = (function () {
  35185. function AndOrNotEvaluator() {
  35186. }
  35187. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  35188. if (!query.match(/\([^\(\)]*\)/g)) {
  35189. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  35190. }
  35191. else {
  35192. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  35193. // remove parenthesis
  35194. r = r.slice(1, r.length - 1);
  35195. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  35196. });
  35197. }
  35198. if (query === "true") {
  35199. return true;
  35200. }
  35201. if (query === "false") {
  35202. return false;
  35203. }
  35204. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  35205. };
  35206. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  35207. evaluateCallback = evaluateCallback || (function (r) {
  35208. return r === "true" ? true : false;
  35209. });
  35210. var result;
  35211. var or = parenthesisContent.split("||");
  35212. for (var i in or) {
  35213. if (or.hasOwnProperty(i)) {
  35214. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  35215. var and = ori.split("&&");
  35216. if (and.length > 1) {
  35217. for (var j = 0; j < and.length; ++j) {
  35218. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  35219. if (andj !== "true" && andj !== "false") {
  35220. if (andj[0] === "!") {
  35221. result = !evaluateCallback(andj.substring(1));
  35222. }
  35223. else {
  35224. result = evaluateCallback(andj);
  35225. }
  35226. }
  35227. else {
  35228. result = andj === "true" ? true : false;
  35229. }
  35230. if (!result) {
  35231. ori = "false";
  35232. break;
  35233. }
  35234. }
  35235. }
  35236. if (result || ori === "true") {
  35237. result = true;
  35238. break;
  35239. }
  35240. // result equals false (or undefined)
  35241. if (ori !== "true" && ori !== "false") {
  35242. if (ori[0] === "!") {
  35243. result = !evaluateCallback(ori.substring(1));
  35244. }
  35245. else {
  35246. result = evaluateCallback(ori);
  35247. }
  35248. }
  35249. else {
  35250. result = ori === "true" ? true : false;
  35251. }
  35252. }
  35253. }
  35254. // the whole parenthesis scope is replaced by 'true' or 'false'
  35255. return result ? "true" : "false";
  35256. };
  35257. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  35258. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  35259. // remove whitespaces
  35260. r = r.replace(/[\s]/g, function () { return ""; });
  35261. return r.length % 2 ? "!" : "";
  35262. });
  35263. booleanString = booleanString.trim();
  35264. if (booleanString === "!true") {
  35265. booleanString = "false";
  35266. }
  35267. else if (booleanString === "!false") {
  35268. booleanString = "true";
  35269. }
  35270. return booleanString;
  35271. };
  35272. return AndOrNotEvaluator;
  35273. }());
  35274. Internals.AndOrNotEvaluator = AndOrNotEvaluator;
  35275. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  35276. })(BABYLON || (BABYLON = {}));
  35277. //# sourceMappingURL=babylon.andOrNotEvaluator.js.map
  35278. var BABYLON;
  35279. (function (BABYLON) {
  35280. var PostProcessRenderPass = (function () {
  35281. function PostProcessRenderPass(scene, name, size, renderList, beforeRender, afterRender) {
  35282. this._enabled = true;
  35283. this._refCount = 0;
  35284. this._name = name;
  35285. this._renderTexture = new BABYLON.RenderTargetTexture(name, size, scene);
  35286. this.setRenderList(renderList);
  35287. this._renderTexture.onBeforeRenderObservable.add(beforeRender);
  35288. this._renderTexture.onAfterRenderObservable.add(afterRender);
  35289. this._scene = scene;
  35290. this._renderList = renderList;
  35291. }
  35292. // private
  35293. PostProcessRenderPass.prototype._incRefCount = function () {
  35294. if (this._refCount === 0) {
  35295. this._scene.customRenderTargets.push(this._renderTexture);
  35296. }
  35297. return ++this._refCount;
  35298. };
  35299. PostProcessRenderPass.prototype._decRefCount = function () {
  35300. this._refCount--;
  35301. if (this._refCount <= 0) {
  35302. this._scene.customRenderTargets.splice(this._scene.customRenderTargets.indexOf(this._renderTexture), 1);
  35303. }
  35304. return this._refCount;
  35305. };
  35306. PostProcessRenderPass.prototype._update = function () {
  35307. this.setRenderList(this._renderList);
  35308. };
  35309. // public
  35310. PostProcessRenderPass.prototype.setRenderList = function (renderList) {
  35311. this._renderTexture.renderList = renderList;
  35312. };
  35313. PostProcessRenderPass.prototype.getRenderTexture = function () {
  35314. return this._renderTexture;
  35315. };
  35316. return PostProcessRenderPass;
  35317. }());
  35318. BABYLON.PostProcessRenderPass = PostProcessRenderPass;
  35319. })(BABYLON || (BABYLON = {}));
  35320. //# sourceMappingURL=babylon.postProcessRenderPass.js.map
  35321. var BABYLON;
  35322. (function (BABYLON) {
  35323. var PostProcessRenderEffect = (function () {
  35324. function PostProcessRenderEffect(engine, name, getPostProcess, singleInstance) {
  35325. this._engine = engine;
  35326. this._name = name;
  35327. this._singleInstance = singleInstance || true;
  35328. this._getPostProcess = getPostProcess;
  35329. this._cameras = [];
  35330. this._indicesForCamera = [];
  35331. this._postProcesses = {};
  35332. this._renderPasses = {};
  35333. this._renderEffectAsPasses = {};
  35334. }
  35335. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  35336. get: function () {
  35337. for (var index in this._postProcesses) {
  35338. if (!this._postProcesses[index].isSupported) {
  35339. return false;
  35340. }
  35341. }
  35342. return true;
  35343. },
  35344. enumerable: true,
  35345. configurable: true
  35346. });
  35347. PostProcessRenderEffect.prototype._update = function () {
  35348. for (var renderPassName in this._renderPasses) {
  35349. this._renderPasses[renderPassName]._update();
  35350. }
  35351. };
  35352. PostProcessRenderEffect.prototype.addPass = function (renderPass) {
  35353. this._renderPasses[renderPass._name] = renderPass;
  35354. this._linkParameters();
  35355. };
  35356. PostProcessRenderEffect.prototype.removePass = function (renderPass) {
  35357. delete this._renderPasses[renderPass._name];
  35358. this._linkParameters();
  35359. };
  35360. PostProcessRenderEffect.prototype.addRenderEffectAsPass = function (renderEffect) {
  35361. this._renderEffectAsPasses[renderEffect._name] = renderEffect;
  35362. this._linkParameters();
  35363. };
  35364. PostProcessRenderEffect.prototype.getPass = function (passName) {
  35365. for (var renderPassName in this._renderPasses) {
  35366. if (renderPassName === passName) {
  35367. return this._renderPasses[passName];
  35368. }
  35369. }
  35370. };
  35371. PostProcessRenderEffect.prototype.emptyPasses = function () {
  35372. this._renderPasses = {};
  35373. this._linkParameters();
  35374. };
  35375. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  35376. var cameraKey;
  35377. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  35378. for (var i = 0; i < _cam.length; i++) {
  35379. var camera = _cam[i];
  35380. var cameraName = camera.name;
  35381. if (this._singleInstance) {
  35382. cameraKey = 0;
  35383. }
  35384. else {
  35385. cameraKey = cameraName;
  35386. }
  35387. this._postProcesses[cameraKey] = this._postProcesses[cameraKey] || this._getPostProcess();
  35388. var index = camera.attachPostProcess(this._postProcesses[cameraKey]);
  35389. if (!this._indicesForCamera[cameraName]) {
  35390. this._indicesForCamera[cameraName] = [];
  35391. }
  35392. this._indicesForCamera[cameraName].push(index);
  35393. if (this._cameras.indexOf(camera) === -1) {
  35394. this._cameras[cameraName] = camera;
  35395. }
  35396. for (var passName in this._renderPasses) {
  35397. this._renderPasses[passName]._incRefCount();
  35398. }
  35399. }
  35400. this._linkParameters();
  35401. };
  35402. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  35403. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  35404. for (var i = 0; i < _cam.length; i++) {
  35405. var camera = _cam[i];
  35406. var cameraName = camera.name;
  35407. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  35408. var index = this._cameras.indexOf(cameraName);
  35409. this._indicesForCamera.splice(index, 1);
  35410. this._cameras.splice(index, 1);
  35411. for (var passName in this._renderPasses) {
  35412. this._renderPasses[passName]._decRefCount();
  35413. }
  35414. }
  35415. };
  35416. PostProcessRenderEffect.prototype._enable = function (cameras) {
  35417. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  35418. for (var i = 0; i < _cam.length; i++) {
  35419. var camera = _cam[i];
  35420. var cameraName = camera.name;
  35421. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  35422. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
  35423. cameras[i].attachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName][j]);
  35424. }
  35425. }
  35426. for (var passName in this._renderPasses) {
  35427. this._renderPasses[passName]._incRefCount();
  35428. }
  35429. }
  35430. };
  35431. PostProcessRenderEffect.prototype._disable = function (cameras) {
  35432. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  35433. for (var i = 0; i < _cam.length; i++) {
  35434. var camera = _cam[i];
  35435. var cameraName = camera.Name;
  35436. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  35437. for (var passName in this._renderPasses) {
  35438. this._renderPasses[passName]._decRefCount();
  35439. }
  35440. }
  35441. };
  35442. PostProcessRenderEffect.prototype.getPostProcess = function (camera) {
  35443. if (this._singleInstance) {
  35444. return this._postProcesses[0];
  35445. }
  35446. else {
  35447. return this._postProcesses[camera.name];
  35448. }
  35449. };
  35450. PostProcessRenderEffect.prototype._linkParameters = function () {
  35451. var _this = this;
  35452. for (var index in this._postProcesses) {
  35453. if (this.applyParameters) {
  35454. this.applyParameters(this._postProcesses[index]);
  35455. }
  35456. this._postProcesses[index].onBeforeRenderObservable.add(function (effect) {
  35457. _this._linkTextures(effect);
  35458. });
  35459. }
  35460. };
  35461. PostProcessRenderEffect.prototype._linkTextures = function (effect) {
  35462. for (var renderPassName in this._renderPasses) {
  35463. effect.setTexture(renderPassName, this._renderPasses[renderPassName].getRenderTexture());
  35464. }
  35465. for (var renderEffectName in this._renderEffectAsPasses) {
  35466. effect.setTextureFromPostProcess(renderEffectName + "Sampler", this._renderEffectAsPasses[renderEffectName].getPostProcess());
  35467. }
  35468. };
  35469. return PostProcessRenderEffect;
  35470. }());
  35471. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  35472. })(BABYLON || (BABYLON = {}));
  35473. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  35474. var BABYLON;
  35475. (function (BABYLON) {
  35476. var PostProcessRenderPipeline = (function () {
  35477. function PostProcessRenderPipeline(engine, name) {
  35478. this._engine = engine;
  35479. this._name = name;
  35480. this._renderEffects = {};
  35481. this._renderEffectsForIsolatedPass = {};
  35482. this._cameras = [];
  35483. }
  35484. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  35485. get: function () {
  35486. for (var renderEffectName in this._renderEffects) {
  35487. if (!this._renderEffects[renderEffectName].isSupported) {
  35488. return false;
  35489. }
  35490. }
  35491. return true;
  35492. },
  35493. enumerable: true,
  35494. configurable: true
  35495. });
  35496. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  35497. this._renderEffects[renderEffect._name] = renderEffect;
  35498. };
  35499. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  35500. var renderEffects = this._renderEffects[renderEffectName];
  35501. if (!renderEffects) {
  35502. return;
  35503. }
  35504. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  35505. };
  35506. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  35507. var renderEffects = this._renderEffects[renderEffectName];
  35508. if (!renderEffects) {
  35509. return;
  35510. }
  35511. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  35512. };
  35513. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  35514. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  35515. var indicesToDelete = [];
  35516. var i;
  35517. for (i = 0; i < _cam.length; i++) {
  35518. var camera = _cam[i];
  35519. var cameraName = camera.name;
  35520. if (this._cameras.indexOf(camera) === -1) {
  35521. this._cameras[cameraName] = camera;
  35522. }
  35523. else if (unique) {
  35524. indicesToDelete.push(i);
  35525. }
  35526. }
  35527. for (i = 0; i < indicesToDelete.length; i++) {
  35528. cameras.splice(indicesToDelete[i], 1);
  35529. }
  35530. for (var renderEffectName in this._renderEffects) {
  35531. this._renderEffects[renderEffectName]._attachCameras(_cam);
  35532. }
  35533. };
  35534. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  35535. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  35536. for (var renderEffectName in this._renderEffects) {
  35537. this._renderEffects[renderEffectName]._detachCameras(_cam);
  35538. }
  35539. for (var i = 0; i < _cam.length; i++) {
  35540. this._cameras.splice(this._cameras.indexOf(_cam[i]), 1);
  35541. }
  35542. };
  35543. PostProcessRenderPipeline.prototype._enableDisplayOnlyPass = function (passName, cameras) {
  35544. var _this = this;
  35545. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  35546. var pass = null;
  35547. var renderEffectName;
  35548. for (renderEffectName in this._renderEffects) {
  35549. pass = this._renderEffects[renderEffectName].getPass(passName);
  35550. if (pass != null) {
  35551. break;
  35552. }
  35553. }
  35554. if (pass === null) {
  35555. return;
  35556. }
  35557. for (renderEffectName in this._renderEffects) {
  35558. this._renderEffects[renderEffectName]._disable(_cam);
  35559. }
  35560. pass._name = PostProcessRenderPipeline.PASS_SAMPLER_NAME;
  35561. for (var i = 0; i < _cam.length; i++) {
  35562. var camera = _cam[i];
  35563. var cameraName = camera.name;
  35564. 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); });
  35565. this._renderEffectsForIsolatedPass[cameraName].emptyPasses();
  35566. this._renderEffectsForIsolatedPass[cameraName].addPass(pass);
  35567. this._renderEffectsForIsolatedPass[cameraName]._attachCameras(camera);
  35568. }
  35569. };
  35570. PostProcessRenderPipeline.prototype._disableDisplayOnlyPass = function (cameras) {
  35571. var _this = this;
  35572. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  35573. for (var i = 0; i < _cam.length; i++) {
  35574. var camera = _cam[i];
  35575. var cameraName = camera.name;
  35576. 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); });
  35577. this._renderEffectsForIsolatedPass[cameraName]._disable(camera);
  35578. }
  35579. for (var renderEffectName in this._renderEffects) {
  35580. this._renderEffects[renderEffectName]._enable(_cam);
  35581. }
  35582. };
  35583. PostProcessRenderPipeline.prototype._update = function () {
  35584. for (var renderEffectName in this._renderEffects) {
  35585. this._renderEffects[renderEffectName]._update();
  35586. }
  35587. for (var i = 0; i < this._cameras.length; i++) {
  35588. var cameraName = this._cameras[i].name;
  35589. if (this._renderEffectsForIsolatedPass[cameraName]) {
  35590. this._renderEffectsForIsolatedPass[cameraName]._update();
  35591. }
  35592. }
  35593. };
  35594. PostProcessRenderPipeline.prototype.dispose = function () {
  35595. // Must be implemented by children
  35596. };
  35597. return PostProcessRenderPipeline;
  35598. }());
  35599. PostProcessRenderPipeline.PASS_EFFECT_NAME = "passEffect";
  35600. PostProcessRenderPipeline.PASS_SAMPLER_NAME = "passSampler";
  35601. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  35602. })(BABYLON || (BABYLON = {}));
  35603. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  35604. var BABYLON;
  35605. (function (BABYLON) {
  35606. var PostProcessRenderPipelineManager = (function () {
  35607. function PostProcessRenderPipelineManager() {
  35608. this._renderPipelines = {};
  35609. }
  35610. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  35611. this._renderPipelines[renderPipeline._name] = renderPipeline;
  35612. };
  35613. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  35614. var renderPipeline = this._renderPipelines[renderPipelineName];
  35615. if (!renderPipeline) {
  35616. return;
  35617. }
  35618. renderPipeline._attachCameras(cameras, unique);
  35619. };
  35620. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  35621. var renderPipeline = this._renderPipelines[renderPipelineName];
  35622. if (!renderPipeline) {
  35623. return;
  35624. }
  35625. renderPipeline._detachCameras(cameras);
  35626. };
  35627. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  35628. var renderPipeline = this._renderPipelines[renderPipelineName];
  35629. if (!renderPipeline) {
  35630. return;
  35631. }
  35632. renderPipeline._enableEffect(renderEffectName, cameras);
  35633. };
  35634. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  35635. var renderPipeline = this._renderPipelines[renderPipelineName];
  35636. if (!renderPipeline) {
  35637. return;
  35638. }
  35639. renderPipeline._disableEffect(renderEffectName, cameras);
  35640. };
  35641. PostProcessRenderPipelineManager.prototype.enableDisplayOnlyPassInPipeline = function (renderPipelineName, passName, cameras) {
  35642. var renderPipeline = this._renderPipelines[renderPipelineName];
  35643. if (!renderPipeline) {
  35644. return;
  35645. }
  35646. renderPipeline._enableDisplayOnlyPass(passName, cameras);
  35647. };
  35648. PostProcessRenderPipelineManager.prototype.disableDisplayOnlyPassInPipeline = function (renderPipelineName, cameras) {
  35649. var renderPipeline = this._renderPipelines[renderPipelineName];
  35650. if (!renderPipeline) {
  35651. return;
  35652. }
  35653. renderPipeline._disableDisplayOnlyPass(cameras);
  35654. };
  35655. PostProcessRenderPipelineManager.prototype.update = function () {
  35656. for (var renderPipelineName in this._renderPipelines) {
  35657. var pipeline = this._renderPipelines[renderPipelineName];
  35658. if (!pipeline.isSupported) {
  35659. pipeline.dispose();
  35660. delete this._renderPipelines[renderPipelineName];
  35661. }
  35662. else {
  35663. pipeline._update();
  35664. }
  35665. }
  35666. };
  35667. return PostProcessRenderPipelineManager;
  35668. }());
  35669. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  35670. })(BABYLON || (BABYLON = {}));
  35671. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  35672. var BABYLON;
  35673. (function (BABYLON) {
  35674. var BoundingBoxRenderer = (function () {
  35675. function BoundingBoxRenderer(scene) {
  35676. this.frontColor = new BABYLON.Color3(1, 1, 1);
  35677. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  35678. this.showBackLines = true;
  35679. this.renderList = new BABYLON.SmartArray(32);
  35680. this._vertexBuffers = {};
  35681. this._scene = scene;
  35682. }
  35683. BoundingBoxRenderer.prototype._prepareRessources = function () {
  35684. if (this._colorShader) {
  35685. return;
  35686. }
  35687. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  35688. attributes: [BABYLON.VertexBuffer.PositionKind],
  35689. uniforms: ["worldViewProjection", "color"]
  35690. });
  35691. var engine = this._scene.getEngine();
  35692. var boxdata = BABYLON.VertexData.CreateBox(1.0);
  35693. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  35694. 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]);
  35695. };
  35696. BoundingBoxRenderer.prototype.reset = function () {
  35697. this.renderList.reset();
  35698. };
  35699. BoundingBoxRenderer.prototype.render = function () {
  35700. if (this.renderList.length === 0) {
  35701. return;
  35702. }
  35703. this._prepareRessources();
  35704. if (!this._colorShader.isReady()) {
  35705. return;
  35706. }
  35707. var engine = this._scene.getEngine();
  35708. engine.setDepthWrite(false);
  35709. this._colorShader._preBind();
  35710. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  35711. var boundingBox = this.renderList.data[boundingBoxIndex];
  35712. var min = boundingBox.minimum;
  35713. var max = boundingBox.maximum;
  35714. var diff = max.subtract(min);
  35715. var median = min.add(diff.scale(0.5));
  35716. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  35717. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  35718. .multiply(boundingBox.getWorldMatrix());
  35719. // VBOs
  35720. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  35721. if (this.showBackLines) {
  35722. // Back
  35723. engine.setDepthFunctionToGreaterOrEqual();
  35724. this._scene.resetCachedMaterial();
  35725. this._colorShader.setColor4("color", this.backColor.toColor4());
  35726. this._colorShader.bind(worldMatrix);
  35727. // Draw order
  35728. engine.draw(false, 0, 24);
  35729. }
  35730. // Front
  35731. engine.setDepthFunctionToLess();
  35732. this._scene.resetCachedMaterial();
  35733. this._colorShader.setColor4("color", this.frontColor.toColor4());
  35734. this._colorShader.bind(worldMatrix);
  35735. // Draw order
  35736. engine.draw(false, 0, 24);
  35737. }
  35738. this._colorShader.unbind();
  35739. engine.setDepthFunctionToLessOrEqual();
  35740. engine.setDepthWrite(true);
  35741. };
  35742. BoundingBoxRenderer.prototype.dispose = function () {
  35743. if (!this._colorShader) {
  35744. return;
  35745. }
  35746. this._colorShader.dispose();
  35747. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  35748. if (buffer) {
  35749. buffer.dispose();
  35750. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  35751. }
  35752. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  35753. };
  35754. return BoundingBoxRenderer;
  35755. }());
  35756. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  35757. })(BABYLON || (BABYLON = {}));
  35758. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  35759. var BABYLON;
  35760. (function (BABYLON) {
  35761. var Condition = (function () {
  35762. function Condition(actionManager) {
  35763. this._actionManager = actionManager;
  35764. }
  35765. Condition.prototype.isValid = function () {
  35766. return true;
  35767. };
  35768. Condition.prototype._getProperty = function (propertyPath) {
  35769. return this._actionManager._getProperty(propertyPath);
  35770. };
  35771. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  35772. return this._actionManager._getEffectiveTarget(target, propertyPath);
  35773. };
  35774. Condition.prototype.serialize = function () {
  35775. };
  35776. Condition.prototype._serialize = function (serializedCondition) {
  35777. return {
  35778. type: 2,
  35779. children: [],
  35780. name: serializedCondition.name,
  35781. properties: serializedCondition.properties
  35782. };
  35783. };
  35784. return Condition;
  35785. }());
  35786. BABYLON.Condition = Condition;
  35787. var ValueCondition = (function (_super) {
  35788. __extends(ValueCondition, _super);
  35789. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  35790. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  35791. var _this = _super.call(this, actionManager) || this;
  35792. _this.propertyPath = propertyPath;
  35793. _this.value = value;
  35794. _this.operator = operator;
  35795. _this._target = target;
  35796. _this._effectiveTarget = _this._getEffectiveTarget(target, _this.propertyPath);
  35797. _this._property = _this._getProperty(_this.propertyPath);
  35798. return _this;
  35799. }
  35800. Object.defineProperty(ValueCondition, "IsEqual", {
  35801. get: function () {
  35802. return ValueCondition._IsEqual;
  35803. },
  35804. enumerable: true,
  35805. configurable: true
  35806. });
  35807. Object.defineProperty(ValueCondition, "IsDifferent", {
  35808. get: function () {
  35809. return ValueCondition._IsDifferent;
  35810. },
  35811. enumerable: true,
  35812. configurable: true
  35813. });
  35814. Object.defineProperty(ValueCondition, "IsGreater", {
  35815. get: function () {
  35816. return ValueCondition._IsGreater;
  35817. },
  35818. enumerable: true,
  35819. configurable: true
  35820. });
  35821. Object.defineProperty(ValueCondition, "IsLesser", {
  35822. get: function () {
  35823. return ValueCondition._IsLesser;
  35824. },
  35825. enumerable: true,
  35826. configurable: true
  35827. });
  35828. // Methods
  35829. ValueCondition.prototype.isValid = function () {
  35830. switch (this.operator) {
  35831. case ValueCondition.IsGreater:
  35832. return this._effectiveTarget[this._property] > this.value;
  35833. case ValueCondition.IsLesser:
  35834. return this._effectiveTarget[this._property] < this.value;
  35835. case ValueCondition.IsEqual:
  35836. case ValueCondition.IsDifferent:
  35837. var check;
  35838. if (this.value.equals) {
  35839. check = this.value.equals(this._effectiveTarget[this._property]);
  35840. }
  35841. else {
  35842. check = this.value === this._effectiveTarget[this._property];
  35843. }
  35844. return this.operator === ValueCondition.IsEqual ? check : !check;
  35845. }
  35846. return false;
  35847. };
  35848. ValueCondition.prototype.serialize = function () {
  35849. return this._serialize({
  35850. name: "ValueCondition",
  35851. properties: [
  35852. BABYLON.Action._GetTargetProperty(this._target),
  35853. { name: "propertyPath", value: this.propertyPath },
  35854. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  35855. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  35856. ]
  35857. });
  35858. };
  35859. ValueCondition.GetOperatorName = function (operator) {
  35860. switch (operator) {
  35861. case ValueCondition._IsEqual: return "IsEqual";
  35862. case ValueCondition._IsDifferent: return "IsDifferent";
  35863. case ValueCondition._IsGreater: return "IsGreater";
  35864. case ValueCondition._IsLesser: return "IsLesser";
  35865. default: return "";
  35866. }
  35867. };
  35868. return ValueCondition;
  35869. }(Condition));
  35870. // Statics
  35871. ValueCondition._IsEqual = 0;
  35872. ValueCondition._IsDifferent = 1;
  35873. ValueCondition._IsGreater = 2;
  35874. ValueCondition._IsLesser = 3;
  35875. BABYLON.ValueCondition = ValueCondition;
  35876. var PredicateCondition = (function (_super) {
  35877. __extends(PredicateCondition, _super);
  35878. function PredicateCondition(actionManager, predicate) {
  35879. var _this = _super.call(this, actionManager) || this;
  35880. _this.predicate = predicate;
  35881. return _this;
  35882. }
  35883. PredicateCondition.prototype.isValid = function () {
  35884. return this.predicate();
  35885. };
  35886. return PredicateCondition;
  35887. }(Condition));
  35888. BABYLON.PredicateCondition = PredicateCondition;
  35889. var StateCondition = (function (_super) {
  35890. __extends(StateCondition, _super);
  35891. function StateCondition(actionManager, target, value) {
  35892. var _this = _super.call(this, actionManager) || this;
  35893. _this.value = value;
  35894. _this._target = target;
  35895. return _this;
  35896. }
  35897. // Methods
  35898. StateCondition.prototype.isValid = function () {
  35899. return this._target.state === this.value;
  35900. };
  35901. StateCondition.prototype.serialize = function () {
  35902. return this._serialize({
  35903. name: "StateCondition",
  35904. properties: [
  35905. BABYLON.Action._GetTargetProperty(this._target),
  35906. { name: "value", value: this.value }
  35907. ]
  35908. });
  35909. };
  35910. return StateCondition;
  35911. }(Condition));
  35912. BABYLON.StateCondition = StateCondition;
  35913. })(BABYLON || (BABYLON = {}));
  35914. //# sourceMappingURL=babylon.condition.js.map
  35915. var BABYLON;
  35916. (function (BABYLON) {
  35917. var Action = (function () {
  35918. function Action(triggerOptions, condition) {
  35919. this.triggerOptions = triggerOptions;
  35920. if (triggerOptions.parameter) {
  35921. this.trigger = triggerOptions.trigger;
  35922. this._triggerParameter = triggerOptions.parameter;
  35923. }
  35924. else {
  35925. this.trigger = triggerOptions;
  35926. }
  35927. this._nextActiveAction = this;
  35928. this._condition = condition;
  35929. }
  35930. // Methods
  35931. Action.prototype._prepare = function () {
  35932. };
  35933. Action.prototype.getTriggerParameter = function () {
  35934. return this._triggerParameter;
  35935. };
  35936. Action.prototype._executeCurrent = function (evt) {
  35937. if (this._nextActiveAction._condition) {
  35938. var condition = this._nextActiveAction._condition;
  35939. var currentRenderId = this._actionManager.getScene().getRenderId();
  35940. // We cache the current evaluation for the current frame
  35941. if (condition._evaluationId === currentRenderId) {
  35942. if (!condition._currentResult) {
  35943. return;
  35944. }
  35945. }
  35946. else {
  35947. condition._evaluationId = currentRenderId;
  35948. if (!condition.isValid()) {
  35949. condition._currentResult = false;
  35950. return;
  35951. }
  35952. condition._currentResult = true;
  35953. }
  35954. }
  35955. this._nextActiveAction.execute(evt);
  35956. this.skipToNextActiveAction();
  35957. };
  35958. Action.prototype.execute = function (evt) {
  35959. };
  35960. Action.prototype.skipToNextActiveAction = function () {
  35961. if (this._nextActiveAction._child) {
  35962. if (!this._nextActiveAction._child._actionManager) {
  35963. this._nextActiveAction._child._actionManager = this._actionManager;
  35964. }
  35965. this._nextActiveAction = this._nextActiveAction._child;
  35966. }
  35967. else {
  35968. this._nextActiveAction = this;
  35969. }
  35970. };
  35971. Action.prototype.then = function (action) {
  35972. this._child = action;
  35973. action._actionManager = this._actionManager;
  35974. action._prepare();
  35975. return action;
  35976. };
  35977. Action.prototype._getProperty = function (propertyPath) {
  35978. return this._actionManager._getProperty(propertyPath);
  35979. };
  35980. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  35981. return this._actionManager._getEffectiveTarget(target, propertyPath);
  35982. };
  35983. Action.prototype.serialize = function (parent) {
  35984. };
  35985. // Called by BABYLON.Action objects in serialize(...). Internal use
  35986. Action.prototype._serialize = function (serializedAction, parent) {
  35987. var serializationObject = {
  35988. type: 1,
  35989. children: [],
  35990. name: serializedAction.name,
  35991. properties: serializedAction.properties || []
  35992. };
  35993. // Serialize child
  35994. if (this._child) {
  35995. this._child.serialize(serializationObject);
  35996. }
  35997. // Check if "this" has a condition
  35998. if (this._condition) {
  35999. var serializedCondition = this._condition.serialize();
  36000. serializedCondition.children.push(serializationObject);
  36001. if (parent) {
  36002. parent.children.push(serializedCondition);
  36003. }
  36004. return serializedCondition;
  36005. }
  36006. if (parent) {
  36007. parent.children.push(serializationObject);
  36008. }
  36009. return serializationObject;
  36010. };
  36011. return Action;
  36012. }());
  36013. Action._SerializeValueAsString = function (value) {
  36014. if (typeof value === "number") {
  36015. return value.toString();
  36016. }
  36017. if (typeof value === "boolean") {
  36018. return value ? "true" : "false";
  36019. }
  36020. if (value instanceof BABYLON.Vector2) {
  36021. return value.x + ", " + value.y;
  36022. }
  36023. if (value instanceof BABYLON.Vector3) {
  36024. return value.x + ", " + value.y + ", " + value.z;
  36025. }
  36026. if (value instanceof BABYLON.Color3) {
  36027. return value.r + ", " + value.g + ", " + value.b;
  36028. }
  36029. if (value instanceof BABYLON.Color4) {
  36030. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  36031. }
  36032. return value; // string
  36033. };
  36034. Action._GetTargetProperty = function (target) {
  36035. return {
  36036. name: "target",
  36037. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  36038. : target instanceof BABYLON.Light ? "LightProperties"
  36039. : target instanceof BABYLON.Camera ? "CameraProperties"
  36040. : "SceneProperties",
  36041. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  36042. };
  36043. };
  36044. BABYLON.Action = Action;
  36045. })(BABYLON || (BABYLON = {}));
  36046. //# sourceMappingURL=babylon.action.js.map
  36047. var BABYLON;
  36048. (function (BABYLON) {
  36049. /**
  36050. * ActionEvent is the event beint sent when an action is triggered.
  36051. */
  36052. var ActionEvent = (function () {
  36053. /**
  36054. * @constructor
  36055. * @param source The mesh or sprite that triggered the action.
  36056. * @param pointerX The X mouse cursor position at the time of the event
  36057. * @param pointerY The Y mouse cursor position at the time of the event
  36058. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  36059. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  36060. */
  36061. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent, additionalData) {
  36062. this.source = source;
  36063. this.pointerX = pointerX;
  36064. this.pointerY = pointerY;
  36065. this.meshUnderPointer = meshUnderPointer;
  36066. this.sourceEvent = sourceEvent;
  36067. this.additionalData = additionalData;
  36068. }
  36069. /**
  36070. * Helper function to auto-create an ActionEvent from a source mesh.
  36071. * @param source The source mesh that triggered the event
  36072. * @param evt {Event} The original (browser) event
  36073. */
  36074. ActionEvent.CreateNew = function (source, evt, additionalData) {
  36075. var scene = source.getScene();
  36076. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  36077. };
  36078. /**
  36079. * Helper function to auto-create an ActionEvent from a source mesh.
  36080. * @param source The source sprite that triggered the event
  36081. * @param scene Scene associated with the sprite
  36082. * @param evt {Event} The original (browser) event
  36083. */
  36084. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  36085. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  36086. };
  36087. /**
  36088. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  36089. * @param scene the scene where the event occurred
  36090. * @param evt {Event} The original (browser) event
  36091. */
  36092. ActionEvent.CreateNewFromScene = function (scene, evt) {
  36093. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  36094. };
  36095. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  36096. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  36097. };
  36098. return ActionEvent;
  36099. }());
  36100. BABYLON.ActionEvent = ActionEvent;
  36101. /**
  36102. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  36103. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  36104. */
  36105. var ActionManager = (function () {
  36106. function ActionManager(scene) {
  36107. // Members
  36108. this.actions = new Array();
  36109. this.hoverCursor = '';
  36110. this._scene = scene;
  36111. scene._actionManagers.push(this);
  36112. }
  36113. Object.defineProperty(ActionManager, "NothingTrigger", {
  36114. get: function () {
  36115. return ActionManager._NothingTrigger;
  36116. },
  36117. enumerable: true,
  36118. configurable: true
  36119. });
  36120. Object.defineProperty(ActionManager, "OnPickTrigger", {
  36121. get: function () {
  36122. return ActionManager._OnPickTrigger;
  36123. },
  36124. enumerable: true,
  36125. configurable: true
  36126. });
  36127. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  36128. get: function () {
  36129. return ActionManager._OnLeftPickTrigger;
  36130. },
  36131. enumerable: true,
  36132. configurable: true
  36133. });
  36134. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  36135. get: function () {
  36136. return ActionManager._OnRightPickTrigger;
  36137. },
  36138. enumerable: true,
  36139. configurable: true
  36140. });
  36141. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  36142. get: function () {
  36143. return ActionManager._OnCenterPickTrigger;
  36144. },
  36145. enumerable: true,
  36146. configurable: true
  36147. });
  36148. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  36149. get: function () {
  36150. return ActionManager._OnPickDownTrigger;
  36151. },
  36152. enumerable: true,
  36153. configurable: true
  36154. });
  36155. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  36156. get: function () {
  36157. return ActionManager._OnPickUpTrigger;
  36158. },
  36159. enumerable: true,
  36160. configurable: true
  36161. });
  36162. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  36163. /// This trigger will only be raised if you also declared a OnPickDown
  36164. get: function () {
  36165. return ActionManager._OnPickOutTrigger;
  36166. },
  36167. enumerable: true,
  36168. configurable: true
  36169. });
  36170. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  36171. get: function () {
  36172. return ActionManager._OnLongPressTrigger;
  36173. },
  36174. enumerable: true,
  36175. configurable: true
  36176. });
  36177. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  36178. get: function () {
  36179. return ActionManager._OnPointerOverTrigger;
  36180. },
  36181. enumerable: true,
  36182. configurable: true
  36183. });
  36184. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  36185. get: function () {
  36186. return ActionManager._OnPointerOutTrigger;
  36187. },
  36188. enumerable: true,
  36189. configurable: true
  36190. });
  36191. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  36192. get: function () {
  36193. return ActionManager._OnEveryFrameTrigger;
  36194. },
  36195. enumerable: true,
  36196. configurable: true
  36197. });
  36198. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  36199. get: function () {
  36200. return ActionManager._OnIntersectionEnterTrigger;
  36201. },
  36202. enumerable: true,
  36203. configurable: true
  36204. });
  36205. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  36206. get: function () {
  36207. return ActionManager._OnIntersectionExitTrigger;
  36208. },
  36209. enumerable: true,
  36210. configurable: true
  36211. });
  36212. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  36213. get: function () {
  36214. return ActionManager._OnKeyDownTrigger;
  36215. },
  36216. enumerable: true,
  36217. configurable: true
  36218. });
  36219. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  36220. get: function () {
  36221. return ActionManager._OnKeyUpTrigger;
  36222. },
  36223. enumerable: true,
  36224. configurable: true
  36225. });
  36226. // Methods
  36227. ActionManager.prototype.dispose = function () {
  36228. var index = this._scene._actionManagers.indexOf(this);
  36229. if (index > -1) {
  36230. this._scene._actionManagers.splice(index, 1);
  36231. }
  36232. };
  36233. ActionManager.prototype.getScene = function () {
  36234. return this._scene;
  36235. };
  36236. /**
  36237. * Does this action manager handles actions of any of the given triggers
  36238. * @param {number[]} triggers - the triggers to be tested
  36239. * @return {boolean} whether one (or more) of the triggers is handeled
  36240. */
  36241. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  36242. for (var index = 0; index < this.actions.length; index++) {
  36243. var action = this.actions[index];
  36244. if (triggers.indexOf(action.trigger) > -1) {
  36245. return true;
  36246. }
  36247. }
  36248. return false;
  36249. };
  36250. /**
  36251. * Does this action manager handles actions of a given trigger
  36252. * @param {number} trigger - the trigger to be tested
  36253. * @return {boolean} whether the trigger is handeled
  36254. */
  36255. ActionManager.prototype.hasSpecificTrigger = function (trigger) {
  36256. for (var index = 0; index < this.actions.length; index++) {
  36257. var action = this.actions[index];
  36258. if (action.trigger === trigger) {
  36259. return true;
  36260. }
  36261. }
  36262. return false;
  36263. };
  36264. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  36265. /**
  36266. * Does this action manager has pointer triggers
  36267. * @return {boolean} whether or not it has pointer triggers
  36268. */
  36269. get: function () {
  36270. for (var index = 0; index < this.actions.length; index++) {
  36271. var action = this.actions[index];
  36272. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  36273. return true;
  36274. }
  36275. }
  36276. return false;
  36277. },
  36278. enumerable: true,
  36279. configurable: true
  36280. });
  36281. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  36282. /**
  36283. * Does this action manager has pick triggers
  36284. * @return {boolean} whether or not it has pick triggers
  36285. */
  36286. get: function () {
  36287. for (var index = 0; index < this.actions.length; index++) {
  36288. var action = this.actions[index];
  36289. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  36290. return true;
  36291. }
  36292. }
  36293. return false;
  36294. },
  36295. enumerable: true,
  36296. configurable: true
  36297. });
  36298. /**
  36299. * Registers an action to this action manager
  36300. * @param {BABYLON.Action} action - the action to be registered
  36301. * @return {BABYLON.Action} the action amended (prepared) after registration
  36302. */
  36303. ActionManager.prototype.registerAction = function (action) {
  36304. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  36305. if (this.getScene().actionManager !== this) {
  36306. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  36307. return null;
  36308. }
  36309. }
  36310. this.actions.push(action);
  36311. action._actionManager = this;
  36312. action._prepare();
  36313. return action;
  36314. };
  36315. /**
  36316. * Process a specific trigger
  36317. * @param {number} trigger - the trigger to process
  36318. * @param evt {BABYLON.ActionEvent} the event details to be processed
  36319. */
  36320. ActionManager.prototype.processTrigger = function (trigger, evt) {
  36321. for (var index = 0; index < this.actions.length; index++) {
  36322. var action = this.actions[index];
  36323. if (action.trigger === trigger) {
  36324. if (trigger === ActionManager.OnKeyUpTrigger
  36325. || trigger === ActionManager.OnKeyDownTrigger) {
  36326. var parameter = action.getTriggerParameter();
  36327. if (parameter) {
  36328. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  36329. var actualkey = String.fromCharCode(unicode).toLowerCase();
  36330. if (actualkey !== parameter.toLowerCase()) {
  36331. continue;
  36332. }
  36333. }
  36334. }
  36335. action._executeCurrent(evt);
  36336. }
  36337. }
  36338. };
  36339. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  36340. var properties = propertyPath.split(".");
  36341. for (var index = 0; index < properties.length - 1; index++) {
  36342. target = target[properties[index]];
  36343. }
  36344. return target;
  36345. };
  36346. ActionManager.prototype._getProperty = function (propertyPath) {
  36347. var properties = propertyPath.split(".");
  36348. return properties[properties.length - 1];
  36349. };
  36350. ActionManager.prototype.serialize = function (name) {
  36351. var root = {
  36352. children: [],
  36353. name: name,
  36354. type: 3,
  36355. properties: [] // Empty for root but required
  36356. };
  36357. for (var i = 0; i < this.actions.length; i++) {
  36358. var triggerObject = {
  36359. type: 0,
  36360. children: [],
  36361. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  36362. properties: []
  36363. };
  36364. var triggerOptions = this.actions[i].triggerOptions;
  36365. if (triggerOptions && typeof triggerOptions !== "number") {
  36366. if (triggerOptions.parameter instanceof BABYLON.Node) {
  36367. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  36368. }
  36369. else {
  36370. var parameter = {};
  36371. BABYLON.Tools.DeepCopy(triggerOptions.parameter, parameter, ["mesh"]);
  36372. if (triggerOptions.parameter.mesh) {
  36373. parameter._meshId = triggerOptions.parameter.mesh.id;
  36374. }
  36375. triggerObject.properties.push({ name: "parameter", targetType: null, value: parameter });
  36376. }
  36377. }
  36378. // Serialize child action, recursively
  36379. this.actions[i].serialize(triggerObject);
  36380. // Add serialized trigger
  36381. root.children.push(triggerObject);
  36382. }
  36383. return root;
  36384. };
  36385. ActionManager.Parse = function (parsedActions, object, scene) {
  36386. var actionManager = new BABYLON.ActionManager(scene);
  36387. if (object === null)
  36388. scene.actionManager = actionManager;
  36389. else
  36390. object.actionManager = actionManager;
  36391. // instanciate a new object
  36392. var instanciate = function (name, params) {
  36393. var newInstance = Object.create(BABYLON[name].prototype);
  36394. newInstance.constructor.apply(newInstance, params);
  36395. return newInstance;
  36396. };
  36397. var parseParameter = function (name, value, target, propertyPath) {
  36398. if (propertyPath === null) {
  36399. // String, boolean or float
  36400. var floatValue = parseFloat(value);
  36401. if (value === "true" || value === "false")
  36402. return value === "true";
  36403. else
  36404. return isNaN(floatValue) ? value : floatValue;
  36405. }
  36406. var effectiveTarget = propertyPath.split(".");
  36407. var values = value.split(",");
  36408. // Get effective Target
  36409. for (var i = 0; i < effectiveTarget.length; i++) {
  36410. target = target[effectiveTarget[i]];
  36411. }
  36412. // Return appropriate value with its type
  36413. if (typeof (target) === "boolean")
  36414. return values[0] === "true";
  36415. if (typeof (target) === "string")
  36416. return values[0];
  36417. // Parameters with multiple values such as Vector3 etc.
  36418. var split = new Array();
  36419. for (var i = 0; i < values.length; i++)
  36420. split.push(parseFloat(values[i]));
  36421. if (target instanceof BABYLON.Vector3)
  36422. return BABYLON.Vector3.FromArray(split);
  36423. if (target instanceof BABYLON.Vector4)
  36424. return BABYLON.Vector4.FromArray(split);
  36425. if (target instanceof BABYLON.Color3)
  36426. return BABYLON.Color3.FromArray(split);
  36427. if (target instanceof BABYLON.Color4)
  36428. return BABYLON.Color4.FromArray(split);
  36429. return parseFloat(values[0]);
  36430. };
  36431. // traverse graph per trigger
  36432. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  36433. if (combineArray === void 0) { combineArray = null; }
  36434. if (parsedAction.detached)
  36435. return;
  36436. var parameters = new Array();
  36437. var target = null;
  36438. var propertyPath = null;
  36439. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  36440. // Parameters
  36441. if (parsedAction.type === 2)
  36442. parameters.push(actionManager);
  36443. else
  36444. parameters.push(trigger);
  36445. if (combine) {
  36446. var actions = new Array();
  36447. for (var j = 0; j < parsedAction.combine.length; j++) {
  36448. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  36449. }
  36450. parameters.push(actions);
  36451. }
  36452. else {
  36453. for (var i = 0; i < parsedAction.properties.length; i++) {
  36454. var value = parsedAction.properties[i].value;
  36455. var name = parsedAction.properties[i].name;
  36456. var targetType = parsedAction.properties[i].targetType;
  36457. if (name === "target")
  36458. if (targetType !== null && targetType === "SceneProperties")
  36459. value = target = scene;
  36460. else
  36461. value = target = scene.getNodeByName(value);
  36462. else if (name === "parent")
  36463. value = scene.getNodeByName(value);
  36464. else if (name === "sound")
  36465. value = scene.getSoundByName(value);
  36466. else if (name !== "propertyPath") {
  36467. if (parsedAction.type === 2 && name === "operator")
  36468. value = BABYLON.ValueCondition[value];
  36469. else
  36470. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  36471. }
  36472. else {
  36473. propertyPath = value;
  36474. }
  36475. parameters.push(value);
  36476. }
  36477. }
  36478. if (combineArray === null) {
  36479. parameters.push(condition);
  36480. }
  36481. else {
  36482. parameters.push(null);
  36483. }
  36484. // If interpolate value action
  36485. if (parsedAction.name === "InterpolateValueAction") {
  36486. var param = parameters[parameters.length - 2];
  36487. parameters[parameters.length - 1] = param;
  36488. parameters[parameters.length - 2] = condition;
  36489. }
  36490. // Action or condition(s) and not CombineAction
  36491. var newAction = instanciate(parsedAction.name, parameters);
  36492. if (newAction instanceof BABYLON.Condition && condition !== null) {
  36493. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  36494. if (action)
  36495. action.then(nothing);
  36496. else
  36497. actionManager.registerAction(nothing);
  36498. action = nothing;
  36499. }
  36500. if (combineArray === null) {
  36501. if (newAction instanceof BABYLON.Condition) {
  36502. condition = newAction;
  36503. newAction = action;
  36504. }
  36505. else {
  36506. condition = null;
  36507. if (action)
  36508. action.then(newAction);
  36509. else
  36510. actionManager.registerAction(newAction);
  36511. }
  36512. }
  36513. else {
  36514. combineArray.push(newAction);
  36515. }
  36516. for (var i = 0; i < parsedAction.children.length; i++)
  36517. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  36518. };
  36519. // triggers
  36520. for (var i = 0; i < parsedActions.children.length; i++) {
  36521. var triggerParams;
  36522. var trigger = parsedActions.children[i];
  36523. if (trigger.properties.length > 0) {
  36524. var param = trigger.properties[0].value;
  36525. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  36526. if (value._meshId) {
  36527. value.mesh = scene.getMeshByID(value._meshId);
  36528. }
  36529. triggerParams = { trigger: BABYLON.ActionManager[trigger.name], parameter: value };
  36530. }
  36531. else
  36532. triggerParams = BABYLON.ActionManager[trigger.name];
  36533. for (var j = 0; j < trigger.children.length; j++) {
  36534. if (!trigger.detached)
  36535. traverse(trigger.children[j], triggerParams, null, null);
  36536. }
  36537. }
  36538. };
  36539. ActionManager.GetTriggerName = function (trigger) {
  36540. switch (trigger) {
  36541. case 0: return "NothingTrigger";
  36542. case 1: return "OnPickTrigger";
  36543. case 2: return "OnLeftPickTrigger";
  36544. case 3: return "OnRightPickTrigger";
  36545. case 4: return "OnCenterPickTrigger";
  36546. case 5: return "OnPickDownTrigger";
  36547. case 6: return "OnPickUpTrigger";
  36548. case 7: return "OnLongPressTrigger";
  36549. case 8: return "OnPointerOverTrigger";
  36550. case 9: return "OnPointerOutTrigger";
  36551. case 10: return "OnEveryFrameTrigger";
  36552. case 11: return "OnIntersectionEnterTrigger";
  36553. case 12: return "OnIntersectionExitTrigger";
  36554. case 13: return "OnKeyDownTrigger";
  36555. case 14: return "OnKeyUpTrigger";
  36556. case 15: return "OnPickOutTrigger";
  36557. default: return "";
  36558. }
  36559. };
  36560. return ActionManager;
  36561. }());
  36562. // Statics
  36563. ActionManager._NothingTrigger = 0;
  36564. ActionManager._OnPickTrigger = 1;
  36565. ActionManager._OnLeftPickTrigger = 2;
  36566. ActionManager._OnRightPickTrigger = 3;
  36567. ActionManager._OnCenterPickTrigger = 4;
  36568. ActionManager._OnPickDownTrigger = 5;
  36569. ActionManager._OnPickUpTrigger = 6;
  36570. ActionManager._OnLongPressTrigger = 7;
  36571. ActionManager._OnPointerOverTrigger = 8;
  36572. ActionManager._OnPointerOutTrigger = 9;
  36573. ActionManager._OnEveryFrameTrigger = 10;
  36574. ActionManager._OnIntersectionEnterTrigger = 11;
  36575. ActionManager._OnIntersectionExitTrigger = 12;
  36576. ActionManager._OnKeyDownTrigger = 13;
  36577. ActionManager._OnKeyUpTrigger = 14;
  36578. ActionManager._OnPickOutTrigger = 15;
  36579. ActionManager.DragMovementThreshold = 10; // in pixels
  36580. ActionManager.LongPressDelay = 500; // in milliseconds
  36581. BABYLON.ActionManager = ActionManager;
  36582. })(BABYLON || (BABYLON = {}));
  36583. //# sourceMappingURL=babylon.actionManager.js.map
  36584. var BABYLON;
  36585. (function (BABYLON) {
  36586. var InterpolateValueAction = (function (_super) {
  36587. __extends(InterpolateValueAction, _super);
  36588. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  36589. if (duration === void 0) { duration = 1000; }
  36590. var _this = _super.call(this, triggerOptions, condition) || this;
  36591. _this.propertyPath = propertyPath;
  36592. _this.value = value;
  36593. _this.duration = duration;
  36594. _this.stopOtherAnimations = stopOtherAnimations;
  36595. _this.onInterpolationDone = onInterpolationDone;
  36596. _this._target = _this._effectiveTarget = target;
  36597. return _this;
  36598. }
  36599. InterpolateValueAction.prototype._prepare = function () {
  36600. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  36601. this._property = this._getProperty(this.propertyPath);
  36602. };
  36603. InterpolateValueAction.prototype.execute = function () {
  36604. var scene = this._actionManager.getScene();
  36605. var keys = [
  36606. {
  36607. frame: 0,
  36608. value: this._effectiveTarget[this._property]
  36609. }, {
  36610. frame: 100,
  36611. value: this.value
  36612. }
  36613. ];
  36614. var dataType;
  36615. if (typeof this.value === "number") {
  36616. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  36617. }
  36618. else if (this.value instanceof BABYLON.Color3) {
  36619. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  36620. }
  36621. else if (this.value instanceof BABYLON.Vector3) {
  36622. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  36623. }
  36624. else if (this.value instanceof BABYLON.Matrix) {
  36625. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  36626. }
  36627. else if (this.value instanceof BABYLON.Quaternion) {
  36628. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  36629. }
  36630. else {
  36631. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  36632. return;
  36633. }
  36634. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  36635. animation.setKeys(keys);
  36636. if (this.stopOtherAnimations) {
  36637. scene.stopAnimation(this._effectiveTarget);
  36638. }
  36639. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, this.onInterpolationDone);
  36640. };
  36641. InterpolateValueAction.prototype.serialize = function (parent) {
  36642. return _super.prototype._serialize.call(this, {
  36643. name: "InterpolateValueAction",
  36644. properties: [
  36645. BABYLON.Action._GetTargetProperty(this._target),
  36646. { name: "propertyPath", value: this.propertyPath },
  36647. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  36648. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  36649. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  36650. ]
  36651. }, parent);
  36652. };
  36653. return InterpolateValueAction;
  36654. }(BABYLON.Action));
  36655. BABYLON.InterpolateValueAction = InterpolateValueAction;
  36656. })(BABYLON || (BABYLON = {}));
  36657. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  36658. var BABYLON;
  36659. (function (BABYLON) {
  36660. var SwitchBooleanAction = (function (_super) {
  36661. __extends(SwitchBooleanAction, _super);
  36662. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  36663. var _this = _super.call(this, triggerOptions, condition) || this;
  36664. _this.propertyPath = propertyPath;
  36665. _this._target = _this._effectiveTarget = target;
  36666. return _this;
  36667. }
  36668. SwitchBooleanAction.prototype._prepare = function () {
  36669. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  36670. this._property = this._getProperty(this.propertyPath);
  36671. };
  36672. SwitchBooleanAction.prototype.execute = function () {
  36673. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  36674. };
  36675. SwitchBooleanAction.prototype.serialize = function (parent) {
  36676. return _super.prototype._serialize.call(this, {
  36677. name: "SwitchBooleanAction",
  36678. properties: [
  36679. BABYLON.Action._GetTargetProperty(this._target),
  36680. { name: "propertyPath", value: this.propertyPath }
  36681. ]
  36682. }, parent);
  36683. };
  36684. return SwitchBooleanAction;
  36685. }(BABYLON.Action));
  36686. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  36687. var SetStateAction = (function (_super) {
  36688. __extends(SetStateAction, _super);
  36689. function SetStateAction(triggerOptions, target, value, condition) {
  36690. var _this = _super.call(this, triggerOptions, condition) || this;
  36691. _this.value = value;
  36692. _this._target = target;
  36693. return _this;
  36694. }
  36695. SetStateAction.prototype.execute = function () {
  36696. this._target.state = this.value;
  36697. };
  36698. SetStateAction.prototype.serialize = function (parent) {
  36699. return _super.prototype._serialize.call(this, {
  36700. name: "SetStateAction",
  36701. properties: [
  36702. BABYLON.Action._GetTargetProperty(this._target),
  36703. { name: "value", value: this.value }
  36704. ]
  36705. }, parent);
  36706. };
  36707. return SetStateAction;
  36708. }(BABYLON.Action));
  36709. BABYLON.SetStateAction = SetStateAction;
  36710. var SetValueAction = (function (_super) {
  36711. __extends(SetValueAction, _super);
  36712. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  36713. var _this = _super.call(this, triggerOptions, condition) || this;
  36714. _this.propertyPath = propertyPath;
  36715. _this.value = value;
  36716. _this._target = _this._effectiveTarget = target;
  36717. return _this;
  36718. }
  36719. SetValueAction.prototype._prepare = function () {
  36720. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  36721. this._property = this._getProperty(this.propertyPath);
  36722. };
  36723. SetValueAction.prototype.execute = function () {
  36724. this._effectiveTarget[this._property] = this.value;
  36725. if (this._target.markAsDirty) {
  36726. this._target.markAsDirty(this._property);
  36727. }
  36728. };
  36729. SetValueAction.prototype.serialize = function (parent) {
  36730. return _super.prototype._serialize.call(this, {
  36731. name: "SetValueAction",
  36732. properties: [
  36733. BABYLON.Action._GetTargetProperty(this._target),
  36734. { name: "propertyPath", value: this.propertyPath },
  36735. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  36736. ]
  36737. }, parent);
  36738. };
  36739. return SetValueAction;
  36740. }(BABYLON.Action));
  36741. BABYLON.SetValueAction = SetValueAction;
  36742. var IncrementValueAction = (function (_super) {
  36743. __extends(IncrementValueAction, _super);
  36744. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  36745. var _this = _super.call(this, triggerOptions, condition) || this;
  36746. _this.propertyPath = propertyPath;
  36747. _this.value = value;
  36748. _this._target = _this._effectiveTarget = target;
  36749. return _this;
  36750. }
  36751. IncrementValueAction.prototype._prepare = function () {
  36752. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  36753. this._property = this._getProperty(this.propertyPath);
  36754. if (typeof this._effectiveTarget[this._property] !== "number") {
  36755. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  36756. }
  36757. };
  36758. IncrementValueAction.prototype.execute = function () {
  36759. this._effectiveTarget[this._property] += this.value;
  36760. if (this._target.markAsDirty) {
  36761. this._target.markAsDirty(this._property);
  36762. }
  36763. };
  36764. IncrementValueAction.prototype.serialize = function (parent) {
  36765. return _super.prototype._serialize.call(this, {
  36766. name: "IncrementValueAction",
  36767. properties: [
  36768. BABYLON.Action._GetTargetProperty(this._target),
  36769. { name: "propertyPath", value: this.propertyPath },
  36770. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  36771. ]
  36772. }, parent);
  36773. };
  36774. return IncrementValueAction;
  36775. }(BABYLON.Action));
  36776. BABYLON.IncrementValueAction = IncrementValueAction;
  36777. var PlayAnimationAction = (function (_super) {
  36778. __extends(PlayAnimationAction, _super);
  36779. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  36780. var _this = _super.call(this, triggerOptions, condition) || this;
  36781. _this.from = from;
  36782. _this.to = to;
  36783. _this.loop = loop;
  36784. _this._target = target;
  36785. return _this;
  36786. }
  36787. PlayAnimationAction.prototype._prepare = function () {
  36788. };
  36789. PlayAnimationAction.prototype.execute = function () {
  36790. var scene = this._actionManager.getScene();
  36791. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  36792. };
  36793. PlayAnimationAction.prototype.serialize = function (parent) {
  36794. return _super.prototype._serialize.call(this, {
  36795. name: "PlayAnimationAction",
  36796. properties: [
  36797. BABYLON.Action._GetTargetProperty(this._target),
  36798. { name: "from", value: String(this.from) },
  36799. { name: "to", value: String(this.to) },
  36800. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  36801. ]
  36802. }, parent);
  36803. };
  36804. return PlayAnimationAction;
  36805. }(BABYLON.Action));
  36806. BABYLON.PlayAnimationAction = PlayAnimationAction;
  36807. var StopAnimationAction = (function (_super) {
  36808. __extends(StopAnimationAction, _super);
  36809. function StopAnimationAction(triggerOptions, target, condition) {
  36810. var _this = _super.call(this, triggerOptions, condition) || this;
  36811. _this._target = target;
  36812. return _this;
  36813. }
  36814. StopAnimationAction.prototype._prepare = function () {
  36815. };
  36816. StopAnimationAction.prototype.execute = function () {
  36817. var scene = this._actionManager.getScene();
  36818. scene.stopAnimation(this._target);
  36819. };
  36820. StopAnimationAction.prototype.serialize = function (parent) {
  36821. return _super.prototype._serialize.call(this, {
  36822. name: "StopAnimationAction",
  36823. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  36824. }, parent);
  36825. };
  36826. return StopAnimationAction;
  36827. }(BABYLON.Action));
  36828. BABYLON.StopAnimationAction = StopAnimationAction;
  36829. var DoNothingAction = (function (_super) {
  36830. __extends(DoNothingAction, _super);
  36831. function DoNothingAction(triggerOptions, condition) {
  36832. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  36833. return _super.call(this, triggerOptions, condition) || this;
  36834. }
  36835. DoNothingAction.prototype.execute = function () {
  36836. };
  36837. DoNothingAction.prototype.serialize = function (parent) {
  36838. return _super.prototype._serialize.call(this, {
  36839. name: "DoNothingAction",
  36840. properties: []
  36841. }, parent);
  36842. };
  36843. return DoNothingAction;
  36844. }(BABYLON.Action));
  36845. BABYLON.DoNothingAction = DoNothingAction;
  36846. var CombineAction = (function (_super) {
  36847. __extends(CombineAction, _super);
  36848. function CombineAction(triggerOptions, children, condition) {
  36849. var _this = _super.call(this, triggerOptions, condition) || this;
  36850. _this.children = children;
  36851. return _this;
  36852. }
  36853. CombineAction.prototype._prepare = function () {
  36854. for (var index = 0; index < this.children.length; index++) {
  36855. this.children[index]._actionManager = this._actionManager;
  36856. this.children[index]._prepare();
  36857. }
  36858. };
  36859. CombineAction.prototype.execute = function (evt) {
  36860. for (var index = 0; index < this.children.length; index++) {
  36861. this.children[index].execute(evt);
  36862. }
  36863. };
  36864. CombineAction.prototype.serialize = function (parent) {
  36865. var serializationObject = _super.prototype._serialize.call(this, {
  36866. name: "CombineAction",
  36867. properties: [],
  36868. combine: []
  36869. }, parent);
  36870. for (var i = 0; i < this.children.length; i++) {
  36871. serializationObject.combine.push(this.children[i].serialize(null));
  36872. }
  36873. return serializationObject;
  36874. };
  36875. return CombineAction;
  36876. }(BABYLON.Action));
  36877. BABYLON.CombineAction = CombineAction;
  36878. var ExecuteCodeAction = (function (_super) {
  36879. __extends(ExecuteCodeAction, _super);
  36880. function ExecuteCodeAction(triggerOptions, func, condition) {
  36881. var _this = _super.call(this, triggerOptions, condition) || this;
  36882. _this.func = func;
  36883. return _this;
  36884. }
  36885. ExecuteCodeAction.prototype.execute = function (evt) {
  36886. this.func(evt);
  36887. };
  36888. return ExecuteCodeAction;
  36889. }(BABYLON.Action));
  36890. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  36891. var SetParentAction = (function (_super) {
  36892. __extends(SetParentAction, _super);
  36893. function SetParentAction(triggerOptions, target, parent, condition) {
  36894. var _this = _super.call(this, triggerOptions, condition) || this;
  36895. _this._target = target;
  36896. _this._parent = parent;
  36897. return _this;
  36898. }
  36899. SetParentAction.prototype._prepare = function () {
  36900. };
  36901. SetParentAction.prototype.execute = function () {
  36902. if (this._target.parent === this._parent) {
  36903. return;
  36904. }
  36905. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  36906. invertParentWorldMatrix.invert();
  36907. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  36908. this._target.parent = this._parent;
  36909. };
  36910. SetParentAction.prototype.serialize = function (parent) {
  36911. return _super.prototype._serialize.call(this, {
  36912. name: "SetParentAction",
  36913. properties: [
  36914. BABYLON.Action._GetTargetProperty(this._target),
  36915. BABYLON.Action._GetTargetProperty(this._parent),
  36916. ]
  36917. }, parent);
  36918. };
  36919. return SetParentAction;
  36920. }(BABYLON.Action));
  36921. BABYLON.SetParentAction = SetParentAction;
  36922. var PlaySoundAction = (function (_super) {
  36923. __extends(PlaySoundAction, _super);
  36924. function PlaySoundAction(triggerOptions, sound, condition) {
  36925. var _this = _super.call(this, triggerOptions, condition) || this;
  36926. _this._sound = sound;
  36927. return _this;
  36928. }
  36929. PlaySoundAction.prototype._prepare = function () {
  36930. };
  36931. PlaySoundAction.prototype.execute = function () {
  36932. if (this._sound !== undefined)
  36933. this._sound.play();
  36934. };
  36935. PlaySoundAction.prototype.serialize = function (parent) {
  36936. return _super.prototype._serialize.call(this, {
  36937. name: "PlaySoundAction",
  36938. properties: [{ name: "sound", value: this._sound.name }]
  36939. }, parent);
  36940. };
  36941. return PlaySoundAction;
  36942. }(BABYLON.Action));
  36943. BABYLON.PlaySoundAction = PlaySoundAction;
  36944. var StopSoundAction = (function (_super) {
  36945. __extends(StopSoundAction, _super);
  36946. function StopSoundAction(triggerOptions, sound, condition) {
  36947. var _this = _super.call(this, triggerOptions, condition) || this;
  36948. _this._sound = sound;
  36949. return _this;
  36950. }
  36951. StopSoundAction.prototype._prepare = function () {
  36952. };
  36953. StopSoundAction.prototype.execute = function () {
  36954. if (this._sound !== undefined)
  36955. this._sound.stop();
  36956. };
  36957. StopSoundAction.prototype.serialize = function (parent) {
  36958. return _super.prototype._serialize.call(this, {
  36959. name: "StopSoundAction",
  36960. properties: [{ name: "sound", value: this._sound.name }]
  36961. }, parent);
  36962. };
  36963. return StopSoundAction;
  36964. }(BABYLON.Action));
  36965. BABYLON.StopSoundAction = StopSoundAction;
  36966. })(BABYLON || (BABYLON = {}));
  36967. //# sourceMappingURL=babylon.directActions.js.map
  36968. var BABYLON;
  36969. (function (BABYLON) {
  36970. var Geometry = (function () {
  36971. function Geometry(id, scene, vertexData, updatable, mesh) {
  36972. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  36973. this._totalVertices = 0;
  36974. this._isDisposed = false;
  36975. this.id = id;
  36976. this._engine = scene.getEngine();
  36977. this._meshes = [];
  36978. this._scene = scene;
  36979. //Init vertex buffer cache
  36980. this._vertexBuffers = {};
  36981. this._indices = [];
  36982. // vertexData
  36983. if (vertexData) {
  36984. this.setAllVerticesData(vertexData, updatable);
  36985. }
  36986. else {
  36987. this._totalVertices = 0;
  36988. this._indices = [];
  36989. }
  36990. if (this._engine.getCaps().vertexArrayObject) {
  36991. this._vertexArrayObjects = {};
  36992. }
  36993. // applyToMesh
  36994. if (mesh) {
  36995. if (mesh instanceof BABYLON.LinesMesh) {
  36996. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  36997. this.updateExtend();
  36998. }
  36999. this.applyToMesh(mesh);
  37000. mesh.computeWorldMatrix(true);
  37001. }
  37002. }
  37003. Object.defineProperty(Geometry.prototype, "boundingBias", {
  37004. /**
  37005. * 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
  37006. * @returns The Bias Vector
  37007. */
  37008. get: function () {
  37009. return this._boundingBias;
  37010. },
  37011. set: function (value) {
  37012. if (this._boundingBias && this._boundingBias.equals(value)) {
  37013. return;
  37014. }
  37015. this._boundingBias = value.clone();
  37016. this.updateBoundingInfo(true, null);
  37017. },
  37018. enumerable: true,
  37019. configurable: true
  37020. });
  37021. Object.defineProperty(Geometry.prototype, "extend", {
  37022. get: function () {
  37023. return this._extend;
  37024. },
  37025. enumerable: true,
  37026. configurable: true
  37027. });
  37028. Geometry.prototype.getScene = function () {
  37029. return this._scene;
  37030. };
  37031. Geometry.prototype.getEngine = function () {
  37032. return this._engine;
  37033. };
  37034. Geometry.prototype.isReady = function () {
  37035. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  37036. };
  37037. Object.defineProperty(Geometry.prototype, "doNotSerialize", {
  37038. get: function () {
  37039. for (var index = 0; index < this._meshes.length; index++) {
  37040. if (!this._meshes[index].doNotSerialize) {
  37041. return false;
  37042. }
  37043. }
  37044. return true;
  37045. },
  37046. enumerable: true,
  37047. configurable: true
  37048. });
  37049. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  37050. vertexData.applyToGeometry(this, updatable);
  37051. this.notifyUpdate();
  37052. };
  37053. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  37054. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  37055. this.setVerticesBuffer(buffer);
  37056. };
  37057. Geometry.prototype.setVerticesBuffer = function (buffer) {
  37058. var kind = buffer.getKind();
  37059. if (this._vertexBuffers[kind]) {
  37060. this._vertexBuffers[kind].dispose();
  37061. }
  37062. this._vertexBuffers[kind] = buffer;
  37063. if (kind === BABYLON.VertexBuffer.PositionKind) {
  37064. var data = buffer.getData();
  37065. var stride = buffer.getStrideSize();
  37066. this._totalVertices = data.length / stride;
  37067. this.updateExtend(data, stride);
  37068. var meshes = this._meshes;
  37069. var numOfMeshes = meshes.length;
  37070. for (var index = 0; index < numOfMeshes; index++) {
  37071. var mesh = meshes[index];
  37072. mesh._resetPointsArrayCache();
  37073. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  37074. mesh._createGlobalSubMesh();
  37075. mesh.computeWorldMatrix(true);
  37076. }
  37077. }
  37078. this.notifyUpdate(kind);
  37079. if (this._vertexArrayObjects) {
  37080. this._disposeVertexArrayObjects();
  37081. this._vertexArrayObjects = {}; // Will trigger a rebuild of the VAO if supported
  37082. }
  37083. };
  37084. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  37085. var vertexBuffer = this.getVertexBuffer(kind);
  37086. if (!vertexBuffer) {
  37087. return;
  37088. }
  37089. vertexBuffer.updateDirectly(data, offset);
  37090. this.notifyUpdate(kind);
  37091. };
  37092. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  37093. var vertexBuffer = this.getVertexBuffer(kind);
  37094. if (!vertexBuffer) {
  37095. return;
  37096. }
  37097. vertexBuffer.update(data);
  37098. if (kind === BABYLON.VertexBuffer.PositionKind) {
  37099. var stride = vertexBuffer.getStrideSize();
  37100. this._totalVertices = data.length / stride;
  37101. this.updateBoundingInfo(updateExtends, data);
  37102. }
  37103. this.notifyUpdate(kind);
  37104. };
  37105. Geometry.prototype.updateBoundingInfo = function (updateExtends, data) {
  37106. if (updateExtends) {
  37107. this.updateExtend(data);
  37108. }
  37109. var meshes = this._meshes;
  37110. var numOfMeshes = meshes.length;
  37111. for (var index = 0; index < numOfMeshes; index++) {
  37112. var mesh = meshes[index];
  37113. mesh._resetPointsArrayCache();
  37114. if (updateExtends) {
  37115. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  37116. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  37117. var subMesh = mesh.subMeshes[subIndex];
  37118. subMesh.refreshBoundingInfo();
  37119. }
  37120. }
  37121. }
  37122. };
  37123. Geometry.prototype._bind = function (effect, indexToBind) {
  37124. if (indexToBind === void 0) { indexToBind = undefined; }
  37125. if (indexToBind === undefined) {
  37126. indexToBind = this._indexBuffer;
  37127. }
  37128. if (indexToBind != this._indexBuffer || !this._vertexArrayObjects) {
  37129. this._engine.bindBuffers(this.getVertexBuffers(), indexToBind, effect);
  37130. return;
  37131. }
  37132. // Using VAO
  37133. if (!this._vertexArrayObjects[effect.key]) {
  37134. this._vertexArrayObjects[effect.key] = this._engine.recordVertexArrayObject(this.getVertexBuffers(), indexToBind, effect);
  37135. }
  37136. this._engine.bindVertexArrayObject(this._vertexArrayObjects[effect.key], indexToBind);
  37137. };
  37138. Geometry.prototype.getTotalVertices = function () {
  37139. if (!this.isReady()) {
  37140. return 0;
  37141. }
  37142. return this._totalVertices;
  37143. };
  37144. Geometry.prototype.getVerticesData = function (kind, copyWhenShared) {
  37145. var vertexBuffer = this.getVertexBuffer(kind);
  37146. if (!vertexBuffer) {
  37147. return null;
  37148. }
  37149. var orig = vertexBuffer.getData();
  37150. if (!copyWhenShared || this._meshes.length === 1) {
  37151. return orig;
  37152. }
  37153. else {
  37154. var len = orig.length;
  37155. var copy = [];
  37156. for (var i = 0; i < len; i++) {
  37157. copy.push(orig[i]);
  37158. }
  37159. return copy;
  37160. }
  37161. };
  37162. Geometry.prototype.getVertexBuffer = function (kind) {
  37163. if (!this.isReady()) {
  37164. return null;
  37165. }
  37166. return this._vertexBuffers[kind];
  37167. };
  37168. Geometry.prototype.getVertexBuffers = function () {
  37169. if (!this.isReady()) {
  37170. return null;
  37171. }
  37172. return this._vertexBuffers;
  37173. };
  37174. Geometry.prototype.isVerticesDataPresent = function (kind) {
  37175. if (!this._vertexBuffers) {
  37176. if (this._delayInfo) {
  37177. return this._delayInfo.indexOf(kind) !== -1;
  37178. }
  37179. return false;
  37180. }
  37181. return this._vertexBuffers[kind] !== undefined;
  37182. };
  37183. Geometry.prototype.getVerticesDataKinds = function () {
  37184. var result = [];
  37185. var kind;
  37186. if (!this._vertexBuffers && this._delayInfo) {
  37187. for (kind in this._delayInfo) {
  37188. result.push(kind);
  37189. }
  37190. }
  37191. else {
  37192. for (kind in this._vertexBuffers) {
  37193. result.push(kind);
  37194. }
  37195. }
  37196. return result;
  37197. };
  37198. Geometry.prototype.setIndices = function (indices, totalVertices) {
  37199. if (this._indexBuffer) {
  37200. this._engine._releaseBuffer(this._indexBuffer);
  37201. }
  37202. this._disposeVertexArrayObjects();
  37203. this._indices = indices;
  37204. if (this._meshes.length !== 0 && this._indices) {
  37205. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  37206. }
  37207. if (totalVertices !== undefined) {
  37208. this._totalVertices = totalVertices;
  37209. }
  37210. var meshes = this._meshes;
  37211. var numOfMeshes = meshes.length;
  37212. for (var index = 0; index < numOfMeshes; index++) {
  37213. meshes[index]._createGlobalSubMesh();
  37214. }
  37215. this.notifyUpdate();
  37216. };
  37217. Geometry.prototype.getTotalIndices = function () {
  37218. if (!this.isReady()) {
  37219. return 0;
  37220. }
  37221. return this._indices.length;
  37222. };
  37223. Geometry.prototype.getIndices = function (copyWhenShared) {
  37224. if (!this.isReady()) {
  37225. return null;
  37226. }
  37227. var orig = this._indices;
  37228. if (!copyWhenShared || this._meshes.length === 1) {
  37229. return orig;
  37230. }
  37231. else {
  37232. var len = orig.length;
  37233. var copy = [];
  37234. for (var i = 0; i < len; i++) {
  37235. copy.push(orig[i]);
  37236. }
  37237. return copy;
  37238. }
  37239. };
  37240. Geometry.prototype.getIndexBuffer = function () {
  37241. if (!this.isReady()) {
  37242. return null;
  37243. }
  37244. return this._indexBuffer;
  37245. };
  37246. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  37247. var meshes = this._meshes;
  37248. var index = meshes.indexOf(mesh);
  37249. if (index === -1) {
  37250. return;
  37251. }
  37252. meshes.splice(index, 1);
  37253. mesh._geometry = null;
  37254. if (meshes.length === 0 && shouldDispose) {
  37255. this.dispose();
  37256. }
  37257. };
  37258. Geometry.prototype.applyToMesh = function (mesh) {
  37259. if (mesh._geometry === this) {
  37260. return;
  37261. }
  37262. var previousGeometry = mesh._geometry;
  37263. if (previousGeometry) {
  37264. previousGeometry.releaseForMesh(mesh);
  37265. }
  37266. var meshes = this._meshes;
  37267. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  37268. mesh._geometry = this;
  37269. this._scene.pushGeometry(this);
  37270. meshes.push(mesh);
  37271. if (this.isReady()) {
  37272. this._applyToMesh(mesh);
  37273. }
  37274. else {
  37275. mesh._boundingInfo = this._boundingInfo;
  37276. }
  37277. };
  37278. Geometry.prototype.updateExtend = function (data, stride) {
  37279. if (data === void 0) { data = null; }
  37280. if (!data) {
  37281. data = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind].getData();
  37282. }
  37283. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, stride);
  37284. };
  37285. Geometry.prototype._applyToMesh = function (mesh) {
  37286. var numOfMeshes = this._meshes.length;
  37287. // vertexBuffers
  37288. for (var kind in this._vertexBuffers) {
  37289. if (numOfMeshes === 1) {
  37290. this._vertexBuffers[kind].create();
  37291. }
  37292. this._vertexBuffers[kind].getBuffer().references = numOfMeshes;
  37293. if (kind === BABYLON.VertexBuffer.PositionKind) {
  37294. mesh._resetPointsArrayCache();
  37295. if (!this._extend) {
  37296. this.updateExtend(this._vertexBuffers[kind].getData());
  37297. }
  37298. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  37299. mesh._createGlobalSubMesh();
  37300. //bounding info was just created again, world matrix should be applied again.
  37301. mesh._updateBoundingInfo();
  37302. }
  37303. }
  37304. // indexBuffer
  37305. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  37306. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  37307. }
  37308. if (this._indexBuffer) {
  37309. this._indexBuffer.references = numOfMeshes;
  37310. }
  37311. };
  37312. Geometry.prototype.notifyUpdate = function (kind) {
  37313. if (this.onGeometryUpdated) {
  37314. this.onGeometryUpdated(this, kind);
  37315. }
  37316. };
  37317. Geometry.prototype.load = function (scene, onLoaded) {
  37318. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  37319. return;
  37320. }
  37321. if (this.isReady()) {
  37322. if (onLoaded) {
  37323. onLoaded();
  37324. }
  37325. return;
  37326. }
  37327. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  37328. this._queueLoad(scene, onLoaded);
  37329. };
  37330. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  37331. var _this = this;
  37332. scene._addPendingData(this);
  37333. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  37334. _this._delayLoadingFunction(JSON.parse(data), _this);
  37335. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  37336. _this._delayInfo = [];
  37337. scene._removePendingData(_this);
  37338. var meshes = _this._meshes;
  37339. var numOfMeshes = meshes.length;
  37340. for (var index = 0; index < numOfMeshes; index++) {
  37341. _this._applyToMesh(meshes[index]);
  37342. }
  37343. if (onLoaded) {
  37344. onLoaded();
  37345. }
  37346. }, function () { }, scene.database);
  37347. };
  37348. /**
  37349. * Invert the geometry to move from a right handed system to a left handed one.
  37350. */
  37351. Geometry.prototype.toLeftHanded = function () {
  37352. // Flip faces
  37353. var tIndices = this.getIndices(false);
  37354. if (tIndices != null && tIndices.length > 0) {
  37355. for (var i = 0; i < tIndices.length; i += 3) {
  37356. var tTemp = tIndices[i + 0];
  37357. tIndices[i + 0] = tIndices[i + 2];
  37358. tIndices[i + 2] = tTemp;
  37359. }
  37360. this.setIndices(tIndices);
  37361. }
  37362. // Negate position.z
  37363. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  37364. if (tPositions != null && tPositions.length > 0) {
  37365. for (var i = 0; i < tPositions.length; i += 3) {
  37366. tPositions[i + 2] = -tPositions[i + 2];
  37367. }
  37368. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  37369. }
  37370. // Negate normal.z
  37371. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  37372. if (tNormals != null && tNormals.length > 0) {
  37373. for (var i = 0; i < tNormals.length; i += 3) {
  37374. tNormals[i + 2] = -tNormals[i + 2];
  37375. }
  37376. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  37377. }
  37378. };
  37379. Geometry.prototype.isDisposed = function () {
  37380. return this._isDisposed;
  37381. };
  37382. Geometry.prototype._disposeVertexArrayObjects = function () {
  37383. if (this._vertexArrayObjects) {
  37384. for (var kind in this._vertexArrayObjects) {
  37385. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[kind]);
  37386. }
  37387. this._vertexArrayObjects = {};
  37388. }
  37389. };
  37390. Geometry.prototype.dispose = function () {
  37391. var meshes = this._meshes;
  37392. var numOfMeshes = meshes.length;
  37393. var index;
  37394. for (index = 0; index < numOfMeshes; index++) {
  37395. this.releaseForMesh(meshes[index]);
  37396. }
  37397. this._meshes = [];
  37398. this._disposeVertexArrayObjects();
  37399. for (var kind in this._vertexBuffers) {
  37400. this._vertexBuffers[kind].dispose();
  37401. }
  37402. this._vertexBuffers = {};
  37403. this._totalVertices = 0;
  37404. if (this._indexBuffer) {
  37405. this._engine._releaseBuffer(this._indexBuffer);
  37406. }
  37407. this._indexBuffer = null;
  37408. this._indices = [];
  37409. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  37410. this.delayLoadingFile = null;
  37411. this._delayLoadingFunction = null;
  37412. this._delayInfo = [];
  37413. this._boundingInfo = null;
  37414. this._scene.removeGeometry(this);
  37415. this._isDisposed = true;
  37416. };
  37417. Geometry.prototype.copy = function (id) {
  37418. var vertexData = new BABYLON.VertexData();
  37419. vertexData.indices = [];
  37420. var indices = this.getIndices();
  37421. for (var index = 0; index < indices.length; index++) {
  37422. vertexData.indices.push(indices[index]);
  37423. }
  37424. var updatable = false;
  37425. var stopChecking = false;
  37426. var kind;
  37427. for (kind in this._vertexBuffers) {
  37428. // using slice() to make a copy of the array and not just reference it
  37429. var data = this.getVerticesData(kind);
  37430. if (data instanceof Float32Array) {
  37431. vertexData.set(new Float32Array(data), kind);
  37432. }
  37433. else {
  37434. vertexData.set(data.slice(0), kind);
  37435. }
  37436. if (!stopChecking) {
  37437. updatable = this.getVertexBuffer(kind).isUpdatable();
  37438. stopChecking = !updatable;
  37439. }
  37440. }
  37441. var geometry = new Geometry(id, this._scene, vertexData, updatable, null);
  37442. geometry.delayLoadState = this.delayLoadState;
  37443. geometry.delayLoadingFile = this.delayLoadingFile;
  37444. geometry._delayLoadingFunction = this._delayLoadingFunction;
  37445. for (kind in this._delayInfo) {
  37446. geometry._delayInfo = geometry._delayInfo || [];
  37447. geometry._delayInfo.push(kind);
  37448. }
  37449. // Bounding info
  37450. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  37451. return geometry;
  37452. };
  37453. Geometry.prototype.serialize = function () {
  37454. var serializationObject = {};
  37455. serializationObject.id = this.id;
  37456. if (BABYLON.Tags.HasTags(this)) {
  37457. serializationObject.tags = BABYLON.Tags.GetTags(this);
  37458. }
  37459. return serializationObject;
  37460. };
  37461. Geometry.prototype.serializeVerticeData = function () {
  37462. var serializationObject = this.serialize();
  37463. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  37464. serializationObject.positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  37465. if (this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable) {
  37466. serializationObject.positions._updatable = true;
  37467. }
  37468. }
  37469. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  37470. serializationObject.normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  37471. if (this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable) {
  37472. serializationObject.normals._updatable = true;
  37473. }
  37474. }
  37475. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  37476. serializationObject.uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  37477. if (this.getVertexBuffer(BABYLON.VertexBuffer.UVKind).isUpdatable) {
  37478. serializationObject.uvs._updatable = true;
  37479. }
  37480. }
  37481. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  37482. serializationObject.uv2s = this.getVerticesData(BABYLON.VertexBuffer.UV2Kind);
  37483. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV2Kind).isUpdatable) {
  37484. serializationObject.uv2s._updatable = true;
  37485. }
  37486. }
  37487. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  37488. serializationObject.uv3s = this.getVerticesData(BABYLON.VertexBuffer.UV3Kind);
  37489. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV3Kind).isUpdatable) {
  37490. serializationObject.uv3s._updatable = true;
  37491. }
  37492. }
  37493. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  37494. serializationObject.uv4s = this.getVerticesData(BABYLON.VertexBuffer.UV4Kind);
  37495. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV4Kind).isUpdatable) {
  37496. serializationObject.uv4s._updatable = true;
  37497. }
  37498. }
  37499. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  37500. serializationObject.uv5s = this.getVerticesData(BABYLON.VertexBuffer.UV5Kind);
  37501. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV5Kind).isUpdatable) {
  37502. serializationObject.uv5s._updatable = true;
  37503. }
  37504. }
  37505. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  37506. serializationObject.uv6s = this.getVerticesData(BABYLON.VertexBuffer.UV6Kind);
  37507. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV6Kind).isUpdatable) {
  37508. serializationObject.uv6s._updatable = true;
  37509. }
  37510. }
  37511. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  37512. serializationObject.colors = this.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  37513. if (this.getVertexBuffer(BABYLON.VertexBuffer.ColorKind).isUpdatable) {
  37514. serializationObject.colors._updatable = true;
  37515. }
  37516. }
  37517. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  37518. serializationObject.matricesIndices = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  37519. serializationObject.matricesIndices._isExpanded = true;
  37520. if (this.getVertexBuffer(BABYLON.VertexBuffer.MatricesIndicesKind).isUpdatable) {
  37521. serializationObject.matricesIndices._updatable = true;
  37522. }
  37523. }
  37524. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  37525. serializationObject.matricesWeights = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  37526. if (this.getVertexBuffer(BABYLON.VertexBuffer.MatricesWeightsKind).isUpdatable) {
  37527. serializationObject.matricesWeights._updatable = true;
  37528. }
  37529. }
  37530. serializationObject.indices = this.getIndices();
  37531. return serializationObject;
  37532. };
  37533. // Statics
  37534. Geometry.ExtractFromMesh = function (mesh, id) {
  37535. var geometry = mesh._geometry;
  37536. if (!geometry) {
  37537. return null;
  37538. }
  37539. return geometry.copy(id);
  37540. };
  37541. /**
  37542. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  37543. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  37544. * Be aware Math.random() could cause collisions, but:
  37545. * "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"
  37546. */
  37547. Geometry.RandomId = function () {
  37548. return BABYLON.Tools.RandomId();
  37549. };
  37550. Geometry.ImportGeometry = function (parsedGeometry, mesh) {
  37551. var scene = mesh.getScene();
  37552. // Geometry
  37553. var geometryId = parsedGeometry.geometryId;
  37554. if (geometryId) {
  37555. var geometry = scene.getGeometryByID(geometryId);
  37556. if (geometry) {
  37557. geometry.applyToMesh(mesh);
  37558. }
  37559. }
  37560. else if (parsedGeometry instanceof ArrayBuffer) {
  37561. var binaryInfo = mesh._binaryInfo;
  37562. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  37563. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  37564. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  37565. }
  37566. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  37567. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  37568. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  37569. }
  37570. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  37571. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  37572. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  37573. }
  37574. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  37575. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  37576. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  37577. }
  37578. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  37579. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  37580. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  37581. }
  37582. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  37583. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  37584. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  37585. }
  37586. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  37587. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  37588. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  37589. }
  37590. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  37591. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  37592. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  37593. }
  37594. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  37595. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  37596. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  37597. }
  37598. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  37599. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  37600. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  37601. }
  37602. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  37603. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  37604. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  37605. }
  37606. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  37607. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  37608. mesh.setIndices(indicesData);
  37609. }
  37610. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  37611. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  37612. mesh.subMeshes = [];
  37613. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  37614. var materialIndex = subMeshesData[(i * 5) + 0];
  37615. var verticesStart = subMeshesData[(i * 5) + 1];
  37616. var verticesCount = subMeshesData[(i * 5) + 2];
  37617. var indexStart = subMeshesData[(i * 5) + 3];
  37618. var indexCount = subMeshesData[(i * 5) + 4];
  37619. var subMesh = new BABYLON.SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  37620. }
  37621. }
  37622. }
  37623. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  37624. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, parsedGeometry.positions._updatable);
  37625. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, parsedGeometry.normals._updatable);
  37626. if (parsedGeometry.uvs) {
  37627. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, parsedGeometry.uvs._updatable);
  37628. }
  37629. if (parsedGeometry.uvs2) {
  37630. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, parsedGeometry.uvs2._updatable);
  37631. }
  37632. if (parsedGeometry.uvs3) {
  37633. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, parsedGeometry.uvs3._updatable);
  37634. }
  37635. if (parsedGeometry.uvs4) {
  37636. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, parsedGeometry.uvs4._updatable);
  37637. }
  37638. if (parsedGeometry.uvs5) {
  37639. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, parsedGeometry.uvs5._updatable);
  37640. }
  37641. if (parsedGeometry.uvs6) {
  37642. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, parsedGeometry.uvs6._updatable);
  37643. }
  37644. if (parsedGeometry.colors) {
  37645. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), parsedGeometry.colors._updatable);
  37646. }
  37647. if (parsedGeometry.matricesIndices) {
  37648. if (!parsedGeometry.matricesIndices._isExpanded) {
  37649. var floatIndices = [];
  37650. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  37651. var matricesIndex = parsedGeometry.matricesIndices[i];
  37652. floatIndices.push(matricesIndex & 0x000000FF);
  37653. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  37654. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  37655. floatIndices.push(matricesIndex >> 24);
  37656. }
  37657. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, parsedGeometry.matricesIndices._updatable);
  37658. }
  37659. else {
  37660. delete parsedGeometry.matricesIndices._isExpanded;
  37661. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, parsedGeometry.matricesIndices._updatable);
  37662. }
  37663. }
  37664. if (parsedGeometry.matricesIndicesExtra) {
  37665. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  37666. var floatIndices = [];
  37667. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  37668. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  37669. floatIndices.push(matricesIndex & 0x000000FF);
  37670. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  37671. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  37672. floatIndices.push(matricesIndex >> 24);
  37673. }
  37674. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, parsedGeometry.matricesIndicesExtra._updatable);
  37675. }
  37676. else {
  37677. delete parsedGeometry.matricesIndices._isExpanded;
  37678. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, parsedGeometry.matricesIndicesExtra._updatable);
  37679. }
  37680. }
  37681. if (parsedGeometry.matricesWeights) {
  37682. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, parsedGeometry.matricesWeights._updatable);
  37683. }
  37684. if (parsedGeometry.matricesWeightsExtra) {
  37685. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, parsedGeometry.matricesWeights._updatable);
  37686. }
  37687. mesh.setIndices(parsedGeometry.indices);
  37688. }
  37689. // SubMeshes
  37690. if (parsedGeometry.subMeshes) {
  37691. mesh.subMeshes = [];
  37692. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  37693. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  37694. var subMesh = new BABYLON.SubMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  37695. }
  37696. }
  37697. // Flat shading
  37698. if (mesh._shouldGenerateFlatShading) {
  37699. mesh.convertToFlatShadedMesh();
  37700. delete mesh._shouldGenerateFlatShading;
  37701. }
  37702. // Update
  37703. mesh.computeWorldMatrix(true);
  37704. // Octree
  37705. if (scene['_selectionOctree']) {
  37706. scene['_selectionOctree'].addMesh(mesh);
  37707. }
  37708. };
  37709. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  37710. if (scene.getGeometryByID(parsedVertexData.id)) {
  37711. return null; // null since geometry could be something else than a box...
  37712. }
  37713. var geometry = new Geometry(parsedVertexData.id, scene);
  37714. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  37715. if (parsedVertexData.delayLoadingFile) {
  37716. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  37717. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  37718. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  37719. geometry._delayInfo = [];
  37720. if (parsedVertexData.hasUVs) {
  37721. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  37722. }
  37723. if (parsedVertexData.hasUVs2) {
  37724. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  37725. }
  37726. if (parsedVertexData.hasUVs3) {
  37727. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  37728. }
  37729. if (parsedVertexData.hasUVs4) {
  37730. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  37731. }
  37732. if (parsedVertexData.hasUVs5) {
  37733. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  37734. }
  37735. if (parsedVertexData.hasUVs6) {
  37736. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  37737. }
  37738. if (parsedVertexData.hasColors) {
  37739. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  37740. }
  37741. if (parsedVertexData.hasMatricesIndices) {
  37742. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  37743. }
  37744. if (parsedVertexData.hasMatricesWeights) {
  37745. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  37746. }
  37747. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  37748. }
  37749. else {
  37750. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  37751. }
  37752. scene.pushGeometry(geometry, true);
  37753. return geometry;
  37754. };
  37755. return Geometry;
  37756. }());
  37757. BABYLON.Geometry = Geometry;
  37758. /////// Primitives //////////////////////////////////////////////
  37759. (function (Geometry) {
  37760. var Primitives;
  37761. (function (Primitives) {
  37762. /// Abstract class
  37763. var _Primitive = (function (_super) {
  37764. __extends(_Primitive, _super);
  37765. function _Primitive(id, scene, _canBeRegenerated, mesh) {
  37766. var _this = _super.call(this, id, scene, null, false, mesh) || this;
  37767. _this._canBeRegenerated = _canBeRegenerated;
  37768. _this._beingRegenerated = true;
  37769. _this.regenerate();
  37770. _this._beingRegenerated = false;
  37771. return _this;
  37772. }
  37773. _Primitive.prototype.canBeRegenerated = function () {
  37774. return this._canBeRegenerated;
  37775. };
  37776. _Primitive.prototype.regenerate = function () {
  37777. if (!this._canBeRegenerated) {
  37778. return;
  37779. }
  37780. this._beingRegenerated = true;
  37781. this.setAllVerticesData(this._regenerateVertexData(), false);
  37782. this._beingRegenerated = false;
  37783. };
  37784. _Primitive.prototype.asNewGeometry = function (id) {
  37785. return _super.prototype.copy.call(this, id);
  37786. };
  37787. // overrides
  37788. _Primitive.prototype.setAllVerticesData = function (vertexData, updatable) {
  37789. if (!this._beingRegenerated) {
  37790. return;
  37791. }
  37792. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  37793. };
  37794. _Primitive.prototype.setVerticesData = function (kind, data, updatable) {
  37795. if (!this._beingRegenerated) {
  37796. return;
  37797. }
  37798. _super.prototype.setVerticesData.call(this, kind, data, false);
  37799. };
  37800. // to override
  37801. // protected
  37802. _Primitive.prototype._regenerateVertexData = function () {
  37803. throw new Error("Abstract method");
  37804. };
  37805. _Primitive.prototype.copy = function (id) {
  37806. throw new Error("Must be overriden in sub-classes.");
  37807. };
  37808. _Primitive.prototype.serialize = function () {
  37809. var serializationObject = _super.prototype.serialize.call(this);
  37810. serializationObject.canBeRegenerated = this.canBeRegenerated();
  37811. return serializationObject;
  37812. };
  37813. return _Primitive;
  37814. }(Geometry));
  37815. Primitives._Primitive = _Primitive;
  37816. var Ribbon = (function (_super) {
  37817. __extends(Ribbon, _super);
  37818. // Members
  37819. function Ribbon(id, scene, pathArray, closeArray, closePath, offset, canBeRegenerated, mesh, side) {
  37820. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  37821. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  37822. _this.pathArray = pathArray;
  37823. _this.closeArray = closeArray;
  37824. _this.closePath = closePath;
  37825. _this.offset = offset;
  37826. _this.side = side;
  37827. return _this;
  37828. }
  37829. Ribbon.prototype._regenerateVertexData = function () {
  37830. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  37831. };
  37832. Ribbon.prototype.copy = function (id) {
  37833. return new Ribbon(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), null, this.side);
  37834. };
  37835. return Ribbon;
  37836. }(_Primitive));
  37837. Primitives.Ribbon = Ribbon;
  37838. var Box = (function (_super) {
  37839. __extends(Box, _super);
  37840. // Members
  37841. function Box(id, scene, size, canBeRegenerated, mesh, side) {
  37842. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  37843. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  37844. _this.size = size;
  37845. _this.side = side;
  37846. return _this;
  37847. }
  37848. Box.prototype._regenerateVertexData = function () {
  37849. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  37850. };
  37851. Box.prototype.copy = function (id) {
  37852. return new Box(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  37853. };
  37854. Box.prototype.serialize = function () {
  37855. var serializationObject = _super.prototype.serialize.call(this);
  37856. serializationObject.size = this.size;
  37857. return serializationObject;
  37858. };
  37859. Box.Parse = function (parsedBox, scene) {
  37860. if (scene.getGeometryByID(parsedBox.id)) {
  37861. return null; // null since geometry could be something else than a box...
  37862. }
  37863. var box = new Geometry.Primitives.Box(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  37864. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  37865. scene.pushGeometry(box, true);
  37866. return box;
  37867. };
  37868. return Box;
  37869. }(_Primitive));
  37870. Primitives.Box = Box;
  37871. var Sphere = (function (_super) {
  37872. __extends(Sphere, _super);
  37873. function Sphere(id, scene, segments, diameter, canBeRegenerated, mesh, side) {
  37874. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  37875. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  37876. _this.segments = segments;
  37877. _this.diameter = diameter;
  37878. _this.side = side;
  37879. return _this;
  37880. }
  37881. Sphere.prototype._regenerateVertexData = function () {
  37882. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  37883. };
  37884. Sphere.prototype.copy = function (id) {
  37885. return new Sphere(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  37886. };
  37887. Sphere.prototype.serialize = function () {
  37888. var serializationObject = _super.prototype.serialize.call(this);
  37889. serializationObject.segments = this.segments;
  37890. serializationObject.diameter = this.diameter;
  37891. return serializationObject;
  37892. };
  37893. Sphere.Parse = function (parsedSphere, scene) {
  37894. if (scene.getGeometryByID(parsedSphere.id)) {
  37895. return null; // null since geometry could be something else than a sphere...
  37896. }
  37897. var sphere = new Geometry.Primitives.Sphere(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  37898. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  37899. scene.pushGeometry(sphere, true);
  37900. return sphere;
  37901. };
  37902. return Sphere;
  37903. }(_Primitive));
  37904. Primitives.Sphere = Sphere;
  37905. var Disc = (function (_super) {
  37906. __extends(Disc, _super);
  37907. // Members
  37908. function Disc(id, scene, radius, tessellation, canBeRegenerated, mesh, side) {
  37909. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  37910. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  37911. _this.radius = radius;
  37912. _this.tessellation = tessellation;
  37913. _this.side = side;
  37914. return _this;
  37915. }
  37916. Disc.prototype._regenerateVertexData = function () {
  37917. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  37918. };
  37919. Disc.prototype.copy = function (id) {
  37920. return new Disc(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  37921. };
  37922. return Disc;
  37923. }(_Primitive));
  37924. Primitives.Disc = Disc;
  37925. var Cylinder = (function (_super) {
  37926. __extends(Cylinder, _super);
  37927. function Cylinder(id, scene, height, diameterTop, diameterBottom, tessellation, subdivisions, canBeRegenerated, mesh, side) {
  37928. if (subdivisions === void 0) { subdivisions = 1; }
  37929. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  37930. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  37931. _this.height = height;
  37932. _this.diameterTop = diameterTop;
  37933. _this.diameterBottom = diameterBottom;
  37934. _this.tessellation = tessellation;
  37935. _this.subdivisions = subdivisions;
  37936. _this.side = side;
  37937. return _this;
  37938. }
  37939. Cylinder.prototype._regenerateVertexData = function () {
  37940. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  37941. };
  37942. Cylinder.prototype.copy = function (id) {
  37943. return new Cylinder(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  37944. };
  37945. Cylinder.prototype.serialize = function () {
  37946. var serializationObject = _super.prototype.serialize.call(this);
  37947. serializationObject.height = this.height;
  37948. serializationObject.diameterTop = this.diameterTop;
  37949. serializationObject.diameterBottom = this.diameterBottom;
  37950. serializationObject.tessellation = this.tessellation;
  37951. return serializationObject;
  37952. };
  37953. Cylinder.Parse = function (parsedCylinder, scene) {
  37954. if (scene.getGeometryByID(parsedCylinder.id)) {
  37955. return null; // null since geometry could be something else than a cylinder...
  37956. }
  37957. var cylinder = new Geometry.Primitives.Cylinder(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  37958. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  37959. scene.pushGeometry(cylinder, true);
  37960. return cylinder;
  37961. };
  37962. return Cylinder;
  37963. }(_Primitive));
  37964. Primitives.Cylinder = Cylinder;
  37965. var Torus = (function (_super) {
  37966. __extends(Torus, _super);
  37967. function Torus(id, scene, diameter, thickness, tessellation, canBeRegenerated, mesh, side) {
  37968. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  37969. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  37970. _this.diameter = diameter;
  37971. _this.thickness = thickness;
  37972. _this.tessellation = tessellation;
  37973. _this.side = side;
  37974. return _this;
  37975. }
  37976. Torus.prototype._regenerateVertexData = function () {
  37977. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  37978. };
  37979. Torus.prototype.copy = function (id) {
  37980. return new Torus(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  37981. };
  37982. Torus.prototype.serialize = function () {
  37983. var serializationObject = _super.prototype.serialize.call(this);
  37984. serializationObject.diameter = this.diameter;
  37985. serializationObject.thickness = this.thickness;
  37986. serializationObject.tessellation = this.tessellation;
  37987. return serializationObject;
  37988. };
  37989. Torus.Parse = function (parsedTorus, scene) {
  37990. if (scene.getGeometryByID(parsedTorus.id)) {
  37991. return null; // null since geometry could be something else than a torus...
  37992. }
  37993. var torus = new Geometry.Primitives.Torus(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  37994. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  37995. scene.pushGeometry(torus, true);
  37996. return torus;
  37997. };
  37998. return Torus;
  37999. }(_Primitive));
  38000. Primitives.Torus = Torus;
  38001. var Ground = (function (_super) {
  38002. __extends(Ground, _super);
  38003. function Ground(id, scene, width, height, subdivisions, canBeRegenerated, mesh) {
  38004. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  38005. _this.width = width;
  38006. _this.height = height;
  38007. _this.subdivisions = subdivisions;
  38008. return _this;
  38009. }
  38010. Ground.prototype._regenerateVertexData = function () {
  38011. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  38012. };
  38013. Ground.prototype.copy = function (id) {
  38014. return new Ground(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  38015. };
  38016. Ground.prototype.serialize = function () {
  38017. var serializationObject = _super.prototype.serialize.call(this);
  38018. serializationObject.width = this.width;
  38019. serializationObject.height = this.height;
  38020. serializationObject.subdivisions = this.subdivisions;
  38021. return serializationObject;
  38022. };
  38023. Ground.Parse = function (parsedGround, scene) {
  38024. if (scene.getGeometryByID(parsedGround.id)) {
  38025. return null; // null since geometry could be something else than a ground...
  38026. }
  38027. var ground = new Geometry.Primitives.Ground(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  38028. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  38029. scene.pushGeometry(ground, true);
  38030. return ground;
  38031. };
  38032. return Ground;
  38033. }(_Primitive));
  38034. Primitives.Ground = Ground;
  38035. var TiledGround = (function (_super) {
  38036. __extends(TiledGround, _super);
  38037. function TiledGround(id, scene, xmin, zmin, xmax, zmax, subdivisions, precision, canBeRegenerated, mesh) {
  38038. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  38039. _this.xmin = xmin;
  38040. _this.zmin = zmin;
  38041. _this.xmax = xmax;
  38042. _this.zmax = zmax;
  38043. _this.subdivisions = subdivisions;
  38044. _this.precision = precision;
  38045. return _this;
  38046. }
  38047. TiledGround.prototype._regenerateVertexData = function () {
  38048. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  38049. };
  38050. TiledGround.prototype.copy = function (id) {
  38051. return new TiledGround(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  38052. };
  38053. return TiledGround;
  38054. }(_Primitive));
  38055. Primitives.TiledGround = TiledGround;
  38056. var Plane = (function (_super) {
  38057. __extends(Plane, _super);
  38058. function Plane(id, scene, size, canBeRegenerated, mesh, side) {
  38059. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  38060. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  38061. _this.size = size;
  38062. _this.side = side;
  38063. return _this;
  38064. }
  38065. Plane.prototype._regenerateVertexData = function () {
  38066. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  38067. };
  38068. Plane.prototype.copy = function (id) {
  38069. return new Plane(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  38070. };
  38071. Plane.prototype.serialize = function () {
  38072. var serializationObject = _super.prototype.serialize.call(this);
  38073. serializationObject.size = this.size;
  38074. return serializationObject;
  38075. };
  38076. Plane.Parse = function (parsedPlane, scene) {
  38077. if (scene.getGeometryByID(parsedPlane.id)) {
  38078. return null; // null since geometry could be something else than a ground...
  38079. }
  38080. var plane = new Geometry.Primitives.Plane(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  38081. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  38082. scene.pushGeometry(plane, true);
  38083. return plane;
  38084. };
  38085. return Plane;
  38086. }(_Primitive));
  38087. Primitives.Plane = Plane;
  38088. var TorusKnot = (function (_super) {
  38089. __extends(TorusKnot, _super);
  38090. function TorusKnot(id, scene, radius, tube, radialSegments, tubularSegments, p, q, canBeRegenerated, mesh, side) {
  38091. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  38092. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  38093. _this.radius = radius;
  38094. _this.tube = tube;
  38095. _this.radialSegments = radialSegments;
  38096. _this.tubularSegments = tubularSegments;
  38097. _this.p = p;
  38098. _this.q = q;
  38099. _this.side = side;
  38100. return _this;
  38101. }
  38102. TorusKnot.prototype._regenerateVertexData = function () {
  38103. 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 });
  38104. };
  38105. TorusKnot.prototype.copy = function (id) {
  38106. return new TorusKnot(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  38107. };
  38108. TorusKnot.prototype.serialize = function () {
  38109. var serializationObject = _super.prototype.serialize.call(this);
  38110. serializationObject.radius = this.radius;
  38111. serializationObject.tube = this.tube;
  38112. serializationObject.radialSegments = this.radialSegments;
  38113. serializationObject.tubularSegments = this.tubularSegments;
  38114. serializationObject.p = this.p;
  38115. serializationObject.q = this.q;
  38116. return serializationObject;
  38117. };
  38118. ;
  38119. TorusKnot.Parse = function (parsedTorusKnot, scene) {
  38120. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  38121. return null; // null since geometry could be something else than a ground...
  38122. }
  38123. var torusKnot = new Geometry.Primitives.TorusKnot(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  38124. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  38125. scene.pushGeometry(torusKnot, true);
  38126. return torusKnot;
  38127. };
  38128. return TorusKnot;
  38129. }(_Primitive));
  38130. Primitives.TorusKnot = TorusKnot;
  38131. })(Primitives = Geometry.Primitives || (Geometry.Primitives = {}));
  38132. })(Geometry = BABYLON.Geometry || (BABYLON.Geometry = {}));
  38133. })(BABYLON || (BABYLON = {}));
  38134. //# sourceMappingURL=babylon.geometry.js.map
  38135. var BABYLON;
  38136. (function (BABYLON) {
  38137. var GroundMesh = (function (_super) {
  38138. __extends(GroundMesh, _super);
  38139. function GroundMesh(name, scene) {
  38140. var _this = _super.call(this, name, scene) || this;
  38141. _this.generateOctree = false;
  38142. _this._worldInverse = new BABYLON.Matrix();
  38143. return _this;
  38144. }
  38145. GroundMesh.prototype.getClassName = function () {
  38146. return "GroundMesh";
  38147. };
  38148. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  38149. get: function () {
  38150. return Math.min(this._subdivisionsX, this._subdivisionsY);
  38151. },
  38152. enumerable: true,
  38153. configurable: true
  38154. });
  38155. Object.defineProperty(GroundMesh.prototype, "subdivisionsX", {
  38156. get: function () {
  38157. return this._subdivisionsX;
  38158. },
  38159. enumerable: true,
  38160. configurable: true
  38161. });
  38162. Object.defineProperty(GroundMesh.prototype, "subdivisionsY", {
  38163. get: function () {
  38164. return this._subdivisionsY;
  38165. },
  38166. enumerable: true,
  38167. configurable: true
  38168. });
  38169. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  38170. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  38171. this._subdivisionsX = chunksCount;
  38172. this._subdivisionsY = chunksCount;
  38173. this.subdivide(chunksCount);
  38174. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  38175. };
  38176. /**
  38177. * Returns a height (y) value in the Worl system :
  38178. * the ground altitude at the coordinates (x, z) expressed in the World system.
  38179. * Returns the ground y position if (x, z) are outside the ground surface.
  38180. */
  38181. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  38182. var world = this.getWorldMatrix();
  38183. var invMat = BABYLON.Tmp.Matrix[5];
  38184. world.invertToRef(invMat);
  38185. var tmpVect = BABYLON.Tmp.Vector3[8];
  38186. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, invMat, tmpVect); // transform x,z in the mesh local space
  38187. x = tmpVect.x;
  38188. z = tmpVect.z;
  38189. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  38190. return this.position.y;
  38191. }
  38192. if (!this._heightQuads || this._heightQuads.length == 0) {
  38193. this._initHeightQuads();
  38194. this._computeHeightQuads();
  38195. }
  38196. var facet = this._getFacetAt(x, z);
  38197. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  38198. // return y in the World system
  38199. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0.0, y, 0.0, world, tmpVect);
  38200. return tmpVect.y;
  38201. };
  38202. /**
  38203. * Returns a normalized vector (Vector3) orthogonal to the ground
  38204. * at the ground coordinates (x, z) expressed in the World system.
  38205. * Returns Vector3(0.0, 1.0, 0.0) if (x, z) are outside the ground surface.
  38206. */
  38207. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  38208. var normal = new BABYLON.Vector3(0.0, 1.0, 0.0);
  38209. this.getNormalAtCoordinatesToRef(x, z, normal);
  38210. return normal;
  38211. };
  38212. /**
  38213. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  38214. * at the ground coordinates (x, z) expressed in the World system.
  38215. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  38216. * Returns the GroundMesh.
  38217. */
  38218. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  38219. var world = this.getWorldMatrix();
  38220. var tmpMat = BABYLON.Tmp.Matrix[5];
  38221. world.invertToRef(tmpMat);
  38222. var tmpVect = BABYLON.Tmp.Vector3[8];
  38223. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, tmpMat, tmpVect); // transform x,z in the mesh local space
  38224. x = tmpVect.x;
  38225. z = tmpVect.z;
  38226. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  38227. return this;
  38228. }
  38229. if (!this._heightQuads || this._heightQuads.length == 0) {
  38230. this._initHeightQuads();
  38231. this._computeHeightQuads();
  38232. }
  38233. var facet = this._getFacetAt(x, z);
  38234. world.getRotationMatrixToRef(tmpMat); // just rotates the normals
  38235. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(facet.x, facet.y, facet.z, tmpMat, ref);
  38236. return this;
  38237. };
  38238. /**
  38239. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  38240. * if the ground has been updated.
  38241. * This can be used in the render loop
  38242. */
  38243. GroundMesh.prototype.updateCoordinateHeights = function () {
  38244. if (!this._heightQuads || this._heightQuads.length == 0) {
  38245. this._initHeightQuads();
  38246. }
  38247. this._computeHeightQuads();
  38248. };
  38249. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  38250. GroundMesh.prototype._getFacetAt = function (x, z) {
  38251. // retrieve col and row from x, z coordinates in the ground local system
  38252. var subdivisionsX = this._subdivisionsX;
  38253. var subdivisionsY = this._subdivisionsY;
  38254. var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);
  38255. var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);
  38256. var quad = this._heightQuads[row * this._subdivisionsX + col];
  38257. var facet;
  38258. if (z < quad.slope.x * x + quad.slope.y) {
  38259. facet = quad.facet1;
  38260. }
  38261. else {
  38262. facet = quad.facet2;
  38263. }
  38264. return facet;
  38265. };
  38266. // Creates and populates the heightMap array with "facet" elements :
  38267. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  38268. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  38269. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  38270. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  38271. GroundMesh.prototype._initHeightQuads = function () {
  38272. var subdivisionsX = this._subdivisionsX;
  38273. var subdivisionsY = this._subdivisionsY;
  38274. this._heightQuads = new Array();
  38275. for (var row = 0; row < subdivisionsY; row++) {
  38276. for (var col = 0; col < subdivisionsX; col++) {
  38277. 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) };
  38278. this._heightQuads[row * subdivisionsX + col] = quad;
  38279. }
  38280. }
  38281. };
  38282. // Compute each quad element values and update the the heightMap array :
  38283. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  38284. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  38285. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  38286. GroundMesh.prototype._computeHeightQuads = function () {
  38287. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  38288. var v1 = BABYLON.Tmp.Vector3[3];
  38289. var v2 = BABYLON.Tmp.Vector3[2];
  38290. var v3 = BABYLON.Tmp.Vector3[1];
  38291. var v4 = BABYLON.Tmp.Vector3[0];
  38292. var v1v2 = BABYLON.Tmp.Vector3[4];
  38293. var v1v3 = BABYLON.Tmp.Vector3[5];
  38294. var v1v4 = BABYLON.Tmp.Vector3[6];
  38295. var norm1 = BABYLON.Tmp.Vector3[7];
  38296. var norm2 = BABYLON.Tmp.Vector3[8];
  38297. var i = 0;
  38298. var j = 0;
  38299. var k = 0;
  38300. var cd = 0; // 2D slope coefficient : z = cd * x + h
  38301. var h = 0;
  38302. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  38303. var d2 = 0;
  38304. var subdivisionsX = this._subdivisionsX;
  38305. var subdivisionsY = this._subdivisionsY;
  38306. for (var row = 0; row < subdivisionsY; row++) {
  38307. for (var col = 0; col < subdivisionsX; col++) {
  38308. i = col * 3;
  38309. j = row * (subdivisionsX + 1) * 3;
  38310. k = (row + 1) * (subdivisionsX + 1) * 3;
  38311. v1.x = positions[j + i];
  38312. v1.y = positions[j + i + 1];
  38313. v1.z = positions[j + i + 2];
  38314. v2.x = positions[j + i + 3];
  38315. v2.y = positions[j + i + 4];
  38316. v2.z = positions[j + i + 5];
  38317. v3.x = positions[k + i];
  38318. v3.y = positions[k + i + 1];
  38319. v3.z = positions[k + i + 2];
  38320. v4.x = positions[k + i + 3];
  38321. v4.y = positions[k + i + 4];
  38322. v4.z = positions[k + i + 5];
  38323. // 2D slope V1V4
  38324. cd = (v4.z - v1.z) / (v4.x - v1.x);
  38325. h = v1.z - cd * v1.x; // v1 belongs to the slope
  38326. // facet equations :
  38327. // we compute each facet normal vector
  38328. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  38329. // we compute the value d by applying the equation to v1 which belongs to the plane
  38330. // then we store the facet equation in a Vector4
  38331. v2.subtractToRef(v1, v1v2);
  38332. v3.subtractToRef(v1, v1v3);
  38333. v4.subtractToRef(v1, v1v4);
  38334. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  38335. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  38336. norm1.normalize();
  38337. norm2.normalize();
  38338. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  38339. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  38340. var quad = this._heightQuads[row * subdivisionsX + col];
  38341. quad.slope.copyFromFloats(cd, h);
  38342. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  38343. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  38344. }
  38345. }
  38346. };
  38347. return GroundMesh;
  38348. }(BABYLON.Mesh));
  38349. BABYLON.GroundMesh = GroundMesh;
  38350. })(BABYLON || (BABYLON = {}));
  38351. //# sourceMappingURL=babylon.groundMesh.js.map
  38352. var BABYLON;
  38353. (function (BABYLON) {
  38354. var LinesMesh = (function (_super) {
  38355. __extends(LinesMesh, _super);
  38356. function LinesMesh(name, scene, parent, source, doNotCloneChildren) {
  38357. if (parent === void 0) { parent = null; }
  38358. var _this = _super.call(this, name, scene, parent, source, doNotCloneChildren) || this;
  38359. _this.color = new BABYLON.Color3(1, 1, 1);
  38360. _this.alpha = 1;
  38361. _this._positionBuffer = {};
  38362. if (source) {
  38363. _this.color = source.color.clone();
  38364. _this.alpha = source.alpha;
  38365. }
  38366. _this._intersectionThreshold = 0.1;
  38367. _this._colorShader = new BABYLON.ShaderMaterial("colorShader", scene, "color", {
  38368. attributes: [BABYLON.VertexBuffer.PositionKind],
  38369. uniforms: ["worldViewProjection", "color"],
  38370. needAlphaBlending: true
  38371. });
  38372. _this._positionBuffer[BABYLON.VertexBuffer.PositionKind] = null;
  38373. return _this;
  38374. }
  38375. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  38376. /**
  38377. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  38378. * This margin is expressed in world space coordinates, so its value may vary.
  38379. * Default value is 0.1
  38380. * @returns the intersection Threshold value.
  38381. */
  38382. get: function () {
  38383. return this._intersectionThreshold;
  38384. },
  38385. /**
  38386. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  38387. * This margin is expressed in world space coordinates, so its value may vary.
  38388. * @param value the new threshold to apply
  38389. */
  38390. set: function (value) {
  38391. if (this._intersectionThreshold === value) {
  38392. return;
  38393. }
  38394. this._intersectionThreshold = value;
  38395. if (this.geometry) {
  38396. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  38397. }
  38398. },
  38399. enumerable: true,
  38400. configurable: true
  38401. });
  38402. LinesMesh.prototype.getClassName = function () {
  38403. return "LinesMesh";
  38404. };
  38405. Object.defineProperty(LinesMesh.prototype, "material", {
  38406. get: function () {
  38407. return this._colorShader;
  38408. },
  38409. enumerable: true,
  38410. configurable: true
  38411. });
  38412. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  38413. get: function () {
  38414. return false;
  38415. },
  38416. enumerable: true,
  38417. configurable: true
  38418. });
  38419. LinesMesh.prototype.createInstance = function (name) {
  38420. BABYLON.Tools.Log("LinesMeshes do not support createInstance.");
  38421. return null;
  38422. };
  38423. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  38424. var engine = this.getScene().getEngine();
  38425. this._positionBuffer[BABYLON.VertexBuffer.PositionKind] = this._geometry.getVertexBuffer(BABYLON.VertexBuffer.PositionKind);
  38426. // VBOs
  38427. engine.bindBuffers(this._positionBuffer, this._geometry.getIndexBuffer(), this._colorShader.getEffect());
  38428. // Color
  38429. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  38430. };
  38431. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  38432. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  38433. return;
  38434. }
  38435. var engine = this.getScene().getEngine();
  38436. // Draw order
  38437. engine.draw(false, subMesh.indexStart, subMesh.indexCount);
  38438. };
  38439. LinesMesh.prototype.dispose = function (doNotRecurse) {
  38440. this._colorShader.dispose();
  38441. _super.prototype.dispose.call(this, doNotRecurse);
  38442. };
  38443. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  38444. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  38445. };
  38446. return LinesMesh;
  38447. }(BABYLON.Mesh));
  38448. BABYLON.LinesMesh = LinesMesh;
  38449. })(BABYLON || (BABYLON = {}));
  38450. //# sourceMappingURL=babylon.linesMesh.js.map
  38451. var BABYLON;
  38452. (function (BABYLON) {
  38453. var DefaultLoadingScreen = (function () {
  38454. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  38455. if (_loadingText === void 0) { _loadingText = ""; }
  38456. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  38457. var _this = this;
  38458. this._renderingCanvas = _renderingCanvas;
  38459. this._loadingText = _loadingText;
  38460. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  38461. // Resize
  38462. this._resizeLoadingUI = function () {
  38463. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  38464. _this._loadingDiv.style.position = "absolute";
  38465. _this._loadingDiv.style.left = canvasRect.left + "px";
  38466. _this._loadingDiv.style.top = canvasRect.top + "px";
  38467. _this._loadingDiv.style.width = canvasRect.width + "px";
  38468. _this._loadingDiv.style.height = canvasRect.height + "px";
  38469. };
  38470. }
  38471. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  38472. var _this = this;
  38473. if (this._loadingDiv) {
  38474. // Do not add a loading screen if there is already one
  38475. return;
  38476. }
  38477. this._loadingDiv = document.createElement("div");
  38478. this._loadingDiv.id = "babylonjsLoadingDiv";
  38479. this._loadingDiv.style.opacity = "0";
  38480. this._loadingDiv.style.transition = "opacity 1.5s ease";
  38481. // Loading text
  38482. this._loadingTextDiv = document.createElement("div");
  38483. this._loadingTextDiv.style.position = "absolute";
  38484. this._loadingTextDiv.style.left = "0";
  38485. this._loadingTextDiv.style.top = "50%";
  38486. this._loadingTextDiv.style.marginTop = "80px";
  38487. this._loadingTextDiv.style.width = "100%";
  38488. this._loadingTextDiv.style.height = "20px";
  38489. this._loadingTextDiv.style.fontFamily = "Arial";
  38490. this._loadingTextDiv.style.fontSize = "14px";
  38491. this._loadingTextDiv.style.color = "white";
  38492. this._loadingTextDiv.style.textAlign = "center";
  38493. this._loadingTextDiv.innerHTML = "Loading";
  38494. this._loadingDiv.appendChild(this._loadingTextDiv);
  38495. //set the predefined text
  38496. this._loadingTextDiv.innerHTML = this._loadingText;
  38497. // Loading img
  38498. var imgBack = new Image();
  38499. 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==";
  38500. imgBack.style.position = "absolute";
  38501. imgBack.style.left = "50%";
  38502. imgBack.style.top = "50%";
  38503. imgBack.style.marginLeft = "-50px";
  38504. imgBack.style.marginTop = "-50px";
  38505. imgBack.style.transition = "transform 1.0s ease";
  38506. imgBack.style.webkitTransition = "-webkit-transform 1.0s ease";
  38507. var deg = 360;
  38508. var onTransitionEnd = function () {
  38509. deg += 360;
  38510. imgBack.style.transform = "rotateZ(" + deg + "deg)";
  38511. imgBack.style.webkitTransform = "rotateZ(" + deg + "deg)";
  38512. };
  38513. imgBack.addEventListener("transitionend", onTransitionEnd);
  38514. imgBack.addEventListener("webkitTransitionEnd", onTransitionEnd);
  38515. this._loadingDiv.appendChild(imgBack);
  38516. // front image
  38517. var imgFront = new Image();
  38518. 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=";
  38519. imgFront.style.position = "absolute";
  38520. imgFront.style.left = "50%";
  38521. imgFront.style.top = "50%";
  38522. imgFront.style.marginLeft = "-50px";
  38523. imgFront.style.marginTop = "-50px";
  38524. this._loadingDiv.appendChild(imgFront);
  38525. this._resizeLoadingUI();
  38526. window.addEventListener("resize", this._resizeLoadingUI);
  38527. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  38528. document.body.appendChild(this._loadingDiv);
  38529. setTimeout(function () {
  38530. _this._loadingDiv.style.opacity = "1";
  38531. imgBack.style.transform = "rotateZ(360deg)";
  38532. imgBack.style.webkitTransform = "rotateZ(360deg)";
  38533. }, 0);
  38534. };
  38535. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  38536. var _this = this;
  38537. if (!this._loadingDiv) {
  38538. return;
  38539. }
  38540. var onTransitionEnd = function () {
  38541. if (!_this._loadingDiv) {
  38542. return;
  38543. }
  38544. document.body.removeChild(_this._loadingDiv);
  38545. window.removeEventListener("resize", _this._resizeLoadingUI);
  38546. _this._loadingDiv = null;
  38547. };
  38548. this._loadingDiv.style.opacity = "0";
  38549. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  38550. };
  38551. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  38552. set: function (text) {
  38553. this._loadingText = text;
  38554. if (this._loadingTextDiv) {
  38555. this._loadingTextDiv.innerHTML = this._loadingText;
  38556. }
  38557. },
  38558. enumerable: true,
  38559. configurable: true
  38560. });
  38561. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  38562. get: function () {
  38563. return this._loadingDivBackgroundColor;
  38564. },
  38565. set: function (color) {
  38566. this._loadingDivBackgroundColor = color;
  38567. if (!this._loadingDiv) {
  38568. return;
  38569. }
  38570. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  38571. },
  38572. enumerable: true,
  38573. configurable: true
  38574. });
  38575. return DefaultLoadingScreen;
  38576. }());
  38577. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  38578. })(BABYLON || (BABYLON = {}));
  38579. //# sourceMappingURL=babylon.loadingScreen.js.map
  38580. var BABYLON;
  38581. (function (BABYLON) {
  38582. var AudioEngine = (function () {
  38583. function AudioEngine() {
  38584. this._audioContext = null;
  38585. this._audioContextInitialized = false;
  38586. this.canUseWebAudio = false;
  38587. this.WarnedWebAudioUnsupported = false;
  38588. this.unlocked = false;
  38589. this.isMP3supported = false;
  38590. this.isOGGsupported = false;
  38591. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  38592. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  38593. this.canUseWebAudio = true;
  38594. }
  38595. var audioElem = document.createElement('audio');
  38596. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/, '')) {
  38597. this.isMP3supported = true;
  38598. }
  38599. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) {
  38600. this.isOGGsupported = true;
  38601. }
  38602. if (/iPad|iPhone|iPod/.test(navigator.platform)) {
  38603. this._unlockiOSaudio();
  38604. }
  38605. else {
  38606. this.unlocked = true;
  38607. }
  38608. }
  38609. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  38610. get: function () {
  38611. if (!this._audioContextInitialized) {
  38612. this._initializeAudioContext();
  38613. }
  38614. return this._audioContext;
  38615. },
  38616. enumerable: true,
  38617. configurable: true
  38618. });
  38619. AudioEngine.prototype._unlockiOSaudio = function () {
  38620. var _this = this;
  38621. var unlockaudio = function () {
  38622. var buffer = _this.audioContext.createBuffer(1, 1, 22050);
  38623. var source = _this.audioContext.createBufferSource();
  38624. source.buffer = buffer;
  38625. source.connect(_this.audioContext.destination);
  38626. source.start(0);
  38627. setTimeout(function () {
  38628. if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
  38629. _this.unlocked = true;
  38630. window.removeEventListener('touchend', unlockaudio, false);
  38631. if (_this.onAudioUnlocked) {
  38632. _this.onAudioUnlocked();
  38633. }
  38634. }
  38635. }, 0);
  38636. };
  38637. window.addEventListener('touchend', unlockaudio, false);
  38638. };
  38639. AudioEngine.prototype._initializeAudioContext = function () {
  38640. try {
  38641. if (this.canUseWebAudio) {
  38642. this._audioContext = new AudioContext();
  38643. // create a global volume gain node
  38644. this.masterGain = this._audioContext.createGain();
  38645. this.masterGain.gain.value = 1;
  38646. this.masterGain.connect(this._audioContext.destination);
  38647. this._audioContextInitialized = true;
  38648. }
  38649. }
  38650. catch (e) {
  38651. this.canUseWebAudio = false;
  38652. BABYLON.Tools.Error("Web Audio: " + e.message);
  38653. }
  38654. };
  38655. AudioEngine.prototype.dispose = function () {
  38656. if (this.canUseWebAudio && this._audioContextInitialized) {
  38657. if (this._connectedAnalyser) {
  38658. this._connectedAnalyser.stopDebugCanvas();
  38659. this._connectedAnalyser.dispose();
  38660. this.masterGain.disconnect();
  38661. this.masterGain.connect(this._audioContext.destination);
  38662. this._connectedAnalyser = null;
  38663. }
  38664. this.masterGain.gain.value = 1;
  38665. }
  38666. this.WarnedWebAudioUnsupported = false;
  38667. };
  38668. AudioEngine.prototype.getGlobalVolume = function () {
  38669. if (this.canUseWebAudio && this._audioContextInitialized) {
  38670. return this.masterGain.gain.value;
  38671. }
  38672. else {
  38673. return -1;
  38674. }
  38675. };
  38676. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  38677. if (this.canUseWebAudio && this._audioContextInitialized) {
  38678. this.masterGain.gain.value = newVolume;
  38679. }
  38680. };
  38681. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  38682. if (this._connectedAnalyser) {
  38683. this._connectedAnalyser.stopDebugCanvas();
  38684. }
  38685. if (this.canUseWebAudio && this._audioContextInitialized) {
  38686. this._connectedAnalyser = analyser;
  38687. this.masterGain.disconnect();
  38688. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  38689. }
  38690. };
  38691. return AudioEngine;
  38692. }());
  38693. BABYLON.AudioEngine = AudioEngine;
  38694. })(BABYLON || (BABYLON = {}));
  38695. //# sourceMappingURL=babylon.audioEngine.js.map
  38696. var BABYLON;
  38697. (function (BABYLON) {
  38698. var Sound = (function () {
  38699. /**
  38700. * Create a sound and attach it to a scene
  38701. * @param name Name of your sound
  38702. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  38703. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  38704. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  38705. */
  38706. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  38707. var _this = this;
  38708. this.autoplay = false;
  38709. this.loop = false;
  38710. this.useCustomAttenuation = false;
  38711. this.spatialSound = false;
  38712. this.refDistance = 1;
  38713. this.rolloffFactor = 1;
  38714. this.maxDistance = 100;
  38715. this.distanceModel = "linear";
  38716. this._panningModel = "equalpower";
  38717. this._playbackRate = 1;
  38718. this._streaming = false;
  38719. this._startTime = 0;
  38720. this._startOffset = 0;
  38721. this._position = BABYLON.Vector3.Zero();
  38722. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  38723. this._volume = 1;
  38724. this._isLoaded = false;
  38725. this._isReadyToPlay = false;
  38726. this.isPlaying = false;
  38727. this.isPaused = false;
  38728. this._isDirectional = false;
  38729. // Used if you'd like to create a directional sound.
  38730. // If not set, the sound will be omnidirectional
  38731. this._coneInnerAngle = 360;
  38732. this._coneOuterAngle = 360;
  38733. this._coneOuterGain = 0;
  38734. this._isOutputConnected = false;
  38735. this._urlType = "Unknown";
  38736. this.name = name;
  38737. this._scene = scene;
  38738. this._readyToPlayCallback = readyToPlayCallback;
  38739. // Default custom attenuation function is a linear attenuation
  38740. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  38741. if (currentDistance < maxDistance) {
  38742. return currentVolume * (1 - currentDistance / maxDistance);
  38743. }
  38744. else {
  38745. return 0;
  38746. }
  38747. };
  38748. if (options) {
  38749. this.autoplay = options.autoplay || false;
  38750. this.loop = options.loop || false;
  38751. // if volume === 0, we need another way to check this option
  38752. if (options.volume !== undefined) {
  38753. this._volume = options.volume;
  38754. }
  38755. this.spatialSound = options.spatialSound || false;
  38756. this.maxDistance = options.maxDistance || 100;
  38757. this.useCustomAttenuation = options.useCustomAttenuation || false;
  38758. this.rolloffFactor = options.rolloffFactor || 1;
  38759. this.refDistance = options.refDistance || 1;
  38760. this.distanceModel = options.distanceModel || "linear";
  38761. this._playbackRate = options.playbackRate || 1;
  38762. this._streaming = options.streaming || false;
  38763. }
  38764. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  38765. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  38766. this._soundGain.gain.value = this._volume;
  38767. this._inputAudioNode = this._soundGain;
  38768. this._ouputAudioNode = this._soundGain;
  38769. if (this.spatialSound) {
  38770. this._createSpatialParameters();
  38771. }
  38772. this._scene.mainSoundTrack.AddSound(this);
  38773. var validParameter = true;
  38774. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  38775. if (urlOrArrayBuffer) {
  38776. if (typeof (urlOrArrayBuffer) === "string")
  38777. this._urlType = "String";
  38778. if (Array.isArray(urlOrArrayBuffer))
  38779. this._urlType = "Array";
  38780. if (urlOrArrayBuffer instanceof ArrayBuffer)
  38781. this._urlType = "ArrayBuffer";
  38782. var urls = [];
  38783. var codecSupportedFound = false;
  38784. switch (this._urlType) {
  38785. case "ArrayBuffer":
  38786. if (urlOrArrayBuffer.byteLength > 0) {
  38787. codecSupportedFound = true;
  38788. this._soundLoaded(urlOrArrayBuffer);
  38789. }
  38790. break;
  38791. case "String":
  38792. urls.push(urlOrArrayBuffer);
  38793. case "Array":
  38794. if (urls.length === 0)
  38795. urls = urlOrArrayBuffer;
  38796. // If we found a supported format, we load it immediately and stop the loop
  38797. for (var i = 0; i < urls.length; i++) {
  38798. var url = urls[i];
  38799. if (url.indexOf(".mp3", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isMP3supported) {
  38800. codecSupportedFound = true;
  38801. }
  38802. if (url.indexOf(".ogg", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isOGGsupported) {
  38803. codecSupportedFound = true;
  38804. }
  38805. if (url.indexOf(".wav", url.length - 4) !== -1) {
  38806. codecSupportedFound = true;
  38807. }
  38808. if (codecSupportedFound) {
  38809. // Loading sound using XHR2
  38810. if (!this._streaming) {
  38811. BABYLON.Tools.LoadFile(url, function (data) { _this._soundLoaded(data); }, null, this._scene.database, true);
  38812. }
  38813. else {
  38814. this._htmlAudioElement = new Audio(url);
  38815. this._htmlAudioElement.controls = false;
  38816. this._htmlAudioElement.loop = this.loop;
  38817. this._htmlAudioElement.crossOrigin = "anonymous";
  38818. this._htmlAudioElement.preload = "auto";
  38819. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  38820. _this._isReadyToPlay = true;
  38821. if (_this.autoplay) {
  38822. _this.play();
  38823. }
  38824. if (_this._readyToPlayCallback) {
  38825. _this._readyToPlayCallback();
  38826. }
  38827. });
  38828. document.body.appendChild(this._htmlAudioElement);
  38829. }
  38830. break;
  38831. }
  38832. }
  38833. break;
  38834. default:
  38835. validParameter = false;
  38836. break;
  38837. }
  38838. if (!validParameter) {
  38839. BABYLON.Tools.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.");
  38840. }
  38841. else {
  38842. if (!codecSupportedFound) {
  38843. this._isReadyToPlay = true;
  38844. // Simulating a ready to play event to avoid breaking code path
  38845. if (this._readyToPlayCallback) {
  38846. window.setTimeout(function () {
  38847. _this._readyToPlayCallback();
  38848. }, 1000);
  38849. }
  38850. }
  38851. }
  38852. }
  38853. }
  38854. else {
  38855. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  38856. this._scene.mainSoundTrack.AddSound(this);
  38857. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  38858. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  38859. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  38860. }
  38861. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  38862. if (this._readyToPlayCallback) {
  38863. window.setTimeout(function () {
  38864. _this._readyToPlayCallback();
  38865. }, 1000);
  38866. }
  38867. }
  38868. }
  38869. Sound.prototype.dispose = function () {
  38870. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isReadyToPlay) {
  38871. if (this.isPlaying) {
  38872. this.stop();
  38873. }
  38874. this._isReadyToPlay = false;
  38875. if (this.soundTrackId === -1) {
  38876. this._scene.mainSoundTrack.RemoveSound(this);
  38877. }
  38878. else {
  38879. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  38880. }
  38881. if (this._soundGain) {
  38882. this._soundGain.disconnect();
  38883. this._soundGain = null;
  38884. }
  38885. if (this._soundPanner) {
  38886. this._soundPanner.disconnect();
  38887. this._soundPanner = null;
  38888. }
  38889. if (this._soundSource) {
  38890. this._soundSource.disconnect();
  38891. this._soundSource = null;
  38892. }
  38893. this._audioBuffer = null;
  38894. if (this._htmlAudioElement) {
  38895. this._htmlAudioElement.pause();
  38896. this._htmlAudioElement.src = "";
  38897. document.body.removeChild(this._htmlAudioElement);
  38898. }
  38899. if (this._connectedMesh) {
  38900. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  38901. this._connectedMesh = null;
  38902. }
  38903. }
  38904. };
  38905. Sound.prototype.isReady = function () {
  38906. return this._isReadyToPlay;
  38907. };
  38908. Sound.prototype._soundLoaded = function (audioData) {
  38909. var _this = this;
  38910. this._isLoaded = true;
  38911. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  38912. _this._audioBuffer = buffer;
  38913. _this._isReadyToPlay = true;
  38914. if (_this.autoplay) {
  38915. _this.play();
  38916. }
  38917. if (_this._readyToPlayCallback) {
  38918. _this._readyToPlayCallback();
  38919. }
  38920. }, function (err) { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name + " / Error: " + err); });
  38921. };
  38922. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  38923. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  38924. this._audioBuffer = audioBuffer;
  38925. this._isReadyToPlay = true;
  38926. }
  38927. };
  38928. Sound.prototype.updateOptions = function (options) {
  38929. if (options) {
  38930. this.loop = options.loop || this.loop;
  38931. this.maxDistance = options.maxDistance || this.maxDistance;
  38932. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  38933. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  38934. this.refDistance = options.refDistance || this.refDistance;
  38935. this.distanceModel = options.distanceModel || this.distanceModel;
  38936. this._playbackRate = options.playbackRate || this._playbackRate;
  38937. this._updateSpatialParameters();
  38938. if (this.isPlaying) {
  38939. if (this._streaming) {
  38940. this._htmlAudioElement.playbackRate = this._playbackRate;
  38941. }
  38942. else {
  38943. this._soundSource.playbackRate.value = this._playbackRate;
  38944. }
  38945. }
  38946. }
  38947. };
  38948. Sound.prototype._createSpatialParameters = function () {
  38949. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  38950. if (this._scene.headphone) {
  38951. this._panningModel = "HRTF";
  38952. }
  38953. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  38954. this._updateSpatialParameters();
  38955. this._soundPanner.connect(this._ouputAudioNode);
  38956. this._inputAudioNode = this._soundPanner;
  38957. }
  38958. };
  38959. Sound.prototype._updateSpatialParameters = function () {
  38960. if (this.spatialSound) {
  38961. if (this.useCustomAttenuation) {
  38962. // Tricks to disable in a way embedded Web Audio attenuation
  38963. this._soundPanner.distanceModel = "linear";
  38964. this._soundPanner.maxDistance = Number.MAX_VALUE;
  38965. this._soundPanner.refDistance = 1;
  38966. this._soundPanner.rolloffFactor = 1;
  38967. this._soundPanner.panningModel = this._panningModel;
  38968. }
  38969. else {
  38970. this._soundPanner.distanceModel = this.distanceModel;
  38971. this._soundPanner.maxDistance = this.maxDistance;
  38972. this._soundPanner.refDistance = this.refDistance;
  38973. this._soundPanner.rolloffFactor = this.rolloffFactor;
  38974. this._soundPanner.panningModel = this._panningModel;
  38975. }
  38976. }
  38977. };
  38978. Sound.prototype.switchPanningModelToHRTF = function () {
  38979. this._panningModel = "HRTF";
  38980. this._switchPanningModel();
  38981. };
  38982. Sound.prototype.switchPanningModelToEqualPower = function () {
  38983. this._panningModel = "equalpower";
  38984. this._switchPanningModel();
  38985. };
  38986. Sound.prototype._switchPanningModel = function () {
  38987. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  38988. this._soundPanner.panningModel = this._panningModel;
  38989. }
  38990. };
  38991. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  38992. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  38993. if (this._isOutputConnected) {
  38994. this._ouputAudioNode.disconnect();
  38995. }
  38996. this._ouputAudioNode.connect(soundTrackAudioNode);
  38997. this._isOutputConnected = true;
  38998. }
  38999. };
  39000. /**
  39001. * Transform this sound into a directional source
  39002. * @param coneInnerAngle Size of the inner cone in degree
  39003. * @param coneOuterAngle Size of the outer cone in degree
  39004. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  39005. */
  39006. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  39007. if (coneOuterAngle < coneInnerAngle) {
  39008. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  39009. return;
  39010. }
  39011. this._coneInnerAngle = coneInnerAngle;
  39012. this._coneOuterAngle = coneOuterAngle;
  39013. this._coneOuterGain = coneOuterGain;
  39014. this._isDirectional = true;
  39015. if (this.isPlaying && this.loop) {
  39016. this.stop();
  39017. this.play();
  39018. }
  39019. };
  39020. Sound.prototype.setPosition = function (newPosition) {
  39021. this._position = newPosition;
  39022. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  39023. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  39024. }
  39025. };
  39026. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  39027. this._localDirection = newLocalDirection;
  39028. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  39029. this._updateDirection();
  39030. }
  39031. };
  39032. Sound.prototype._updateDirection = function () {
  39033. var mat = this._connectedMesh.getWorldMatrix();
  39034. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  39035. direction.normalize();
  39036. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  39037. };
  39038. Sound.prototype.updateDistanceFromListener = function () {
  39039. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation) {
  39040. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  39041. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  39042. }
  39043. };
  39044. Sound.prototype.setAttenuationFunction = function (callback) {
  39045. this._customAttenuationFunction = callback;
  39046. };
  39047. /**
  39048. * Play the sound
  39049. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  39050. * @param offset (optional) Start the sound setting it at a specific time
  39051. */
  39052. Sound.prototype.play = function (time, offset) {
  39053. var _this = this;
  39054. if (this._isReadyToPlay && this._scene.audioEnabled) {
  39055. try {
  39056. if (this._startOffset < 0) {
  39057. time = -this._startOffset;
  39058. this._startOffset = 0;
  39059. }
  39060. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  39061. if (!this._soundSource || !this._streamingSource) {
  39062. if (this.spatialSound) {
  39063. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  39064. if (this._isDirectional) {
  39065. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  39066. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  39067. this._soundPanner.coneOuterGain = this._coneOuterGain;
  39068. if (this._connectedMesh) {
  39069. this._updateDirection();
  39070. }
  39071. else {
  39072. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  39073. }
  39074. }
  39075. }
  39076. }
  39077. if (this._streaming) {
  39078. if (!this._streamingSource) {
  39079. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  39080. this._htmlAudioElement.onended = function () { _this._onended(); };
  39081. this._htmlAudioElement.playbackRate = this._playbackRate;
  39082. }
  39083. this._streamingSource.disconnect();
  39084. this._streamingSource.connect(this._inputAudioNode);
  39085. this._htmlAudioElement.play();
  39086. }
  39087. else {
  39088. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  39089. this._soundSource.buffer = this._audioBuffer;
  39090. this._soundSource.connect(this._inputAudioNode);
  39091. this._soundSource.loop = this.loop;
  39092. this._soundSource.playbackRate.value = this._playbackRate;
  39093. this._soundSource.onended = function () { _this._onended(); };
  39094. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : offset ? offset : 0);
  39095. }
  39096. this._startTime = startTime;
  39097. this.isPlaying = true;
  39098. this.isPaused = false;
  39099. }
  39100. catch (ex) {
  39101. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  39102. }
  39103. }
  39104. };
  39105. Sound.prototype._onended = function () {
  39106. this.isPlaying = false;
  39107. if (this.onended) {
  39108. this.onended();
  39109. }
  39110. };
  39111. /**
  39112. * Stop the sound
  39113. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  39114. */
  39115. Sound.prototype.stop = function (time) {
  39116. if (this.isPlaying) {
  39117. if (this._streaming) {
  39118. this._htmlAudioElement.pause();
  39119. // Test needed for Firefox or it will generate an Invalid State Error
  39120. if (this._htmlAudioElement.currentTime > 0) {
  39121. this._htmlAudioElement.currentTime = 0;
  39122. }
  39123. }
  39124. else {
  39125. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  39126. this._soundSource.stop(stopTime);
  39127. this._soundSource.onended = null;
  39128. if (!this.isPaused) {
  39129. this._startOffset = 0;
  39130. }
  39131. }
  39132. this.isPlaying = false;
  39133. }
  39134. };
  39135. Sound.prototype.pause = function () {
  39136. if (this.isPlaying) {
  39137. this.isPaused = true;
  39138. if (this._streaming) {
  39139. this._htmlAudioElement.pause();
  39140. }
  39141. else {
  39142. this.stop(0);
  39143. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  39144. }
  39145. }
  39146. };
  39147. Sound.prototype.setVolume = function (newVolume, time) {
  39148. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  39149. if (time) {
  39150. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  39151. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  39152. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  39153. }
  39154. else {
  39155. this._soundGain.gain.value = newVolume;
  39156. }
  39157. }
  39158. this._volume = newVolume;
  39159. };
  39160. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  39161. this._playbackRate = newPlaybackRate;
  39162. if (this.isPlaying) {
  39163. if (this._streaming) {
  39164. this._htmlAudioElement.playbackRate = this._playbackRate;
  39165. }
  39166. else {
  39167. this._soundSource.playbackRate.value = this._playbackRate;
  39168. }
  39169. }
  39170. };
  39171. Sound.prototype.getVolume = function () {
  39172. return this._volume;
  39173. };
  39174. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  39175. var _this = this;
  39176. if (this._connectedMesh) {
  39177. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  39178. this._registerFunc = null;
  39179. }
  39180. this._connectedMesh = meshToConnectTo;
  39181. if (!this.spatialSound) {
  39182. this.spatialSound = true;
  39183. this._createSpatialParameters();
  39184. if (this.isPlaying && this.loop) {
  39185. this.stop();
  39186. this.play();
  39187. }
  39188. }
  39189. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  39190. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  39191. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  39192. };
  39193. Sound.prototype.detachFromMesh = function () {
  39194. if (this._connectedMesh) {
  39195. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  39196. this._registerFunc = null;
  39197. this._connectedMesh = null;
  39198. }
  39199. };
  39200. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (connectedMesh) {
  39201. this.setPosition(connectedMesh.getBoundingInfo().boundingSphere.centerWorld);
  39202. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  39203. this._updateDirection();
  39204. }
  39205. };
  39206. Sound.prototype.clone = function () {
  39207. var _this = this;
  39208. if (!this._streaming) {
  39209. var setBufferAndRun = function () {
  39210. if (_this._isReadyToPlay) {
  39211. clonedSound._audioBuffer = _this.getAudioBuffer();
  39212. clonedSound._isReadyToPlay = true;
  39213. if (clonedSound.autoplay) {
  39214. clonedSound.play();
  39215. }
  39216. }
  39217. else {
  39218. window.setTimeout(setBufferAndRun, 300);
  39219. }
  39220. };
  39221. var currentOptions = {
  39222. autoplay: this.autoplay, loop: this.loop,
  39223. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  39224. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  39225. refDistance: this.refDistance, distanceModel: this.distanceModel
  39226. };
  39227. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  39228. if (this.useCustomAttenuation) {
  39229. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  39230. }
  39231. clonedSound.setPosition(this._position);
  39232. clonedSound.setPlaybackRate(this._playbackRate);
  39233. setBufferAndRun();
  39234. return clonedSound;
  39235. }
  39236. else {
  39237. return null;
  39238. }
  39239. };
  39240. Sound.prototype.getAudioBuffer = function () {
  39241. return this._audioBuffer;
  39242. };
  39243. Sound.prototype.serialize = function () {
  39244. var serializationObject = {
  39245. name: this.name,
  39246. url: this.name,
  39247. autoplay: this.autoplay,
  39248. loop: this.loop,
  39249. volume: this._volume,
  39250. spatialSound: this.spatialSound,
  39251. maxDistance: this.maxDistance,
  39252. rolloffFactor: this.rolloffFactor,
  39253. refDistance: this.refDistance,
  39254. distanceModel: this.distanceModel,
  39255. playbackRate: this._playbackRate,
  39256. panningModel: this._panningModel,
  39257. soundTrackId: this.soundTrackId
  39258. };
  39259. if (this.spatialSound) {
  39260. if (this._connectedMesh)
  39261. serializationObject.connectedMeshId = this._connectedMesh.id;
  39262. serializationObject.position = this._position.asArray();
  39263. serializationObject.refDistance = this.refDistance;
  39264. serializationObject.distanceModel = this.distanceModel;
  39265. serializationObject.isDirectional = this._isDirectional;
  39266. serializationObject.localDirectionToMesh = this._localDirection.asArray();
  39267. serializationObject.coneInnerAngle = this._coneInnerAngle;
  39268. serializationObject.coneOuterAngle = this._coneOuterAngle;
  39269. serializationObject.coneOuterGain = this._coneOuterGain;
  39270. }
  39271. return serializationObject;
  39272. };
  39273. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  39274. var soundName = parsedSound.name;
  39275. var soundUrl;
  39276. if (parsedSound.url) {
  39277. soundUrl = rootUrl + parsedSound.url;
  39278. }
  39279. else {
  39280. soundUrl = rootUrl + soundName;
  39281. }
  39282. var options = {
  39283. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  39284. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  39285. rolloffFactor: parsedSound.rolloffFactor,
  39286. refDistance: parsedSound.refDistance,
  39287. distanceModel: parsedSound.distanceModel,
  39288. playbackRate: parsedSound.playbackRate
  39289. };
  39290. var newSound;
  39291. if (!sourceSound) {
  39292. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  39293. scene._addPendingData(newSound);
  39294. }
  39295. else {
  39296. var setBufferAndRun = function () {
  39297. if (sourceSound._isReadyToPlay) {
  39298. newSound._audioBuffer = sourceSound.getAudioBuffer();
  39299. newSound._isReadyToPlay = true;
  39300. if (newSound.autoplay) {
  39301. newSound.play();
  39302. }
  39303. }
  39304. else {
  39305. window.setTimeout(setBufferAndRun, 300);
  39306. }
  39307. };
  39308. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  39309. setBufferAndRun();
  39310. }
  39311. if (parsedSound.position) {
  39312. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  39313. newSound.setPosition(soundPosition);
  39314. }
  39315. if (parsedSound.isDirectional) {
  39316. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  39317. if (parsedSound.localDirectionToMesh) {
  39318. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  39319. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  39320. }
  39321. }
  39322. if (parsedSound.connectedMeshId) {
  39323. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  39324. if (connectedMesh) {
  39325. newSound.attachToMesh(connectedMesh);
  39326. }
  39327. }
  39328. return newSound;
  39329. };
  39330. return Sound;
  39331. }());
  39332. BABYLON.Sound = Sound;
  39333. })(BABYLON || (BABYLON = {}));
  39334. //# sourceMappingURL=babylon.sound.js.map
  39335. var BABYLON;
  39336. (function (BABYLON) {
  39337. var SoundTrack = (function () {
  39338. function SoundTrack(scene, options) {
  39339. this.id = -1;
  39340. this._isMainTrack = false;
  39341. this._isInitialized = false;
  39342. this._scene = scene;
  39343. this.soundCollection = new Array();
  39344. this._options = options;
  39345. if (!this._isMainTrack) {
  39346. this._scene.soundTracks.push(this);
  39347. this.id = this._scene.soundTracks.length - 1;
  39348. }
  39349. }
  39350. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  39351. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  39352. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  39353. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  39354. if (this._options) {
  39355. if (this._options.volume) {
  39356. this._outputAudioNode.gain.value = this._options.volume;
  39357. }
  39358. if (this._options.mainTrack) {
  39359. this._isMainTrack = this._options.mainTrack;
  39360. }
  39361. }
  39362. this._isInitialized = true;
  39363. }
  39364. };
  39365. SoundTrack.prototype.dispose = function () {
  39366. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  39367. if (this._connectedAnalyser) {
  39368. this._connectedAnalyser.stopDebugCanvas();
  39369. }
  39370. while (this.soundCollection.length) {
  39371. this.soundCollection[0].dispose();
  39372. }
  39373. if (this._outputAudioNode) {
  39374. this._outputAudioNode.disconnect();
  39375. }
  39376. this._outputAudioNode = null;
  39377. }
  39378. };
  39379. SoundTrack.prototype.AddSound = function (sound) {
  39380. if (!this._isInitialized) {
  39381. this._initializeSoundTrackAudioGraph();
  39382. }
  39383. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  39384. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  39385. }
  39386. if (sound.soundTrackId) {
  39387. if (sound.soundTrackId === -1) {
  39388. this._scene.mainSoundTrack.RemoveSound(sound);
  39389. }
  39390. else {
  39391. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  39392. }
  39393. }
  39394. this.soundCollection.push(sound);
  39395. sound.soundTrackId = this.id;
  39396. };
  39397. SoundTrack.prototype.RemoveSound = function (sound) {
  39398. var index = this.soundCollection.indexOf(sound);
  39399. if (index !== -1) {
  39400. this.soundCollection.splice(index, 1);
  39401. }
  39402. };
  39403. SoundTrack.prototype.setVolume = function (newVolume) {
  39404. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  39405. this._outputAudioNode.gain.value = newVolume;
  39406. }
  39407. };
  39408. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  39409. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  39410. for (var i = 0; i < this.soundCollection.length; i++) {
  39411. this.soundCollection[i].switchPanningModelToHRTF();
  39412. }
  39413. }
  39414. };
  39415. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  39416. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  39417. for (var i = 0; i < this.soundCollection.length; i++) {
  39418. this.soundCollection[i].switchPanningModelToEqualPower();
  39419. }
  39420. }
  39421. };
  39422. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  39423. if (this._connectedAnalyser) {
  39424. this._connectedAnalyser.stopDebugCanvas();
  39425. }
  39426. this._connectedAnalyser = analyser;
  39427. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  39428. this._outputAudioNode.disconnect();
  39429. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  39430. }
  39431. };
  39432. return SoundTrack;
  39433. }());
  39434. BABYLON.SoundTrack = SoundTrack;
  39435. })(BABYLON || (BABYLON = {}));
  39436. //# sourceMappingURL=babylon.soundtrack.js.map
  39437. var BABYLON;
  39438. (function (BABYLON) {
  39439. /**
  39440. * Special Glow Blur post process only blurring the alpha channel
  39441. * It enforces keeping the most luminous color in the color channel.
  39442. */
  39443. var GlowBlurPostProcess = (function (_super) {
  39444. __extends(GlowBlurPostProcess, _super);
  39445. function GlowBlurPostProcess(name, direction, blurWidth, options, camera, samplingMode, engine, reusable) {
  39446. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  39447. var _this = _super.call(this, name, "glowBlurPostProcess", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable) || this;
  39448. _this.direction = direction;
  39449. _this.blurWidth = blurWidth;
  39450. _this.onApplyObservable.add(function (effect) {
  39451. effect.setFloat2("screenSize", _this.width, _this.height);
  39452. effect.setVector2("direction", _this.direction);
  39453. effect.setFloat("blurWidth", _this.blurWidth);
  39454. });
  39455. return _this;
  39456. }
  39457. return GlowBlurPostProcess;
  39458. }(BABYLON.PostProcess));
  39459. /**
  39460. * The highlight layer Helps adding a glow effect around a mesh.
  39461. *
  39462. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  39463. * glowy meshes to your scene.
  39464. *
  39465. * !!! THIS REQUIRES AN ACTIVE STENCIL BUFFER ON THE CANVAS !!!
  39466. */
  39467. var HighlightLayer = (function () {
  39468. /**
  39469. * Instantiates a new highlight Layer and references it to the scene..
  39470. * @param name The name of the layer
  39471. * @param scene The scene to use the layer in
  39472. * @param options Sets of none mandatory options to use with the layer (see IHighlightLayerOptions for more information)
  39473. */
  39474. function HighlightLayer(name, scene, options) {
  39475. this._vertexBuffers = {};
  39476. this._mainTextureDesiredSize = { width: 0, height: 0 };
  39477. this._meshes = {};
  39478. this._maxSize = 0;
  39479. this._shouldRender = false;
  39480. this._instanceGlowingMeshStencilReference = HighlightLayer.glowingMeshStencilReference++;
  39481. this._excludedMeshes = {};
  39482. /**
  39483. * Specifies whether or not the inner glow is ACTIVE in the layer.
  39484. */
  39485. this.innerGlow = true;
  39486. /**
  39487. * Specifies whether or not the outer glow is ACTIVE in the layer.
  39488. */
  39489. this.outerGlow = true;
  39490. /**
  39491. * Specifies wether the highlight layer is enabled or not.
  39492. */
  39493. this.isEnabled = true;
  39494. /**
  39495. * An event triggered when the highlight layer has been disposed.
  39496. * @type {BABYLON.Observable}
  39497. */
  39498. this.onDisposeObservable = new BABYLON.Observable();
  39499. /**
  39500. * An event triggered when the highlight layer is about rendering the main texture with the glowy parts.
  39501. * @type {BABYLON.Observable}
  39502. */
  39503. this.onBeforeRenderMainTextureObservable = new BABYLON.Observable();
  39504. /**
  39505. * An event triggered when the highlight layer is being blurred.
  39506. * @type {BABYLON.Observable}
  39507. */
  39508. this.onBeforeBlurObservable = new BABYLON.Observable();
  39509. /**
  39510. * An event triggered when the highlight layer has been blurred.
  39511. * @type {BABYLON.Observable}
  39512. */
  39513. this.onAfterBlurObservable = new BABYLON.Observable();
  39514. /**
  39515. * An event triggered when the glowing blurred texture is being merged in the scene.
  39516. * @type {BABYLON.Observable}
  39517. */
  39518. this.onBeforeComposeObservable = new BABYLON.Observable();
  39519. /**
  39520. * An event triggered when the glowing blurred texture has been merged in the scene.
  39521. * @type {BABYLON.Observable}
  39522. */
  39523. this.onAfterComposeObservable = new BABYLON.Observable();
  39524. /**
  39525. * An event triggered when the highlight layer changes its size.
  39526. * @type {BABYLON.Observable}
  39527. */
  39528. this.onSizeChangedObservable = new BABYLON.Observable();
  39529. this._scene = scene;
  39530. var engine = scene.getEngine();
  39531. this._engine = engine;
  39532. this._maxSize = this._engine.getCaps().maxTextureSize;
  39533. this._scene.highlightLayers.push(this);
  39534. // Warn on stencil.
  39535. if (!this._engine.isStencilEnable) {
  39536. 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 }");
  39537. }
  39538. // Adapt options
  39539. this._options = options || {
  39540. mainTextureRatio: 0.25,
  39541. blurTextureSizeRatio: 0.5,
  39542. blurHorizontalSize: 1,
  39543. blurVerticalSize: 1,
  39544. alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE
  39545. };
  39546. this._options.mainTextureRatio = this._options.mainTextureRatio || 0.25;
  39547. this._options.blurTextureSizeRatio = this._options.blurTextureSizeRatio || 0.5;
  39548. this._options.blurHorizontalSize = this._options.blurHorizontalSize || 1;
  39549. this._options.blurVerticalSize = this._options.blurVerticalSize || 1;
  39550. this._options.alphaBlendingMode = this._options.alphaBlendingMode || BABYLON.Engine.ALPHA_COMBINE;
  39551. // VBO
  39552. var vertices = [];
  39553. vertices.push(1, 1);
  39554. vertices.push(-1, 1);
  39555. vertices.push(-1, -1);
  39556. vertices.push(1, -1);
  39557. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  39558. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  39559. // Indices
  39560. var indices = [];
  39561. indices.push(0);
  39562. indices.push(1);
  39563. indices.push(2);
  39564. indices.push(0);
  39565. indices.push(2);
  39566. indices.push(3);
  39567. this._indexBuffer = engine.createIndexBuffer(indices);
  39568. // Effect
  39569. this._glowMapMergeEffect = engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler"], "");
  39570. // Render target
  39571. this.setMainTextureSize();
  39572. // Create Textures and post processes
  39573. this.createTextureAndPostProcesses();
  39574. }
  39575. Object.defineProperty(HighlightLayer.prototype, "blurHorizontalSize", {
  39576. /**
  39577. * Gets the horizontal size of the blur.
  39578. */
  39579. get: function () {
  39580. return this._horizontalBlurPostprocess.blurWidth;
  39581. },
  39582. /**
  39583. * Specifies the horizontal size of the blur.
  39584. */
  39585. set: function (value) {
  39586. this._horizontalBlurPostprocess.blurWidth = value;
  39587. },
  39588. enumerable: true,
  39589. configurable: true
  39590. });
  39591. Object.defineProperty(HighlightLayer.prototype, "blurVerticalSize", {
  39592. /**
  39593. * Gets the vertical size of the blur.
  39594. */
  39595. get: function () {
  39596. return this._verticalBlurPostprocess.blurWidth;
  39597. },
  39598. /**
  39599. * Specifies the vertical size of the blur.
  39600. */
  39601. set: function (value) {
  39602. this._verticalBlurPostprocess.blurWidth = value;
  39603. },
  39604. enumerable: true,
  39605. configurable: true
  39606. });
  39607. Object.defineProperty(HighlightLayer.prototype, "camera", {
  39608. /**
  39609. * Gets the camera attached to the layer.
  39610. */
  39611. get: function () {
  39612. return this._options.camera;
  39613. },
  39614. enumerable: true,
  39615. configurable: true
  39616. });
  39617. /**
  39618. * Creates the render target textures and post processes used in the highlight layer.
  39619. */
  39620. HighlightLayer.prototype.createTextureAndPostProcesses = function () {
  39621. var _this = this;
  39622. var blurTextureWidth = this._mainTextureDesiredSize.width * this._options.blurTextureSizeRatio;
  39623. var blurTextureHeight = this._mainTextureDesiredSize.height * this._options.blurTextureSizeRatio;
  39624. blurTextureWidth = BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize);
  39625. blurTextureHeight = BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize);
  39626. this._mainTexture = new BABYLON.RenderTargetTexture("HighlightLayerMainRTT", {
  39627. width: this._mainTextureDesiredSize.width,
  39628. height: this._mainTextureDesiredSize.height
  39629. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  39630. this._mainTexture.activeCamera = this._options.camera;
  39631. this._mainTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  39632. this._mainTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  39633. this._mainTexture.anisotropicFilteringLevel = 1;
  39634. this._mainTexture.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  39635. this._mainTexture.renderParticles = false;
  39636. this._mainTexture.renderList = null;
  39637. this._blurTexture = new BABYLON.RenderTargetTexture("HighlightLayerBlurRTT", {
  39638. width: blurTextureWidth,
  39639. height: blurTextureHeight
  39640. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  39641. this._blurTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  39642. this._blurTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  39643. this._blurTexture.anisotropicFilteringLevel = 16;
  39644. this._blurTexture.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  39645. this._blurTexture.renderParticles = false;
  39646. this._downSamplePostprocess = new BABYLON.PassPostProcess("HighlightLayerPPP", this._options.blurTextureSizeRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  39647. this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  39648. effect.setTexture("textureSampler", _this._mainTexture);
  39649. });
  39650. if (this._options.alphaBlendingMode === BABYLON.Engine.ALPHA_COMBINE) {
  39651. this._horizontalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  39652. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  39653. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  39654. });
  39655. this._verticalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  39656. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  39657. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  39658. });
  39659. }
  39660. else {
  39661. this._horizontalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  39662. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  39663. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  39664. });
  39665. this._verticalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  39666. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  39667. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  39668. });
  39669. }
  39670. this._mainTexture.onAfterUnbindObservable.add(function () {
  39671. _this.onBeforeBlurObservable.notifyObservers(_this);
  39672. _this._scene.postProcessManager.directRender([_this._downSamplePostprocess, _this._horizontalBlurPostprocess, _this._verticalBlurPostprocess], _this._blurTexture.getInternalTexture());
  39673. _this.onAfterBlurObservable.notifyObservers(_this);
  39674. });
  39675. // Custom render function
  39676. var renderSubMesh = function (subMesh) {
  39677. var mesh = subMesh.getRenderingMesh();
  39678. var scene = _this._scene;
  39679. var engine = scene.getEngine();
  39680. // Culling
  39681. engine.setState(subMesh.getMaterial().backFaceCulling);
  39682. // Managing instances
  39683. var batch = mesh._getInstancesRenderList(subMesh._id);
  39684. if (batch.mustReturn) {
  39685. return;
  39686. }
  39687. // Excluded Mesh
  39688. if (_this._excludedMeshes[mesh.uniqueId]) {
  39689. return;
  39690. }
  39691. ;
  39692. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  39693. var highlightLayerMesh = _this._meshes[mesh.uniqueId];
  39694. var material = subMesh.getMaterial();
  39695. var emissiveTexture = null;
  39696. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  39697. emissiveTexture = material.emissiveTexture;
  39698. }
  39699. if (_this.isReady(subMesh, hardwareInstancedRendering, emissiveTexture)) {
  39700. engine.enableEffect(_this._glowMapGenerationEffect);
  39701. mesh._bind(subMesh, _this._glowMapGenerationEffect, BABYLON.Material.TriangleFillMode);
  39702. _this._glowMapGenerationEffect.setMatrix("viewProjection", scene.getTransformMatrix());
  39703. if (highlightLayerMesh) {
  39704. _this._glowMapGenerationEffect.setFloat4("color", highlightLayerMesh.color.r, highlightLayerMesh.color.g, highlightLayerMesh.color.b, 1.0);
  39705. }
  39706. else {
  39707. _this._glowMapGenerationEffect.setFloat4("color", HighlightLayer.neutralColor.r, HighlightLayer.neutralColor.g, HighlightLayer.neutralColor.b, HighlightLayer.neutralColor.a);
  39708. }
  39709. // Alpha test
  39710. if (material && material.needAlphaTesting()) {
  39711. var alphaTexture = material.getAlphaTestTexture();
  39712. _this._glowMapGenerationEffect.setTexture("diffuseSampler", alphaTexture);
  39713. _this._glowMapGenerationEffect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  39714. }
  39715. // Glow emissive only
  39716. if (emissiveTexture) {
  39717. _this._glowMapGenerationEffect.setTexture("emissiveSampler", emissiveTexture);
  39718. _this._glowMapGenerationEffect.setMatrix("emissiveMatrix", emissiveTexture.getTextureMatrix());
  39719. }
  39720. // Bones
  39721. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  39722. _this._glowMapGenerationEffect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  39723. }
  39724. // Draw
  39725. mesh._processRendering(subMesh, _this._glowMapGenerationEffect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._glowMapGenerationEffect.setMatrix("world", world); });
  39726. }
  39727. else {
  39728. // Need to reset refresh rate of the shadowMap
  39729. _this._mainTexture.resetRefreshCounter();
  39730. }
  39731. };
  39732. this._mainTexture.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  39733. _this.onBeforeRenderMainTextureObservable.notifyObservers(_this);
  39734. var index;
  39735. for (index = 0; index < opaqueSubMeshes.length; index++) {
  39736. renderSubMesh(opaqueSubMeshes.data[index]);
  39737. }
  39738. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  39739. renderSubMesh(alphaTestSubMeshes.data[index]);
  39740. }
  39741. for (index = 0; index < transparentSubMeshes.length; index++) {
  39742. renderSubMesh(transparentSubMeshes.data[index]);
  39743. }
  39744. };
  39745. this._mainTexture.onClearObservable.add(function (engine) {
  39746. engine.clear(HighlightLayer.neutralColor, true, true, true);
  39747. });
  39748. };
  39749. /**
  39750. * Checks for the readiness of the element composing the layer.
  39751. * @param subMesh the mesh to check for
  39752. * @param useInstances specify wether or not to use instances to render the mesh
  39753. * @param emissiveTexture the associated emissive texture used to generate the glow
  39754. * @return true if ready otherwise, false
  39755. */
  39756. HighlightLayer.prototype.isReady = function (subMesh, useInstances, emissiveTexture) {
  39757. if (!subMesh.getMaterial().isReady(subMesh.getMesh(), useInstances)) {
  39758. return false;
  39759. }
  39760. var defines = [];
  39761. var attribs = [BABYLON.VertexBuffer.PositionKind];
  39762. var mesh = subMesh.getMesh();
  39763. var material = subMesh.getMaterial();
  39764. var uv1 = false;
  39765. var uv2 = false;
  39766. // Alpha test
  39767. if (material && material.needAlphaTesting()) {
  39768. var alphaTexture = material.getAlphaTestTexture();
  39769. if (alphaTexture) {
  39770. defines.push("#define ALPHATEST");
  39771. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  39772. alphaTexture.coordinatesIndex === 1) {
  39773. defines.push("#define DIFFUSEUV2");
  39774. uv2 = true;
  39775. }
  39776. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  39777. defines.push("#define DIFFUSEUV1");
  39778. uv1 = true;
  39779. }
  39780. }
  39781. }
  39782. // Emissive
  39783. if (emissiveTexture) {
  39784. defines.push("#define EMISSIVE");
  39785. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  39786. emissiveTexture.coordinatesIndex === 1) {
  39787. defines.push("#define EMISSIVEUV2");
  39788. uv2 = true;
  39789. }
  39790. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  39791. defines.push("#define EMISSIVEUV1");
  39792. uv1 = true;
  39793. }
  39794. }
  39795. if (uv1) {
  39796. attribs.push(BABYLON.VertexBuffer.UVKind);
  39797. defines.push("#define UV1");
  39798. }
  39799. if (uv2) {
  39800. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  39801. defines.push("#define UV2");
  39802. }
  39803. // Bones
  39804. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  39805. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  39806. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  39807. if (mesh.numBoneInfluencers > 4) {
  39808. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  39809. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  39810. }
  39811. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  39812. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  39813. }
  39814. else {
  39815. defines.push("#define NUM_BONE_INFLUENCERS 0");
  39816. }
  39817. // Instances
  39818. if (useInstances) {
  39819. defines.push("#define INSTANCES");
  39820. attribs.push("world0");
  39821. attribs.push("world1");
  39822. attribs.push("world2");
  39823. attribs.push("world3");
  39824. }
  39825. // Get correct effect
  39826. var join = defines.join("\n");
  39827. if (this._cachedDefines !== join) {
  39828. this._cachedDefines = join;
  39829. this._glowMapGenerationEffect = this._scene.getEngine().createEffect("glowMapGeneration", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "color", "emissiveMatrix"], ["diffuseSampler", "emissiveSampler"], join);
  39830. }
  39831. return this._glowMapGenerationEffect.isReady();
  39832. };
  39833. /**
  39834. * Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene.
  39835. */
  39836. HighlightLayer.prototype.render = function () {
  39837. var currentEffect = this._glowMapMergeEffect;
  39838. // Check
  39839. if (!currentEffect.isReady() || !this._blurTexture.isReady())
  39840. return;
  39841. var engine = this._scene.getEngine();
  39842. this.onBeforeComposeObservable.notifyObservers(this);
  39843. // Render
  39844. engine.enableEffect(currentEffect);
  39845. engine.setState(false);
  39846. // Cache
  39847. var previousStencilBuffer = engine.getStencilBuffer();
  39848. var previousStencilFunction = engine.getStencilFunction();
  39849. var previousStencilMask = engine.getStencilMask();
  39850. var previousAlphaMode = engine.getAlphaMode();
  39851. // Texture
  39852. currentEffect.setTexture("textureSampler", this._blurTexture);
  39853. // VBOs
  39854. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  39855. // Draw order
  39856. engine.setAlphaMode(this._options.alphaBlendingMode);
  39857. engine.setStencilMask(0x00);
  39858. engine.setStencilBuffer(true);
  39859. engine.setStencilFunctionReference(this._instanceGlowingMeshStencilReference);
  39860. if (this.outerGlow) {
  39861. currentEffect.setFloat("offset", 0);
  39862. engine.setStencilFunction(BABYLON.Engine.NOTEQUAL);
  39863. engine.draw(true, 0, 6);
  39864. }
  39865. if (this.innerGlow) {
  39866. currentEffect.setFloat("offset", 1);
  39867. engine.setStencilFunction(BABYLON.Engine.EQUAL);
  39868. engine.draw(true, 0, 6);
  39869. }
  39870. // Restore Cache
  39871. engine.setStencilFunction(previousStencilFunction);
  39872. engine.setStencilMask(previousStencilMask);
  39873. engine.setAlphaMode(previousAlphaMode);
  39874. engine.setStencilBuffer(previousStencilBuffer);
  39875. this.onAfterComposeObservable.notifyObservers(this);
  39876. // Handle size changes.
  39877. var size = this._mainTexture.getSize();
  39878. this.setMainTextureSize();
  39879. if (size.width !== this._mainTextureDesiredSize.width || size.height !== this._mainTextureDesiredSize.height) {
  39880. // Recreate RTT and post processes on size change.
  39881. this.onSizeChangedObservable.notifyObservers(this);
  39882. this.disposeTextureAndPostProcesses();
  39883. this.createTextureAndPostProcesses();
  39884. }
  39885. };
  39886. /**
  39887. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the highlight layer.
  39888. * @param mesh The mesh to exclude from the highlight layer
  39889. */
  39890. HighlightLayer.prototype.addExcludedMesh = function (mesh) {
  39891. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  39892. if (!meshExcluded) {
  39893. this._excludedMeshes[mesh.uniqueId] = {
  39894. mesh: mesh,
  39895. beforeRender: mesh.onBeforeRenderObservable.add(function (mesh) {
  39896. mesh.getEngine().setStencilBuffer(false);
  39897. }),
  39898. afterRender: mesh.onAfterRenderObservable.add(function (mesh) {
  39899. mesh.getEngine().setStencilBuffer(true);
  39900. }),
  39901. };
  39902. }
  39903. };
  39904. /**
  39905. * Remove a mesh from the exclusion list to let it impact or being impacted by the highlight layer.
  39906. * @param mesh The mesh to highlight
  39907. */
  39908. HighlightLayer.prototype.removeExcludedMesh = function (mesh) {
  39909. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  39910. if (meshExcluded) {
  39911. mesh.onBeforeRenderObservable.remove(meshExcluded.beforeRender);
  39912. mesh.onAfterRenderObservable.remove(meshExcluded.afterRender);
  39913. }
  39914. this._excludedMeshes[mesh.uniqueId] = undefined;
  39915. };
  39916. /**
  39917. * Add a mesh in the highlight layer in order to make it glow with the chosen color.
  39918. * @param mesh The mesh to highlight
  39919. * @param color The color of the highlight
  39920. * @param glowEmissiveOnly Extract the glow from the emissive texture
  39921. */
  39922. HighlightLayer.prototype.addMesh = function (mesh, color, glowEmissiveOnly) {
  39923. var _this = this;
  39924. if (glowEmissiveOnly === void 0) { glowEmissiveOnly = false; }
  39925. var meshHighlight = this._meshes[mesh.uniqueId];
  39926. if (meshHighlight) {
  39927. meshHighlight.color = color;
  39928. }
  39929. else {
  39930. this._meshes[mesh.uniqueId] = {
  39931. mesh: mesh,
  39932. color: color,
  39933. // Lambda required for capture due to Observable this context
  39934. observerHighlight: mesh.onBeforeRenderObservable.add(function (mesh) {
  39935. if (_this._excludedMeshes[mesh.uniqueId]) {
  39936. _this.defaultStencilReference(mesh);
  39937. }
  39938. else {
  39939. mesh.getScene().getEngine().setStencilFunctionReference(_this._instanceGlowingMeshStencilReference);
  39940. }
  39941. }),
  39942. observerDefault: mesh.onAfterRenderObservable.add(this.defaultStencilReference),
  39943. glowEmissiveOnly: glowEmissiveOnly
  39944. };
  39945. }
  39946. this._shouldRender = true;
  39947. };
  39948. /**
  39949. * Remove a mesh from the highlight layer in order to make it stop glowing.
  39950. * @param mesh The mesh to highlight
  39951. */
  39952. HighlightLayer.prototype.removeMesh = function (mesh) {
  39953. var meshHighlight = this._meshes[mesh.uniqueId];
  39954. if (meshHighlight) {
  39955. mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  39956. mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  39957. }
  39958. this._meshes[mesh.uniqueId] = undefined;
  39959. this._shouldRender = false;
  39960. for (var meshHighlightToCheck in this._meshes) {
  39961. if (meshHighlightToCheck) {
  39962. this._shouldRender = true;
  39963. break;
  39964. }
  39965. }
  39966. };
  39967. /**
  39968. * Returns true if the layer contains information to display, otherwise false.
  39969. */
  39970. HighlightLayer.prototype.shouldRender = function () {
  39971. return this.isEnabled && this._shouldRender;
  39972. };
  39973. /**
  39974. * Sets the main texture desired size which is the closest power of two
  39975. * of the engine canvas size.
  39976. */
  39977. HighlightLayer.prototype.setMainTextureSize = function () {
  39978. if (this._options.mainTextureFixedSize) {
  39979. this._mainTextureDesiredSize.width = this._options.mainTextureFixedSize;
  39980. this._mainTextureDesiredSize.height = this._options.mainTextureFixedSize;
  39981. }
  39982. else {
  39983. this._mainTextureDesiredSize.width = this._engine.getRenderingCanvas().width * this._options.mainTextureRatio;
  39984. this._mainTextureDesiredSize.height = this._engine.getRenderingCanvas().height * this._options.mainTextureRatio;
  39985. this._mainTextureDesiredSize.width = BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.width, this._maxSize);
  39986. this._mainTextureDesiredSize.height = BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.height, this._maxSize);
  39987. }
  39988. };
  39989. /**
  39990. * Force the stencil to the normal expected value for none glowing parts
  39991. */
  39992. HighlightLayer.prototype.defaultStencilReference = function (mesh) {
  39993. mesh.getScene().getEngine().setStencilFunctionReference(HighlightLayer.normalMeshStencilReference);
  39994. };
  39995. /**
  39996. * Dispose only the render target textures and post process.
  39997. */
  39998. HighlightLayer.prototype.disposeTextureAndPostProcesses = function () {
  39999. this._blurTexture.dispose();
  40000. this._mainTexture.dispose();
  40001. this._downSamplePostprocess.dispose();
  40002. this._horizontalBlurPostprocess.dispose();
  40003. this._verticalBlurPostprocess.dispose();
  40004. };
  40005. /**
  40006. * Dispose the highlight layer and free resources.
  40007. */
  40008. HighlightLayer.prototype.dispose = function () {
  40009. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  40010. if (vertexBuffer) {
  40011. vertexBuffer.dispose();
  40012. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  40013. }
  40014. if (this._indexBuffer) {
  40015. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  40016. this._indexBuffer = null;
  40017. }
  40018. // Clean textures and post processes
  40019. this.disposeTextureAndPostProcesses();
  40020. // Clean mesh references
  40021. for (var id in this._meshes) {
  40022. var meshHighlight = this._meshes[id];
  40023. if (meshHighlight && meshHighlight.mesh) {
  40024. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  40025. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  40026. }
  40027. }
  40028. this._meshes = null;
  40029. for (var id in this._excludedMeshes) {
  40030. var meshHighlight = this._excludedMeshes[id];
  40031. if (meshHighlight) {
  40032. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.beforeRender);
  40033. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.afterRender);
  40034. }
  40035. }
  40036. this._excludedMeshes = null;
  40037. // Remove from scene
  40038. var index = this._scene.highlightLayers.indexOf(this, 0);
  40039. if (index > -1) {
  40040. this._scene.highlightLayers.splice(index, 1);
  40041. }
  40042. // Callback
  40043. this.onDisposeObservable.notifyObservers(this);
  40044. this.onDisposeObservable.clear();
  40045. this.onBeforeRenderMainTextureObservable.clear();
  40046. this.onBeforeBlurObservable.clear();
  40047. this.onBeforeComposeObservable.clear();
  40048. this.onAfterComposeObservable.clear();
  40049. this.onSizeChangedObservable.clear();
  40050. };
  40051. return HighlightLayer;
  40052. }());
  40053. /**
  40054. * The neutral color used during the preparation of the glow effect.
  40055. * This is black by default as the blend operation is a blend operation.
  40056. */
  40057. HighlightLayer.neutralColor = new BABYLON.Color4(0, 0, 0, 0);
  40058. /**
  40059. * Stencil value used for glowing meshes.
  40060. */
  40061. HighlightLayer.glowingMeshStencilReference = 0x02;
  40062. /**
  40063. * Stencil value used for the other meshes in the scene.
  40064. */
  40065. HighlightLayer.normalMeshStencilReference = 0x01;
  40066. BABYLON.HighlightLayer = HighlightLayer;
  40067. })(BABYLON || (BABYLON = {}));
  40068. //# sourceMappingURL=babylon.highlightlayer.js.map
  40069. var BABYLON;
  40070. (function (BABYLON) {
  40071. var SIMDVector3 = (function () {
  40072. function SIMDVector3() {
  40073. }
  40074. SIMDVector3.TransformCoordinatesToRefSIMD = function (vector, transformation, result) {
  40075. SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD(vector.x, vector.y, vector.z, transformation, result);
  40076. };
  40077. SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD = function (x, y, z, transformation, result) {
  40078. var m = transformation.m;
  40079. var m0 = SIMD.Float32x4.load(m, 0);
  40080. var m1 = SIMD.Float32x4.load(m, 4);
  40081. var m2 = SIMD.Float32x4.load(m, 8);
  40082. var m3 = SIMD.Float32x4.load(m, 12);
  40083. 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));
  40084. r = SIMD.Float32x4.div(r, SIMD.Float32x4.swizzle(r, 3, 3, 3, 3));
  40085. result.x = SIMD.Float32x4.extractLane(r, 0);
  40086. result.y = SIMD.Float32x4.extractLane(r, 1);
  40087. result.z = SIMD.Float32x4.extractLane(r, 2);
  40088. };
  40089. return SIMDVector3;
  40090. }());
  40091. var SIMDMatrix = (function () {
  40092. function SIMDMatrix() {
  40093. }
  40094. SIMDMatrix.prototype.multiplyToArraySIMD = function (other, result, offset) {
  40095. var tm = this.m;
  40096. var om = other.m;
  40097. var m0 = SIMD.Float32x4.load(om, 0);
  40098. var m1 = SIMD.Float32x4.load(om, 4);
  40099. var m2 = SIMD.Float32x4.load(om, 8);
  40100. var m3 = SIMD.Float32x4.load(om, 12);
  40101. for (var i = 0; i < 16; i += 4) {
  40102. 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)))));
  40103. }
  40104. return this;
  40105. };
  40106. SIMDMatrix.prototype.invertToRefSIMD = function (other) {
  40107. var src = this.m;
  40108. var dest = other.m;
  40109. // Load the 4 rows
  40110. var src0 = SIMD.Float32x4.load(src, 0);
  40111. var src1 = SIMD.Float32x4.load(src, 4);
  40112. var src2 = SIMD.Float32x4.load(src, 8);
  40113. var src3 = SIMD.Float32x4.load(src, 12);
  40114. // Transpose the source matrix. Sort of. Not a true transpose operation
  40115. var tmp1 = SIMD.Float32x4.shuffle(src0, src1, 0, 1, 4, 5);
  40116. var row1 = SIMD.Float32x4.shuffle(src2, src3, 0, 1, 4, 5);
  40117. var row0 = SIMD.Float32x4.shuffle(tmp1, row1, 0, 2, 4, 6);
  40118. row1 = SIMD.Float32x4.shuffle(row1, tmp1, 1, 3, 5, 7);
  40119. tmp1 = SIMD.Float32x4.shuffle(src0, src1, 2, 3, 6, 7);
  40120. var row3 = SIMD.Float32x4.shuffle(src2, src3, 2, 3, 6, 7);
  40121. var row2 = SIMD.Float32x4.shuffle(tmp1, row3, 0, 2, 4, 6);
  40122. row3 = SIMD.Float32x4.shuffle(row3, tmp1, 1, 3, 5, 7);
  40123. // This is a true transposition, but it will lead to an incorrect result
  40124. //tmp1 = shuffle(src0, src1, 0, 1, 4, 5);
  40125. //tmp2 = shuffle(src2, src3, 0, 1, 4, 5);
  40126. //row0 = shuffle(tmp1, tmp2, 0, 2, 4, 6);
  40127. //row1 = shuffle(tmp1, tmp2, 1, 3, 5, 7);
  40128. //tmp1 = shuffle(src0, src1, 2, 3, 6, 7);
  40129. //tmp2 = shuffle(src2, src3, 2, 3, 6, 7);
  40130. //row2 = shuffle(tmp1, tmp2, 0, 2, 4, 6);
  40131. //row3 = shuffle(tmp1, tmp2, 1, 3, 5, 7);
  40132. // ----
  40133. tmp1 = SIMD.Float32x4.mul(row2, row3);
  40134. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  40135. var minor0 = SIMD.Float32x4.mul(row1, tmp1);
  40136. var minor1 = SIMD.Float32x4.mul(row0, tmp1);
  40137. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  40138. minor0 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row1, tmp1), minor0);
  40139. minor1 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row0, tmp1), minor1);
  40140. minor1 = SIMD.Float32x4.swizzle(minor1, 2, 3, 0, 1); // 0x4E = 01001110
  40141. // ----
  40142. tmp1 = SIMD.Float32x4.mul(row1, row2);
  40143. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  40144. minor0 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row3, tmp1), minor0);
  40145. var minor3 = SIMD.Float32x4.mul(row0, tmp1);
  40146. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  40147. minor0 = SIMD.Float32x4.sub(minor0, SIMD.Float32x4.mul(row3, tmp1));
  40148. minor3 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row0, tmp1), minor3);
  40149. minor3 = SIMD.Float32x4.swizzle(minor3, 2, 3, 0, 1); // 0x4E = 01001110
  40150. // ----
  40151. tmp1 = SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(row1, 2, 3, 0, 1), row3); // 0x4E = 01001110
  40152. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  40153. row2 = SIMD.Float32x4.swizzle(row2, 2, 3, 0, 1); // 0x4E = 01001110
  40154. minor0 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row2, tmp1), minor0);
  40155. var minor2 = SIMD.Float32x4.mul(row0, tmp1);
  40156. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  40157. minor0 = SIMD.Float32x4.sub(minor0, SIMD.Float32x4.mul(row2, tmp1));
  40158. minor2 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row0, tmp1), minor2);
  40159. minor2 = SIMD.Float32x4.swizzle(minor2, 2, 3, 0, 1); // 0x4E = 01001110
  40160. // ----
  40161. tmp1 = SIMD.Float32x4.mul(row0, row1);
  40162. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  40163. minor2 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row3, tmp1), minor2);
  40164. minor3 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row2, tmp1), minor3);
  40165. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  40166. minor2 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row3, tmp1), minor2);
  40167. minor3 = SIMD.Float32x4.sub(minor3, SIMD.Float32x4.mul(row2, tmp1));
  40168. // ----
  40169. tmp1 = SIMD.Float32x4.mul(row0, row3);
  40170. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  40171. minor1 = SIMD.Float32x4.sub(minor1, SIMD.Float32x4.mul(row2, tmp1));
  40172. minor2 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row1, tmp1), minor2);
  40173. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  40174. minor1 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row2, tmp1), minor1);
  40175. minor2 = SIMD.Float32x4.sub(minor2, SIMD.Float32x4.mul(row1, tmp1));
  40176. // ----
  40177. tmp1 = SIMD.Float32x4.mul(row0, row2);
  40178. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  40179. minor1 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row3, tmp1), minor1);
  40180. minor3 = SIMD.Float32x4.sub(minor3, SIMD.Float32x4.mul(row1, tmp1));
  40181. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  40182. minor1 = SIMD.Float32x4.sub(minor1, SIMD.Float32x4.mul(row3, tmp1));
  40183. minor3 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row1, tmp1), minor3);
  40184. // Compute determinant
  40185. var det = SIMD.Float32x4.mul(row0, minor0);
  40186. det = SIMD.Float32x4.add(SIMD.Float32x4.swizzle(det, 2, 3, 0, 1), det); // 0x4E = 01001110
  40187. det = SIMD.Float32x4.add(SIMD.Float32x4.swizzle(det, 1, 0, 3, 2), det); // 0xB1 = 10110001
  40188. tmp1 = SIMD.Float32x4.reciprocalApproximation(det);
  40189. det = SIMD.Float32x4.sub(SIMD.Float32x4.add(tmp1, tmp1), SIMD.Float32x4.mul(det, SIMD.Float32x4.mul(tmp1, tmp1)));
  40190. det = SIMD.Float32x4.swizzle(det, 0, 0, 0, 0);
  40191. // These shuffles aren't necessary if the faulty transposition is done
  40192. // up at the top of this function.
  40193. //minor0 =SIMD.Float32x4.swizzle(minor0, 2, 1, 0, 3);
  40194. //minor1 =SIMD.Float32x4.swizzle(minor1, 2, 1, 0, 3);
  40195. //minor2 =SIMD.Float32x4.swizzle(minor2, 2, 1, 0, 3);
  40196. //minor3 =SIMD.Float32x4.swizzle(minor3, 2, 1, 0, 3);
  40197. // Compute final values by multiplying with 1/det
  40198. SIMD.Float32x4.store(dest, 0, SIMD.Float32x4.mul(det, minor0));
  40199. SIMD.Float32x4.store(dest, 4, SIMD.Float32x4.mul(det, minor1));
  40200. SIMD.Float32x4.store(dest, 8, minor2 = SIMD.Float32x4.mul(det, minor2));
  40201. SIMD.Float32x4.store(dest, 12, SIMD.Float32x4.mul(det, minor3));
  40202. return this;
  40203. };
  40204. SIMDMatrix.LookAtLHToRefSIMD = function (eyeRef, targetRef, upRef, result) {
  40205. var out = result.m;
  40206. var center = SIMD.Float32x4(targetRef.x, targetRef.y, targetRef.z, 0.0);
  40207. var eye = SIMD.Float32x4(eyeRef.x, eyeRef.y, eyeRef.z, 0.0);
  40208. var up = SIMD.Float32x4(upRef.x, upRef.y, upRef.z, 0.0);
  40209. // cc.kmVec3Subtract(f, pCenter, pEye);
  40210. var f = SIMD.Float32x4.sub(center, eye);
  40211. // cc.kmVec3Normalize(f, f);
  40212. var tmp = SIMD.Float32x4.mul(f, f);
  40213. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  40214. f = SIMD.Float32x4.mul(f, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  40215. // cc.kmVec3Assign(up, pUp);
  40216. // cc.kmVec3Normalize(up, up);
  40217. tmp = SIMD.Float32x4.mul(up, up);
  40218. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  40219. up = SIMD.Float32x4.mul(up, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  40220. // cc.kmVec3Cross(s, f, up);
  40221. 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)));
  40222. // cc.kmVec3Normalize(s, s);
  40223. tmp = SIMD.Float32x4.mul(s, s);
  40224. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  40225. s = SIMD.Float32x4.mul(s, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  40226. // cc.kmVec3Cross(u, s, f);
  40227. 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)));
  40228. // cc.kmVec3Normalize(s, s);
  40229. tmp = SIMD.Float32x4.mul(s, s);
  40230. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  40231. s = SIMD.Float32x4.mul(s, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  40232. var zero = SIMD.Float32x4.splat(0.0);
  40233. s = SIMD.Float32x4.neg(s);
  40234. var tmp01 = SIMD.Float32x4.shuffle(s, u, 0, 1, 4, 5);
  40235. var tmp23 = SIMD.Float32x4.shuffle(f, zero, 0, 1, 4, 5);
  40236. var a0 = SIMD.Float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6);
  40237. var a1 = SIMD.Float32x4.shuffle(tmp01, tmp23, 1, 3, 5, 7);
  40238. 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);
  40239. var a3 = SIMD.Float32x4(0.0, 0.0, 0.0, 1.0);
  40240. var b = SIMD.Float32x4(1.0, 0.0, 0.0, 0.0);
  40241. 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)))));
  40242. b = SIMD.Float32x4(0.0, 1.0, 0.0, 0.0);
  40243. 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)))));
  40244. b = SIMD.Float32x4(0.0, 0.0, 1.0, 0.0);
  40245. 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)))));
  40246. b = SIMD.Float32x4.replaceLane(SIMD.Float32x4.neg(eye), 3, 1.0);
  40247. 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)))));
  40248. };
  40249. return SIMDMatrix;
  40250. }());
  40251. var previousMultiplyToArray = BABYLON.Matrix.prototype.multiplyToArray;
  40252. var previousInvertToRef = BABYLON.Matrix.prototype.invertToRef;
  40253. var previousLookAtLHToRef = BABYLON.Matrix.LookAtLHToRef;
  40254. var previousTransformCoordinatesToRef = BABYLON.Vector3.TransformCoordinatesToRef;
  40255. var previousTransformCoordinatesFromFloatsToRef = BABYLON.Vector3.TransformCoordinatesFromFloatsToRef;
  40256. var SIMDHelper = (function () {
  40257. function SIMDHelper() {
  40258. }
  40259. Object.defineProperty(SIMDHelper, "IsEnabled", {
  40260. get: function () {
  40261. return SIMDHelper._isEnabled;
  40262. },
  40263. enumerable: true,
  40264. configurable: true
  40265. });
  40266. SIMDHelper.DisableSIMD = function () {
  40267. // Replace functions
  40268. BABYLON.Matrix.prototype.multiplyToArray = previousMultiplyToArray;
  40269. BABYLON.Matrix.prototype.invertToRef = previousInvertToRef;
  40270. BABYLON.Matrix.LookAtLHToRef = previousLookAtLHToRef;
  40271. BABYLON.Vector3.TransformCoordinatesToRef = previousTransformCoordinatesToRef;
  40272. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = previousTransformCoordinatesFromFloatsToRef;
  40273. SIMDHelper._isEnabled = false;
  40274. };
  40275. SIMDHelper.EnableSIMD = function () {
  40276. if (self.SIMD === undefined) {
  40277. return;
  40278. }
  40279. // check if polyfills needed
  40280. if (!self.Math.fround) {
  40281. self.Math.fround = (function (array) { return function (x) {
  40282. return array[0] = x, array[0];
  40283. }; })(new Float32Array(1));
  40284. }
  40285. if (!self.Math.imul) {
  40286. self.Math.imul = function (a, b) {
  40287. var ah = (a >>> 16) & 0xffff;
  40288. var al = a & 0xffff;
  40289. var bh = (b >>> 16) & 0xffff;
  40290. var bl = b & 0xffff;
  40291. // the shift by 0 fixes the sign on the high part
  40292. // the final |0 converts the unsigned value into a signed value
  40293. return ((al * bl) + (((ah * bl + al * bh) << 16) >>> 0) | 0);
  40294. };
  40295. }
  40296. // Replace functions
  40297. BABYLON.Matrix.prototype.multiplyToArray = SIMDMatrix.prototype.multiplyToArraySIMD;
  40298. BABYLON.Matrix.prototype.invertToRef = SIMDMatrix.prototype.invertToRefSIMD;
  40299. BABYLON.Matrix.LookAtLHToRef = SIMDMatrix.LookAtLHToRefSIMD;
  40300. BABYLON.Vector3.TransformCoordinatesToRef = SIMDVector3.TransformCoordinatesToRefSIMD;
  40301. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD;
  40302. SIMDHelper._isEnabled = true;
  40303. };
  40304. return SIMDHelper;
  40305. }());
  40306. SIMDHelper._isEnabled = false;
  40307. BABYLON.SIMDHelper = SIMDHelper;
  40308. })(BABYLON || (BABYLON = {}));
  40309. //# sourceMappingURL=babylon.math.SIMD.js.map
  40310. var BABYLON;
  40311. (function (BABYLON) {
  40312. /**
  40313. * This class describe a rectangle that were added to the map.
  40314. * You have access to its coordinates either in pixel or normalized (UV)
  40315. */
  40316. var PackedRect = (function () {
  40317. function PackedRect(root, parent, pos, size) {
  40318. this._pos = pos;
  40319. this._size = size;
  40320. this._root = root;
  40321. this._parent = parent;
  40322. this._contentSize = null;
  40323. this._bottomNode = null;
  40324. this._leftNode = null;
  40325. this._initialSize = null;
  40326. this._rightNode = null;
  40327. }
  40328. Object.defineProperty(PackedRect.prototype, "pos", {
  40329. /**
  40330. * @returns the position of this node into the map
  40331. */
  40332. get: function () {
  40333. return this._pos;
  40334. },
  40335. enumerable: true,
  40336. configurable: true
  40337. });
  40338. Object.defineProperty(PackedRect.prototype, "contentSize", {
  40339. /**
  40340. * @returns the size of the rectangle this node handles
  40341. */
  40342. get: function () {
  40343. return this._contentSize;
  40344. },
  40345. enumerable: true,
  40346. configurable: true
  40347. });
  40348. Object.defineProperty(PackedRect.prototype, "UVs", {
  40349. /**
  40350. * Compute the UV of the top/left, top/right, bottom/right, bottom/left points of the rectangle this node handles into the map
  40351. * @returns And array of 4 Vector2, containing UV coordinates for the four corners of the Rectangle into the map
  40352. */
  40353. get: function () {
  40354. return this.getUVsForCustomSize(this._root._size);
  40355. },
  40356. enumerable: true,
  40357. configurable: true
  40358. });
  40359. /**
  40360. * 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.
  40361. * This method will return the UVs for this part by given the custom size of what you really use
  40362. * @param customSize must be less/equal to the allocated size, UV will be compute from this
  40363. */
  40364. PackedRect.prototype.getUVsForCustomSize = function (customSize) {
  40365. var mainWidth = this._root._size.width;
  40366. var mainHeight = this._root._size.height;
  40367. var topLeft = new BABYLON.Vector2(this._pos.x / mainWidth, this._pos.y / mainHeight);
  40368. var rightBottom = new BABYLON.Vector2((this._pos.x + customSize.width - 1) / mainWidth, (this._pos.y + customSize.height - 1) / mainHeight);
  40369. var uvs = new Array();
  40370. uvs.push(topLeft);
  40371. uvs.push(new BABYLON.Vector2(rightBottom.x, topLeft.y));
  40372. uvs.push(rightBottom);
  40373. uvs.push(new BABYLON.Vector2(topLeft.x, rightBottom.y));
  40374. return uvs;
  40375. };
  40376. /**
  40377. * Free this rectangle from the map.
  40378. * Call this method when you no longer need the rectangle to be in the map.
  40379. */
  40380. PackedRect.prototype.freeContent = function () {
  40381. if (!this.contentSize) {
  40382. return;
  40383. }
  40384. this._contentSize = null;
  40385. // If everything below is also free, reset the whole node, and attempt to reset parents if they also become free
  40386. this.attemptDefrag();
  40387. };
  40388. Object.defineProperty(PackedRect.prototype, "isUsed", {
  40389. get: function () {
  40390. return this._contentSize != null || this._leftNode != null;
  40391. },
  40392. enumerable: true,
  40393. configurable: true
  40394. });
  40395. PackedRect.prototype.findAndSplitNode = function (contentSize) {
  40396. var node = this.findNode(contentSize);
  40397. // Not enough space...
  40398. if (!node) {
  40399. return null;
  40400. }
  40401. node.splitNode(contentSize);
  40402. return node;
  40403. };
  40404. PackedRect.prototype.findNode = function (size) {
  40405. var resNode = null;
  40406. // If this node is used, recurse to each of his subNodes to find an available one in its branch
  40407. if (this.isUsed) {
  40408. if (this._leftNode) {
  40409. resNode = this._leftNode.findNode(size);
  40410. }
  40411. if (!resNode && this._rightNode) {
  40412. resNode = this._rightNode.findNode(size);
  40413. }
  40414. if (!resNode && this._bottomNode) {
  40415. resNode = this._bottomNode.findNode(size);
  40416. }
  40417. }
  40418. else if (this._initialSize) {
  40419. if ((size.width <= this._initialSize.width) && (size.height <= this._initialSize.height)) {
  40420. resNode = this;
  40421. }
  40422. else {
  40423. return null;
  40424. }
  40425. }
  40426. else if ((size.width <= this._size.width) && (size.height <= this._size.height)) {
  40427. resNode = this;
  40428. }
  40429. return resNode;
  40430. };
  40431. PackedRect.prototype.splitNode = function (contentSize) {
  40432. // 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)
  40433. if (!this._contentSize && this._initialSize) {
  40434. this._contentSize = contentSize.clone();
  40435. 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));
  40436. return this._leftNode.splitNode(contentSize);
  40437. }
  40438. else {
  40439. this._contentSize = contentSize.clone();
  40440. this._initialSize = contentSize.clone();
  40441. if (contentSize.width !== this._size.width) {
  40442. 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));
  40443. }
  40444. if (contentSize.height !== this._size.height) {
  40445. 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));
  40446. }
  40447. return this;
  40448. }
  40449. };
  40450. PackedRect.prototype.attemptDefrag = function () {
  40451. if (!this.isUsed && this.isRecursiveFree) {
  40452. this.clearNode();
  40453. if (this._parent) {
  40454. this._parent.attemptDefrag();
  40455. }
  40456. }
  40457. };
  40458. PackedRect.prototype.clearNode = function () {
  40459. this._initialSize = null;
  40460. this._rightNode = null;
  40461. this._bottomNode = null;
  40462. };
  40463. Object.defineProperty(PackedRect.prototype, "isRecursiveFree", {
  40464. get: function () {
  40465. return !this.contentSize && (!this._leftNode || this._leftNode.isRecursiveFree) && (!this._rightNode || this._rightNode.isRecursiveFree) && (!this._bottomNode || this._bottomNode.isRecursiveFree);
  40466. },
  40467. enumerable: true,
  40468. configurable: true
  40469. });
  40470. PackedRect.prototype.evalFreeSize = function (size) {
  40471. var levelSize = 0;
  40472. if (!this.isUsed) {
  40473. if (this._initialSize) {
  40474. levelSize = this._initialSize.surface;
  40475. }
  40476. else {
  40477. levelSize = this._size.surface;
  40478. }
  40479. }
  40480. if (this._rightNode) {
  40481. levelSize += this._rightNode.evalFreeSize(0);
  40482. }
  40483. if (this._bottomNode) {
  40484. levelSize += this._bottomNode.evalFreeSize(0);
  40485. }
  40486. return levelSize + size;
  40487. };
  40488. return PackedRect;
  40489. }());
  40490. BABYLON.PackedRect = PackedRect;
  40491. /**
  40492. * The purpose of this class is to pack several Rectangles into a big map, while trying to fit everything as optimally as possible.
  40493. * This class is typically used to build lightmaps, sprite map or to pack several little textures into a big one.
  40494. * 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.
  40495. */
  40496. var RectPackingMap = (function (_super) {
  40497. __extends(RectPackingMap, _super);
  40498. /**
  40499. * Create an instance of the object with a dimension using the given size
  40500. * @param size The dimension of the rectangle that will contain all the sub ones.
  40501. */
  40502. function RectPackingMap(size) {
  40503. var _this = _super.call(this, null, null, BABYLON.Vector2.Zero(), size) || this;
  40504. _this._root = _this;
  40505. return _this;
  40506. }
  40507. /**
  40508. * Add a rectangle, finding the best location to store it into the map
  40509. * @param size the dimension of the rectangle to store
  40510. * @return the Node containing the rectangle information, or null if we couldn't find a free spot
  40511. */
  40512. RectPackingMap.prototype.addRect = function (size) {
  40513. var node = this.findAndSplitNode(size);
  40514. return node;
  40515. };
  40516. Object.defineProperty(RectPackingMap.prototype, "freeSpace", {
  40517. /**
  40518. * Return the current space free normalized between [0;1]
  40519. * @returns {}
  40520. */
  40521. get: function () {
  40522. var freeSize = 0;
  40523. freeSize = this.evalFreeSize(freeSize);
  40524. return freeSize / (this._size.width * this._size.height);
  40525. },
  40526. enumerable: true,
  40527. configurable: true
  40528. });
  40529. return RectPackingMap;
  40530. }(PackedRect));
  40531. BABYLON.RectPackingMap = RectPackingMap;
  40532. })(BABYLON || (BABYLON = {}));
  40533. //# sourceMappingURL=babylon.rectPackingMap.js.map
  40534. var BABYLON;
  40535. (function (BABYLON) {
  40536. var DynamicFloatArrayElementInfo = (function () {
  40537. function DynamicFloatArrayElementInfo() {
  40538. }
  40539. return DynamicFloatArrayElementInfo;
  40540. }());
  40541. BABYLON.DynamicFloatArrayElementInfo = DynamicFloatArrayElementInfo;
  40542. /**
  40543. * 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.
  40544. * The intent is to maintain through time data that will be bound to a WebGlBuffer with the ability to change add/remove elements.
  40545. * It was first built to efficiently maintain the WebGlBuffer that contain instancing based data.
  40546. * 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.
  40547. * 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.
  40548. * 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".
  40549. */
  40550. var DynamicFloatArray = (function () {
  40551. /**
  40552. * Construct an instance of the dynamic float array
  40553. * @param stride size of one element in float (i.e. not bytes!)
  40554. * @param initialElementCount the number of available entries at construction
  40555. */
  40556. function DynamicFloatArray(stride, initialElementCount) {
  40557. this.compareValueOffset = null;
  40558. this.sortingAscending = true;
  40559. this._stride = stride;
  40560. this.buffer = new Float32Array(stride * initialElementCount);
  40561. this._lastUsed = 0;
  40562. this._firstFree = 0;
  40563. this._allEntries = new Array(initialElementCount);
  40564. this._freeEntries = new Array(initialElementCount);
  40565. for (var i = 0; i < initialElementCount; i++) {
  40566. var element = new DynamicFloatArrayElementInfo();
  40567. element.offset = i * stride;
  40568. this._allEntries[i] = element;
  40569. this._freeEntries[initialElementCount - i - 1] = element;
  40570. }
  40571. }
  40572. /**
  40573. * Allocate an element in the array.
  40574. * @return the element info instance that contains the offset into the main buffer of the element's location.
  40575. * Beware, this offset may change when you call pack()
  40576. */
  40577. DynamicFloatArray.prototype.allocElement = function () {
  40578. if (this._freeEntries.length === 0) {
  40579. this._growBuffer();
  40580. }
  40581. var el = this._freeEntries.pop();
  40582. this._lastUsed = Math.max(el.offset, this._lastUsed);
  40583. if (el.offset === this._firstFree) {
  40584. if (this._freeEntries.length > 0) {
  40585. this._firstFree = this._freeEntries[this._freeEntries.length - 1].offset;
  40586. }
  40587. else {
  40588. this._firstFree += this._stride;
  40589. }
  40590. }
  40591. return el;
  40592. };
  40593. /**
  40594. * Free the element corresponding to the given element info
  40595. * @param elInfo the element that describe the allocated element
  40596. */
  40597. DynamicFloatArray.prototype.freeElement = function (elInfo) {
  40598. this._firstFree = Math.min(elInfo.offset, this._firstFree);
  40599. this._freeEntries.push(elInfo);
  40600. };
  40601. /**
  40602. * This method will pack all the used elements into a linear sequence and put all the free space at the end.
  40603. * 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().
  40604. * @return the subArray that is the view of the used elements area, you can use it as a source to update a WebGLBuffer
  40605. */
  40606. DynamicFloatArray.prototype.pack = function () {
  40607. // no free slot? no need to pack
  40608. if (this._freeEntries.length === 0) {
  40609. return this.buffer;
  40610. }
  40611. // If the buffer is already packed the last used will always be lower than the first free
  40612. // 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.
  40613. if (this._lastUsed < this._firstFree) {
  40614. var elementsBuffer_1 = this.buffer.subarray(0, this._lastUsed + this._stride);
  40615. return elementsBuffer_1;
  40616. }
  40617. var s = this._stride;
  40618. // 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
  40619. var lastFree = new DynamicFloatArrayElementInfo();
  40620. lastFree.offset = this.totalElementCount * s;
  40621. this._freeEntries.push(lastFree);
  40622. var sortedFree = this._freeEntries.sort(function (a, b) { return a.offset - b.offset; });
  40623. var sortedAll = this._allEntries.sort(function (a, b) { return a.offset - b.offset; });
  40624. var firstFreeSlotOffset = sortedFree[0].offset;
  40625. var freeZoneSize = 1;
  40626. var occupiedZoneSize = (this.usedElementCount + 1) * s;
  40627. var prevOffset = sortedFree[0].offset;
  40628. for (var i = 1; i < sortedFree.length; i++) {
  40629. // 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
  40630. if (firstFreeSlotOffset >= occupiedZoneSize) {
  40631. break;
  40632. }
  40633. var curFree = sortedFree[i];
  40634. var curOffset = curFree.offset;
  40635. // Compute the distance between this offset and the previous
  40636. var distance = curOffset - prevOffset;
  40637. // If the distance is the stride size, they are adjacent, it good, move to the next
  40638. if (distance === s) {
  40639. // Free zone is one element bigger
  40640. ++freeZoneSize;
  40641. // as we're about to iterate to the next, the cur becomes the previous...
  40642. prevOffset = curOffset;
  40643. continue;
  40644. }
  40645. // Distance is bigger, which means there's x element between the previous free and this one
  40646. var usedRange = (distance / s) - 1;
  40647. // Two cases the free zone is smaller than the data to move or bigger
  40648. // Copy what can fit in the free zone
  40649. var curMoveOffset = curOffset - s;
  40650. var copyCount = Math.min(freeZoneSize, usedRange);
  40651. for (var j = 0; j < copyCount; j++) {
  40652. var freeI = firstFreeSlotOffset / s;
  40653. var curI = curMoveOffset / s;
  40654. var moveEl = sortedAll[curI];
  40655. this._moveElement(moveEl, firstFreeSlotOffset);
  40656. var replacedEl = sortedAll[freeI];
  40657. // set the offset of the element we replaced with a value that will make it discard at the end of the method
  40658. replacedEl.offset = curMoveOffset;
  40659. // Swap the element we moved and the one it replaced in the sorted array to reflect the action we've made
  40660. sortedAll[freeI] = moveEl;
  40661. sortedAll[curI] = replacedEl;
  40662. curMoveOffset -= s;
  40663. firstFreeSlotOffset += s;
  40664. }
  40665. // Free Zone is smaller or equal so it's no longer a free zone, set the new one to the current location
  40666. if (freeZoneSize <= usedRange) {
  40667. firstFreeSlotOffset = curMoveOffset + s;
  40668. freeZoneSize = 1 + copyCount;
  40669. }
  40670. else {
  40671. freeZoneSize = ((curOffset - firstFreeSlotOffset) / s) + 1;
  40672. }
  40673. // as we're about to iterate to the next, the cur becomes the previous...
  40674. prevOffset = curOffset;
  40675. }
  40676. var elementsBuffer = this.buffer.subarray(0, firstFreeSlotOffset);
  40677. this._lastUsed = firstFreeSlotOffset - s;
  40678. this._firstFree = firstFreeSlotOffset;
  40679. sortedFree.pop(); // Remove the last free because that's the one we added at the start of the method
  40680. this._freeEntries = sortedFree.sort(function (a, b) { return b.offset - a.offset; });
  40681. this._allEntries = sortedAll;
  40682. return elementsBuffer;
  40683. };
  40684. DynamicFloatArray.prototype._moveElement = function (element, destOffset) {
  40685. for (var i = 0; i < this._stride; i++) {
  40686. this.buffer[destOffset + i] = this.buffer[element.offset + i];
  40687. }
  40688. element.offset = destOffset;
  40689. };
  40690. DynamicFloatArray.prototype._growBuffer = function () {
  40691. // Allocate the new buffer with 50% more entries, copy the content of the current one
  40692. var newElCount = Math.floor(this.totalElementCount * 1.5);
  40693. var newBuffer = new Float32Array(newElCount * this._stride);
  40694. newBuffer.set(this.buffer);
  40695. var curCount = this.totalElementCount;
  40696. var addedCount = newElCount - this.totalElementCount;
  40697. for (var i = 0; i < addedCount; i++) {
  40698. var element = new DynamicFloatArrayElementInfo();
  40699. element.offset = (curCount + i) * this.stride;
  40700. this._allEntries.push(element);
  40701. this._freeEntries[addedCount - i - 1] = element;
  40702. }
  40703. this._firstFree = curCount * this.stride;
  40704. this.buffer = newBuffer;
  40705. };
  40706. Object.defineProperty(DynamicFloatArray.prototype, "totalElementCount", {
  40707. /**
  40708. * Get the total count of entries that can fit in the current buffer
  40709. * @returns the elements count
  40710. */
  40711. get: function () {
  40712. return this._allEntries.length;
  40713. },
  40714. enumerable: true,
  40715. configurable: true
  40716. });
  40717. Object.defineProperty(DynamicFloatArray.prototype, "freeElementCount", {
  40718. /**
  40719. * Get the count of free entries that can still be allocated without resizing the buffer
  40720. * @returns the free elements count
  40721. */
  40722. get: function () {
  40723. return this._freeEntries.length;
  40724. },
  40725. enumerable: true,
  40726. configurable: true
  40727. });
  40728. Object.defineProperty(DynamicFloatArray.prototype, "usedElementCount", {
  40729. /**
  40730. * Get the count of allocated elements
  40731. * @returns the allocated elements count
  40732. */
  40733. get: function () {
  40734. return this._allEntries.length - this._freeEntries.length;
  40735. },
  40736. enumerable: true,
  40737. configurable: true
  40738. });
  40739. Object.defineProperty(DynamicFloatArray.prototype, "stride", {
  40740. /**
  40741. * Return the size of one element in float
  40742. * @returns the size in float
  40743. */
  40744. get: function () {
  40745. return this._stride;
  40746. },
  40747. enumerable: true,
  40748. configurable: true
  40749. });
  40750. DynamicFloatArray.prototype.sort = function () {
  40751. var _this = this;
  40752. if (!this.compareValueOffset) {
  40753. throw new Error("The DynamicFloatArray.sort() method needs a valid 'compareValueOffset' property");
  40754. }
  40755. var count = this.usedElementCount;
  40756. // Do we have to (re)create the sort table?
  40757. if (!this._sortTable || this._sortTable.length < count) {
  40758. // 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...
  40759. var newCount = Math.min(this.totalElementCount, count * 2);
  40760. this._sortTable = new Array(newCount);
  40761. }
  40762. if (!this._sortedTable || this._sortedTable.length !== count) {
  40763. this._sortedTable = new Array(count);
  40764. }
  40765. // Because, you know...
  40766. this.pack();
  40767. //let stride = this.stride;
  40768. //for (let i = 0; i < count; i++) {
  40769. // let si = this._sortTable[i];
  40770. // if (!si) {
  40771. // si = new SortInfo();
  40772. // this._sortTable[i] = si;
  40773. // }
  40774. // si.entry = this._allEntries[i];
  40775. // si.compareData = this.buffer[si.entry.offset + this.compareValueOffset];
  40776. // si.swapedOffset = null;
  40777. // this._sortedTable[i] = si;
  40778. //}
  40779. var curOffset = 0;
  40780. var stride = this.stride;
  40781. for (var i = 0; i < count; i++, curOffset += stride) {
  40782. var si = this._sortTable[i];
  40783. if (!si) {
  40784. si = new SortInfo();
  40785. this._sortTable[i] = si;
  40786. }
  40787. si.compareData = this.buffer[curOffset + this.compareValueOffset];
  40788. si.offset = curOffset;
  40789. si.swapedOffset = null;
  40790. this._sortedTable[i] = si;
  40791. }
  40792. // Let's sort the sorted table, we want to keep a track of the original one (that's why we have two buffers)
  40793. if (this.sortingAscending) {
  40794. this._sortedTable.sort(function (a, b) { return a.compareData - b.compareData; });
  40795. }
  40796. else {
  40797. this._sortedTable.sort(function (a, b) { return b.compareData - a.compareData; });
  40798. }
  40799. var swapElements = function (src, dst) {
  40800. for (var i = 0; i < stride; i++) {
  40801. var tps = _this.buffer[dst + i];
  40802. _this.buffer[dst + i] = _this.buffer[src + i];
  40803. _this.buffer[src + i] = tps;
  40804. }
  40805. };
  40806. // 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:
  40807. // 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),
  40808. // and I still want something with a good algorithm complexity.
  40809. // 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,
  40810. // we need sortTable for that, it contains the original layout of SortInfo object, not the sorted one.
  40811. // The best way is to use an extra field in SortInfo, because potentially every element can be replaced.
  40812. // 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
  40813. // until we find a SortInfo object without a swapedOffset which means we got the right location
  40814. // 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
  40815. // than a double allocation of the whole float32Array or a O(n²/2) typical algorithm.
  40816. for (var i = 0; i < count; i++) {
  40817. // Get the element to move
  40818. var sourceSI = this._sortedTable[i];
  40819. var destSI = this._sortTable[i];
  40820. var sourceOff = sourceSI.offset;
  40821. // If the source changed location, find the new one
  40822. if (sourceSI.swapedOffset) {
  40823. // Follow the swapedOffset until there's none, it will mean that curSI contains the new location in its offset member
  40824. var curSI = sourceSI;
  40825. while (curSI.swapedOffset) {
  40826. curSI = this._sortTable[curSI.swapedOffset / stride];
  40827. }
  40828. // Finally get the right location
  40829. sourceOff = curSI.offset;
  40830. }
  40831. // Tag the element being replaced with its new location
  40832. destSI.swapedOffset = sourceOff;
  40833. // Swap elements (only if needed)
  40834. if (sourceOff !== destSI.offset) {
  40835. swapElements(sourceOff, destSI.offset);
  40836. }
  40837. // Update the offset in the corresponding DFAE
  40838. //sourceSI.entry.offset = destSI.entry.offset;
  40839. this._allEntries[sourceSI.offset / stride].offset = destSI.offset;
  40840. }
  40841. this._allEntries.sort(function (a, b) { return a.offset - b.offset; });
  40842. return true;
  40843. };
  40844. return DynamicFloatArray;
  40845. }());
  40846. BABYLON.DynamicFloatArray = DynamicFloatArray;
  40847. var SortInfo = (function () {
  40848. function SortInfo() {
  40849. this.compareData = this.offset = this.swapedOffset = null;
  40850. }
  40851. return SortInfo;
  40852. }());
  40853. })(BABYLON || (BABYLON = {}));
  40854. //# sourceMappingURL=babylon.dynamicFloatArray.js.map
  40855. var BABYLON;
  40856. (function (BABYLON) {
  40857. var MapTexture = (function (_super) {
  40858. __extends(MapTexture, _super);
  40859. function MapTexture(name, scene, size, samplingMode, useMipMap) {
  40860. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  40861. if (useMipMap === void 0) { useMipMap = false; }
  40862. var _this = _super.call(this, null, scene, !useMipMap, false, samplingMode) || this;
  40863. _this.name = name;
  40864. _this._size = size;
  40865. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  40866. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  40867. // Create the rectPackMap that will allocate portion of the texture
  40868. _this._rectPackingMap = new BABYLON.RectPackingMap(new BABYLON.Size(size.width, size.height));
  40869. // Create the texture that will store the content
  40870. _this._texture = scene.getEngine().createRenderTargetTexture(size, { generateMipMaps: !_this.noMipmap, type: BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT });
  40871. return _this;
  40872. }
  40873. /**
  40874. * Allocate a rectangle of a given size in the texture map
  40875. * @param size the size of the rectangle to allocation
  40876. * @return the PackedRect instance corresponding to the allocated rect or null is there was not enough space to allocate it.
  40877. */
  40878. MapTexture.prototype.allocateRect = function (size) {
  40879. return this._rectPackingMap.addRect(size);
  40880. };
  40881. /**
  40882. * Free a given rectangle from the texture map
  40883. * @param rectInfo the instance corresponding to the rect to free.
  40884. */
  40885. MapTexture.prototype.freeRect = function (rectInfo) {
  40886. if (rectInfo) {
  40887. rectInfo.freeContent();
  40888. }
  40889. };
  40890. Object.defineProperty(MapTexture.prototype, "freeSpace", {
  40891. /**
  40892. * Return the available space in the range of [O;1]. 0 being not space left at all, 1 being an empty texture map.
  40893. * This is the cumulated space, not the biggest available surface. Due to fragmentation you may not allocate a rect corresponding to this surface.
  40894. * @returns {}
  40895. */
  40896. get: function () {
  40897. return this._rectPackingMap.freeSpace;
  40898. },
  40899. enumerable: true,
  40900. configurable: true
  40901. });
  40902. /**
  40903. * Bind the texture to the rendering engine to render in the zone of a given rectangle.
  40904. * 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.
  40905. * Don't forget to call unbindTexture when you're done rendering
  40906. * @param rect the zone to render to
  40907. * @param clear true to clear the portion's color/depth data
  40908. */
  40909. MapTexture.prototype.bindTextureForRect = function (rect, clear) {
  40910. return this.bindTextureForPosSize(rect.pos, rect.contentSize, clear);
  40911. };
  40912. /**
  40913. * Bind the texture to the rendering engine to render in the zone of the given size at the given position.
  40914. * 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.
  40915. * Don't forget to call unbindTexture when you're done rendering
  40916. * @param pos the position into the texture
  40917. * @param size the portion to fit the clip space to
  40918. * @param clear true to clear the portion's color/depth data
  40919. */
  40920. MapTexture.prototype.bindTextureForPosSize = function (pos, size, clear) {
  40921. var engine = this.getScene().getEngine();
  40922. engine.bindFramebuffer(this._texture);
  40923. this._replacedViewport = engine.setDirectViewport(pos.x, pos.y, size.width, size.height);
  40924. if (clear) {
  40925. // We only want to clear the part of the texture we're binding to, only the scissor can help us to achieve that
  40926. engine.scissorClear(pos.x, pos.y, size.width, size.height, new BABYLON.Color4(0, 0, 0, 0));
  40927. }
  40928. };
  40929. /**
  40930. * Unbind the texture map from the rendering engine.
  40931. * Call this method when you're done rendering. A previous call to bindTextureForRect has to be made.
  40932. * @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.
  40933. */
  40934. MapTexture.prototype.unbindTexture = function (dumpForDebug) {
  40935. // Dump ?
  40936. if (dumpForDebug) {
  40937. BABYLON.Tools.DumpFramebuffer(this._size.width, this._size.height, this.getScene().getEngine());
  40938. }
  40939. var engine = this.getScene().getEngine();
  40940. if (this._replacedViewport) {
  40941. engine.setViewport(this._replacedViewport);
  40942. this._replacedViewport = null;
  40943. }
  40944. engine.unBindFramebuffer(this._texture);
  40945. };
  40946. Object.defineProperty(MapTexture.prototype, "canRescale", {
  40947. get: function () {
  40948. return false;
  40949. },
  40950. enumerable: true,
  40951. configurable: true
  40952. });
  40953. // Note, I don't know what behavior this method should have: clone the underlying texture/rectPackingMap or just reference them?
  40954. // Anyway, there's not much point to use this method for this kind of texture I guess
  40955. MapTexture.prototype.clone = function () {
  40956. return null;
  40957. };
  40958. return MapTexture;
  40959. }(BABYLON.Texture));
  40960. BABYLON.MapTexture = MapTexture;
  40961. })(BABYLON || (BABYLON = {}));
  40962. //# sourceMappingURL=babylon.mapTexture.js.map
  40963. var BABYLON;
  40964. (function (BABYLON) {
  40965. var ShaderMaterial = (function (_super) {
  40966. __extends(ShaderMaterial, _super);
  40967. function ShaderMaterial(name, scene, shaderPath, options) {
  40968. var _this = _super.call(this, name, scene) || this;
  40969. _this._textures = {};
  40970. _this._textureArrays = {};
  40971. _this._floats = {};
  40972. _this._floatsArrays = {};
  40973. _this._colors3 = {};
  40974. _this._colors4 = {};
  40975. _this._vectors2 = {};
  40976. _this._vectors3 = {};
  40977. _this._vectors4 = {};
  40978. _this._matrices = {};
  40979. _this._matrices3x3 = {};
  40980. _this._matrices2x2 = {};
  40981. _this._vectors3Arrays = {};
  40982. _this._cachedWorldViewMatrix = new BABYLON.Matrix();
  40983. _this._shaderPath = shaderPath;
  40984. options.needAlphaBlending = options.needAlphaBlending || false;
  40985. options.needAlphaTesting = options.needAlphaTesting || false;
  40986. options.attributes = options.attributes || ["position", "normal", "uv"];
  40987. options.uniforms = options.uniforms || ["worldViewProjection"];
  40988. options.samplers = options.samplers || [];
  40989. options.defines = options.defines || [];
  40990. _this._options = options;
  40991. return _this;
  40992. }
  40993. ShaderMaterial.prototype.getClassName = function () {
  40994. return "ShaderMaterial";
  40995. };
  40996. ShaderMaterial.prototype.needAlphaBlending = function () {
  40997. return this._options.needAlphaBlending;
  40998. };
  40999. ShaderMaterial.prototype.needAlphaTesting = function () {
  41000. return this._options.needAlphaTesting;
  41001. };
  41002. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  41003. if (this._options.uniforms.indexOf(uniformName) === -1) {
  41004. this._options.uniforms.push(uniformName);
  41005. }
  41006. };
  41007. ShaderMaterial.prototype.setTexture = function (name, texture) {
  41008. if (this._options.samplers.indexOf(name) === -1) {
  41009. this._options.samplers.push(name);
  41010. }
  41011. this._textures[name] = texture;
  41012. return this;
  41013. };
  41014. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  41015. if (this._options.samplers.indexOf(name) === -1) {
  41016. this._options.samplers.push(name);
  41017. }
  41018. this._checkUniform(name);
  41019. this._textureArrays[name] = textures;
  41020. return this;
  41021. };
  41022. ShaderMaterial.prototype.setFloat = function (name, value) {
  41023. this._checkUniform(name);
  41024. this._floats[name] = value;
  41025. return this;
  41026. };
  41027. ShaderMaterial.prototype.setFloats = function (name, value) {
  41028. this._checkUniform(name);
  41029. this._floatsArrays[name] = value;
  41030. return this;
  41031. };
  41032. ShaderMaterial.prototype.setColor3 = function (name, value) {
  41033. this._checkUniform(name);
  41034. this._colors3[name] = value;
  41035. return this;
  41036. };
  41037. ShaderMaterial.prototype.setColor4 = function (name, value) {
  41038. this._checkUniform(name);
  41039. this._colors4[name] = value;
  41040. return this;
  41041. };
  41042. ShaderMaterial.prototype.setVector2 = function (name, value) {
  41043. this._checkUniform(name);
  41044. this._vectors2[name] = value;
  41045. return this;
  41046. };
  41047. ShaderMaterial.prototype.setVector3 = function (name, value) {
  41048. this._checkUniform(name);
  41049. this._vectors3[name] = value;
  41050. return this;
  41051. };
  41052. ShaderMaterial.prototype.setVector4 = function (name, value) {
  41053. this._checkUniform(name);
  41054. this._vectors4[name] = value;
  41055. return this;
  41056. };
  41057. ShaderMaterial.prototype.setMatrix = function (name, value) {
  41058. this._checkUniform(name);
  41059. this._matrices[name] = value;
  41060. return this;
  41061. };
  41062. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  41063. this._checkUniform(name);
  41064. this._matrices3x3[name] = value;
  41065. return this;
  41066. };
  41067. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  41068. this._checkUniform(name);
  41069. this._matrices2x2[name] = value;
  41070. return this;
  41071. };
  41072. ShaderMaterial.prototype.setArray3 = function (name, value) {
  41073. this._checkUniform(name);
  41074. this._vectors3Arrays[name] = value;
  41075. return this;
  41076. };
  41077. ShaderMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  41078. if (!mesh) {
  41079. return true;
  41080. }
  41081. if (this._effect && (this._effect.defines.indexOf("#define INSTANCES") !== -1) !== useInstances) {
  41082. return false;
  41083. }
  41084. return false;
  41085. };
  41086. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  41087. var scene = this.getScene();
  41088. var engine = scene.getEngine();
  41089. if (!this.checkReadyOnEveryCall) {
  41090. if (this._renderId === scene.getRenderId()) {
  41091. if (this._checkCache(scene, mesh, useInstances)) {
  41092. return true;
  41093. }
  41094. }
  41095. }
  41096. // Instances
  41097. var defines = [];
  41098. var fallbacks = new BABYLON.EffectFallbacks();
  41099. if (useInstances) {
  41100. defines.push("#define INSTANCES");
  41101. }
  41102. for (var index = 0; index < this._options.defines.length; index++) {
  41103. defines.push(this._options.defines[index]);
  41104. }
  41105. // Bones
  41106. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  41107. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  41108. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  41109. fallbacks.addCPUSkinningFallback(0, mesh);
  41110. }
  41111. // Alpha test
  41112. if (engine.getAlphaTesting()) {
  41113. defines.push("#define ALPHATEST");
  41114. }
  41115. var previousEffect = this._effect;
  41116. var join = defines.join("\n");
  41117. this._effect = engine.createEffect(this._shaderPath, this._options.attributes, this._options.uniforms, this._options.samplers, join, fallbacks, this.onCompiled, this.onError);
  41118. if (!this._effect.isReady()) {
  41119. return false;
  41120. }
  41121. if (previousEffect !== this._effect) {
  41122. scene.resetCachedMaterial();
  41123. }
  41124. this._renderId = scene.getRenderId();
  41125. return true;
  41126. };
  41127. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  41128. var scene = this.getScene();
  41129. if (this._options.uniforms.indexOf("world") !== -1) {
  41130. this._effect.setMatrix("world", world);
  41131. }
  41132. if (this._options.uniforms.indexOf("worldView") !== -1) {
  41133. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  41134. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  41135. }
  41136. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  41137. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  41138. }
  41139. };
  41140. ShaderMaterial.prototype.bind = function (world, mesh) {
  41141. // Std values
  41142. this.bindOnlyWorldMatrix(world);
  41143. if (this.getScene().getCachedMaterial() !== this) {
  41144. if (this._options.uniforms.indexOf("view") !== -1) {
  41145. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  41146. }
  41147. if (this._options.uniforms.indexOf("projection") !== -1) {
  41148. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  41149. }
  41150. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  41151. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  41152. }
  41153. // Bones
  41154. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  41155. var name;
  41156. // Texture
  41157. for (name in this._textures) {
  41158. this._effect.setTexture(name, this._textures[name]);
  41159. }
  41160. // Texture arrays
  41161. for (name in this._textureArrays) {
  41162. this._effect.setTextureArray(name, this._textureArrays[name]);
  41163. }
  41164. // Float
  41165. for (name in this._floats) {
  41166. this._effect.setFloat(name, this._floats[name]);
  41167. }
  41168. // Float s
  41169. for (name in this._floatsArrays) {
  41170. this._effect.setArray(name, this._floatsArrays[name]);
  41171. }
  41172. // Color3
  41173. for (name in this._colors3) {
  41174. this._effect.setColor3(name, this._colors3[name]);
  41175. }
  41176. // Color4
  41177. for (name in this._colors4) {
  41178. var color = this._colors4[name];
  41179. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  41180. }
  41181. // Vector2
  41182. for (name in this._vectors2) {
  41183. this._effect.setVector2(name, this._vectors2[name]);
  41184. }
  41185. // Vector3
  41186. for (name in this._vectors3) {
  41187. this._effect.setVector3(name, this._vectors3[name]);
  41188. }
  41189. // Vector4
  41190. for (name in this._vectors4) {
  41191. this._effect.setVector4(name, this._vectors4[name]);
  41192. }
  41193. // Matrix
  41194. for (name in this._matrices) {
  41195. this._effect.setMatrix(name, this._matrices[name]);
  41196. }
  41197. // Matrix 3x3
  41198. for (name in this._matrices3x3) {
  41199. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  41200. }
  41201. // Matrix 2x2
  41202. for (name in this._matrices2x2) {
  41203. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  41204. }
  41205. // Vector3Array
  41206. for (name in this._vectors3Arrays) {
  41207. this._effect.setArray3(name, this._vectors3Arrays[name]);
  41208. }
  41209. }
  41210. _super.prototype.bind.call(this, world, mesh);
  41211. };
  41212. ShaderMaterial.prototype.clone = function (name) {
  41213. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  41214. return newShaderMaterial;
  41215. };
  41216. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  41217. if (forceDisposeTextures) {
  41218. var name;
  41219. for (name in this._textures) {
  41220. this._textures[name].dispose();
  41221. }
  41222. for (name in this._textureArrays) {
  41223. var array = this._textureArrays[name];
  41224. for (var index = 0; index < array.length; index++) {
  41225. array[index].dispose();
  41226. }
  41227. }
  41228. }
  41229. this._textures = {};
  41230. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  41231. };
  41232. ShaderMaterial.prototype.serialize = function () {
  41233. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  41234. serializationObject.customType = "BABYLON.ShaderMaterial";
  41235. serializationObject.options = this._options;
  41236. serializationObject.shaderPath = this._shaderPath;
  41237. var name;
  41238. // Texture
  41239. serializationObject.textures = {};
  41240. for (name in this._textures) {
  41241. serializationObject.textures[name] = this._textures[name].serialize();
  41242. }
  41243. // Texture arrays
  41244. serializationObject.textureArrays = {};
  41245. for (name in this._textureArrays) {
  41246. serializationObject.textureArrays[name] = [];
  41247. var array = this._textureArrays[name];
  41248. for (var index = 0; index < array.length; index++) {
  41249. serializationObject.textureArrays[name].push(array[index].serialize());
  41250. }
  41251. }
  41252. // Float
  41253. serializationObject.floats = {};
  41254. for (name in this._floats) {
  41255. serializationObject.floats[name] = this._floats[name];
  41256. }
  41257. // Float s
  41258. serializationObject.floatArrays = {};
  41259. for (name in this._floatsArrays) {
  41260. serializationObject.floatArrays[name] = this._floatsArrays[name];
  41261. }
  41262. // Color3
  41263. serializationObject.colors3 = {};
  41264. for (name in this._colors3) {
  41265. serializationObject.colors3[name] = this._colors3[name].asArray();
  41266. }
  41267. // Color4
  41268. serializationObject.colors4 = {};
  41269. for (name in this._colors4) {
  41270. serializationObject.colors4[name] = this._colors4[name].asArray();
  41271. }
  41272. // Vector2
  41273. serializationObject.vectors2 = {};
  41274. for (name in this._vectors2) {
  41275. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  41276. }
  41277. // Vector3
  41278. serializationObject.vectors3 = {};
  41279. for (name in this._vectors3) {
  41280. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  41281. }
  41282. // Vector4
  41283. serializationObject.vectors4 = {};
  41284. for (name in this._vectors4) {
  41285. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  41286. }
  41287. // Matrix
  41288. serializationObject.matrices = {};
  41289. for (name in this._matrices) {
  41290. serializationObject.matrices[name] = this._matrices[name].asArray();
  41291. }
  41292. // Matrix 3x3
  41293. serializationObject.matrices3x3 = {};
  41294. for (name in this._matrices3x3) {
  41295. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  41296. }
  41297. // Matrix 2x2
  41298. serializationObject.matrices2x2 = {};
  41299. for (name in this._matrices2x2) {
  41300. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  41301. }
  41302. // Vector3Array
  41303. serializationObject.vectors3Arrays = {};
  41304. for (name in this._vectors3Arrays) {
  41305. serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];
  41306. }
  41307. return serializationObject;
  41308. };
  41309. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  41310. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  41311. var name;
  41312. // Texture
  41313. for (name in source.textures) {
  41314. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  41315. }
  41316. // Texture arrays
  41317. for (name in source.textureArrays) {
  41318. var array = source.textureArrays[name];
  41319. var textureArray = new Array();
  41320. for (var index = 0; index < array.length; index++) {
  41321. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  41322. }
  41323. material.setTextureArray(name, textureArray);
  41324. }
  41325. // Float
  41326. for (name in source.floats) {
  41327. material.setFloat(name, source.floats[name]);
  41328. }
  41329. // Float s
  41330. for (name in source.floatsArrays) {
  41331. material.setFloats(name, source.floatsArrays[name]);
  41332. }
  41333. // Color3
  41334. for (name in source.colors3) {
  41335. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  41336. }
  41337. // Color4
  41338. for (name in source.colors4) {
  41339. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  41340. }
  41341. // Vector2
  41342. for (name in source.vectors2) {
  41343. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  41344. }
  41345. // Vector3
  41346. for (name in source.vectors3) {
  41347. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  41348. }
  41349. // Vector4
  41350. for (name in source.vectors4) {
  41351. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  41352. }
  41353. // Matrix
  41354. for (name in source.matrices) {
  41355. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  41356. }
  41357. // Matrix 3x3
  41358. for (name in source.matrices3x3) {
  41359. material.setMatrix3x3(name, source.matrices3x3[name]);
  41360. }
  41361. // Matrix 2x2
  41362. for (name in source.matrices2x2) {
  41363. material.setMatrix2x2(name, source.matrices2x2[name]);
  41364. }
  41365. // Vector3Array
  41366. for (name in source.vectors3Arrays) {
  41367. material.setArray3(name, source.vectors3Arrays[name]);
  41368. }
  41369. return material;
  41370. };
  41371. return ShaderMaterial;
  41372. }(BABYLON.Material));
  41373. BABYLON.ShaderMaterial = ShaderMaterial;
  41374. })(BABYLON || (BABYLON = {}));
  41375. //# sourceMappingURL=babylon.shaderMaterial.js.map
  41376. var BABYLON;
  41377. (function (BABYLON) {
  41378. var Internals;
  41379. (function (Internals) {
  41380. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  41381. // All values and structures referenced from:
  41382. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  41383. var DDS_MAGIC = 0x20534444;
  41384. 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;
  41385. var DDSCAPS_COMPLEX = 0x8, DDSCAPS_MIPMAP = 0x400000, DDSCAPS_TEXTURE = 0x1000;
  41386. 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;
  41387. var DDPF_ALPHAPIXELS = 0x1, DDPF_ALPHA = 0x2, DDPF_FOURCC = 0x4, DDPF_RGB = 0x40, DDPF_YUV = 0x200, DDPF_LUMINANCE = 0x20000;
  41388. function FourCCToInt32(value) {
  41389. return value.charCodeAt(0) +
  41390. (value.charCodeAt(1) << 8) +
  41391. (value.charCodeAt(2) << 16) +
  41392. (value.charCodeAt(3) << 24);
  41393. }
  41394. function Int32ToFourCC(value) {
  41395. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  41396. }
  41397. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  41398. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  41399. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  41400. var headerLengthInt = 31; // The header length in 32 bit ints
  41401. // Offsets into the header array
  41402. var off_magic = 0;
  41403. var off_size = 1;
  41404. var off_flags = 2;
  41405. var off_height = 3;
  41406. var off_width = 4;
  41407. var off_mipmapCount = 7;
  41408. var off_pfFlags = 20;
  41409. var off_pfFourCC = 21;
  41410. var off_RGBbpp = 22;
  41411. var off_RMask = 23;
  41412. var off_GMask = 24;
  41413. var off_BMask = 25;
  41414. var off_AMask = 26;
  41415. var off_caps1 = 27;
  41416. var off_caps2 = 28;
  41417. ;
  41418. var DDSTools = (function () {
  41419. function DDSTools() {
  41420. }
  41421. DDSTools.GetDDSInfo = function (arrayBuffer) {
  41422. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  41423. var mipmapCount = 1;
  41424. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  41425. mipmapCount = Math.max(1, header[off_mipmapCount]);
  41426. }
  41427. return {
  41428. width: header[off_width],
  41429. height: header[off_height],
  41430. mipmapCount: mipmapCount,
  41431. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  41432. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  41433. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  41434. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP
  41435. };
  41436. };
  41437. DDSTools.GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  41438. var byteArray = new Uint8Array(dataLength);
  41439. var srcData = new Uint8Array(arrayBuffer);
  41440. var index = 0;
  41441. for (var y = height - 1; y >= 0; y--) {
  41442. for (var x = 0; x < width; x++) {
  41443. var srcPos = dataOffset + (x + y * width) * 4;
  41444. byteArray[index + 2] = srcData[srcPos];
  41445. byteArray[index + 1] = srcData[srcPos + 1];
  41446. byteArray[index] = srcData[srcPos + 2];
  41447. byteArray[index + 3] = srcData[srcPos + 3];
  41448. index += 4;
  41449. }
  41450. }
  41451. return byteArray;
  41452. };
  41453. DDSTools.GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  41454. var byteArray = new Uint8Array(dataLength);
  41455. var srcData = new Uint8Array(arrayBuffer);
  41456. var index = 0;
  41457. for (var y = height - 1; y >= 0; y--) {
  41458. for (var x = 0; x < width; x++) {
  41459. var srcPos = dataOffset + (x + y * width) * 3;
  41460. byteArray[index + 2] = srcData[srcPos];
  41461. byteArray[index + 1] = srcData[srcPos + 1];
  41462. byteArray[index] = srcData[srcPos + 2];
  41463. index += 3;
  41464. }
  41465. }
  41466. return byteArray;
  41467. };
  41468. DDSTools.GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  41469. var byteArray = new Uint8Array(dataLength);
  41470. var srcData = new Uint8Array(arrayBuffer);
  41471. var index = 0;
  41472. for (var y = height - 1; y >= 0; y--) {
  41473. for (var x = 0; x < width; x++) {
  41474. var srcPos = dataOffset + (x + y * width);
  41475. byteArray[index] = srcData[srcPos];
  41476. index++;
  41477. }
  41478. }
  41479. return byteArray;
  41480. };
  41481. DDSTools.UploadDDSLevels = function (gl, ext, arrayBuffer, info, loadMipmaps, faces) {
  41482. var header = new Int32Array(arrayBuffer, 0, headerLengthInt), fourCC, blockBytes, internalFormat, width, height, dataLength, dataOffset, byteArray, mipmapCount, i;
  41483. if (header[off_magic] != DDS_MAGIC) {
  41484. BABYLON.Tools.Error("Invalid magic number in DDS header");
  41485. return;
  41486. }
  41487. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  41488. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  41489. return;
  41490. }
  41491. if (info.isFourCC) {
  41492. fourCC = header[off_pfFourCC];
  41493. switch (fourCC) {
  41494. case FOURCC_DXT1:
  41495. blockBytes = 8;
  41496. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  41497. break;
  41498. case FOURCC_DXT3:
  41499. blockBytes = 16;
  41500. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  41501. break;
  41502. case FOURCC_DXT5:
  41503. blockBytes = 16;
  41504. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  41505. break;
  41506. default:
  41507. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  41508. return;
  41509. }
  41510. }
  41511. mipmapCount = 1;
  41512. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  41513. mipmapCount = Math.max(1, header[off_mipmapCount]);
  41514. }
  41515. var bpp = header[off_RGBbpp];
  41516. for (var face = 0; face < faces; face++) {
  41517. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  41518. width = header[off_width];
  41519. height = header[off_height];
  41520. dataOffset = header[off_size] + 4;
  41521. for (i = 0; i < mipmapCount; ++i) {
  41522. if (info.isRGB) {
  41523. if (bpp === 24) {
  41524. dataLength = width * height * 3;
  41525. byteArray = DDSTools.GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  41526. gl.texImage2D(sampler, i, gl.RGB, width, height, 0, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  41527. }
  41528. else {
  41529. dataLength = width * height * 4;
  41530. byteArray = DDSTools.GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  41531. gl.texImage2D(sampler, i, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  41532. }
  41533. }
  41534. else if (info.isLuminance) {
  41535. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  41536. var unpaddedRowSize = width;
  41537. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  41538. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  41539. byteArray = DDSTools.GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  41540. gl.texImage2D(sampler, i, gl.LUMINANCE, width, height, 0, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  41541. }
  41542. else {
  41543. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  41544. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  41545. gl.compressedTexImage2D(sampler, i, internalFormat, width, height, 0, byteArray);
  41546. }
  41547. dataOffset += dataLength;
  41548. width *= 0.5;
  41549. height *= 0.5;
  41550. width = Math.max(1.0, width);
  41551. height = Math.max(1.0, height);
  41552. }
  41553. }
  41554. };
  41555. return DDSTools;
  41556. }());
  41557. Internals.DDSTools = DDSTools;
  41558. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  41559. })(BABYLON || (BABYLON = {}));
  41560. //# sourceMappingURL=babylon.tools.dds.js.map
  41561. var BABYLON;
  41562. (function (BABYLON) {
  41563. var Internals;
  41564. (function (Internals) {
  41565. /**
  41566. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  41567. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  41568. */
  41569. var KhronosTextureContainer = (function () {
  41570. /**
  41571. * @param {ArrayBuffer} arrayBuffer- contents of the KTX container file
  41572. * @param {number} facesExpected- should be either 1 or 6, based whether a cube texture or or
  41573. * @param {boolean} threeDExpected- provision for indicating that data should be a 3D texture, not implemented
  41574. * @param {boolean} textureArrayExpected- provision for indicating that data should be a texture array, not implemented
  41575. */
  41576. function KhronosTextureContainer(arrayBuffer, facesExpected, threeDExpected, textureArrayExpected) {
  41577. this.arrayBuffer = arrayBuffer;
  41578. // Test that it is a ktx formatted file, based on the first 12 bytes, character representation is:
  41579. // '�', 'K', 'T', 'X', ' ', '1', '1', '�', '\r', '\n', '\x1A', '\n'
  41580. // 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A
  41581. var identifier = new Uint8Array(this.arrayBuffer, 0, 12);
  41582. if (identifier[0] !== 0xAB || identifier[1] !== 0x4B || identifier[2] !== 0x54 || identifier[3] !== 0x58 || identifier[4] !== 0x20 || identifier[5] !== 0x31 ||
  41583. identifier[6] !== 0x31 || identifier[7] !== 0xBB || identifier[8] !== 0x0D || identifier[9] !== 0x0A || identifier[10] !== 0x1A || identifier[11] !== 0x0A) {
  41584. BABYLON.Tools.Error("texture missing KTX identifier");
  41585. return;
  41586. }
  41587. // load the reset of the header in native 32 bit int
  41588. var header = new Int32Array(this.arrayBuffer, 12, 13);
  41589. // determine of the remaining header values are recorded in the opposite endianness & require conversion
  41590. var oppositeEndianess = header[0] === 0x01020304;
  41591. // read all the header elements in order they exist in the file, without modification (sans endainness)
  41592. this.glType = oppositeEndianess ? this.switchEndainness(header[1]) : header[1]; // must be 0 for compressed textures
  41593. this.glTypeSize = oppositeEndianess ? this.switchEndainness(header[2]) : header[2]; // must be 1 for compressed textures
  41594. this.glFormat = oppositeEndianess ? this.switchEndainness(header[3]) : header[3]; // must be 0 for compressed textures
  41595. this.glInternalFormat = oppositeEndianess ? this.switchEndainness(header[4]) : header[4]; // the value of arg passed to gl.compressedTexImage2D(,,x,,,,)
  41596. this.glBaseInternalFormat = oppositeEndianess ? this.switchEndainness(header[5]) : header[5]; // specify GL_RGB, GL_RGBA, GL_ALPHA, etc (un-compressed only)
  41597. this.pixelWidth = oppositeEndianess ? this.switchEndainness(header[6]) : header[6]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,x,,,)
  41598. this.pixelHeight = oppositeEndianess ? this.switchEndainness(header[7]) : header[7]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,,x,,)
  41599. this.pixelDepth = oppositeEndianess ? this.switchEndainness(header[8]) : header[8]; // level 0 value of arg passed to gl.compressedTexImage3D(,,,,,x,,)
  41600. this.numberOfArrayElements = oppositeEndianess ? this.switchEndainness(header[9]) : header[9]; // used for texture arrays
  41601. this.numberOfFaces = oppositeEndianess ? this.switchEndainness(header[10]) : header[10]; // used for cubemap textures, should either be 1 or 6
  41602. this.numberOfMipmapLevels = oppositeEndianess ? this.switchEndainness(header[11]) : header[11]; // number of levels; disregard possibility of 0 for compressed textures
  41603. this.bytesOfKeyValueData = oppositeEndianess ? this.switchEndainness(header[12]) : header[12]; // the amount of space after the header for meta-data
  41604. // Make sure we have a compressed type. Not only reduces work, but probably better to let dev know they are not compressing.
  41605. if (this.glType !== 0) {
  41606. BABYLON.Tools.Error("only compressed formats currently supported");
  41607. return;
  41608. }
  41609. else {
  41610. // value of zero is an indication to generate mipmaps @ runtime. Not usually allowed for compressed, so disregard.
  41611. this.numberOfMipmapLevels = Math.max(1, this.numberOfMipmapLevels);
  41612. }
  41613. if (this.pixelHeight === 0 || this.pixelDepth !== 0) {
  41614. BABYLON.Tools.Error("only 2D textures currently supported");
  41615. return;
  41616. }
  41617. if (this.numberOfArrayElements !== 0) {
  41618. BABYLON.Tools.Error("texture arrays not currently supported");
  41619. return;
  41620. }
  41621. if (this.numberOfFaces !== facesExpected) {
  41622. BABYLON.Tools.Error("number of faces expected" + facesExpected + ", but found " + this.numberOfFaces);
  41623. return;
  41624. }
  41625. // we now have a completely validated file, so could use existence of loadType as success
  41626. // would need to make this more elaborate & adjust checks above to support more than one load type
  41627. this.loadType = KhronosTextureContainer.COMPRESSED_2D;
  41628. }
  41629. // not as fast hardware based, but will probably never need to use
  41630. KhronosTextureContainer.prototype.switchEndainness = function (val) {
  41631. return ((val & 0xFF) << 24)
  41632. | ((val & 0xFF00) << 8)
  41633. | ((val >> 8) & 0xFF00)
  41634. | ((val >> 24) & 0xFF);
  41635. };
  41636. /**
  41637. * It is assumed that the texture has already been created & is currently bound
  41638. */
  41639. KhronosTextureContainer.prototype.uploadLevels = function (gl, loadMipmaps) {
  41640. switch (this.loadType) {
  41641. case KhronosTextureContainer.COMPRESSED_2D:
  41642. this._upload2DCompressedLevels(gl, loadMipmaps);
  41643. break;
  41644. case KhronosTextureContainer.TEX_2D:
  41645. case KhronosTextureContainer.COMPRESSED_3D:
  41646. case KhronosTextureContainer.TEX_3D:
  41647. }
  41648. };
  41649. KhronosTextureContainer.prototype._upload2DCompressedLevels = function (gl, loadMipmaps) {
  41650. // initialize width & height for level 1
  41651. var dataOffset = KhronosTextureContainer.HEADER_LEN + this.bytesOfKeyValueData;
  41652. var width = this.pixelWidth;
  41653. var height = this.pixelHeight;
  41654. var mipmapCount = loadMipmaps ? this.numberOfMipmapLevels : 1;
  41655. for (var level = 0; level < mipmapCount; level++) {
  41656. var imageSize = new Int32Array(this.arrayBuffer, dataOffset, 1)[0]; // size per face, since not supporting array cubemaps
  41657. for (var face = 0; face < this.numberOfFaces; face++) {
  41658. var sampler = this.numberOfFaces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  41659. var byteArray = new Uint8Array(this.arrayBuffer, dataOffset + 4, imageSize);
  41660. gl.compressedTexImage2D(sampler, level, this.glInternalFormat, width, height, 0, byteArray);
  41661. dataOffset += imageSize + 4; // size of the image + 4 for the imageSize field
  41662. dataOffset += 3 - ((imageSize + 3) % 4); // add padding for odd sized image
  41663. }
  41664. width = Math.max(1.0, width * 0.5);
  41665. height = Math.max(1.0, height * 0.5);
  41666. }
  41667. };
  41668. return KhronosTextureContainer;
  41669. }());
  41670. KhronosTextureContainer.HEADER_LEN = 12 + (13 * 4); // identifier + header elements (not including key value meta-data pairs)
  41671. // load types
  41672. KhronosTextureContainer.COMPRESSED_2D = 0; // uses a gl.compressedTexImage2D()
  41673. KhronosTextureContainer.COMPRESSED_3D = 1; // uses a gl.compressedTexImage3D()
  41674. KhronosTextureContainer.TEX_2D = 2; // uses a gl.texImage2D()
  41675. KhronosTextureContainer.TEX_3D = 3; // uses a gl.texImage3D()
  41676. Internals.KhronosTextureContainer = KhronosTextureContainer;
  41677. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  41678. })(BABYLON || (BABYLON = {}));
  41679. //# sourceMappingURL=babylon.khronosTextureContainer.js.map
  41680. var BABYLON;
  41681. (function (BABYLON) {
  41682. var CannonJSPlugin = (function () {
  41683. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  41684. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  41685. if (iterations === void 0) { iterations = 10; }
  41686. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  41687. this.name = "CannonJSPlugin";
  41688. this._physicsMaterials = [];
  41689. this._fixedTimeStep = 1 / 60;
  41690. //See https://github.com/schteppe/cannon.js/blob/gh-pages/demos/collisionFilter.html
  41691. this._currentCollisionGroup = 2;
  41692. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  41693. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  41694. this._tmpPosition = BABYLON.Vector3.Zero();
  41695. this._tmpQuaternion = new BABYLON.Quaternion();
  41696. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  41697. this._tmpDeltaRotation = new BABYLON.Quaternion();
  41698. this._tmpUnityRotation = new BABYLON.Quaternion();
  41699. if (!this.isSupported()) {
  41700. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  41701. return;
  41702. }
  41703. this.world = new CANNON.World();
  41704. this.world.broadphase = new CANNON.NaiveBroadphase();
  41705. this.world.solver.iterations = iterations;
  41706. }
  41707. CannonJSPlugin.prototype.setGravity = function (gravity) {
  41708. this.world.gravity.copy(gravity);
  41709. };
  41710. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  41711. this._fixedTimeStep = timeStep;
  41712. };
  41713. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  41714. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta * 1000 : 0, 3);
  41715. };
  41716. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  41717. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  41718. var impulse = new CANNON.Vec3(force.x, force.y, force.z);
  41719. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  41720. };
  41721. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  41722. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  41723. var impulse = new CANNON.Vec3(force.x, force.y, force.z);
  41724. impostor.physicsBody.applyForce(impulse, worldPoint);
  41725. };
  41726. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  41727. //parent-child relationship. Does this impostor has a parent impostor?
  41728. if (impostor.parent) {
  41729. if (impostor.physicsBody) {
  41730. this.removePhysicsBody(impostor);
  41731. //TODO is that needed?
  41732. impostor.forceUpdate();
  41733. }
  41734. return;
  41735. }
  41736. //should a new body be created for this impostor?
  41737. if (impostor.isBodyInitRequired()) {
  41738. var shape = this._createShape(impostor);
  41739. //unregister events, if body is being changed
  41740. var oldBody = impostor.physicsBody;
  41741. if (oldBody) {
  41742. this.removePhysicsBody(impostor);
  41743. }
  41744. //create the body and material
  41745. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  41746. var bodyCreationObject = {
  41747. mass: impostor.getParam("mass"),
  41748. material: material
  41749. };
  41750. // A simple extend, in case native options were used.
  41751. var nativeOptions = impostor.getParam("nativeOptions");
  41752. for (var key in nativeOptions) {
  41753. if (nativeOptions.hasOwnProperty(key)) {
  41754. bodyCreationObject[key] = nativeOptions[key];
  41755. }
  41756. }
  41757. impostor.physicsBody = new CANNON.Body(bodyCreationObject);
  41758. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  41759. this.world.addEventListener("preStep", impostor.beforeStep);
  41760. this.world.addEventListener("postStep", impostor.afterStep);
  41761. impostor.physicsBody.addShape(shape);
  41762. this.world.add(impostor.physicsBody);
  41763. //try to keep the body moving in the right direction by taking old properties.
  41764. //Should be tested!
  41765. if (oldBody) {
  41766. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  41767. impostor.physicsBody[param].copy(oldBody[param]);
  41768. });
  41769. }
  41770. this._processChildMeshes(impostor);
  41771. }
  41772. //now update the body's transformation
  41773. this._updatePhysicsBodyTransformation(impostor);
  41774. };
  41775. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  41776. var _this = this;
  41777. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes() : [];
  41778. if (meshChildren.length) {
  41779. var processMesh = function (localPosition, mesh) {
  41780. var childImpostor = mesh.getPhysicsImpostor();
  41781. if (childImpostor) {
  41782. var parent = childImpostor.parent;
  41783. if (parent !== mainImpostor) {
  41784. var localPosition = mesh.position;
  41785. if (childImpostor.physicsBody) {
  41786. _this.removePhysicsBody(childImpostor);
  41787. childImpostor.physicsBody = null;
  41788. }
  41789. childImpostor.parent = mainImpostor;
  41790. childImpostor.resetUpdateFlags();
  41791. mainImpostor.physicsBody.addShape(_this._createShape(childImpostor), new CANNON.Vec3(localPosition.x, localPosition.y, localPosition.z));
  41792. //Add the mass of the children.
  41793. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  41794. }
  41795. }
  41796. mesh.getChildMeshes().forEach(processMesh.bind(_this, mesh.position));
  41797. };
  41798. meshChildren.forEach(processMesh.bind(this, BABYLON.Vector3.Zero()));
  41799. }
  41800. };
  41801. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  41802. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  41803. this.world.removeEventListener("preStep", impostor.beforeStep);
  41804. this.world.removeEventListener("postStep", impostor.afterStep);
  41805. this.world.remove(impostor.physicsBody);
  41806. };
  41807. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  41808. var mainBody = impostorJoint.mainImpostor.physicsBody;
  41809. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  41810. if (!mainBody || !connectedBody) {
  41811. return;
  41812. }
  41813. var constraint;
  41814. var jointData = impostorJoint.joint.jointData;
  41815. //TODO - https://github.com/schteppe/cannon.js/blob/gh-pages/demos/collisionFilter.html
  41816. var constraintData = {
  41817. pivotA: jointData.mainPivot ? new CANNON.Vec3().copy(jointData.mainPivot) : null,
  41818. pivotB: jointData.connectedPivot ? new CANNON.Vec3().copy(jointData.connectedPivot) : null,
  41819. axisA: jointData.mainAxis ? new CANNON.Vec3().copy(jointData.mainAxis) : null,
  41820. axisB: jointData.connectedAxis ? new CANNON.Vec3().copy(jointData.connectedAxis) : null,
  41821. maxForce: jointData.nativeParams.maxForce,
  41822. collideConnected: !!jointData.collision
  41823. };
  41824. switch (impostorJoint.joint.type) {
  41825. case BABYLON.PhysicsJoint.HingeJoint:
  41826. case BABYLON.PhysicsJoint.Hinge2Joint:
  41827. constraint = new CANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  41828. break;
  41829. case BABYLON.PhysicsJoint.DistanceJoint:
  41830. constraint = new CANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  41831. break;
  41832. case BABYLON.PhysicsJoint.SpringJoint:
  41833. var springData = jointData;
  41834. constraint = new CANNON.Spring(mainBody, connectedBody, {
  41835. restLength: springData.length,
  41836. stiffness: springData.stiffness,
  41837. damping: springData.damping,
  41838. localAnchorA: constraintData.pivotA,
  41839. localAnchorB: constraintData.pivotB
  41840. });
  41841. break;
  41842. case BABYLON.PhysicsJoint.LockJoint:
  41843. constraint = new CANNON.LockConstraint(mainBody, connectedBody, constraintData);
  41844. break;
  41845. case BABYLON.PhysicsJoint.PointToPointJoint:
  41846. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  41847. default:
  41848. constraint = new CANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  41849. break;
  41850. }
  41851. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  41852. constraint.collideConnected = !!jointData.collision;
  41853. impostorJoint.joint.physicsJoint = constraint;
  41854. //don't add spring as constraint, as it is not one.
  41855. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  41856. this.world.addConstraint(constraint);
  41857. }
  41858. else {
  41859. impostorJoint.mainImpostor.registerAfterPhysicsStep(function () {
  41860. constraint.applyForce();
  41861. });
  41862. }
  41863. };
  41864. CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
  41865. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  41866. };
  41867. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  41868. var index;
  41869. var mat;
  41870. for (index = 0; index < this._physicsMaterials.length; index++) {
  41871. mat = this._physicsMaterials[index];
  41872. if (mat.friction === friction && mat.restitution === restitution) {
  41873. return mat;
  41874. }
  41875. }
  41876. var currentMat = new CANNON.Material(name);
  41877. currentMat.friction = friction;
  41878. currentMat.restitution = restitution;
  41879. this._physicsMaterials.push(currentMat);
  41880. return currentMat;
  41881. };
  41882. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  41883. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  41884. };
  41885. CannonJSPlugin.prototype._createShape = function (impostor) {
  41886. var object = impostor.object;
  41887. var returnValue;
  41888. var extendSize = impostor.getObjectExtendSize();
  41889. switch (impostor.type) {
  41890. case BABYLON.PhysicsEngine.SphereImpostor:
  41891. var radiusX = extendSize.x;
  41892. var radiusY = extendSize.y;
  41893. var radiusZ = extendSize.z;
  41894. returnValue = new CANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  41895. break;
  41896. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  41897. case BABYLON.PhysicsImpostor.CylinderImpostor:
  41898. returnValue = new CANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  41899. break;
  41900. case BABYLON.PhysicsImpostor.BoxImpostor:
  41901. var box = extendSize.scale(0.5);
  41902. returnValue = new CANNON.Box(new CANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  41903. break;
  41904. case BABYLON.PhysicsImpostor.PlaneImpostor:
  41905. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  41906. returnValue = new CANNON.Plane();
  41907. break;
  41908. case BABYLON.PhysicsImpostor.MeshImpostor:
  41909. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  41910. var rawFaces = object.getIndices ? object.getIndices() : [];
  41911. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  41912. returnValue = new CANNON.Trimesh(rawVerts, rawFaces);
  41913. break;
  41914. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  41915. returnValue = this._createHeightmap(object);
  41916. break;
  41917. case BABYLON.PhysicsImpostor.ParticleImpostor:
  41918. returnValue = new CANNON.Particle();
  41919. break;
  41920. }
  41921. return returnValue;
  41922. };
  41923. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  41924. var pos = object.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  41925. var matrix = [];
  41926. //For now pointDepth will not be used and will be automatically calculated.
  41927. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  41928. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  41929. var dim = Math.min(object.getBoundingInfo().boundingBox.extendSize.x, object.getBoundingInfo().boundingBox.extendSize.z);
  41930. var elementSize = dim * 2 / arraySize;
  41931. var minY = object.getBoundingInfo().boundingBox.extendSize.y;
  41932. for (var i = 0; i < pos.length; i = i + 3) {
  41933. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  41934. var z = Math.round(((pos[i + 2]) / elementSize - arraySize / 2) * -1);
  41935. var y = pos[i + 1] + minY;
  41936. if (!matrix[x]) {
  41937. matrix[x] = [];
  41938. }
  41939. if (!matrix[x][z]) {
  41940. matrix[x][z] = y;
  41941. }
  41942. matrix[x][z] = Math.max(y, matrix[x][z]);
  41943. }
  41944. for (var x = 0; x <= arraySize; ++x) {
  41945. if (!matrix[x]) {
  41946. var loc = 1;
  41947. while (!matrix[(x + loc) % arraySize]) {
  41948. loc++;
  41949. }
  41950. matrix[x] = matrix[(x + loc) % arraySize].slice();
  41951. }
  41952. for (var z = 0; z <= arraySize; ++z) {
  41953. if (!matrix[x][z]) {
  41954. var loc = 1;
  41955. var newValue;
  41956. while (newValue === undefined) {
  41957. newValue = matrix[x][(z + loc++) % arraySize];
  41958. }
  41959. matrix[x][z] = newValue;
  41960. }
  41961. }
  41962. }
  41963. var shape = new CANNON.Heightfield(matrix, {
  41964. elementSize: elementSize
  41965. });
  41966. //For future reference, needed for body transformation
  41967. shape.minY = minY;
  41968. return shape;
  41969. };
  41970. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  41971. var object = impostor.object;
  41972. //make sure it is updated...
  41973. object.computeWorldMatrix && object.computeWorldMatrix(true);
  41974. // The delta between the mesh position and the mesh bounding box center
  41975. var center = impostor.getObjectCenter();
  41976. var extendSize = impostor.getObjectExtendSize();
  41977. this._tmpDeltaPosition.copyFrom(object.position.subtract(center));
  41978. this._tmpPosition.copyFrom(center);
  41979. var quaternion = object.rotationQuaternion;
  41980. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  41981. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  41982. //-90 DEG in X, precalculated
  41983. quaternion = quaternion.multiply(this._minus90X);
  41984. //Invert! (Precalculated, 90 deg in X)
  41985. //No need to clone. this will never change.
  41986. impostor.setDeltaRotation(this._plus90X);
  41987. }
  41988. //If it is a heightfield, if should be centered.
  41989. if (impostor.type === BABYLON.PhysicsEngine.HeightmapImpostor) {
  41990. var mesh = object;
  41991. //calculate the correct body position:
  41992. var rotationQuaternion = mesh.rotationQuaternion;
  41993. mesh.rotationQuaternion = this._tmpUnityRotation;
  41994. mesh.computeWorldMatrix(true);
  41995. //get original center with no rotation
  41996. var c = center.clone();
  41997. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  41998. //rotation is back
  41999. mesh.rotationQuaternion = rotationQuaternion;
  42000. //calculate the new center using a pivot (since Cannon.js doesn't center height maps)
  42001. var p = BABYLON.Matrix.Translation(mesh.getBoundingInfo().boundingBox.extendSize.x, 0, -mesh.getBoundingInfo().boundingBox.extendSize.z);
  42002. mesh.setPivotMatrix(p);
  42003. mesh.computeWorldMatrix(true);
  42004. //calculate the translation
  42005. var translation = mesh.getBoundingInfo().boundingBox.center.subtract(center).subtract(mesh.position).negate();
  42006. this._tmpPosition.copyFromFloats(translation.x, translation.y - mesh.getBoundingInfo().boundingBox.extendSize.y, translation.z);
  42007. //add it inverted to the delta
  42008. this._tmpDeltaPosition.copyFrom(mesh.getBoundingInfo().boundingBox.center.subtract(c));
  42009. this._tmpDeltaPosition.y += mesh.getBoundingInfo().boundingBox.extendSize.y;
  42010. mesh.setPivotMatrix(oldPivot);
  42011. mesh.computeWorldMatrix(true);
  42012. }
  42013. else if (impostor.type === BABYLON.PhysicsEngine.MeshImpostor) {
  42014. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  42015. this._tmpPosition.copyFrom(object.position);
  42016. }
  42017. impostor.setDeltaPosition(this._tmpDeltaPosition);
  42018. //Now update the impostor object
  42019. impostor.physicsBody.position.copy(this._tmpPosition);
  42020. impostor.physicsBody.quaternion.copy(quaternion);
  42021. };
  42022. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  42023. impostor.object.position.copyFrom(impostor.physicsBody.position);
  42024. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  42025. };
  42026. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  42027. impostor.physicsBody.position.copy(newPosition);
  42028. impostor.physicsBody.quaternion.copy(newRotation);
  42029. };
  42030. CannonJSPlugin.prototype.isSupported = function () {
  42031. return window.CANNON !== undefined;
  42032. };
  42033. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  42034. impostor.physicsBody.velocity.copy(velocity);
  42035. };
  42036. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  42037. impostor.physicsBody.angularVelocity.copy(velocity);
  42038. };
  42039. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  42040. var v = impostor.physicsBody.velocity;
  42041. if (!v)
  42042. return null;
  42043. return new BABYLON.Vector3(v.x, v.y, v.z);
  42044. };
  42045. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  42046. var v = impostor.physicsBody.angularVelocity;
  42047. if (!v)
  42048. return null;
  42049. return new BABYLON.Vector3(v.x, v.y, v.z);
  42050. };
  42051. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  42052. impostor.physicsBody.mass = mass;
  42053. impostor.physicsBody.updateMassProperties();
  42054. };
  42055. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  42056. impostor.physicsBody.sleep();
  42057. };
  42058. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  42059. impostor.physicsBody.wakeUp();
  42060. };
  42061. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  42062. joint.physicsJoint.distance = maxDistance;
  42063. };
  42064. CannonJSPlugin.prototype.enableMotor = function (joint, motorIndex) {
  42065. if (!motorIndex) {
  42066. joint.physicsJoint.enableMotor();
  42067. }
  42068. };
  42069. CannonJSPlugin.prototype.disableMotor = function (joint, motorIndex) {
  42070. if (!motorIndex) {
  42071. joint.physicsJoint.disableMotor();
  42072. }
  42073. };
  42074. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  42075. if (!motorIndex) {
  42076. joint.physicsJoint.enableMotor();
  42077. joint.physicsJoint.setMotorSpeed(speed);
  42078. if (maxForce) {
  42079. this.setLimit(joint, maxForce);
  42080. }
  42081. }
  42082. };
  42083. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  42084. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  42085. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  42086. };
  42087. CannonJSPlugin.prototype.dispose = function () {
  42088. //nothing to do, actually.
  42089. };
  42090. return CannonJSPlugin;
  42091. }());
  42092. BABYLON.CannonJSPlugin = CannonJSPlugin;
  42093. })(BABYLON || (BABYLON = {}));
  42094. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  42095. var BABYLON;
  42096. (function (BABYLON) {
  42097. var OimoJSPlugin = (function () {
  42098. function OimoJSPlugin(iterations) {
  42099. this.name = "OimoJSPlugin";
  42100. this._tmpImpostorsArray = [];
  42101. this._tmpPositionVector = BABYLON.Vector3.Zero();
  42102. this.world = new OIMO.World(1 / 60, 2, iterations, true);
  42103. this.world.worldscale(1);
  42104. this.world.clear();
  42105. //making sure no stats are calculated
  42106. this.world.isNoStat = true;
  42107. }
  42108. OimoJSPlugin.prototype.setGravity = function (gravity) {
  42109. this.world.gravity.copy(gravity);
  42110. };
  42111. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  42112. this.world.timeStep = timeStep;
  42113. };
  42114. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  42115. var _this = this;
  42116. impostors.forEach(function (impostor) {
  42117. impostor.beforeStep();
  42118. });
  42119. this.world.step();
  42120. impostors.forEach(function (impostor) {
  42121. impostor.afterStep();
  42122. //update the ordered impostors array
  42123. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  42124. });
  42125. //check for collisions
  42126. var contact = this.world.contacts;
  42127. while (contact !== null) {
  42128. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  42129. contact = contact.next;
  42130. continue;
  42131. }
  42132. //is this body colliding with any other? get the impostor
  42133. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  42134. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  42135. if (!mainImpostor || !collidingImpostor) {
  42136. contact = contact.next;
  42137. continue;
  42138. }
  42139. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  42140. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  42141. contact = contact.next;
  42142. }
  42143. };
  42144. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  42145. var mass = impostor.physicsBody.massInfo.mass;
  42146. impostor.physicsBody.applyImpulse(contactPoint.scale(OIMO.INV_SCALE), force.scale(OIMO.INV_SCALE * mass));
  42147. };
  42148. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  42149. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  42150. this.applyImpulse(impostor, force, contactPoint);
  42151. };
  42152. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  42153. var _this = this;
  42154. //parent-child relationship. Does this impostor has a parent impostor?
  42155. if (impostor.parent) {
  42156. if (impostor.physicsBody) {
  42157. this.removePhysicsBody(impostor);
  42158. //TODO is that needed?
  42159. impostor.forceUpdate();
  42160. }
  42161. return;
  42162. }
  42163. if (impostor.isBodyInitRequired()) {
  42164. var bodyConfig = {
  42165. name: impostor.uniqueId,
  42166. //Oimo must have mass, also for static objects.
  42167. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  42168. size: [],
  42169. type: [],
  42170. pos: [],
  42171. rot: [],
  42172. move: impostor.getParam("mass") !== 0,
  42173. //Supporting older versions of Oimo
  42174. world: this.world
  42175. };
  42176. var impostors = [impostor];
  42177. var addToArray = function (parent) {
  42178. if (!parent.getChildMeshes)
  42179. return;
  42180. parent.getChildMeshes().forEach(function (m) {
  42181. if (m.physicsImpostor) {
  42182. impostors.push(m.physicsImpostor);
  42183. m.physicsImpostor._init();
  42184. }
  42185. });
  42186. };
  42187. addToArray(impostor.object);
  42188. var checkWithEpsilon_1 = function (value) {
  42189. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  42190. };
  42191. impostors.forEach(function (i) {
  42192. //get the correct bounding box
  42193. var oldQuaternion = i.object.rotationQuaternion;
  42194. var rot = new OIMO.Euler().setFromQuaternion({
  42195. x: impostor.object.rotationQuaternion.x,
  42196. y: impostor.object.rotationQuaternion.y,
  42197. z: impostor.object.rotationQuaternion.z,
  42198. s: impostor.object.rotationQuaternion.w
  42199. });
  42200. var extendSize = i.getObjectExtendSize();
  42201. if (i === impostor) {
  42202. var center = impostor.getObjectCenter();
  42203. impostor.object.position.subtractToRef(center, _this._tmpPositionVector);
  42204. //Can also use Array.prototype.push.apply
  42205. bodyConfig.pos.push(center.x);
  42206. bodyConfig.pos.push(center.y);
  42207. bodyConfig.pos.push(center.z);
  42208. //tmp solution
  42209. bodyConfig.rot.push(rot.x / (OIMO.degtorad || OIMO.TO_RAD));
  42210. bodyConfig.rot.push(rot.y / (OIMO.degtorad || OIMO.TO_RAD));
  42211. bodyConfig.rot.push(rot.z / (OIMO.degtorad || OIMO.TO_RAD));
  42212. }
  42213. else {
  42214. bodyConfig.pos.push(i.object.position.x);
  42215. bodyConfig.pos.push(i.object.position.y);
  42216. bodyConfig.pos.push(i.object.position.z);
  42217. //tmp solution until https://github.com/lo-th/Oimo.js/pull/37 is merged
  42218. bodyConfig.rot.push(0);
  42219. bodyConfig.rot.push(0);
  42220. bodyConfig.rot.push(0);
  42221. }
  42222. // register mesh
  42223. switch (i.type) {
  42224. case BABYLON.PhysicsImpostor.ParticleImpostor:
  42225. BABYLON.Tools.Warn("No Particle support in Oimo.js. using SphereImpostor instead");
  42226. case BABYLON.PhysicsImpostor.SphereImpostor:
  42227. var radiusX = extendSize.x;
  42228. var radiusY = extendSize.y;
  42229. var radiusZ = extendSize.z;
  42230. var size = Math.max(checkWithEpsilon_1(radiusX), checkWithEpsilon_1(radiusY), checkWithEpsilon_1(radiusZ)) / 2;
  42231. bodyConfig.type.push('sphere');
  42232. //due to the way oimo works with compounds, add 3 times
  42233. bodyConfig.size.push(size);
  42234. bodyConfig.size.push(size);
  42235. bodyConfig.size.push(size);
  42236. break;
  42237. case BABYLON.PhysicsImpostor.CylinderImpostor:
  42238. var sizeX = checkWithEpsilon_1(extendSize.x) / 2;
  42239. var sizeY = checkWithEpsilon_1(extendSize.y);
  42240. bodyConfig.type.push('cylinder');
  42241. bodyConfig.size.push(sizeX);
  42242. bodyConfig.size.push(sizeY);
  42243. //due to the way oimo works with compounds, add one more value.
  42244. bodyConfig.size.push(sizeY);
  42245. break;
  42246. case BABYLON.PhysicsImpostor.PlaneImpostor:
  42247. case BABYLON.PhysicsImpostor.BoxImpostor:
  42248. default:
  42249. var sizeX = checkWithEpsilon_1(extendSize.x);
  42250. var sizeY = checkWithEpsilon_1(extendSize.y);
  42251. var sizeZ = checkWithEpsilon_1(extendSize.z);
  42252. bodyConfig.type.push('box');
  42253. bodyConfig.size.push(sizeX);
  42254. bodyConfig.size.push(sizeY);
  42255. bodyConfig.size.push(sizeZ);
  42256. break;
  42257. }
  42258. //actually not needed, but hey...
  42259. i.object.rotationQuaternion = oldQuaternion;
  42260. });
  42261. impostor.physicsBody = new OIMO.Body(bodyConfig).body; //this.world.add(bodyConfig);
  42262. }
  42263. else {
  42264. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  42265. }
  42266. impostor.setDeltaPosition(this._tmpPositionVector);
  42267. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  42268. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  42269. };
  42270. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  42271. //impostor.physicsBody.dispose();
  42272. //Same as : (older oimo versions)
  42273. this.world.removeRigidBody(impostor.physicsBody);
  42274. };
  42275. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  42276. var mainBody = impostorJoint.mainImpostor.physicsBody;
  42277. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  42278. if (!mainBody || !connectedBody) {
  42279. return;
  42280. }
  42281. var jointData = impostorJoint.joint.jointData;
  42282. var options = jointData.nativeParams || {};
  42283. var type;
  42284. var nativeJointData = {
  42285. body1: mainBody,
  42286. body2: connectedBody,
  42287. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  42288. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  42289. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  42290. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  42291. min: options.min,
  42292. max: options.max,
  42293. collision: options.collision || jointData.collision,
  42294. spring: options.spring,
  42295. //supporting older version of Oimo
  42296. world: this.world
  42297. };
  42298. switch (impostorJoint.joint.type) {
  42299. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  42300. type = "jointBall";
  42301. break;
  42302. case BABYLON.PhysicsJoint.SpringJoint:
  42303. BABYLON.Tools.Warn("Oimo.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  42304. var springData = jointData;
  42305. nativeJointData.min = springData.length || nativeJointData.min;
  42306. //Max should also be set, just make sure it is at least min
  42307. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  42308. case BABYLON.PhysicsJoint.DistanceJoint:
  42309. type = "jointDistance";
  42310. nativeJointData.max = jointData.maxDistance;
  42311. break;
  42312. case BABYLON.PhysicsJoint.PrismaticJoint:
  42313. type = "jointPrisme";
  42314. break;
  42315. case BABYLON.PhysicsJoint.SliderJoint:
  42316. type = "jointSlide";
  42317. break;
  42318. case BABYLON.PhysicsJoint.WheelJoint:
  42319. type = "jointWheel";
  42320. break;
  42321. case BABYLON.PhysicsJoint.HingeJoint:
  42322. default:
  42323. type = "jointHinge";
  42324. break;
  42325. }
  42326. nativeJointData.type = type;
  42327. impostorJoint.joint.physicsJoint = new OIMO.Link(nativeJointData).joint; //this.world.add(nativeJointData);
  42328. };
  42329. OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
  42330. //Bug in Oimo prevents us from disposing a joint in the playground
  42331. //joint.joint.physicsJoint.dispose();
  42332. //So we will bruteforce it!
  42333. try {
  42334. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  42335. }
  42336. catch (e) {
  42337. BABYLON.Tools.Warn(e);
  42338. }
  42339. };
  42340. OimoJSPlugin.prototype.isSupported = function () {
  42341. return OIMO !== undefined;
  42342. };
  42343. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  42344. if (!impostor.physicsBody.sleeping) {
  42345. //TODO check that
  42346. if (impostor.physicsBody.shapes.next) {
  42347. var parentShape = this._getLastShape(impostor.physicsBody);
  42348. impostor.object.position.x = parentShape.position.x * OIMO.WORLD_SCALE;
  42349. impostor.object.position.y = parentShape.position.y * OIMO.WORLD_SCALE;
  42350. impostor.object.position.z = parentShape.position.z * OIMO.WORLD_SCALE;
  42351. }
  42352. else {
  42353. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  42354. }
  42355. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  42356. impostor.object.rotationQuaternion.normalize();
  42357. }
  42358. };
  42359. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  42360. var body = impostor.physicsBody;
  42361. body.position.init(newPosition.x * OIMO.INV_SCALE, newPosition.y * OIMO.INV_SCALE, newPosition.z * OIMO.INV_SCALE);
  42362. body.orientation.init(newRotation.w, newRotation.x, newRotation.y, newRotation.z);
  42363. body.syncShapes();
  42364. body.awake();
  42365. };
  42366. OimoJSPlugin.prototype._getLastShape = function (body) {
  42367. var lastShape = body.shapes;
  42368. while (lastShape.next) {
  42369. lastShape = lastShape.next;
  42370. }
  42371. return lastShape;
  42372. };
  42373. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  42374. impostor.physicsBody.linearVelocity.init(velocity.x, velocity.y, velocity.z);
  42375. };
  42376. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  42377. impostor.physicsBody.angularVelocity.init(velocity.x, velocity.y, velocity.z);
  42378. };
  42379. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  42380. var v = impostor.physicsBody.linearVelocity;
  42381. if (!v)
  42382. return null;
  42383. return new BABYLON.Vector3(v.x, v.y, v.z);
  42384. };
  42385. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  42386. var v = impostor.physicsBody.angularVelocity;
  42387. if (!v)
  42388. return null;
  42389. return new BABYLON.Vector3(v.x, v.y, v.z);
  42390. };
  42391. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  42392. var staticBody = mass === 0;
  42393. //this will actually set the body's density and not its mass.
  42394. //But this is how oimo treats the mass variable.
  42395. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  42396. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  42397. };
  42398. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  42399. impostor.physicsBody.sleep();
  42400. };
  42401. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  42402. impostor.physicsBody.awake();
  42403. };
  42404. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  42405. joint.physicsJoint.limitMotor.upperLimit = maxDistance;
  42406. if (minDistance !== void 0) {
  42407. joint.physicsJoint.limitMotor.lowerLimit = minDistance;
  42408. }
  42409. };
  42410. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  42411. //TODO separate rotational and transational motors.
  42412. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  42413. if (motor) {
  42414. motor.setMotor(speed, maxForce);
  42415. }
  42416. };
  42417. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  42418. //TODO separate rotational and transational motors.
  42419. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  42420. if (motor) {
  42421. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  42422. }
  42423. };
  42424. OimoJSPlugin.prototype.dispose = function () {
  42425. this.world.clear();
  42426. };
  42427. return OimoJSPlugin;
  42428. }());
  42429. BABYLON.OimoJSPlugin = OimoJSPlugin;
  42430. })(BABYLON || (BABYLON = {}));
  42431. //# sourceMappingURL=babylon.oimoJSPlugin.js.map
  42432. var BABYLON;
  42433. (function (BABYLON) {
  42434. var DisplayPassPostProcess = (function (_super) {
  42435. __extends(DisplayPassPostProcess, _super);
  42436. function DisplayPassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  42437. return _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], options, camera, samplingMode, engine, reusable) || this;
  42438. }
  42439. return DisplayPassPostProcess;
  42440. }(BABYLON.PostProcess));
  42441. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  42442. })(BABYLON || (BABYLON = {}));
  42443. //# sourceMappingURL=babylon.displayPassPostProcess.js.map
  42444. var BABYLON;
  42445. (function (BABYLON) {
  42446. var SimplificationSettings = (function () {
  42447. function SimplificationSettings(quality, distance, optimizeMesh) {
  42448. this.quality = quality;
  42449. this.distance = distance;
  42450. this.optimizeMesh = optimizeMesh;
  42451. }
  42452. return SimplificationSettings;
  42453. }());
  42454. BABYLON.SimplificationSettings = SimplificationSettings;
  42455. var SimplificationQueue = (function () {
  42456. function SimplificationQueue() {
  42457. this.running = false;
  42458. this._simplificationArray = [];
  42459. }
  42460. SimplificationQueue.prototype.addTask = function (task) {
  42461. this._simplificationArray.push(task);
  42462. };
  42463. SimplificationQueue.prototype.executeNext = function () {
  42464. var task = this._simplificationArray.pop();
  42465. if (task) {
  42466. this.running = true;
  42467. this.runSimplification(task);
  42468. }
  42469. else {
  42470. this.running = false;
  42471. }
  42472. };
  42473. SimplificationQueue.prototype.runSimplification = function (task) {
  42474. var _this = this;
  42475. if (task.parallelProcessing) {
  42476. //parallel simplifier
  42477. task.settings.forEach(function (setting) {
  42478. var simplifier = _this.getSimplifier(task);
  42479. simplifier.simplify(setting, function (newMesh) {
  42480. task.mesh.addLODLevel(setting.distance, newMesh);
  42481. newMesh.isVisible = true;
  42482. //check if it is the last
  42483. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  42484. //all done, run the success callback.
  42485. task.successCallback();
  42486. }
  42487. _this.executeNext();
  42488. });
  42489. });
  42490. }
  42491. else {
  42492. //single simplifier.
  42493. var simplifier = this.getSimplifier(task);
  42494. var runDecimation = function (setting, callback) {
  42495. simplifier.simplify(setting, function (newMesh) {
  42496. task.mesh.addLODLevel(setting.distance, newMesh);
  42497. newMesh.isVisible = true;
  42498. //run the next quality level
  42499. callback();
  42500. });
  42501. };
  42502. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  42503. runDecimation(task.settings[loop.index], function () {
  42504. loop.executeNext();
  42505. });
  42506. }, function () {
  42507. //execution ended, run the success callback.
  42508. if (task.successCallback) {
  42509. task.successCallback();
  42510. }
  42511. _this.executeNext();
  42512. });
  42513. }
  42514. };
  42515. SimplificationQueue.prototype.getSimplifier = function (task) {
  42516. switch (task.simplificationType) {
  42517. case SimplificationType.QUADRATIC:
  42518. default:
  42519. return new QuadraticErrorSimplification(task.mesh);
  42520. }
  42521. };
  42522. return SimplificationQueue;
  42523. }());
  42524. BABYLON.SimplificationQueue = SimplificationQueue;
  42525. /**
  42526. * The implemented types of simplification.
  42527. * At the moment only Quadratic Error Decimation is implemented.
  42528. */
  42529. var SimplificationType;
  42530. (function (SimplificationType) {
  42531. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  42532. })(SimplificationType = BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  42533. var DecimationTriangle = (function () {
  42534. function DecimationTriangle(vertices) {
  42535. this.vertices = vertices;
  42536. this.error = new Array(4);
  42537. this.deleted = false;
  42538. this.isDirty = false;
  42539. this.deletePending = false;
  42540. this.borderFactor = 0;
  42541. }
  42542. return DecimationTriangle;
  42543. }());
  42544. BABYLON.DecimationTriangle = DecimationTriangle;
  42545. var DecimationVertex = (function () {
  42546. function DecimationVertex(position, id) {
  42547. this.position = position;
  42548. this.id = id;
  42549. this.isBorder = true;
  42550. this.q = new QuadraticMatrix();
  42551. this.triangleCount = 0;
  42552. this.triangleStart = 0;
  42553. this.originalOffsets = [];
  42554. }
  42555. DecimationVertex.prototype.updatePosition = function (newPosition) {
  42556. this.position.copyFrom(newPosition);
  42557. };
  42558. return DecimationVertex;
  42559. }());
  42560. BABYLON.DecimationVertex = DecimationVertex;
  42561. var QuadraticMatrix = (function () {
  42562. function QuadraticMatrix(data) {
  42563. this.data = new Array(10);
  42564. for (var i = 0; i < 10; ++i) {
  42565. if (data && data[i]) {
  42566. this.data[i] = data[i];
  42567. }
  42568. else {
  42569. this.data[i] = 0;
  42570. }
  42571. }
  42572. }
  42573. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  42574. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  42575. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  42576. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  42577. return det;
  42578. };
  42579. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  42580. for (var i = 0; i < 10; ++i) {
  42581. this.data[i] += matrix.data[i];
  42582. }
  42583. };
  42584. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  42585. for (var i = 0; i < 10; ++i) {
  42586. this.data[i] += data[i];
  42587. }
  42588. };
  42589. QuadraticMatrix.prototype.add = function (matrix) {
  42590. var m = new QuadraticMatrix();
  42591. for (var i = 0; i < 10; ++i) {
  42592. m.data[i] = this.data[i] + matrix.data[i];
  42593. }
  42594. return m;
  42595. };
  42596. QuadraticMatrix.FromData = function (a, b, c, d) {
  42597. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  42598. };
  42599. //returning an array to avoid garbage collection
  42600. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  42601. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  42602. };
  42603. return QuadraticMatrix;
  42604. }());
  42605. BABYLON.QuadraticMatrix = QuadraticMatrix;
  42606. var Reference = (function () {
  42607. function Reference(vertexId, triangleId) {
  42608. this.vertexId = vertexId;
  42609. this.triangleId = triangleId;
  42610. }
  42611. return Reference;
  42612. }());
  42613. BABYLON.Reference = Reference;
  42614. /**
  42615. * An implementation of the Quadratic Error simplification algorithm.
  42616. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  42617. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  42618. * @author RaananW
  42619. */
  42620. var QuadraticErrorSimplification = (function () {
  42621. function QuadraticErrorSimplification(_mesh) {
  42622. this._mesh = _mesh;
  42623. this.initialized = false;
  42624. this.syncIterations = 5000;
  42625. this.aggressiveness = 7;
  42626. this.decimationIterations = 100;
  42627. this.boundingBoxEpsilon = BABYLON.Epsilon;
  42628. }
  42629. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  42630. var _this = this;
  42631. this.initDecimatedMesh();
  42632. //iterating through the submeshes array, one after the other.
  42633. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  42634. _this.initWithMesh(loop.index, function () {
  42635. _this.runDecimation(settings, loop.index, function () {
  42636. loop.executeNext();
  42637. });
  42638. }, settings.optimizeMesh);
  42639. }, function () {
  42640. setTimeout(function () {
  42641. successCallback(_this._reconstructedMesh);
  42642. }, 0);
  42643. });
  42644. };
  42645. QuadraticErrorSimplification.prototype.isTriangleOnBoundingBox = function (triangle) {
  42646. var _this = this;
  42647. var gCount = 0;
  42648. triangle.vertices.forEach(function (vertex) {
  42649. var count = 0;
  42650. var vPos = vertex.position;
  42651. var bbox = _this._mesh.getBoundingInfo().boundingBox;
  42652. if (bbox.maximum.x - vPos.x < _this.boundingBoxEpsilon || vPos.x - bbox.minimum.x > _this.boundingBoxEpsilon)
  42653. ++count;
  42654. if (bbox.maximum.y === vPos.y || vPos.y === bbox.minimum.y)
  42655. ++count;
  42656. if (bbox.maximum.z === vPos.z || vPos.z === bbox.minimum.z)
  42657. ++count;
  42658. if (count > 1) {
  42659. ++gCount;
  42660. }
  42661. ;
  42662. });
  42663. if (gCount > 1) {
  42664. console.log(triangle, gCount);
  42665. }
  42666. return gCount > 1;
  42667. };
  42668. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  42669. var _this = this;
  42670. var targetCount = ~~(this.triangles.length * settings.quality);
  42671. var deletedTriangles = 0;
  42672. var triangleCount = this.triangles.length;
  42673. var iterationFunction = function (iteration, callback) {
  42674. setTimeout(function () {
  42675. if (iteration % 5 === 0) {
  42676. _this.updateMesh(iteration === 0);
  42677. }
  42678. for (var i = 0; i < _this.triangles.length; ++i) {
  42679. _this.triangles[i].isDirty = false;
  42680. }
  42681. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  42682. var trianglesIterator = function (i) {
  42683. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  42684. var t = _this.triangles[tIdx];
  42685. if (!t)
  42686. return;
  42687. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  42688. return;
  42689. }
  42690. for (var j = 0; j < 3; ++j) {
  42691. if (t.error[j] < threshold) {
  42692. var deleted0 = [];
  42693. var deleted1 = [];
  42694. var v0 = t.vertices[j];
  42695. var v1 = t.vertices[(j + 1) % 3];
  42696. if (v0.isBorder || v1.isBorder)
  42697. continue;
  42698. var p = BABYLON.Vector3.Zero();
  42699. var n = BABYLON.Vector3.Zero();
  42700. var uv = BABYLON.Vector2.Zero();
  42701. var color = new BABYLON.Color4(0, 0, 0, 1);
  42702. _this.calculateError(v0, v1, p, n, uv, color);
  42703. var delTr = [];
  42704. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  42705. continue;
  42706. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  42707. continue;
  42708. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  42709. continue;
  42710. var uniqueArray = [];
  42711. delTr.forEach(function (deletedT) {
  42712. if (uniqueArray.indexOf(deletedT) === -1) {
  42713. deletedT.deletePending = true;
  42714. uniqueArray.push(deletedT);
  42715. }
  42716. });
  42717. if (uniqueArray.length % 2 !== 0) {
  42718. continue;
  42719. }
  42720. v0.q = v1.q.add(v0.q);
  42721. v0.updatePosition(p);
  42722. var tStart = _this.references.length;
  42723. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  42724. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  42725. var tCount = _this.references.length - tStart;
  42726. if (tCount <= v0.triangleCount) {
  42727. if (tCount) {
  42728. for (var c = 0; c < tCount; c++) {
  42729. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  42730. }
  42731. }
  42732. }
  42733. else {
  42734. v0.triangleStart = tStart;
  42735. }
  42736. v0.triangleCount = tCount;
  42737. break;
  42738. }
  42739. }
  42740. };
  42741. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  42742. }, 0);
  42743. };
  42744. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  42745. if (triangleCount - deletedTriangles <= targetCount)
  42746. loop.breakLoop();
  42747. else {
  42748. iterationFunction(loop.index, function () {
  42749. loop.executeNext();
  42750. });
  42751. }
  42752. }, function () {
  42753. setTimeout(function () {
  42754. //reconstruct this part of the mesh
  42755. _this.reconstructMesh(submeshIndex);
  42756. successCallback();
  42757. }, 0);
  42758. });
  42759. };
  42760. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  42761. var _this = this;
  42762. this.vertices = [];
  42763. this.triangles = [];
  42764. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  42765. var indices = this._mesh.getIndices();
  42766. var submesh = this._mesh.subMeshes[submeshIndex];
  42767. var findInVertices = function (positionToSearch) {
  42768. if (optimizeMesh) {
  42769. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  42770. if (_this.vertices[ii].position.equals(positionToSearch)) {
  42771. return _this.vertices[ii];
  42772. }
  42773. }
  42774. }
  42775. return null;
  42776. };
  42777. var vertexReferences = [];
  42778. var vertexInit = function (i) {
  42779. var offset = i + submesh.verticesStart;
  42780. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  42781. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  42782. vertex.originalOffsets.push(offset);
  42783. if (vertex.id === _this.vertices.length) {
  42784. _this.vertices.push(vertex);
  42785. }
  42786. vertexReferences.push(vertex.id);
  42787. };
  42788. //var totalVertices = mesh.getTotalVertices();
  42789. var totalVertices = submesh.verticesCount;
  42790. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  42791. var indicesInit = function (i) {
  42792. var offset = (submesh.indexStart / 3) + i;
  42793. var pos = (offset * 3);
  42794. var i0 = indices[pos + 0];
  42795. var i1 = indices[pos + 1];
  42796. var i2 = indices[pos + 2];
  42797. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  42798. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  42799. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  42800. var triangle = new DecimationTriangle([v0, v1, v2]);
  42801. triangle.originalOffset = pos;
  42802. _this.triangles.push(triangle);
  42803. };
  42804. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  42805. _this.init(callback);
  42806. });
  42807. });
  42808. };
  42809. QuadraticErrorSimplification.prototype.init = function (callback) {
  42810. var _this = this;
  42811. var triangleInit1 = function (i) {
  42812. var t = _this.triangles[i];
  42813. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  42814. for (var j = 0; j < 3; j++) {
  42815. 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))));
  42816. }
  42817. };
  42818. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  42819. var triangleInit2 = function (i) {
  42820. var t = _this.triangles[i];
  42821. for (var j = 0; j < 3; ++j) {
  42822. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  42823. }
  42824. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  42825. };
  42826. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  42827. _this.initialized = true;
  42828. callback();
  42829. });
  42830. });
  42831. };
  42832. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  42833. var newTriangles = [];
  42834. var i;
  42835. for (i = 0; i < this.vertices.length; ++i) {
  42836. this.vertices[i].triangleCount = 0;
  42837. }
  42838. var t;
  42839. var j;
  42840. for (i = 0; i < this.triangles.length; ++i) {
  42841. if (!this.triangles[i].deleted) {
  42842. t = this.triangles[i];
  42843. for (j = 0; j < 3; ++j) {
  42844. t.vertices[j].triangleCount = 1;
  42845. }
  42846. newTriangles.push(t);
  42847. }
  42848. }
  42849. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  42850. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  42851. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  42852. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  42853. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  42854. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  42855. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  42856. var vertexCount = 0;
  42857. for (i = 0; i < this.vertices.length; ++i) {
  42858. var vertex = this.vertices[i];
  42859. vertex.id = vertexCount;
  42860. if (vertex.triangleCount) {
  42861. vertex.originalOffsets.forEach(function (originalOffset) {
  42862. newPositionData.push(vertex.position.x);
  42863. newPositionData.push(vertex.position.y);
  42864. newPositionData.push(vertex.position.z);
  42865. newNormalData.push(normalData[originalOffset * 3]);
  42866. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  42867. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  42868. if (uvs && uvs.length) {
  42869. newUVsData.push(uvs[(originalOffset * 2)]);
  42870. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  42871. }
  42872. else if (colorsData && colorsData.length) {
  42873. newColorsData.push(colorsData[(originalOffset * 4)]);
  42874. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  42875. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  42876. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  42877. }
  42878. ++vertexCount;
  42879. });
  42880. }
  42881. }
  42882. var startingIndex = this._reconstructedMesh.getTotalIndices();
  42883. var startingVertex = this._reconstructedMesh.getTotalVertices();
  42884. var submeshesArray = this._reconstructedMesh.subMeshes;
  42885. this._reconstructedMesh.subMeshes = [];
  42886. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  42887. var originalIndices = this._mesh.getIndices();
  42888. for (i = 0; i < newTriangles.length; ++i) {
  42889. t = newTriangles[i]; //now get the new referencing point for each vertex
  42890. [0, 1, 2].forEach(function (idx) {
  42891. var id = originalIndices[t.originalOffset + idx];
  42892. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  42893. if (offset < 0)
  42894. offset = 0;
  42895. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  42896. });
  42897. }
  42898. //overwriting the old vertex buffers and indices.
  42899. this._reconstructedMesh.setIndices(newIndicesArray);
  42900. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  42901. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  42902. if (newUVsData.length > 0)
  42903. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  42904. if (newColorsData.length > 0)
  42905. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  42906. //create submesh
  42907. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  42908. if (submeshIndex > 0) {
  42909. this._reconstructedMesh.subMeshes = [];
  42910. submeshesArray.forEach(function (submesh) {
  42911. new BABYLON.SubMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  42912. });
  42913. var newSubmesh = new BABYLON.SubMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  42914. }
  42915. };
  42916. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  42917. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  42918. this._reconstructedMesh.material = this._mesh.material;
  42919. this._reconstructedMesh.parent = this._mesh.parent;
  42920. this._reconstructedMesh.isVisible = false;
  42921. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  42922. };
  42923. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  42924. for (var i = 0; i < vertex1.triangleCount; ++i) {
  42925. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  42926. if (t.deleted)
  42927. continue;
  42928. var s = this.references[vertex1.triangleStart + i].vertexId;
  42929. var v1 = t.vertices[(s + 1) % 3];
  42930. var v2 = t.vertices[(s + 2) % 3];
  42931. if ((v1 === vertex2 || v2 === vertex2) /* && !this.isTriangleOnBoundingBox(t)*/) {
  42932. deletedArray[i] = true;
  42933. delTr.push(t);
  42934. continue;
  42935. }
  42936. var d1 = v1.position.subtract(point);
  42937. d1 = d1.normalize();
  42938. var d2 = v2.position.subtract(point);
  42939. d2 = d2.normalize();
  42940. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  42941. return true;
  42942. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  42943. deletedArray[i] = false;
  42944. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  42945. return true;
  42946. }
  42947. return false;
  42948. };
  42949. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  42950. var newDeleted = deletedTriangles;
  42951. for (var i = 0; i < vertex.triangleCount; ++i) {
  42952. var ref = this.references[vertex.triangleStart + i];
  42953. var t = this.triangles[ref.triangleId];
  42954. if (t.deleted)
  42955. continue;
  42956. if (deletedArray[i] && t.deletePending) {
  42957. t.deleted = true;
  42958. newDeleted++;
  42959. continue;
  42960. }
  42961. t.vertices[ref.vertexId] = origVertex;
  42962. t.isDirty = true;
  42963. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  42964. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  42965. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  42966. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  42967. this.references.push(ref);
  42968. }
  42969. return newDeleted;
  42970. };
  42971. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  42972. for (var i = 0; i < this.vertices.length; ++i) {
  42973. var vCount = [];
  42974. var vId = [];
  42975. var v = this.vertices[i];
  42976. var j;
  42977. for (j = 0; j < v.triangleCount; ++j) {
  42978. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  42979. for (var ii = 0; ii < 3; ii++) {
  42980. var ofs = 0;
  42981. var vv = triangle.vertices[ii];
  42982. while (ofs < vCount.length) {
  42983. if (vId[ofs] === vv.id)
  42984. break;
  42985. ++ofs;
  42986. }
  42987. if (ofs === vCount.length) {
  42988. vCount.push(1);
  42989. vId.push(vv.id);
  42990. }
  42991. else {
  42992. vCount[ofs]++;
  42993. }
  42994. }
  42995. }
  42996. for (j = 0; j < vCount.length; ++j) {
  42997. if (vCount[j] === 1) {
  42998. this.vertices[vId[j]].isBorder = true;
  42999. }
  43000. else {
  43001. this.vertices[vId[j]].isBorder = false;
  43002. }
  43003. }
  43004. }
  43005. };
  43006. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  43007. if (identifyBorders === void 0) { identifyBorders = false; }
  43008. var i;
  43009. if (!identifyBorders) {
  43010. var newTrianglesVector = [];
  43011. for (i = 0; i < this.triangles.length; ++i) {
  43012. if (!this.triangles[i].deleted) {
  43013. newTrianglesVector.push(this.triangles[i]);
  43014. }
  43015. }
  43016. this.triangles = newTrianglesVector;
  43017. }
  43018. for (i = 0; i < this.vertices.length; ++i) {
  43019. this.vertices[i].triangleCount = 0;
  43020. this.vertices[i].triangleStart = 0;
  43021. }
  43022. var t;
  43023. var j;
  43024. var v;
  43025. for (i = 0; i < this.triangles.length; ++i) {
  43026. t = this.triangles[i];
  43027. for (j = 0; j < 3; ++j) {
  43028. v = t.vertices[j];
  43029. v.triangleCount++;
  43030. }
  43031. }
  43032. var tStart = 0;
  43033. for (i = 0; i < this.vertices.length; ++i) {
  43034. this.vertices[i].triangleStart = tStart;
  43035. tStart += this.vertices[i].triangleCount;
  43036. this.vertices[i].triangleCount = 0;
  43037. }
  43038. var newReferences = new Array(this.triangles.length * 3);
  43039. for (i = 0; i < this.triangles.length; ++i) {
  43040. t = this.triangles[i];
  43041. for (j = 0; j < 3; ++j) {
  43042. v = t.vertices[j];
  43043. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  43044. v.triangleCount++;
  43045. }
  43046. }
  43047. this.references = newReferences;
  43048. if (identifyBorders) {
  43049. this.identifyBorder();
  43050. }
  43051. };
  43052. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  43053. var x = point.x;
  43054. var y = point.y;
  43055. var z = point.z;
  43056. 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
  43057. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  43058. };
  43059. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  43060. var q = vertex1.q.add(vertex2.q);
  43061. var border = vertex1.isBorder && vertex2.isBorder;
  43062. var error = 0;
  43063. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  43064. if (qDet !== 0 && !border) {
  43065. if (!pointResult) {
  43066. pointResult = BABYLON.Vector3.Zero();
  43067. }
  43068. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  43069. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  43070. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  43071. error = this.vertexError(q, pointResult);
  43072. }
  43073. else {
  43074. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  43075. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  43076. var error1 = this.vertexError(q, vertex1.position);
  43077. var error2 = this.vertexError(q, vertex2.position);
  43078. var error3 = this.vertexError(q, p3);
  43079. error = Math.min(error1, error2, error3);
  43080. if (error === error1) {
  43081. if (pointResult) {
  43082. pointResult.copyFrom(vertex1.position);
  43083. }
  43084. }
  43085. else if (error === error2) {
  43086. if (pointResult) {
  43087. pointResult.copyFrom(vertex2.position);
  43088. }
  43089. }
  43090. else {
  43091. if (pointResult) {
  43092. pointResult.copyFrom(p3);
  43093. }
  43094. }
  43095. }
  43096. return error;
  43097. };
  43098. return QuadraticErrorSimplification;
  43099. }());
  43100. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  43101. })(BABYLON || (BABYLON = {}));
  43102. //# sourceMappingURL=babylon.meshSimplification.js.map
  43103. var BABYLON;
  43104. (function (BABYLON) {
  43105. var serializedGeometries = [];
  43106. var serializeGeometry = function (geometry, serializationGeometries) {
  43107. if (serializedGeometries[geometry.id]) {
  43108. return;
  43109. }
  43110. if (geometry.doNotSerialize) {
  43111. return;
  43112. }
  43113. if (geometry instanceof BABYLON.Geometry.Primitives.Box) {
  43114. serializationGeometries.boxes.push(geometry.serialize());
  43115. }
  43116. else if (geometry instanceof BABYLON.Geometry.Primitives.Sphere) {
  43117. serializationGeometries.spheres.push(geometry.serialize());
  43118. }
  43119. else if (geometry instanceof BABYLON.Geometry.Primitives.Cylinder) {
  43120. serializationGeometries.cylinders.push(geometry.serialize());
  43121. }
  43122. else if (geometry instanceof BABYLON.Geometry.Primitives.Torus) {
  43123. serializationGeometries.toruses.push(geometry.serialize());
  43124. }
  43125. else if (geometry instanceof BABYLON.Geometry.Primitives.Ground) {
  43126. serializationGeometries.grounds.push(geometry.serialize());
  43127. }
  43128. else if (geometry instanceof BABYLON.Geometry.Primitives.Plane) {
  43129. serializationGeometries.planes.push(geometry.serialize());
  43130. }
  43131. else if (geometry instanceof BABYLON.Geometry.Primitives.TorusKnot) {
  43132. serializationGeometries.torusKnots.push(geometry.serialize());
  43133. }
  43134. else if (geometry instanceof BABYLON.Geometry.Primitives._Primitive) {
  43135. throw new Error("Unknown primitive type");
  43136. }
  43137. else {
  43138. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  43139. }
  43140. serializedGeometries[geometry.id] = true;
  43141. };
  43142. var serializeMesh = function (mesh, serializationScene) {
  43143. var serializationObject = {};
  43144. serializationObject.name = mesh.name;
  43145. serializationObject.id = mesh.id;
  43146. if (BABYLON.Tags.HasTags(mesh)) {
  43147. serializationObject.tags = BABYLON.Tags.GetTags(mesh);
  43148. }
  43149. serializationObject.position = mesh.position.asArray();
  43150. if (mesh.rotationQuaternion) {
  43151. serializationObject.rotationQuaternion = mesh.rotationQuaternion.asArray();
  43152. }
  43153. else if (mesh.rotation) {
  43154. serializationObject.rotation = mesh.rotation.asArray();
  43155. }
  43156. serializationObject.scaling = mesh.scaling.asArray();
  43157. serializationObject.localMatrix = mesh.getPivotMatrix().asArray();
  43158. serializationObject.isEnabled = mesh.isEnabled();
  43159. serializationObject.isVisible = mesh.isVisible;
  43160. serializationObject.infiniteDistance = mesh.infiniteDistance;
  43161. serializationObject.pickable = mesh.isPickable;
  43162. serializationObject.receiveShadows = mesh.receiveShadows;
  43163. serializationObject.billboardMode = mesh.billboardMode;
  43164. serializationObject.visibility = mesh.visibility;
  43165. serializationObject.checkCollisions = mesh.checkCollisions;
  43166. serializationObject.isBlocker = mesh.isBlocker;
  43167. // Parent
  43168. if (mesh.parent) {
  43169. serializationObject.parentId = mesh.parent.id;
  43170. }
  43171. // Geometry
  43172. var geometry = mesh._geometry;
  43173. if (geometry) {
  43174. var geometryId = geometry.id;
  43175. serializationObject.geometryId = geometryId;
  43176. if (!mesh.getScene().getGeometryByID(geometryId)) {
  43177. // 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
  43178. serializeGeometry(geometry, serializationScene.geometries);
  43179. }
  43180. // SubMeshes
  43181. serializationObject.subMeshes = [];
  43182. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  43183. var subMesh = mesh.subMeshes[subIndex];
  43184. serializationObject.subMeshes.push({
  43185. materialIndex: subMesh.materialIndex,
  43186. verticesStart: subMesh.verticesStart,
  43187. verticesCount: subMesh.verticesCount,
  43188. indexStart: subMesh.indexStart,
  43189. indexCount: subMesh.indexCount
  43190. });
  43191. }
  43192. }
  43193. // Material
  43194. if (mesh.material) {
  43195. serializationObject.materialId = mesh.material.id;
  43196. }
  43197. else {
  43198. mesh.material = null;
  43199. }
  43200. // Skeleton
  43201. if (mesh.skeleton) {
  43202. serializationObject.skeletonId = mesh.skeleton.id;
  43203. }
  43204. // Physics
  43205. //TODO implement correct serialization for physics impostors.
  43206. if (mesh.getPhysicsImpostor()) {
  43207. serializationObject.physicsMass = mesh.getPhysicsMass();
  43208. serializationObject.physicsFriction = mesh.getPhysicsFriction();
  43209. serializationObject.physicsRestitution = mesh.getPhysicsRestitution();
  43210. serializationObject.physicsImpostor = mesh.getPhysicsImpostor().type;
  43211. }
  43212. // Metadata
  43213. if (mesh.metadata) {
  43214. serializationObject.metadata = mesh.metadata;
  43215. }
  43216. // Instances
  43217. serializationObject.instances = [];
  43218. for (var index = 0; index < mesh.instances.length; index++) {
  43219. var instance = mesh.instances[index];
  43220. var serializationInstance = {
  43221. name: instance.name,
  43222. position: instance.position.asArray(),
  43223. scaling: instance.scaling.asArray()
  43224. };
  43225. if (instance.rotationQuaternion) {
  43226. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  43227. }
  43228. else if (instance.rotation) {
  43229. serializationInstance.rotation = instance.rotation.asArray();
  43230. }
  43231. serializationObject.instances.push(serializationInstance);
  43232. // Animations
  43233. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  43234. serializationInstance.ranges = instance.serializeAnimationRanges();
  43235. }
  43236. // Animations
  43237. BABYLON.Animation.AppendSerializedAnimations(mesh, serializationObject);
  43238. serializationObject.ranges = mesh.serializeAnimationRanges();
  43239. // Layer mask
  43240. serializationObject.layerMask = mesh.layerMask;
  43241. // Alpha
  43242. serializationObject.alphaIndex = mesh.alphaIndex;
  43243. serializationObject.hasVertexAlpha = mesh.hasVertexAlpha;
  43244. // Overlay
  43245. serializationObject.overlayAlpha = mesh.overlayAlpha;
  43246. serializationObject.overlayColor = mesh.overlayColor.asArray();
  43247. serializationObject.renderOverlay = mesh.renderOverlay;
  43248. // Fog
  43249. serializationObject.applyFog = mesh.applyFog;
  43250. // Action Manager
  43251. if (mesh.actionManager) {
  43252. serializationObject.actions = mesh.actionManager.serialize(mesh.name);
  43253. }
  43254. return serializationObject;
  43255. };
  43256. var finalizeSingleMesh = function (mesh, serializationObject) {
  43257. //only works if the mesh is already loaded
  43258. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  43259. //serialize material
  43260. if (mesh.material) {
  43261. if (mesh.material instanceof BABYLON.StandardMaterial) {
  43262. serializationObject.materials = serializationObject.materials || [];
  43263. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  43264. serializationObject.materials.push(mesh.material.serialize());
  43265. }
  43266. }
  43267. else if (mesh.material instanceof BABYLON.MultiMaterial) {
  43268. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  43269. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  43270. serializationObject.multiMaterials.push(mesh.material.serialize());
  43271. }
  43272. }
  43273. }
  43274. //serialize geometry
  43275. var geometry = mesh._geometry;
  43276. if (geometry) {
  43277. if (!serializationObject.geometries) {
  43278. serializationObject.geometries = {};
  43279. serializationObject.geometries.boxes = [];
  43280. serializationObject.geometries.spheres = [];
  43281. serializationObject.geometries.cylinders = [];
  43282. serializationObject.geometries.toruses = [];
  43283. serializationObject.geometries.grounds = [];
  43284. serializationObject.geometries.planes = [];
  43285. serializationObject.geometries.torusKnots = [];
  43286. serializationObject.geometries.vertexData = [];
  43287. }
  43288. serializeGeometry(geometry, serializationObject.geometries);
  43289. }
  43290. // Skeletons
  43291. if (mesh.skeleton) {
  43292. serializationObject.skeletons = serializationObject.skeletons || [];
  43293. serializationObject.skeletons.push(mesh.skeleton.serialize());
  43294. }
  43295. //serialize the actual mesh
  43296. serializationObject.meshes = serializationObject.meshes || [];
  43297. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  43298. }
  43299. };
  43300. var SceneSerializer = (function () {
  43301. function SceneSerializer() {
  43302. }
  43303. SceneSerializer.ClearCache = function () {
  43304. serializedGeometries = [];
  43305. };
  43306. SceneSerializer.Serialize = function (scene) {
  43307. var serializationObject = {};
  43308. // Scene
  43309. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  43310. serializationObject.autoClear = scene.autoClear;
  43311. serializationObject.clearColor = scene.clearColor.asArray();
  43312. serializationObject.ambientColor = scene.ambientColor.asArray();
  43313. serializationObject.gravity = scene.gravity.asArray();
  43314. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  43315. serializationObject.workerCollisions = scene.workerCollisions;
  43316. // Fog
  43317. if (scene.fogMode && scene.fogMode !== 0) {
  43318. serializationObject.fogMode = scene.fogMode;
  43319. serializationObject.fogColor = scene.fogColor.asArray();
  43320. serializationObject.fogStart = scene.fogStart;
  43321. serializationObject.fogEnd = scene.fogEnd;
  43322. serializationObject.fogDensity = scene.fogDensity;
  43323. }
  43324. //Physics
  43325. if (scene.isPhysicsEnabled()) {
  43326. serializationObject.physicsEnabled = true;
  43327. serializationObject.physicsGravity = scene.getPhysicsEngine().gravity.asArray();
  43328. serializationObject.physicsEngine = scene.getPhysicsEngine().getPhysicsPluginName();
  43329. }
  43330. // Metadata
  43331. if (scene.metadata) {
  43332. serializationObject.metadata = scene.metadata;
  43333. }
  43334. // Lights
  43335. serializationObject.lights = [];
  43336. var index;
  43337. var light;
  43338. for (index = 0; index < scene.lights.length; index++) {
  43339. light = scene.lights[index];
  43340. if (!light.doNotSerialize) {
  43341. serializationObject.lights.push(light.serialize());
  43342. }
  43343. }
  43344. // Cameras
  43345. serializationObject.cameras = [];
  43346. for (index = 0; index < scene.cameras.length; index++) {
  43347. var camera = scene.cameras[index];
  43348. if (!camera.doNotSerialize) {
  43349. serializationObject.cameras.push(camera.serialize());
  43350. }
  43351. }
  43352. if (scene.activeCamera) {
  43353. serializationObject.activeCameraID = scene.activeCamera.id;
  43354. }
  43355. // Animations
  43356. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  43357. // Materials
  43358. serializationObject.materials = [];
  43359. serializationObject.multiMaterials = [];
  43360. var material;
  43361. for (index = 0; index < scene.materials.length; index++) {
  43362. material = scene.materials[index];
  43363. if (!material.doNotSerialize) {
  43364. serializationObject.materials.push(material.serialize());
  43365. }
  43366. }
  43367. // MultiMaterials
  43368. serializationObject.multiMaterials = [];
  43369. for (index = 0; index < scene.multiMaterials.length; index++) {
  43370. var multiMaterial = scene.multiMaterials[index];
  43371. serializationObject.multiMaterials.push(multiMaterial.serialize());
  43372. }
  43373. // Skeletons
  43374. serializationObject.skeletons = [];
  43375. for (index = 0; index < scene.skeletons.length; index++) {
  43376. serializationObject.skeletons.push(scene.skeletons[index].serialize());
  43377. }
  43378. // Geometries
  43379. serializationObject.geometries = {};
  43380. serializationObject.geometries.boxes = [];
  43381. serializationObject.geometries.spheres = [];
  43382. serializationObject.geometries.cylinders = [];
  43383. serializationObject.geometries.toruses = [];
  43384. serializationObject.geometries.grounds = [];
  43385. serializationObject.geometries.planes = [];
  43386. serializationObject.geometries.torusKnots = [];
  43387. serializationObject.geometries.vertexData = [];
  43388. serializedGeometries = [];
  43389. var geometries = scene.getGeometries();
  43390. for (index = 0; index < geometries.length; index++) {
  43391. var geometry = geometries[index];
  43392. if (geometry.isReady()) {
  43393. serializeGeometry(geometry, serializationObject.geometries);
  43394. }
  43395. }
  43396. // Meshes
  43397. serializationObject.meshes = [];
  43398. for (index = 0; index < scene.meshes.length; index++) {
  43399. var abstractMesh = scene.meshes[index];
  43400. if (abstractMesh instanceof BABYLON.Mesh) {
  43401. var mesh = abstractMesh;
  43402. if (!mesh.doNotSerialize) {
  43403. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  43404. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  43405. }
  43406. }
  43407. }
  43408. }
  43409. // Particles Systems
  43410. serializationObject.particleSystems = [];
  43411. for (index = 0; index < scene.particleSystems.length; index++) {
  43412. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  43413. }
  43414. // Lens flares
  43415. serializationObject.lensFlareSystems = [];
  43416. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  43417. serializationObject.lensFlareSystems.push(scene.lensFlareSystems[index].serialize());
  43418. }
  43419. // Shadows
  43420. serializationObject.shadowGenerators = [];
  43421. for (index = 0; index < scene.lights.length; index++) {
  43422. light = scene.lights[index];
  43423. var shadowGenerator = light.getShadowGenerator();
  43424. // Only support serialization for official generator so far.
  43425. if (shadowGenerator && shadowGenerator instanceof BABYLON.ShadowGenerator) {
  43426. serializationObject.shadowGenerators.push(shadowGenerator.serialize());
  43427. }
  43428. }
  43429. // Action Manager
  43430. if (scene.actionManager) {
  43431. serializationObject.actions = scene.actionManager.serialize("scene");
  43432. }
  43433. // Audio
  43434. serializationObject.sounds = [];
  43435. for (index = 0; index < scene.soundTracks.length; index++) {
  43436. var soundtrack = scene.soundTracks[index];
  43437. for (var soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) {
  43438. serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize());
  43439. }
  43440. }
  43441. return serializationObject;
  43442. };
  43443. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  43444. if (withParents === void 0) { withParents = false; }
  43445. if (withChildren === void 0) { withChildren = false; }
  43446. var serializationObject = {};
  43447. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  43448. if (withParents || withChildren) {
  43449. //deliberate for loop! not for each, appended should be processed as well.
  43450. for (var i = 0; i < toSerialize.length; ++i) {
  43451. if (withChildren) {
  43452. toSerialize[i].getDescendants().forEach(function (node) {
  43453. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  43454. toSerialize.push(node);
  43455. }
  43456. });
  43457. }
  43458. //make sure the array doesn't contain the object already
  43459. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  43460. toSerialize.push(toSerialize[i].parent);
  43461. }
  43462. }
  43463. }
  43464. toSerialize.forEach(function (mesh) {
  43465. finalizeSingleMesh(mesh, serializationObject);
  43466. });
  43467. return serializationObject;
  43468. };
  43469. return SceneSerializer;
  43470. }());
  43471. BABYLON.SceneSerializer = SceneSerializer;
  43472. })(BABYLON || (BABYLON = {}));
  43473. //# sourceMappingURL=babylon.sceneSerializer.js.map
  43474. // All the credit goes to this project and the guy who's behind it https://github.com/mapbox/earcut
  43475. // Huge respect for a such great lib.
  43476. // Earcut license:
  43477. // Copyright (c) 2016, Mapbox
  43478. //
  43479. // Permission to use, copy, modify, and/or distribute this software for any purpose
  43480. // with or without fee is hereby granted, provided that the above copyright notice
  43481. // and this permission notice appear in all copies.
  43482. //
  43483. // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
  43484. // REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
  43485. // FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
  43486. // INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
  43487. // OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
  43488. // TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
  43489. // THIS SOFTWARE.
  43490. var Earcut;
  43491. (function (Earcut) {
  43492. /**
  43493. * The fastest and smallest JavaScript polygon triangulation library for your WebGL apps
  43494. * @param data is a flat array of vertice coordinates like [x0, y0, x1, y1, x2, y2, ...].
  43495. * @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).
  43496. * @param dim is the number of coordinates per vertice in the input array (2 by default).
  43497. */
  43498. function earcut(data, holeIndices, dim) {
  43499. dim = dim || 2;
  43500. var hasHoles = holeIndices && holeIndices.length, outerLen = hasHoles ? holeIndices[0] * dim : data.length, outerNode = linkedList(data, 0, outerLen, dim, true), triangles = [];
  43501. if (!outerNode)
  43502. return triangles;
  43503. var minX, minY, maxX, maxY, x, y, size;
  43504. if (hasHoles)
  43505. outerNode = eliminateHoles(data, holeIndices, outerNode, dim);
  43506. // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
  43507. if (data.length > 80 * dim) {
  43508. minX = maxX = data[0];
  43509. minY = maxY = data[1];
  43510. for (var i = dim; i < outerLen; i += dim) {
  43511. x = data[i];
  43512. y = data[i + 1];
  43513. if (x < minX)
  43514. minX = x;
  43515. if (y < minY)
  43516. minY = y;
  43517. if (x > maxX)
  43518. maxX = x;
  43519. if (y > maxY)
  43520. maxY = y;
  43521. }
  43522. // minX, minY and size are later used to transform coords into integers for z-order calculation
  43523. size = Math.max(maxX - minX, maxY - minY);
  43524. }
  43525. earcutLinked(outerNode, triangles, dim, minX, minY, size, undefined);
  43526. return triangles;
  43527. }
  43528. Earcut.earcut = earcut;
  43529. // create a circular doubly linked list from polygon points in the specified winding order
  43530. function linkedList(data, start, end, dim, clockwise) {
  43531. var i, last;
  43532. if (clockwise === (signedArea(data, start, end, dim) > 0)) {
  43533. for (i = start; i < end; i += dim)
  43534. last = insertNode(i, data[i], data[i + 1], last);
  43535. }
  43536. else {
  43537. for (i = end - dim; i >= start; i -= dim)
  43538. last = insertNode(i, data[i], data[i + 1], last);
  43539. }
  43540. if (last && equals(last, last.next)) {
  43541. removeNode(last);
  43542. last = last.next;
  43543. }
  43544. return last;
  43545. }
  43546. // eliminate colinear or duplicate points
  43547. function filterPoints(start, end) {
  43548. if (!start)
  43549. return start;
  43550. if (!end)
  43551. end = start;
  43552. var p = start, again;
  43553. do {
  43554. again = false;
  43555. if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) {
  43556. removeNode(p);
  43557. p = end = p.prev;
  43558. if (p === p.next)
  43559. return null;
  43560. again = true;
  43561. }
  43562. else {
  43563. p = p.next;
  43564. }
  43565. } while (again || p !== end);
  43566. return end;
  43567. }
  43568. // main ear slicing loop which triangulates a polygon (given as a linked list)
  43569. function earcutLinked(ear, triangles, dim, minX, minY, size, pass) {
  43570. if (!ear)
  43571. return;
  43572. // interlink polygon nodes in z-order
  43573. if (!pass && size)
  43574. indexCurve(ear, minX, minY, size);
  43575. var stop = ear, prev, next;
  43576. // iterate through ears, slicing them one by one
  43577. while (ear.prev !== ear.next) {
  43578. prev = ear.prev;
  43579. next = ear.next;
  43580. if (size ? isEarHashed(ear, minX, minY, size) : isEar(ear)) {
  43581. // cut off the triangle
  43582. triangles.push(prev.i / dim);
  43583. triangles.push(ear.i / dim);
  43584. triangles.push(next.i / dim);
  43585. removeNode(ear);
  43586. // skipping the next vertice leads to less sliver triangles
  43587. ear = next.next;
  43588. stop = next.next;
  43589. continue;
  43590. }
  43591. ear = next;
  43592. // if we looped through the whole remaining polygon and can't find any more ears
  43593. if (ear === stop) {
  43594. // try filtering points and slicing again
  43595. if (!pass) {
  43596. earcutLinked(filterPoints(ear, undefined), triangles, dim, minX, minY, size, 1);
  43597. }
  43598. else if (pass === 1) {
  43599. ear = cureLocalIntersections(ear, triangles, dim);
  43600. earcutLinked(ear, triangles, dim, minX, minY, size, 2);
  43601. }
  43602. else if (pass === 2) {
  43603. splitEarcut(ear, triangles, dim, minX, minY, size);
  43604. }
  43605. break;
  43606. }
  43607. }
  43608. }
  43609. // check whether a polygon node forms a valid ear with adjacent nodes
  43610. function isEar(ear) {
  43611. var a = ear.prev, b = ear, c = ear.next;
  43612. if (area(a, b, c) >= 0)
  43613. return false; // reflex, can't be an ear
  43614. // now make sure we don't have other points inside the potential ear
  43615. var p = ear.next.next;
  43616. while (p !== ear.prev) {
  43617. if (pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  43618. area(p.prev, p, p.next) >= 0)
  43619. return false;
  43620. p = p.next;
  43621. }
  43622. return true;
  43623. }
  43624. function isEarHashed(ear, minX, minY, size) {
  43625. var a = ear.prev, b = ear, c = ear.next;
  43626. if (area(a, b, c) >= 0)
  43627. return false; // reflex, can't be an ear
  43628. // triangle bbox; min & max are calculated like this for speed
  43629. 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);
  43630. // z-order range for the current triangle bbox;
  43631. var minZ = zOrder(minTX, minTY, minX, minY, size), maxZ = zOrder(maxTX, maxTY, minX, minY, size);
  43632. // first look for points inside the triangle in increasing z-order
  43633. var p = ear.nextZ;
  43634. while (p && p.z <= maxZ) {
  43635. if (p !== ear.prev &&
  43636. p !== ear.next &&
  43637. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  43638. area(p.prev, p, p.next) >= 0)
  43639. return false;
  43640. p = p.nextZ;
  43641. }
  43642. // then look for points in decreasing z-order
  43643. p = ear.prevZ;
  43644. while (p && p.z >= minZ) {
  43645. if (p !== ear.prev &&
  43646. p !== ear.next &&
  43647. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  43648. area(p.prev, p, p.next) >= 0)
  43649. return false;
  43650. p = p.prevZ;
  43651. }
  43652. return true;
  43653. }
  43654. // go through all polygon nodes and cure small local self-intersections
  43655. function cureLocalIntersections(start, triangles, dim) {
  43656. var p = start;
  43657. do {
  43658. var a = p.prev, b = p.next.next;
  43659. if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) {
  43660. triangles.push(a.i / dim);
  43661. triangles.push(p.i / dim);
  43662. triangles.push(b.i / dim);
  43663. // remove two nodes involved
  43664. removeNode(p);
  43665. removeNode(p.next);
  43666. p = start = b;
  43667. }
  43668. p = p.next;
  43669. } while (p !== start);
  43670. return p;
  43671. }
  43672. // try splitting polygon into two and triangulate them independently
  43673. function splitEarcut(start, triangles, dim, minX, minY, size) {
  43674. // look for a valid diagonal that divides the polygon into two
  43675. var a = start;
  43676. do {
  43677. var b = a.next.next;
  43678. while (b !== a.prev) {
  43679. if (a.i !== b.i && isValidDiagonal(a, b)) {
  43680. // split the polygon in two by the diagonal
  43681. var c = splitPolygon(a, b);
  43682. // filter colinear points around the cuts
  43683. a = filterPoints(a, a.next);
  43684. c = filterPoints(c, c.next);
  43685. // run earcut on each half
  43686. earcutLinked(a, triangles, dim, minX, minY, size, undefined);
  43687. earcutLinked(c, triangles, dim, minX, minY, size, undefined);
  43688. return;
  43689. }
  43690. b = b.next;
  43691. }
  43692. a = a.next;
  43693. } while (a !== start);
  43694. }
  43695. // link every hole into the outer loop, producing a single-ring polygon without holes
  43696. function eliminateHoles(data, holeIndices, outerNode, dim) {
  43697. var queue = [], i, len, start, end, list;
  43698. for (i = 0, len = holeIndices.length; i < len; i++) {
  43699. start = holeIndices[i] * dim;
  43700. end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  43701. list = linkedList(data, start, end, dim, false);
  43702. if (list === list.next)
  43703. list.steiner = true;
  43704. queue.push(getLeftmost(list));
  43705. }
  43706. queue.sort(compareX);
  43707. // process holes from left to right
  43708. for (i = 0; i < queue.length; i++) {
  43709. eliminateHole(queue[i], outerNode);
  43710. outerNode = filterPoints(outerNode, outerNode.next);
  43711. }
  43712. return outerNode;
  43713. }
  43714. function compareX(a, b) {
  43715. return a.x - b.x;
  43716. }
  43717. // find a bridge between vertices that connects hole with an outer ring and and link it
  43718. function eliminateHole(hole, outerNode) {
  43719. outerNode = findHoleBridge(hole, outerNode);
  43720. if (outerNode) {
  43721. var b = splitPolygon(outerNode, hole);
  43722. filterPoints(b, b.next);
  43723. }
  43724. }
  43725. // David Eberly's algorithm for finding a bridge between hole and outer polygon
  43726. function findHoleBridge(hole, outerNode) {
  43727. var p = outerNode, hx = hole.x, hy = hole.y, qx = -Infinity, m;
  43728. // find a segment intersected by a ray from the hole's leftmost point to the left;
  43729. // segment's endpoint with lesser x will be potential connection point
  43730. do {
  43731. if (hy <= p.y && hy >= p.next.y) {
  43732. var x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y);
  43733. if (x <= hx && x > qx) {
  43734. qx = x;
  43735. if (x === hx) {
  43736. if (hy === p.y)
  43737. return p;
  43738. if (hy === p.next.y)
  43739. return p.next;
  43740. }
  43741. m = p.x < p.next.x ? p : p.next;
  43742. }
  43743. }
  43744. p = p.next;
  43745. } while (p !== outerNode);
  43746. if (!m)
  43747. return null;
  43748. if (hx === qx)
  43749. return m.prev; // hole touches outer segment; pick lower endpoint
  43750. // look for points inside the triangle of hole point, segment intersection and endpoint;
  43751. // if there are no points found, we have a valid connection;
  43752. // otherwise choose the point of the minimum angle with the ray as connection point
  43753. var stop = m, mx = m.x, my = m.y, tanMin = Infinity, tan;
  43754. p = m.next;
  43755. while (p !== stop) {
  43756. if (hx >= p.x &&
  43757. p.x >= mx &&
  43758. pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y)) {
  43759. tan = Math.abs(hy - p.y) / (hx - p.x); // tangential
  43760. if ((tan < tanMin || (tan === tanMin && p.x > m.x)) && locallyInside(p, hole)) {
  43761. m = p;
  43762. tanMin = tan;
  43763. }
  43764. }
  43765. p = p.next;
  43766. }
  43767. return m;
  43768. }
  43769. // interlink polygon nodes in z-order
  43770. function indexCurve(start, minX, minY, size) {
  43771. var p = start;
  43772. do {
  43773. if (p.z === null)
  43774. p.z = zOrder(p.x, p.y, minX, minY, size);
  43775. p.prevZ = p.prev;
  43776. p.nextZ = p.next;
  43777. p = p.next;
  43778. } while (p !== start);
  43779. p.prevZ.nextZ = null;
  43780. p.prevZ = null;
  43781. sortLinked(p);
  43782. }
  43783. // Simon Tatham's linked list merge sort algorithm
  43784. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  43785. function sortLinked(list) {
  43786. var i, p, q, e, tail, numMerges, pSize, qSize, inSize = 1;
  43787. do {
  43788. p = list;
  43789. list = null;
  43790. tail = null;
  43791. numMerges = 0;
  43792. while (p) {
  43793. numMerges++;
  43794. q = p;
  43795. pSize = 0;
  43796. for (i = 0; i < inSize; i++) {
  43797. pSize++;
  43798. q = q.nextZ;
  43799. if (!q)
  43800. break;
  43801. }
  43802. qSize = inSize;
  43803. while (pSize > 0 || (qSize > 0 && q)) {
  43804. if (pSize === 0) {
  43805. e = q;
  43806. q = q.nextZ;
  43807. qSize--;
  43808. }
  43809. else if (qSize === 0 || !q) {
  43810. e = p;
  43811. p = p.nextZ;
  43812. pSize--;
  43813. }
  43814. else if (p.z <= q.z) {
  43815. e = p;
  43816. p = p.nextZ;
  43817. pSize--;
  43818. }
  43819. else {
  43820. e = q;
  43821. q = q.nextZ;
  43822. qSize--;
  43823. }
  43824. if (tail)
  43825. tail.nextZ = e;
  43826. else
  43827. list = e;
  43828. e.prevZ = tail;
  43829. tail = e;
  43830. }
  43831. p = q;
  43832. }
  43833. tail.nextZ = null;
  43834. inSize *= 2;
  43835. } while (numMerges > 1);
  43836. return list;
  43837. }
  43838. // z-order of a point given coords and size of the data bounding box
  43839. function zOrder(x, y, minX, minY, size) {
  43840. // coords are transformed into non-negative 15-bit integer range
  43841. x = 32767 * (x - minX) / size;
  43842. y = 32767 * (y - minY) / size;
  43843. x = (x | (x << 8)) & 0x00FF00FF;
  43844. x = (x | (x << 4)) & 0x0F0F0F0F;
  43845. x = (x | (x << 2)) & 0x33333333;
  43846. x = (x | (x << 1)) & 0x55555555;
  43847. y = (y | (y << 8)) & 0x00FF00FF;
  43848. y = (y | (y << 4)) & 0x0F0F0F0F;
  43849. y = (y | (y << 2)) & 0x33333333;
  43850. y = (y | (y << 1)) & 0x55555555;
  43851. return x | (y << 1);
  43852. }
  43853. // find the leftmost node of a polygon ring
  43854. function getLeftmost(start) {
  43855. var p = start, leftmost = start;
  43856. do {
  43857. if (p.x < leftmost.x)
  43858. leftmost = p;
  43859. p = p.next;
  43860. } while (p !== start);
  43861. return leftmost;
  43862. }
  43863. // check if a point lies within a convex triangle
  43864. function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) {
  43865. return (cx - px) * (ay - py) - (ax - px) * (cy - py) >= 0 &&
  43866. (ax - px) * (by - py) - (bx - px) * (ay - py) >= 0 &&
  43867. (bx - px) * (cy - py) - (cx - px) * (by - py) >= 0;
  43868. }
  43869. // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  43870. function isValidDiagonal(a, b) {
  43871. return a.next.i !== b.i &&
  43872. a.prev.i !== b.i &&
  43873. !intersectsPolygon(a, b) &&
  43874. locallyInside(a, b) &&
  43875. locallyInside(b, a) &&
  43876. middleInside(a, b);
  43877. }
  43878. // signed area of a triangle
  43879. function area(p, q, r) {
  43880. return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);
  43881. }
  43882. // check if two points are equal
  43883. function equals(p1, p2) {
  43884. return p1.x === p2.x && p1.y === p2.y;
  43885. }
  43886. // check if two segments intersect
  43887. function intersects(p1, q1, p2, q2) {
  43888. if ((equals(p1, q1) && equals(p2, q2)) ||
  43889. (equals(p1, q2) && equals(p2, q1)))
  43890. return true;
  43891. return area(p1, q1, p2) > 0 !== area(p1, q1, q2) > 0 &&
  43892. area(p2, q2, p1) > 0 !== area(p2, q2, q1) > 0;
  43893. }
  43894. // check if a polygon diagonal intersects any polygon segments
  43895. function intersectsPolygon(a, b) {
  43896. var p = a;
  43897. do {
  43898. if (p.i !== a.i &&
  43899. p.next.i !== a.i &&
  43900. p.i !== b.i &&
  43901. p.next.i !== b.i &&
  43902. intersects(p, p.next, a, b))
  43903. return true;
  43904. p = p.next;
  43905. } while (p !== a);
  43906. return false;
  43907. }
  43908. // check if a polygon diagonal is locally inside the polygon
  43909. function locallyInside(a, b) {
  43910. return area(a.prev, a, a.next) < 0
  43911. ? area(a, b, a.next) >= 0 && area(a, a.prev, b) >= 0
  43912. : area(a, b, a.prev) < 0 || area(a, a.next, b) < 0;
  43913. }
  43914. // check if the middle point of a polygon diagonal is inside the polygon
  43915. function middleInside(a, b) {
  43916. var p = a, inside = false, px = (a.x + b.x) / 2, py = (a.y + b.y) / 2;
  43917. do {
  43918. if (((p.y > py) !== (p.next.y > py)) && (px < (p.next.x - p.x) * (py - p.y) / (p.next.y - p.y) + p.x))
  43919. inside = !inside;
  43920. p = p.next;
  43921. } while (p !== a);
  43922. return inside;
  43923. }
  43924. // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  43925. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  43926. function splitPolygon(a, b) {
  43927. 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;
  43928. a.next = b;
  43929. b.prev = a;
  43930. a2.next = an;
  43931. an.prev = a2;
  43932. b2.next = a2;
  43933. a2.prev = b2;
  43934. bp.next = b2;
  43935. b2.prev = bp;
  43936. return b2;
  43937. }
  43938. // create a node and optionally link it with previous one (in a circular doubly linked list)
  43939. function insertNode(i, x, y, last) {
  43940. var p = new Node(i, x, y);
  43941. if (!last) {
  43942. p.prev = p;
  43943. p.next = p;
  43944. }
  43945. else {
  43946. p.next = last.next;
  43947. p.prev = last;
  43948. last.next.prev = p;
  43949. last.next = p;
  43950. }
  43951. return p;
  43952. }
  43953. function removeNode(p) {
  43954. p.next.prev = p.prev;
  43955. p.prev.next = p.next;
  43956. if (p.prevZ)
  43957. p.prevZ.nextZ = p.nextZ;
  43958. if (p.nextZ)
  43959. p.nextZ.prevZ = p.prevZ;
  43960. }
  43961. function Node(i, x, y) {
  43962. // vertice index in coordinates array
  43963. this.i = i;
  43964. // vertex coordinates
  43965. this.x = x;
  43966. this.y = y;
  43967. // previous and next vertice nodes in a polygon ring
  43968. this.prev = null;
  43969. this.next = null;
  43970. // z-order curve value
  43971. this.z = null;
  43972. // previous and next nodes in z-order
  43973. this.prevZ = null;
  43974. this.nextZ = null;
  43975. // indicates whether this is a steiner point
  43976. this.steiner = false;
  43977. }
  43978. /**
  43979. * return a percentage difference between the polygon area and its triangulation area;
  43980. * used to verify correctness of triangulation
  43981. */
  43982. function deviation(data, holeIndices, dim, triangles) {
  43983. var hasHoles = holeIndices && holeIndices.length;
  43984. var outerLen = hasHoles ? holeIndices[0] * dim : data.length;
  43985. var polygonArea = Math.abs(signedArea(data, 0, outerLen, dim));
  43986. if (hasHoles) {
  43987. for (var i = 0, len = holeIndices.length; i < len; i++) {
  43988. var start = holeIndices[i] * dim;
  43989. var end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  43990. polygonArea -= Math.abs(signedArea(data, start, end, dim));
  43991. }
  43992. }
  43993. var trianglesArea = 0;
  43994. for (i = 0; i < triangles.length; i += 3) {
  43995. var a = triangles[i] * dim;
  43996. var b = triangles[i + 1] * dim;
  43997. var c = triangles[i + 2] * dim;
  43998. trianglesArea += Math.abs((data[a] - data[c]) * (data[b + 1] - data[a + 1]) -
  43999. (data[a] - data[b]) * (data[c + 1] - data[a + 1]));
  44000. }
  44001. return polygonArea === 0 && trianglesArea === 0 ? 0 : Math.abs((trianglesArea - polygonArea) / polygonArea);
  44002. }
  44003. Earcut.deviation = deviation;
  44004. ;
  44005. function signedArea(data, start, end, dim) {
  44006. var sum = 0;
  44007. for (var i = start, j = end - dim; i < end; i += dim) {
  44008. sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]);
  44009. j = i;
  44010. }
  44011. return sum;
  44012. }
  44013. /**
  44014. * turn a polygon in a multi-dimensional array form (e.g. as in GeoJSON) into a form Earcut accepts
  44015. */
  44016. function flatten(data) {
  44017. var dim = data[0][0].length, result = { vertices: [], holes: [], dimensions: dim }, holeIndex = 0;
  44018. for (var i = 0; i < data.length; i++) {
  44019. for (var j = 0; j < data[i].length; j++) {
  44020. for (var d = 0; d < dim; d++)
  44021. result.vertices.push(data[i][j][d]);
  44022. }
  44023. if (i > 0) {
  44024. holeIndex += data[i - 1].length;
  44025. result.holes.push(holeIndex);
  44026. }
  44027. }
  44028. return result;
  44029. }
  44030. Earcut.flatten = flatten;
  44031. ;
  44032. })(Earcut || (Earcut = {}));
  44033. //# sourceMappingURL=babylon.earcut.js.map
  44034. var BABYLON;
  44035. (function (BABYLON) {
  44036. // Unique ID when we import meshes from Babylon to CSG
  44037. var currentCSGMeshId = 0;
  44038. // # class Vertex
  44039. // Represents a vertex of a polygon. Use your own vertex class instead of this
  44040. // one to provide additional features like texture coordinates and vertex
  44041. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  44042. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  44043. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  44044. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  44045. // is not used anywhere else.
  44046. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  44047. var Vertex = (function () {
  44048. function Vertex(pos, normal, uv) {
  44049. this.pos = pos;
  44050. this.normal = normal;
  44051. this.uv = uv;
  44052. }
  44053. Vertex.prototype.clone = function () {
  44054. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  44055. };
  44056. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  44057. // orientation of a polygon is flipped.
  44058. Vertex.prototype.flip = function () {
  44059. this.normal = this.normal.scale(-1);
  44060. };
  44061. // Create a new vertex between this vertex and `other` by linearly
  44062. // interpolating all properties using a parameter of `t`. Subclasses should
  44063. // override this to interpolate additional properties.
  44064. Vertex.prototype.interpolate = function (other, t) {
  44065. 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));
  44066. };
  44067. return Vertex;
  44068. }());
  44069. // # class Plane
  44070. // Represents a plane in 3D space.
  44071. var Plane = (function () {
  44072. function Plane(normal, w) {
  44073. this.normal = normal;
  44074. this.w = w;
  44075. }
  44076. Plane.FromPoints = function (a, b, c) {
  44077. var v0 = c.subtract(a);
  44078. var v1 = b.subtract(a);
  44079. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  44080. return null;
  44081. }
  44082. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  44083. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  44084. };
  44085. Plane.prototype.clone = function () {
  44086. return new Plane(this.normal.clone(), this.w);
  44087. };
  44088. Plane.prototype.flip = function () {
  44089. this.normal.scaleInPlace(-1);
  44090. this.w = -this.w;
  44091. };
  44092. // Split `polygon` by this plane if needed, then put the polygon or polygon
  44093. // fragments in the appropriate lists. Coplanar polygons go into either
  44094. // `coplanarFront` or `coplanarBack` depending on their orientation with
  44095. // respect to this plane. Polygons in front or in back of this plane go into
  44096. // either `front` or `back`.
  44097. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  44098. var COPLANAR = 0;
  44099. var FRONT = 1;
  44100. var BACK = 2;
  44101. var SPANNING = 3;
  44102. // Classify each point as well as the entire polygon into one of the above
  44103. // four classes.
  44104. var polygonType = 0;
  44105. var types = [];
  44106. var i;
  44107. var t;
  44108. for (i = 0; i < polygon.vertices.length; i++) {
  44109. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  44110. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  44111. polygonType |= type;
  44112. types.push(type);
  44113. }
  44114. // Put the polygon in the correct list, splitting it when necessary.
  44115. switch (polygonType) {
  44116. case COPLANAR:
  44117. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  44118. break;
  44119. case FRONT:
  44120. front.push(polygon);
  44121. break;
  44122. case BACK:
  44123. back.push(polygon);
  44124. break;
  44125. case SPANNING:
  44126. var f = [], b = [];
  44127. for (i = 0; i < polygon.vertices.length; i++) {
  44128. var j = (i + 1) % polygon.vertices.length;
  44129. var ti = types[i], tj = types[j];
  44130. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  44131. if (ti !== BACK)
  44132. f.push(vi);
  44133. if (ti !== FRONT)
  44134. b.push(ti !== BACK ? vi.clone() : vi);
  44135. if ((ti | tj) === SPANNING) {
  44136. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  44137. var v = vi.interpolate(vj, t);
  44138. f.push(v);
  44139. b.push(v.clone());
  44140. }
  44141. }
  44142. var poly;
  44143. if (f.length >= 3) {
  44144. poly = new Polygon(f, polygon.shared);
  44145. if (poly.plane)
  44146. front.push(poly);
  44147. }
  44148. if (b.length >= 3) {
  44149. poly = new Polygon(b, polygon.shared);
  44150. if (poly.plane)
  44151. back.push(poly);
  44152. }
  44153. break;
  44154. }
  44155. };
  44156. return Plane;
  44157. }());
  44158. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  44159. // point is on the plane.
  44160. Plane.EPSILON = 1e-5;
  44161. // # class Polygon
  44162. // Represents a convex polygon. The vertices used to initialize a polygon must
  44163. // be coplanar and form a convex loop.
  44164. //
  44165. // Each convex polygon has a `shared` property, which is shared between all
  44166. // polygons that are clones of each other or were split from the same polygon.
  44167. // This can be used to define per-polygon properties (such as surface color).
  44168. var Polygon = (function () {
  44169. function Polygon(vertices, shared) {
  44170. this.vertices = vertices;
  44171. this.shared = shared;
  44172. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  44173. }
  44174. Polygon.prototype.clone = function () {
  44175. var vertices = this.vertices.map(function (v) { return v.clone(); });
  44176. return new Polygon(vertices, this.shared);
  44177. };
  44178. Polygon.prototype.flip = function () {
  44179. this.vertices.reverse().map(function (v) { v.flip(); });
  44180. this.plane.flip();
  44181. };
  44182. return Polygon;
  44183. }());
  44184. // # class Node
  44185. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  44186. // by picking a polygon to split along. That polygon (and all other coplanar
  44187. // polygons) are added directly to that node and the other polygons are added to
  44188. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  44189. // no distinction between internal and leaf nodes.
  44190. var Node = (function () {
  44191. function Node(polygons) {
  44192. this.plane = null;
  44193. this.front = null;
  44194. this.back = null;
  44195. this.polygons = [];
  44196. if (polygons) {
  44197. this.build(polygons);
  44198. }
  44199. }
  44200. Node.prototype.clone = function () {
  44201. var node = new Node();
  44202. node.plane = this.plane && this.plane.clone();
  44203. node.front = this.front && this.front.clone();
  44204. node.back = this.back && this.back.clone();
  44205. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  44206. return node;
  44207. };
  44208. // Convert solid space to empty space and empty space to solid space.
  44209. Node.prototype.invert = function () {
  44210. for (var i = 0; i < this.polygons.length; i++) {
  44211. this.polygons[i].flip();
  44212. }
  44213. if (this.plane) {
  44214. this.plane.flip();
  44215. }
  44216. if (this.front) {
  44217. this.front.invert();
  44218. }
  44219. if (this.back) {
  44220. this.back.invert();
  44221. }
  44222. var temp = this.front;
  44223. this.front = this.back;
  44224. this.back = temp;
  44225. };
  44226. // Recursively remove all polygons in `polygons` that are inside this BSP
  44227. // tree.
  44228. Node.prototype.clipPolygons = function (polygons) {
  44229. if (!this.plane)
  44230. return polygons.slice();
  44231. var front = [], back = [];
  44232. for (var i = 0; i < polygons.length; i++) {
  44233. this.plane.splitPolygon(polygons[i], front, back, front, back);
  44234. }
  44235. if (this.front) {
  44236. front = this.front.clipPolygons(front);
  44237. }
  44238. if (this.back) {
  44239. back = this.back.clipPolygons(back);
  44240. }
  44241. else {
  44242. back = [];
  44243. }
  44244. return front.concat(back);
  44245. };
  44246. // Remove all polygons in this BSP tree that are inside the other BSP tree
  44247. // `bsp`.
  44248. Node.prototype.clipTo = function (bsp) {
  44249. this.polygons = bsp.clipPolygons(this.polygons);
  44250. if (this.front)
  44251. this.front.clipTo(bsp);
  44252. if (this.back)
  44253. this.back.clipTo(bsp);
  44254. };
  44255. // Return a list of all polygons in this BSP tree.
  44256. Node.prototype.allPolygons = function () {
  44257. var polygons = this.polygons.slice();
  44258. if (this.front)
  44259. polygons = polygons.concat(this.front.allPolygons());
  44260. if (this.back)
  44261. polygons = polygons.concat(this.back.allPolygons());
  44262. return polygons;
  44263. };
  44264. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  44265. // new polygons are filtered down to the bottom of the tree and become new
  44266. // nodes there. Each set of polygons is partitioned using the first polygon
  44267. // (no heuristic is used to pick a good split).
  44268. Node.prototype.build = function (polygons) {
  44269. if (!polygons.length)
  44270. return;
  44271. if (!this.plane)
  44272. this.plane = polygons[0].plane.clone();
  44273. var front = [], back = [];
  44274. for (var i = 0; i < polygons.length; i++) {
  44275. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  44276. }
  44277. if (front.length) {
  44278. if (!this.front)
  44279. this.front = new Node();
  44280. this.front.build(front);
  44281. }
  44282. if (back.length) {
  44283. if (!this.back)
  44284. this.back = new Node();
  44285. this.back.build(back);
  44286. }
  44287. };
  44288. return Node;
  44289. }());
  44290. var CSG = (function () {
  44291. function CSG() {
  44292. this.polygons = new Array();
  44293. }
  44294. // Convert BABYLON.Mesh to BABYLON.CSG
  44295. CSG.FromMesh = function (mesh) {
  44296. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  44297. var matrix, meshPosition, meshRotation, meshRotationQuaternion, meshScaling;
  44298. if (mesh instanceof BABYLON.Mesh) {
  44299. mesh.computeWorldMatrix(true);
  44300. matrix = mesh.getWorldMatrix();
  44301. meshPosition = mesh.position.clone();
  44302. meshRotation = mesh.rotation.clone();
  44303. if (mesh.rotationQuaternion) {
  44304. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  44305. }
  44306. meshScaling = mesh.scaling.clone();
  44307. }
  44308. else {
  44309. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  44310. }
  44311. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  44312. var subMeshes = mesh.subMeshes;
  44313. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  44314. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  44315. vertices = [];
  44316. for (var j = 0; j < 3; j++) {
  44317. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  44318. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  44319. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  44320. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  44321. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  44322. vertex = new Vertex(position, normal, uv);
  44323. vertices.push(vertex);
  44324. }
  44325. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  44326. // To handle the case of degenerated triangle
  44327. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  44328. if (polygon.plane)
  44329. polygons.push(polygon);
  44330. }
  44331. }
  44332. var csg = CSG.FromPolygons(polygons);
  44333. csg.matrix = matrix;
  44334. csg.position = meshPosition;
  44335. csg.rotation = meshRotation;
  44336. csg.scaling = meshScaling;
  44337. csg.rotationQuaternion = meshRotationQuaternion;
  44338. currentCSGMeshId++;
  44339. return csg;
  44340. };
  44341. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  44342. CSG.FromPolygons = function (polygons) {
  44343. var csg = new CSG();
  44344. csg.polygons = polygons;
  44345. return csg;
  44346. };
  44347. CSG.prototype.clone = function () {
  44348. var csg = new CSG();
  44349. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  44350. csg.copyTransformAttributes(this);
  44351. return csg;
  44352. };
  44353. CSG.prototype.toPolygons = function () {
  44354. return this.polygons;
  44355. };
  44356. CSG.prototype.union = function (csg) {
  44357. var a = new Node(this.clone().polygons);
  44358. var b = new Node(csg.clone().polygons);
  44359. a.clipTo(b);
  44360. b.clipTo(a);
  44361. b.invert();
  44362. b.clipTo(a);
  44363. b.invert();
  44364. a.build(b.allPolygons());
  44365. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  44366. };
  44367. CSG.prototype.unionInPlace = function (csg) {
  44368. var a = new Node(this.polygons);
  44369. var b = new Node(csg.polygons);
  44370. a.clipTo(b);
  44371. b.clipTo(a);
  44372. b.invert();
  44373. b.clipTo(a);
  44374. b.invert();
  44375. a.build(b.allPolygons());
  44376. this.polygons = a.allPolygons();
  44377. };
  44378. CSG.prototype.subtract = function (csg) {
  44379. var a = new Node(this.clone().polygons);
  44380. var b = new Node(csg.clone().polygons);
  44381. a.invert();
  44382. a.clipTo(b);
  44383. b.clipTo(a);
  44384. b.invert();
  44385. b.clipTo(a);
  44386. b.invert();
  44387. a.build(b.allPolygons());
  44388. a.invert();
  44389. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  44390. };
  44391. CSG.prototype.subtractInPlace = function (csg) {
  44392. var a = new Node(this.polygons);
  44393. var b = new Node(csg.polygons);
  44394. a.invert();
  44395. a.clipTo(b);
  44396. b.clipTo(a);
  44397. b.invert();
  44398. b.clipTo(a);
  44399. b.invert();
  44400. a.build(b.allPolygons());
  44401. a.invert();
  44402. this.polygons = a.allPolygons();
  44403. };
  44404. CSG.prototype.intersect = function (csg) {
  44405. var a = new Node(this.clone().polygons);
  44406. var b = new Node(csg.clone().polygons);
  44407. a.invert();
  44408. b.clipTo(a);
  44409. b.invert();
  44410. a.clipTo(b);
  44411. b.clipTo(a);
  44412. a.build(b.allPolygons());
  44413. a.invert();
  44414. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  44415. };
  44416. CSG.prototype.intersectInPlace = function (csg) {
  44417. var a = new Node(this.polygons);
  44418. var b = new Node(csg.polygons);
  44419. a.invert();
  44420. b.clipTo(a);
  44421. b.invert();
  44422. a.clipTo(b);
  44423. b.clipTo(a);
  44424. a.build(b.allPolygons());
  44425. a.invert();
  44426. this.polygons = a.allPolygons();
  44427. };
  44428. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  44429. // not modified.
  44430. CSG.prototype.inverse = function () {
  44431. var csg = this.clone();
  44432. csg.inverseInPlace();
  44433. return csg;
  44434. };
  44435. CSG.prototype.inverseInPlace = function () {
  44436. this.polygons.map(function (p) { p.flip(); });
  44437. };
  44438. // This is used to keep meshes transformations so they can be restored
  44439. // when we build back a Babylon Mesh
  44440. // NB : All CSG operations are performed in world coordinates
  44441. CSG.prototype.copyTransformAttributes = function (csg) {
  44442. this.matrix = csg.matrix;
  44443. this.position = csg.position;
  44444. this.rotation = csg.rotation;
  44445. this.scaling = csg.scaling;
  44446. this.rotationQuaternion = csg.rotationQuaternion;
  44447. return this;
  44448. };
  44449. // Build Raw mesh from CSG
  44450. // Coordinates here are in world space
  44451. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  44452. var matrix = this.matrix.clone();
  44453. matrix.invert();
  44454. 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;
  44455. if (keepSubMeshes) {
  44456. // Sort Polygons, since subMeshes are indices range
  44457. polygons.sort(function (a, b) {
  44458. if (a.shared.meshId === b.shared.meshId) {
  44459. return a.shared.subMeshId - b.shared.subMeshId;
  44460. }
  44461. else {
  44462. return a.shared.meshId - b.shared.meshId;
  44463. }
  44464. });
  44465. }
  44466. for (var i = 0, il = polygons.length; i < il; i++) {
  44467. polygon = polygons[i];
  44468. // Building SubMeshes
  44469. if (!subMesh_dict[polygon.shared.meshId]) {
  44470. subMesh_dict[polygon.shared.meshId] = {};
  44471. }
  44472. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  44473. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  44474. indexStart: +Infinity,
  44475. indexEnd: -Infinity,
  44476. materialIndex: polygon.shared.materialIndex
  44477. };
  44478. }
  44479. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  44480. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  44481. polygonIndices[0] = 0;
  44482. polygonIndices[1] = j - 1;
  44483. polygonIndices[2] = j;
  44484. for (var k = 0; k < 3; k++) {
  44485. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  44486. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  44487. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  44488. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  44489. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  44490. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  44491. // Check if 2 points can be merged
  44492. if (!(typeof vertex_idx !== 'undefined' &&
  44493. normals[vertex_idx * 3] === localNormal.x &&
  44494. normals[vertex_idx * 3 + 1] === localNormal.y &&
  44495. normals[vertex_idx * 3 + 2] === localNormal.z &&
  44496. uvs[vertex_idx * 2] === uv.x &&
  44497. uvs[vertex_idx * 2 + 1] === uv.y)) {
  44498. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  44499. uvs.push(uv.x, uv.y);
  44500. normals.push(normal.x, normal.y, normal.z);
  44501. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  44502. }
  44503. indices.push(vertex_idx);
  44504. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  44505. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  44506. currentIndex++;
  44507. }
  44508. }
  44509. }
  44510. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  44511. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  44512. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  44513. mesh.setIndices(indices);
  44514. if (keepSubMeshes) {
  44515. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  44516. var materialIndexOffset = 0, materialMaxIndex;
  44517. mesh.subMeshes = new Array();
  44518. for (var m in subMesh_dict) {
  44519. materialMaxIndex = -1;
  44520. for (var sm in subMesh_dict[m]) {
  44521. subMesh_obj = subMesh_dict[m][sm];
  44522. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  44523. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  44524. }
  44525. materialIndexOffset += ++materialMaxIndex;
  44526. }
  44527. }
  44528. return mesh;
  44529. };
  44530. // Build Mesh from CSG taking material and transforms into account
  44531. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  44532. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  44533. mesh.material = material;
  44534. mesh.position.copyFrom(this.position);
  44535. mesh.rotation.copyFrom(this.rotation);
  44536. if (this.rotationQuaternion) {
  44537. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  44538. }
  44539. mesh.scaling.copyFrom(this.scaling);
  44540. mesh.computeWorldMatrix(true);
  44541. return mesh;
  44542. };
  44543. return CSG;
  44544. }());
  44545. BABYLON.CSG = CSG;
  44546. })(BABYLON || (BABYLON = {}));
  44547. //# sourceMappingURL=babylon.csg.js.map
  44548. var BABYLON;
  44549. (function (BABYLON) {
  44550. var VRDistortionCorrectionPostProcess = (function (_super) {
  44551. __extends(VRDistortionCorrectionPostProcess, _super);
  44552. //ANY
  44553. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  44554. var _this = _super.call(this, name, "vrDistortionCorrection", [
  44555. 'LensCenter',
  44556. 'Scale',
  44557. 'ScaleIn',
  44558. 'HmdWarpParam'
  44559. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE, null, null) || this;
  44560. _this._isRightEye = isRightEye;
  44561. _this._distortionFactors = vrMetrics.distortionK;
  44562. _this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  44563. _this._lensCenterOffset = vrMetrics.lensCenterOffset;
  44564. _this.onSizeChangedObservable.add(function () {
  44565. _this.aspectRatio = _this.width * .5 / _this.height;
  44566. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  44567. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  44568. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  44569. });
  44570. _this.onApplyObservable.add(function (effect) {
  44571. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  44572. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  44573. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  44574. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  44575. });
  44576. return _this;
  44577. }
  44578. return VRDistortionCorrectionPostProcess;
  44579. }(BABYLON.PostProcess));
  44580. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  44581. })(BABYLON || (BABYLON = {}));
  44582. //# sourceMappingURL=babylon.vrDistortionCorrectionPostProcess.js.map
  44583. // Mainly based on these 2 articles :
  44584. // 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
  44585. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  44586. var BABYLON;
  44587. (function (BABYLON) {
  44588. var JoystickAxis;
  44589. (function (JoystickAxis) {
  44590. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  44591. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  44592. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  44593. })(JoystickAxis = BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  44594. var VirtualJoystick = (function () {
  44595. function VirtualJoystick(leftJoystick) {
  44596. var _this = this;
  44597. if (leftJoystick) {
  44598. this._leftJoystick = true;
  44599. }
  44600. else {
  44601. this._leftJoystick = false;
  44602. }
  44603. this._joystickIndex = VirtualJoystick._globalJoystickIndex;
  44604. VirtualJoystick._globalJoystickIndex++;
  44605. // By default left & right arrow keys are moving the X
  44606. // and up & down keys are moving the Y
  44607. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  44608. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  44609. this.reverseLeftRight = false;
  44610. this.reverseUpDown = false;
  44611. // collections of pointers
  44612. this._touches = new BABYLON.StringDictionary();
  44613. this.deltaPosition = BABYLON.Vector3.Zero();
  44614. this._joystickSensibility = 25;
  44615. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  44616. this._rotationSpeed = 25;
  44617. this._inverseRotationSpeed = 1 / (this._rotationSpeed / 1000);
  44618. this._rotateOnAxisRelativeToMesh = false;
  44619. this._onResize = function (evt) {
  44620. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  44621. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  44622. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  44623. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  44624. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  44625. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvasHeight / 2;
  44626. };
  44627. // injecting a canvas element on top of the canvas 3D game
  44628. if (!VirtualJoystick.vjCanvas) {
  44629. window.addEventListener("resize", this._onResize, false);
  44630. VirtualJoystick.vjCanvas = document.createElement("canvas");
  44631. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  44632. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  44633. VirtualJoystick.vjCanvas.width = window.innerWidth;
  44634. VirtualJoystick.vjCanvas.height = window.innerHeight;
  44635. VirtualJoystick.vjCanvas.style.width = "100%";
  44636. VirtualJoystick.vjCanvas.style.height = "100%";
  44637. VirtualJoystick.vjCanvas.style.position = "absolute";
  44638. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  44639. VirtualJoystick.vjCanvas.style.top = "0px";
  44640. VirtualJoystick.vjCanvas.style.left = "0px";
  44641. VirtualJoystick.vjCanvas.style.zIndex = "5";
  44642. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  44643. // Support for jQuery PEP polyfill
  44644. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  44645. VirtualJoystick.vjCanvasContext = VirtualJoystick.vjCanvas.getContext('2d');
  44646. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  44647. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  44648. document.body.appendChild(VirtualJoystick.vjCanvas);
  44649. }
  44650. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  44651. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvas.height / 2;
  44652. this.pressed = false;
  44653. // default joystick color
  44654. this._joystickColor = "cyan";
  44655. this._joystickPointerID = -1;
  44656. // current joystick position
  44657. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  44658. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  44659. // origin joystick position
  44660. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  44661. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  44662. this._onPointerDownHandlerRef = function (evt) {
  44663. _this._onPointerDown(evt);
  44664. };
  44665. this._onPointerMoveHandlerRef = function (evt) {
  44666. _this._onPointerMove(evt);
  44667. };
  44668. this._onPointerOutHandlerRef = function (evt) {
  44669. _this._onPointerUp(evt);
  44670. };
  44671. this._onPointerUpHandlerRef = function (evt) {
  44672. _this._onPointerUp(evt);
  44673. };
  44674. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  44675. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  44676. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  44677. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  44678. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  44679. evt.preventDefault(); // Disables system menu
  44680. }, false);
  44681. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  44682. }
  44683. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  44684. this._joystickSensibility = newJoystickSensibility;
  44685. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  44686. };
  44687. VirtualJoystick.prototype._onPointerDown = function (e) {
  44688. var positionOnScreenCondition;
  44689. e.preventDefault();
  44690. if (this._leftJoystick === true) {
  44691. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  44692. }
  44693. else {
  44694. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  44695. }
  44696. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  44697. // First contact will be dedicated to the virtual joystick
  44698. this._joystickPointerID = e.pointerId;
  44699. this._joystickPointerStartPos.x = e.clientX;
  44700. this._joystickPointerStartPos.y = e.clientY;
  44701. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  44702. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  44703. this._deltaJoystickVector.x = 0;
  44704. this._deltaJoystickVector.y = 0;
  44705. this.pressed = true;
  44706. this._touches.add(e.pointerId.toString(), e);
  44707. }
  44708. else {
  44709. // You can only trigger the action buttons with a joystick declared
  44710. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  44711. this._action();
  44712. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  44713. }
  44714. }
  44715. };
  44716. VirtualJoystick.prototype._onPointerMove = function (e) {
  44717. // If the current pointer is the one associated to the joystick (first touch contact)
  44718. if (this._joystickPointerID == e.pointerId) {
  44719. this._joystickPointerPos.x = e.clientX;
  44720. this._joystickPointerPos.y = e.clientY;
  44721. this._deltaJoystickVector = this._joystickPointerPos.clone();
  44722. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  44723. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  44724. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  44725. switch (this._axisTargetedByLeftAndRight) {
  44726. case JoystickAxis.X:
  44727. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  44728. break;
  44729. case JoystickAxis.Y:
  44730. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  44731. break;
  44732. case JoystickAxis.Z:
  44733. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  44734. break;
  44735. }
  44736. var directionUpDown = this.reverseUpDown ? 1 : -1;
  44737. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  44738. switch (this._axisTargetedByUpAndDown) {
  44739. case JoystickAxis.X:
  44740. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  44741. break;
  44742. case JoystickAxis.Y:
  44743. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  44744. break;
  44745. case JoystickAxis.Z:
  44746. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  44747. break;
  44748. }
  44749. }
  44750. else {
  44751. var data = this._touches.get(e.pointerId.toString());
  44752. if (data) {
  44753. data.x = e.clientX;
  44754. data.y = e.clientY;
  44755. }
  44756. }
  44757. };
  44758. VirtualJoystick.prototype._onPointerUp = function (e) {
  44759. if (this._joystickPointerID == e.pointerId) {
  44760. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 63, this._joystickPointerStartPos.y - 63, 126, 126);
  44761. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 41, this._joystickPreviousPointerPos.y - 41, 82, 82);
  44762. this._joystickPointerID = -1;
  44763. this.pressed = false;
  44764. }
  44765. else {
  44766. var touch = this._touches.get(e.pointerId.toString());
  44767. if (touch) {
  44768. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 43, touch.prevY - 43, 86, 86);
  44769. }
  44770. }
  44771. this._deltaJoystickVector.x = 0;
  44772. this._deltaJoystickVector.y = 0;
  44773. this._touches.remove(e.pointerId.toString());
  44774. };
  44775. /**
  44776. * Change the color of the virtual joystick
  44777. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  44778. */
  44779. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  44780. this._joystickColor = newColor;
  44781. };
  44782. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  44783. this._action = action;
  44784. };
  44785. // Define which axis you'd like to control for left & right
  44786. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  44787. switch (axis) {
  44788. case JoystickAxis.X:
  44789. case JoystickAxis.Y:
  44790. case JoystickAxis.Z:
  44791. this._axisTargetedByLeftAndRight = axis;
  44792. break;
  44793. default:
  44794. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  44795. break;
  44796. }
  44797. };
  44798. // Define which axis you'd like to control for up & down
  44799. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  44800. switch (axis) {
  44801. case JoystickAxis.X:
  44802. case JoystickAxis.Y:
  44803. case JoystickAxis.Z:
  44804. this._axisTargetedByUpAndDown = axis;
  44805. break;
  44806. default:
  44807. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  44808. break;
  44809. }
  44810. };
  44811. VirtualJoystick.prototype._clearCanvas = function () {
  44812. if (this._leftJoystick) {
  44813. VirtualJoystick.vjCanvasContext.clearRect(0, 0, VirtualJoystick.vjCanvasWidth / 2, VirtualJoystick.vjCanvasHeight);
  44814. }
  44815. else {
  44816. VirtualJoystick.vjCanvasContext.clearRect(VirtualJoystick.vjCanvasWidth / 2, 0, VirtualJoystick.vjCanvasWidth, VirtualJoystick.vjCanvasHeight);
  44817. }
  44818. };
  44819. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  44820. var _this = this;
  44821. if (this.pressed) {
  44822. this._touches.forEach(function (key, touch) {
  44823. if (touch.pointerId === _this._joystickPointerID) {
  44824. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 63, _this._joystickPointerStartPos.y - 63, 126, 126);
  44825. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 41, _this._joystickPreviousPointerPos.y - 41, 82, 82);
  44826. VirtualJoystick.vjCanvasContext.beginPath();
  44827. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  44828. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  44829. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  44830. VirtualJoystick.vjCanvasContext.stroke();
  44831. VirtualJoystick.vjCanvasContext.closePath();
  44832. VirtualJoystick.vjCanvasContext.beginPath();
  44833. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  44834. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  44835. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  44836. VirtualJoystick.vjCanvasContext.stroke();
  44837. VirtualJoystick.vjCanvasContext.closePath();
  44838. VirtualJoystick.vjCanvasContext.beginPath();
  44839. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  44840. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  44841. VirtualJoystick.vjCanvasContext.stroke();
  44842. VirtualJoystick.vjCanvasContext.closePath();
  44843. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  44844. }
  44845. else {
  44846. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 43, touch.prevY - 43, 86, 86);
  44847. VirtualJoystick.vjCanvasContext.beginPath();
  44848. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  44849. VirtualJoystick.vjCanvasContext.beginPath();
  44850. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  44851. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  44852. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  44853. VirtualJoystick.vjCanvasContext.stroke();
  44854. VirtualJoystick.vjCanvasContext.closePath();
  44855. touch.prevX = touch.x;
  44856. touch.prevY = touch.y;
  44857. }
  44858. ;
  44859. });
  44860. }
  44861. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  44862. };
  44863. VirtualJoystick.prototype.releaseCanvas = function () {
  44864. if (VirtualJoystick.vjCanvas) {
  44865. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  44866. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  44867. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  44868. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  44869. window.removeEventListener("resize", this._onResize);
  44870. document.body.removeChild(VirtualJoystick.vjCanvas);
  44871. VirtualJoystick.vjCanvas = null;
  44872. }
  44873. };
  44874. return VirtualJoystick;
  44875. }());
  44876. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  44877. VirtualJoystick._globalJoystickIndex = 0;
  44878. BABYLON.VirtualJoystick = VirtualJoystick;
  44879. })(BABYLON || (BABYLON = {}));
  44880. //# sourceMappingURL=babylon.virtualJoystick.js.map
  44881. var BABYLON;
  44882. (function (BABYLON) {
  44883. // We're mainly based on the logic defined into the FreeCamera code
  44884. var VirtualJoysticksCamera = (function (_super) {
  44885. __extends(VirtualJoysticksCamera, _super);
  44886. function VirtualJoysticksCamera(name, position, scene) {
  44887. var _this = _super.call(this, name, position, scene) || this;
  44888. _this.inputs.addVirtualJoystick();
  44889. return _this;
  44890. }
  44891. VirtualJoysticksCamera.prototype.getClassName = function () {
  44892. return "VirtualJoysticksCamera";
  44893. };
  44894. return VirtualJoysticksCamera;
  44895. }(BABYLON.FreeCamera));
  44896. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  44897. })(BABYLON || (BABYLON = {}));
  44898. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  44899. var BABYLON;
  44900. (function (BABYLON) {
  44901. var FreeCameraVirtualJoystickInput = (function () {
  44902. function FreeCameraVirtualJoystickInput() {
  44903. }
  44904. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  44905. return this._leftjoystick;
  44906. };
  44907. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  44908. return this._rightjoystick;
  44909. };
  44910. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  44911. if (this._leftjoystick) {
  44912. var camera = this.camera;
  44913. var speed = camera._computeLocalCameraSpeed() * 50;
  44914. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  44915. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  44916. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  44917. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  44918. if (!this._leftjoystick.pressed) {
  44919. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  44920. }
  44921. if (!this._rightjoystick.pressed) {
  44922. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  44923. }
  44924. }
  44925. };
  44926. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  44927. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  44928. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  44929. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  44930. this._leftjoystick.setJoystickSensibility(0.15);
  44931. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  44932. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  44933. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  44934. this._rightjoystick.reverseUpDown = true;
  44935. this._rightjoystick.setJoystickSensibility(0.05);
  44936. this._rightjoystick.setJoystickColor("yellow");
  44937. };
  44938. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  44939. this._leftjoystick.releaseCanvas();
  44940. this._rightjoystick.releaseCanvas();
  44941. };
  44942. FreeCameraVirtualJoystickInput.prototype.getTypeName = function () {
  44943. return "FreeCameraVirtualJoystickInput";
  44944. };
  44945. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  44946. return "virtualJoystick";
  44947. };
  44948. return FreeCameraVirtualJoystickInput;
  44949. }());
  44950. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  44951. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  44952. })(BABYLON || (BABYLON = {}));
  44953. //# sourceMappingURL=babylon.freecamera.input.virtualjoystick.js.map
  44954. var BABYLON;
  44955. (function (BABYLON) {
  44956. var AnaglyphPostProcess = (function (_super) {
  44957. __extends(AnaglyphPostProcess, _super);
  44958. function AnaglyphPostProcess(name, options, rigCameras, samplingMode, engine, reusable) {
  44959. var _this = _super.call(this, name, "anaglyph", null, ["leftSampler"], options, rigCameras[1], samplingMode, engine, reusable) || this;
  44960. _this._passedProcess = rigCameras[0]._rigPostProcess;
  44961. _this.onApplyObservable.add(function (effect) {
  44962. effect.setTextureFromPostProcess("leftSampler", _this._passedProcess);
  44963. });
  44964. return _this;
  44965. }
  44966. return AnaglyphPostProcess;
  44967. }(BABYLON.PostProcess));
  44968. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  44969. })(BABYLON || (BABYLON = {}));
  44970. //# sourceMappingURL=babylon.anaglyphPostProcess.js.map
  44971. var BABYLON;
  44972. (function (BABYLON) {
  44973. var OutlineRenderer = (function () {
  44974. function OutlineRenderer(scene) {
  44975. this._scene = scene;
  44976. }
  44977. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  44978. var _this = this;
  44979. if (useOverlay === void 0) { useOverlay = false; }
  44980. var scene = this._scene;
  44981. var engine = this._scene.getEngine();
  44982. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  44983. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  44984. return;
  44985. }
  44986. var mesh = subMesh.getRenderingMesh();
  44987. var material = subMesh.getMaterial();
  44988. engine.enableEffect(this._effect);
  44989. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  44990. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : 1.0);
  44991. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  44992. // Bones
  44993. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  44994. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  44995. }
  44996. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  44997. // Alpha test
  44998. if (material && material.needAlphaTesting()) {
  44999. var alphaTexture = material.getAlphaTestTexture();
  45000. this._effect.setTexture("diffuseSampler", alphaTexture);
  45001. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  45002. }
  45003. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  45004. };
  45005. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  45006. var defines = [];
  45007. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  45008. var mesh = subMesh.getMesh();
  45009. var material = subMesh.getMaterial();
  45010. // Alpha test
  45011. if (material && material.needAlphaTesting()) {
  45012. defines.push("#define ALPHATEST");
  45013. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  45014. attribs.push(BABYLON.VertexBuffer.UVKind);
  45015. defines.push("#define UV1");
  45016. }
  45017. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  45018. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  45019. defines.push("#define UV2");
  45020. }
  45021. }
  45022. // Bones
  45023. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  45024. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  45025. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  45026. if (mesh.numBoneInfluencers > 4) {
  45027. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  45028. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  45029. }
  45030. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  45031. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  45032. }
  45033. else {
  45034. defines.push("#define NUM_BONE_INFLUENCERS 0");
  45035. }
  45036. // Instances
  45037. if (useInstances) {
  45038. defines.push("#define INSTANCES");
  45039. attribs.push("world0");
  45040. attribs.push("world1");
  45041. attribs.push("world2");
  45042. attribs.push("world3");
  45043. }
  45044. // Get correct effect
  45045. var join = defines.join("\n");
  45046. if (this._cachedDefines !== join) {
  45047. this._cachedDefines = join;
  45048. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color"], ["diffuseSampler"], join);
  45049. }
  45050. return this._effect.isReady();
  45051. };
  45052. return OutlineRenderer;
  45053. }());
  45054. BABYLON.OutlineRenderer = OutlineRenderer;
  45055. })(BABYLON || (BABYLON = {}));
  45056. //# sourceMappingURL=babylon.outlineRenderer.js.map
  45057. var BABYLON;
  45058. (function (BABYLON) {
  45059. var MeshAssetTask = (function () {
  45060. function MeshAssetTask(name, meshesNames, rootUrl, sceneFilename) {
  45061. this.name = name;
  45062. this.meshesNames = meshesNames;
  45063. this.rootUrl = rootUrl;
  45064. this.sceneFilename = sceneFilename;
  45065. this.isCompleted = false;
  45066. }
  45067. MeshAssetTask.prototype.run = function (scene, onSuccess, onError) {
  45068. var _this = this;
  45069. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  45070. _this.loadedMeshes = meshes;
  45071. _this.loadedParticleSystems = particleSystems;
  45072. _this.loadedSkeletons = skeletons;
  45073. _this.isCompleted = true;
  45074. if (_this.onSuccess) {
  45075. _this.onSuccess(_this);
  45076. }
  45077. onSuccess();
  45078. }, null, function () {
  45079. if (_this.onError) {
  45080. _this.onError(_this);
  45081. }
  45082. onError();
  45083. });
  45084. };
  45085. return MeshAssetTask;
  45086. }());
  45087. BABYLON.MeshAssetTask = MeshAssetTask;
  45088. var TextFileAssetTask = (function () {
  45089. function TextFileAssetTask(name, url) {
  45090. this.name = name;
  45091. this.url = url;
  45092. this.isCompleted = false;
  45093. }
  45094. TextFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  45095. var _this = this;
  45096. BABYLON.Tools.LoadFile(this.url, function (data) {
  45097. _this.text = data;
  45098. _this.isCompleted = true;
  45099. if (_this.onSuccess) {
  45100. _this.onSuccess(_this);
  45101. }
  45102. onSuccess();
  45103. }, null, scene.database, false, function () {
  45104. if (_this.onError) {
  45105. _this.onError(_this);
  45106. }
  45107. onError();
  45108. });
  45109. };
  45110. return TextFileAssetTask;
  45111. }());
  45112. BABYLON.TextFileAssetTask = TextFileAssetTask;
  45113. var BinaryFileAssetTask = (function () {
  45114. function BinaryFileAssetTask(name, url) {
  45115. this.name = name;
  45116. this.url = url;
  45117. this.isCompleted = false;
  45118. }
  45119. BinaryFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  45120. var _this = this;
  45121. BABYLON.Tools.LoadFile(this.url, function (data) {
  45122. _this.data = data;
  45123. _this.isCompleted = true;
  45124. if (_this.onSuccess) {
  45125. _this.onSuccess(_this);
  45126. }
  45127. onSuccess();
  45128. }, null, scene.database, true, function () {
  45129. if (_this.onError) {
  45130. _this.onError(_this);
  45131. }
  45132. onError();
  45133. });
  45134. };
  45135. return BinaryFileAssetTask;
  45136. }());
  45137. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  45138. var ImageAssetTask = (function () {
  45139. function ImageAssetTask(name, url) {
  45140. this.name = name;
  45141. this.url = url;
  45142. this.isCompleted = false;
  45143. }
  45144. ImageAssetTask.prototype.run = function (scene, onSuccess, onError) {
  45145. var _this = this;
  45146. var img = new Image();
  45147. BABYLON.Tools.SetCorsBehavior(this.url, img);
  45148. img.onload = function () {
  45149. _this.image = img;
  45150. _this.isCompleted = true;
  45151. if (_this.onSuccess) {
  45152. _this.onSuccess(_this);
  45153. }
  45154. onSuccess();
  45155. };
  45156. img.onerror = function () {
  45157. if (_this.onError) {
  45158. _this.onError(_this);
  45159. }
  45160. onError();
  45161. };
  45162. img.src = this.url;
  45163. };
  45164. return ImageAssetTask;
  45165. }());
  45166. BABYLON.ImageAssetTask = ImageAssetTask;
  45167. var TextureAssetTask = (function () {
  45168. function TextureAssetTask(name, url, noMipmap, invertY, samplingMode) {
  45169. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  45170. this.name = name;
  45171. this.url = url;
  45172. this.noMipmap = noMipmap;
  45173. this.invertY = invertY;
  45174. this.samplingMode = samplingMode;
  45175. this.isCompleted = false;
  45176. }
  45177. TextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  45178. var _this = this;
  45179. var onload = function () {
  45180. _this.isCompleted = true;
  45181. if (_this.onSuccess) {
  45182. _this.onSuccess(_this);
  45183. }
  45184. onSuccess();
  45185. };
  45186. var onerror = function () {
  45187. if (_this.onError) {
  45188. _this.onError(_this);
  45189. }
  45190. onError();
  45191. };
  45192. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  45193. };
  45194. return TextureAssetTask;
  45195. }());
  45196. BABYLON.TextureAssetTask = TextureAssetTask;
  45197. var CubeTextureAssetTask = (function () {
  45198. function CubeTextureAssetTask(name, url, extensions, noMipmap, files) {
  45199. this.name = name;
  45200. this.url = url;
  45201. this.extensions = extensions;
  45202. this.noMipmap = noMipmap;
  45203. this.files = files;
  45204. this.isCompleted = false;
  45205. }
  45206. CubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  45207. var _this = this;
  45208. var onload = function () {
  45209. _this.isCompleted = true;
  45210. if (_this.onSuccess) {
  45211. _this.onSuccess(_this);
  45212. }
  45213. onSuccess();
  45214. };
  45215. var onerror = function () {
  45216. if (_this.onError) {
  45217. _this.onError(_this);
  45218. }
  45219. onError();
  45220. };
  45221. this.texture = new BABYLON.CubeTexture(this.url, scene, this.extensions, this.noMipmap, this.files, onload, onerror);
  45222. };
  45223. return CubeTextureAssetTask;
  45224. }());
  45225. BABYLON.CubeTextureAssetTask = CubeTextureAssetTask;
  45226. var AssetsManager = (function () {
  45227. function AssetsManager(scene) {
  45228. this.tasks = new Array();
  45229. this.waitingTasksCount = 0;
  45230. this.useDefaultLoadingScreen = true;
  45231. this._scene = scene;
  45232. }
  45233. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  45234. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  45235. this.tasks.push(task);
  45236. return task;
  45237. };
  45238. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  45239. var task = new TextFileAssetTask(taskName, url);
  45240. this.tasks.push(task);
  45241. return task;
  45242. };
  45243. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  45244. var task = new BinaryFileAssetTask(taskName, url);
  45245. this.tasks.push(task);
  45246. return task;
  45247. };
  45248. AssetsManager.prototype.addImageTask = function (taskName, url) {
  45249. var task = new ImageAssetTask(taskName, url);
  45250. this.tasks.push(task);
  45251. return task;
  45252. };
  45253. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  45254. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  45255. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  45256. this.tasks.push(task);
  45257. return task;
  45258. };
  45259. AssetsManager.prototype._decreaseWaitingTasksCount = function () {
  45260. this.waitingTasksCount--;
  45261. if (this.waitingTasksCount === 0) {
  45262. if (this.onFinish) {
  45263. this.onFinish(this.tasks);
  45264. }
  45265. this._scene.getEngine().hideLoadingUI();
  45266. }
  45267. };
  45268. AssetsManager.prototype._runTask = function (task) {
  45269. var _this = this;
  45270. task.run(this._scene, function () {
  45271. if (_this.onTaskSuccess) {
  45272. _this.onTaskSuccess(task);
  45273. }
  45274. _this._decreaseWaitingTasksCount();
  45275. }, function () {
  45276. if (_this.onTaskError) {
  45277. _this.onTaskError(task);
  45278. }
  45279. _this._decreaseWaitingTasksCount();
  45280. });
  45281. };
  45282. AssetsManager.prototype.reset = function () {
  45283. this.tasks = new Array();
  45284. return this;
  45285. };
  45286. AssetsManager.prototype.load = function () {
  45287. this.waitingTasksCount = this.tasks.length;
  45288. if (this.waitingTasksCount === 0) {
  45289. if (this.onFinish) {
  45290. this.onFinish(this.tasks);
  45291. }
  45292. return this;
  45293. }
  45294. if (this.useDefaultLoadingScreen) {
  45295. this._scene.getEngine().displayLoadingUI();
  45296. }
  45297. for (var index = 0; index < this.tasks.length; index++) {
  45298. var task = this.tasks[index];
  45299. this._runTask(task);
  45300. }
  45301. return this;
  45302. };
  45303. return AssetsManager;
  45304. }());
  45305. BABYLON.AssetsManager = AssetsManager;
  45306. })(BABYLON || (BABYLON = {}));
  45307. //# sourceMappingURL=babylon.assetsManager.js.map
  45308. var BABYLON;
  45309. (function (BABYLON) {
  45310. var VRCameraMetrics = (function () {
  45311. function VRCameraMetrics() {
  45312. this.compensateDistortion = true;
  45313. }
  45314. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  45315. get: function () {
  45316. return this.hResolution / (2 * this.vResolution);
  45317. },
  45318. enumerable: true,
  45319. configurable: true
  45320. });
  45321. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  45322. get: function () {
  45323. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  45324. },
  45325. enumerable: true,
  45326. configurable: true
  45327. });
  45328. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  45329. get: function () {
  45330. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  45331. var h = (4 * meters) / this.hScreenSize;
  45332. return BABYLON.Matrix.Translation(h, 0, 0);
  45333. },
  45334. enumerable: true,
  45335. configurable: true
  45336. });
  45337. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  45338. get: function () {
  45339. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  45340. var h = (4 * meters) / this.hScreenSize;
  45341. return BABYLON.Matrix.Translation(-h, 0, 0);
  45342. },
  45343. enumerable: true,
  45344. configurable: true
  45345. });
  45346. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  45347. get: function () {
  45348. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  45349. },
  45350. enumerable: true,
  45351. configurable: true
  45352. });
  45353. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  45354. get: function () {
  45355. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  45356. },
  45357. enumerable: true,
  45358. configurable: true
  45359. });
  45360. VRCameraMetrics.GetDefault = function () {
  45361. var result = new VRCameraMetrics();
  45362. result.hResolution = 1280;
  45363. result.vResolution = 800;
  45364. result.hScreenSize = 0.149759993;
  45365. result.vScreenSize = 0.0935999975;
  45366. result.vScreenCenter = 0.0467999987;
  45367. result.eyeToScreenDistance = 0.0410000011;
  45368. result.lensSeparationDistance = 0.0635000020;
  45369. result.interpupillaryDistance = 0.0640000030;
  45370. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  45371. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  45372. result.postProcessScaleFactor = 1.714605507808412;
  45373. result.lensCenterOffset = 0.151976421;
  45374. return result;
  45375. };
  45376. return VRCameraMetrics;
  45377. }());
  45378. BABYLON.VRCameraMetrics = VRCameraMetrics;
  45379. })(BABYLON || (BABYLON = {}));
  45380. //# sourceMappingURL=babylon.vrCameraMetrics.js.map
  45381. var BABYLON;
  45382. (function (BABYLON) {
  45383. var WebVRFreeCamera = (function (_super) {
  45384. __extends(WebVRFreeCamera, _super);
  45385. function WebVRFreeCamera(name, position, scene, compensateDistortion, webVROptions) {
  45386. if (compensateDistortion === void 0) { compensateDistortion = false; }
  45387. if (webVROptions === void 0) { webVROptions = {}; }
  45388. var _this = _super.call(this, name, position, scene) || this;
  45389. _this.webVROptions = webVROptions;
  45390. _this._vrDevice = null;
  45391. _this._cacheState = null;
  45392. _this._vrEnabled = false;
  45393. _this._attached = false;
  45394. //using the position provided as the current position offset
  45395. _this._positionOffset = position;
  45396. //enable VR
  45397. _this.getEngine().initWebVR();
  45398. if (!_this.getEngine().vrDisplaysPromise) {
  45399. BABYLON.Tools.Error("WebVR is not enabled on your browser");
  45400. }
  45401. else {
  45402. //TODO get the metrics updated using the device's eye parameters!
  45403. //TODO also check that the device has the right capabilities!
  45404. _this._frameData = new VRFrameData();
  45405. _this.getEngine().vrDisplaysPromise.then(function (devices) {
  45406. if (devices.length > 0) {
  45407. _this._vrEnabled = true;
  45408. if (_this.webVROptions.displayName) {
  45409. var found = devices.some(function (device) {
  45410. if (device.displayName === _this.webVROptions.displayName) {
  45411. _this._vrDevice = device;
  45412. return true;
  45413. }
  45414. else {
  45415. return false;
  45416. }
  45417. });
  45418. if (!found) {
  45419. _this._vrDevice = devices[0];
  45420. BABYLON.Tools.Warn("Display " + _this.webVROptions.displayName + " was not found. Using " + _this._vrDevice.displayName);
  45421. }
  45422. }
  45423. else {
  45424. //choose the first one
  45425. _this._vrDevice = devices[0];
  45426. }
  45427. //reset the rig parameters.
  45428. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_WEBVR, { vrDisplay: _this._vrDevice, frameData: _this._frameData });
  45429. if (_this._attached) {
  45430. _this.getEngine().enableVR(_this._vrDevice);
  45431. }
  45432. }
  45433. else {
  45434. BABYLON.Tools.Error("No WebVR devices found!");
  45435. }
  45436. });
  45437. }
  45438. _this.rotationQuaternion = new BABYLON.Quaternion();
  45439. _this._quaternionCache = new BABYLON.Quaternion();
  45440. return _this;
  45441. }
  45442. WebVRFreeCamera.prototype._checkInputs = function () {
  45443. if (this._vrEnabled && this._vrDevice.getFrameData(this._frameData)) {
  45444. var currentPost = this._frameData.pose;
  45445. //make sure we have data
  45446. if (currentPost && currentPost.orientation) {
  45447. this._cacheState = currentPost;
  45448. this.rotationQuaternion.copyFromFloats(this._cacheState.orientation[0], this._cacheState.orientation[1], -this._cacheState.orientation[2], -this._cacheState.orientation[3]);
  45449. if (this.webVROptions.trackPosition && this._cacheState.position) {
  45450. this.position.copyFromFloats(this._cacheState.position[0], this._cacheState.position[1], -this._cacheState.position[2]);
  45451. //scale the position accordingly
  45452. this.webVROptions.positionScale && this.position.scaleInPlace(this.webVROptions.positionScale);
  45453. //add the position offset
  45454. this.position.addInPlace(this._positionOffset);
  45455. }
  45456. }
  45457. }
  45458. _super.prototype._checkInputs.call(this);
  45459. };
  45460. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  45461. _super.prototype.attachControl.call(this, element, noPreventDefault);
  45462. this._attached = true;
  45463. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  45464. if (this._vrEnabled) {
  45465. this.getEngine().enableVR(this._vrDevice);
  45466. }
  45467. };
  45468. WebVRFreeCamera.prototype.detachControl = function (element) {
  45469. _super.prototype.detachControl.call(this, element);
  45470. this._vrEnabled = false;
  45471. this._attached = false;
  45472. this.getEngine().disableVR();
  45473. };
  45474. WebVRFreeCamera.prototype.requestVRFullscreen = function (requestPointerlock) {
  45475. //Backwards comp.
  45476. BABYLON.Tools.Warn("requestVRFullscreen is deprecated. call attachControl() to start sending frames to the VR display.");
  45477. //this.getEngine().switchFullscreen(requestPointerlock);
  45478. };
  45479. WebVRFreeCamera.prototype.getClassName = function () {
  45480. return "WebVRFreeCamera";
  45481. };
  45482. WebVRFreeCamera.prototype.resetToCurrentRotation = function () {
  45483. //uses the vrDisplay's "resetPose()".
  45484. //pitch and roll won't be affected.
  45485. this._vrDevice.resetPose();
  45486. };
  45487. /**
  45488. *
  45489. * Set the position offset of the VR camera
  45490. * The offset will be added to the WebVR pose, after scaling it (if set).
  45491. *
  45492. * @param {Vector3} [newPosition] an optional new position. if not provided, the current camera position will be used.
  45493. *
  45494. * @memberOf WebVRFreeCamera
  45495. */
  45496. WebVRFreeCamera.prototype.setPositionOffset = function (newPosition) {
  45497. if (newPosition) {
  45498. this._positionOffset = newPosition;
  45499. }
  45500. else {
  45501. this._positionOffset.copyFrom(this.position);
  45502. }
  45503. };
  45504. return WebVRFreeCamera;
  45505. }(BABYLON.FreeCamera));
  45506. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  45507. })(BABYLON || (BABYLON = {}));
  45508. //# sourceMappingURL=babylon.webVRCamera.js.map
  45509. var BABYLON;
  45510. (function (BABYLON) {
  45511. // Standard optimizations
  45512. var SceneOptimization = (function () {
  45513. function SceneOptimization(priority) {
  45514. if (priority === void 0) { priority = 0; }
  45515. this.priority = priority;
  45516. this.apply = function (scene) {
  45517. return true; // Return true if everything that can be done was applied
  45518. };
  45519. }
  45520. return SceneOptimization;
  45521. }());
  45522. BABYLON.SceneOptimization = SceneOptimization;
  45523. var TextureOptimization = (function (_super) {
  45524. __extends(TextureOptimization, _super);
  45525. function TextureOptimization(priority, maximumSize) {
  45526. if (priority === void 0) { priority = 0; }
  45527. if (maximumSize === void 0) { maximumSize = 1024; }
  45528. var _this = _super.call(this, priority) || this;
  45529. _this.priority = priority;
  45530. _this.maximumSize = maximumSize;
  45531. _this.apply = function (scene) {
  45532. var allDone = true;
  45533. for (var index = 0; index < scene.textures.length; index++) {
  45534. var texture = scene.textures[index];
  45535. if (!texture.canRescale) {
  45536. continue;
  45537. }
  45538. var currentSize = texture.getSize();
  45539. var maxDimension = Math.max(currentSize.width, currentSize.height);
  45540. if (maxDimension > _this.maximumSize) {
  45541. texture.scale(0.5);
  45542. allDone = false;
  45543. }
  45544. }
  45545. return allDone;
  45546. };
  45547. return _this;
  45548. }
  45549. return TextureOptimization;
  45550. }(SceneOptimization));
  45551. BABYLON.TextureOptimization = TextureOptimization;
  45552. var HardwareScalingOptimization = (function (_super) {
  45553. __extends(HardwareScalingOptimization, _super);
  45554. function HardwareScalingOptimization(priority, maximumScale) {
  45555. if (priority === void 0) { priority = 0; }
  45556. if (maximumScale === void 0) { maximumScale = 2; }
  45557. var _this = _super.call(this, priority) || this;
  45558. _this.priority = priority;
  45559. _this.maximumScale = maximumScale;
  45560. _this._currentScale = 1;
  45561. _this.apply = function (scene) {
  45562. _this._currentScale++;
  45563. scene.getEngine().setHardwareScalingLevel(_this._currentScale);
  45564. return _this._currentScale >= _this.maximumScale;
  45565. };
  45566. return _this;
  45567. }
  45568. return HardwareScalingOptimization;
  45569. }(SceneOptimization));
  45570. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  45571. var ShadowsOptimization = (function (_super) {
  45572. __extends(ShadowsOptimization, _super);
  45573. function ShadowsOptimization() {
  45574. var _this = _super.apply(this, arguments) || this;
  45575. _this.apply = function (scene) {
  45576. scene.shadowsEnabled = false;
  45577. return true;
  45578. };
  45579. return _this;
  45580. }
  45581. return ShadowsOptimization;
  45582. }(SceneOptimization));
  45583. BABYLON.ShadowsOptimization = ShadowsOptimization;
  45584. var PostProcessesOptimization = (function (_super) {
  45585. __extends(PostProcessesOptimization, _super);
  45586. function PostProcessesOptimization() {
  45587. var _this = _super.apply(this, arguments) || this;
  45588. _this.apply = function (scene) {
  45589. scene.postProcessesEnabled = false;
  45590. return true;
  45591. };
  45592. return _this;
  45593. }
  45594. return PostProcessesOptimization;
  45595. }(SceneOptimization));
  45596. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  45597. var LensFlaresOptimization = (function (_super) {
  45598. __extends(LensFlaresOptimization, _super);
  45599. function LensFlaresOptimization() {
  45600. var _this = _super.apply(this, arguments) || this;
  45601. _this.apply = function (scene) {
  45602. scene.lensFlaresEnabled = false;
  45603. return true;
  45604. };
  45605. return _this;
  45606. }
  45607. return LensFlaresOptimization;
  45608. }(SceneOptimization));
  45609. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  45610. var ParticlesOptimization = (function (_super) {
  45611. __extends(ParticlesOptimization, _super);
  45612. function ParticlesOptimization() {
  45613. var _this = _super.apply(this, arguments) || this;
  45614. _this.apply = function (scene) {
  45615. scene.particlesEnabled = false;
  45616. return true;
  45617. };
  45618. return _this;
  45619. }
  45620. return ParticlesOptimization;
  45621. }(SceneOptimization));
  45622. BABYLON.ParticlesOptimization = ParticlesOptimization;
  45623. var RenderTargetsOptimization = (function (_super) {
  45624. __extends(RenderTargetsOptimization, _super);
  45625. function RenderTargetsOptimization() {
  45626. var _this = _super.apply(this, arguments) || this;
  45627. _this.apply = function (scene) {
  45628. scene.renderTargetsEnabled = false;
  45629. return true;
  45630. };
  45631. return _this;
  45632. }
  45633. return RenderTargetsOptimization;
  45634. }(SceneOptimization));
  45635. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  45636. var MergeMeshesOptimization = (function (_super) {
  45637. __extends(MergeMeshesOptimization, _super);
  45638. function MergeMeshesOptimization() {
  45639. var _this = _super.apply(this, arguments) || this;
  45640. _this._canBeMerged = function (abstractMesh) {
  45641. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  45642. return false;
  45643. }
  45644. var mesh = abstractMesh;
  45645. if (!mesh.isVisible || !mesh.isEnabled()) {
  45646. return false;
  45647. }
  45648. if (mesh.instances.length > 0) {
  45649. return false;
  45650. }
  45651. if (mesh.skeleton || mesh.hasLODLevels) {
  45652. return false;
  45653. }
  45654. if (mesh.parent) {
  45655. return false;
  45656. }
  45657. return true;
  45658. };
  45659. _this.apply = function (scene, updateSelectionTree) {
  45660. var globalPool = scene.meshes.slice(0);
  45661. var globalLength = globalPool.length;
  45662. for (var index = 0; index < globalLength; index++) {
  45663. var currentPool = new Array();
  45664. var current = globalPool[index];
  45665. // Checks
  45666. if (!_this._canBeMerged(current)) {
  45667. continue;
  45668. }
  45669. currentPool.push(current);
  45670. // Find compatible meshes
  45671. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  45672. var otherMesh = globalPool[subIndex];
  45673. if (!_this._canBeMerged(otherMesh)) {
  45674. continue;
  45675. }
  45676. if (otherMesh.material !== current.material) {
  45677. continue;
  45678. }
  45679. if (otherMesh.checkCollisions !== current.checkCollisions) {
  45680. continue;
  45681. }
  45682. currentPool.push(otherMesh);
  45683. globalLength--;
  45684. globalPool.splice(subIndex, 1);
  45685. subIndex--;
  45686. }
  45687. if (currentPool.length < 2) {
  45688. continue;
  45689. }
  45690. // Merge meshes
  45691. BABYLON.Mesh.MergeMeshes(currentPool);
  45692. }
  45693. if (updateSelectionTree != undefined) {
  45694. if (updateSelectionTree) {
  45695. scene.createOrUpdateSelectionOctree();
  45696. }
  45697. }
  45698. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  45699. scene.createOrUpdateSelectionOctree();
  45700. }
  45701. return true;
  45702. };
  45703. return _this;
  45704. }
  45705. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  45706. get: function () {
  45707. return MergeMeshesOptimization._UpdateSelectionTree;
  45708. },
  45709. set: function (value) {
  45710. MergeMeshesOptimization._UpdateSelectionTree = value;
  45711. },
  45712. enumerable: true,
  45713. configurable: true
  45714. });
  45715. return MergeMeshesOptimization;
  45716. }(SceneOptimization));
  45717. MergeMeshesOptimization._UpdateSelectionTree = false;
  45718. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  45719. // Options
  45720. var SceneOptimizerOptions = (function () {
  45721. function SceneOptimizerOptions(targetFrameRate, trackerDuration) {
  45722. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  45723. if (trackerDuration === void 0) { trackerDuration = 2000; }
  45724. this.targetFrameRate = targetFrameRate;
  45725. this.trackerDuration = trackerDuration;
  45726. this.optimizations = new Array();
  45727. }
  45728. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  45729. var result = new SceneOptimizerOptions(targetFrameRate);
  45730. var priority = 0;
  45731. result.optimizations.push(new MergeMeshesOptimization(priority));
  45732. result.optimizations.push(new ShadowsOptimization(priority));
  45733. result.optimizations.push(new LensFlaresOptimization(priority));
  45734. // Next priority
  45735. priority++;
  45736. result.optimizations.push(new PostProcessesOptimization(priority));
  45737. result.optimizations.push(new ParticlesOptimization(priority));
  45738. // Next priority
  45739. priority++;
  45740. result.optimizations.push(new TextureOptimization(priority, 1024));
  45741. return result;
  45742. };
  45743. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  45744. var result = new SceneOptimizerOptions(targetFrameRate);
  45745. var priority = 0;
  45746. result.optimizations.push(new MergeMeshesOptimization(priority));
  45747. result.optimizations.push(new ShadowsOptimization(priority));
  45748. result.optimizations.push(new LensFlaresOptimization(priority));
  45749. // Next priority
  45750. priority++;
  45751. result.optimizations.push(new PostProcessesOptimization(priority));
  45752. result.optimizations.push(new ParticlesOptimization(priority));
  45753. // Next priority
  45754. priority++;
  45755. result.optimizations.push(new TextureOptimization(priority, 512));
  45756. // Next priority
  45757. priority++;
  45758. result.optimizations.push(new RenderTargetsOptimization(priority));
  45759. // Next priority
  45760. priority++;
  45761. result.optimizations.push(new HardwareScalingOptimization(priority, 2));
  45762. return result;
  45763. };
  45764. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  45765. var result = new SceneOptimizerOptions(targetFrameRate);
  45766. var priority = 0;
  45767. result.optimizations.push(new MergeMeshesOptimization(priority));
  45768. result.optimizations.push(new ShadowsOptimization(priority));
  45769. result.optimizations.push(new LensFlaresOptimization(priority));
  45770. // Next priority
  45771. priority++;
  45772. result.optimizations.push(new PostProcessesOptimization(priority));
  45773. result.optimizations.push(new ParticlesOptimization(priority));
  45774. // Next priority
  45775. priority++;
  45776. result.optimizations.push(new TextureOptimization(priority, 256));
  45777. // Next priority
  45778. priority++;
  45779. result.optimizations.push(new RenderTargetsOptimization(priority));
  45780. // Next priority
  45781. priority++;
  45782. result.optimizations.push(new HardwareScalingOptimization(priority, 4));
  45783. return result;
  45784. };
  45785. return SceneOptimizerOptions;
  45786. }());
  45787. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  45788. // Scene optimizer tool
  45789. var SceneOptimizer = (function () {
  45790. function SceneOptimizer() {
  45791. }
  45792. SceneOptimizer._CheckCurrentState = function (scene, options, currentPriorityLevel, onSuccess, onFailure) {
  45793. // TODO: add an epsilon
  45794. if (scene.getEngine().getFps() >= options.targetFrameRate) {
  45795. if (onSuccess) {
  45796. onSuccess();
  45797. }
  45798. return;
  45799. }
  45800. // Apply current level of optimizations
  45801. var allDone = true;
  45802. var noOptimizationApplied = true;
  45803. for (var index = 0; index < options.optimizations.length; index++) {
  45804. var optimization = options.optimizations[index];
  45805. if (optimization.priority === currentPriorityLevel) {
  45806. noOptimizationApplied = false;
  45807. allDone = allDone && optimization.apply(scene);
  45808. }
  45809. }
  45810. // If no optimization was applied, this is a failure :(
  45811. if (noOptimizationApplied) {
  45812. if (onFailure) {
  45813. onFailure();
  45814. }
  45815. return;
  45816. }
  45817. // If all optimizations were done, move to next level
  45818. if (allDone) {
  45819. currentPriorityLevel++;
  45820. }
  45821. // Let's the system running for a specific amount of time before checking FPS
  45822. scene.executeWhenReady(function () {
  45823. setTimeout(function () {
  45824. SceneOptimizer._CheckCurrentState(scene, options, currentPriorityLevel, onSuccess, onFailure);
  45825. }, options.trackerDuration);
  45826. });
  45827. };
  45828. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  45829. if (!options) {
  45830. options = SceneOptimizerOptions.ModerateDegradationAllowed();
  45831. }
  45832. // Let's the system running for a specific amount of time before checking FPS
  45833. scene.executeWhenReady(function () {
  45834. setTimeout(function () {
  45835. SceneOptimizer._CheckCurrentState(scene, options, 0, onSuccess, onFailure);
  45836. }, options.trackerDuration);
  45837. });
  45838. };
  45839. return SceneOptimizer;
  45840. }());
  45841. BABYLON.SceneOptimizer = SceneOptimizer;
  45842. })(BABYLON || (BABYLON = {}));
  45843. //# sourceMappingURL=babylon.sceneOptimizer.js.map
  45844. var BABYLON;
  45845. (function (BABYLON) {
  45846. var Internals;
  45847. (function (Internals) {
  45848. var MeshLODLevel = (function () {
  45849. function MeshLODLevel(distance, mesh) {
  45850. this.distance = distance;
  45851. this.mesh = mesh;
  45852. }
  45853. return MeshLODLevel;
  45854. }());
  45855. Internals.MeshLODLevel = MeshLODLevel;
  45856. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  45857. })(BABYLON || (BABYLON = {}));
  45858. //# sourceMappingURL=babylon.meshLODLevel.js.map
  45859. var BABYLON;
  45860. (function (BABYLON) {
  45861. var RawTexture = (function (_super) {
  45862. __extends(RawTexture, _super);
  45863. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode) {
  45864. if (generateMipMaps === void 0) { generateMipMaps = true; }
  45865. if (invertY === void 0) { invertY = false; }
  45866. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  45867. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  45868. _this.format = format;
  45869. _this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode);
  45870. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  45871. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  45872. return _this;
  45873. }
  45874. RawTexture.prototype.update = function (data) {
  45875. this.getScene().getEngine().updateRawTexture(this._texture, data, this.format, this._invertY);
  45876. };
  45877. // Statics
  45878. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  45879. if (generateMipMaps === void 0) { generateMipMaps = true; }
  45880. if (invertY === void 0) { invertY = false; }
  45881. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  45882. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  45883. };
  45884. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  45885. if (generateMipMaps === void 0) { generateMipMaps = true; }
  45886. if (invertY === void 0) { invertY = false; }
  45887. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  45888. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  45889. };
  45890. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  45891. if (generateMipMaps === void 0) { generateMipMaps = true; }
  45892. if (invertY === void 0) { invertY = false; }
  45893. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  45894. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  45895. };
  45896. RawTexture.CreateRGBTexture = 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_RGB, scene, generateMipMaps, invertY, samplingMode);
  45901. };
  45902. RawTexture.CreateRGBATexture = 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_RGBA, scene, generateMipMaps, invertY, samplingMode);
  45907. };
  45908. return RawTexture;
  45909. }(BABYLON.Texture));
  45910. BABYLON.RawTexture = RawTexture;
  45911. })(BABYLON || (BABYLON = {}));
  45912. //# sourceMappingURL=babylon.rawTexture.js.map
  45913. var BABYLON;
  45914. (function (BABYLON) {
  45915. var IndexedVector2 = (function (_super) {
  45916. __extends(IndexedVector2, _super);
  45917. function IndexedVector2(original, index) {
  45918. var _this = _super.call(this, original.x, original.y) || this;
  45919. _this.index = index;
  45920. return _this;
  45921. }
  45922. return IndexedVector2;
  45923. }(BABYLON.Vector2));
  45924. var PolygonPoints = (function () {
  45925. function PolygonPoints() {
  45926. this.elements = new Array();
  45927. }
  45928. PolygonPoints.prototype.add = function (originalPoints) {
  45929. var _this = this;
  45930. var result = new Array();
  45931. originalPoints.forEach(function (point) {
  45932. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  45933. var newPoint = new IndexedVector2(point, _this.elements.length);
  45934. result.push(newPoint);
  45935. _this.elements.push(newPoint);
  45936. }
  45937. });
  45938. return result;
  45939. };
  45940. PolygonPoints.prototype.computeBounds = function () {
  45941. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  45942. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  45943. this.elements.forEach(function (point) {
  45944. // x
  45945. if (point.x < lmin.x) {
  45946. lmin.x = point.x;
  45947. }
  45948. else if (point.x > lmax.x) {
  45949. lmax.x = point.x;
  45950. }
  45951. // y
  45952. if (point.y < lmin.y) {
  45953. lmin.y = point.y;
  45954. }
  45955. else if (point.y > lmax.y) {
  45956. lmax.y = point.y;
  45957. }
  45958. });
  45959. return {
  45960. min: lmin,
  45961. max: lmax,
  45962. width: lmax.x - lmin.x,
  45963. height: lmax.y - lmin.y
  45964. };
  45965. };
  45966. return PolygonPoints;
  45967. }());
  45968. var Polygon = (function () {
  45969. function Polygon() {
  45970. }
  45971. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  45972. return [
  45973. new BABYLON.Vector2(xmin, ymin),
  45974. new BABYLON.Vector2(xmax, ymin),
  45975. new BABYLON.Vector2(xmax, ymax),
  45976. new BABYLON.Vector2(xmin, ymax)
  45977. ];
  45978. };
  45979. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  45980. if (cx === void 0) { cx = 0; }
  45981. if (cy === void 0) { cy = 0; }
  45982. if (numberOfSides === void 0) { numberOfSides = 32; }
  45983. var result = new Array();
  45984. var angle = 0;
  45985. var increment = (Math.PI * 2) / numberOfSides;
  45986. for (var i = 0; i < numberOfSides; i++) {
  45987. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  45988. angle -= increment;
  45989. }
  45990. return result;
  45991. };
  45992. Polygon.Parse = function (input) {
  45993. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  45994. var i, result = [];
  45995. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  45996. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  45997. }
  45998. return result;
  45999. };
  46000. Polygon.StartingAt = function (x, y) {
  46001. return BABYLON.Path2.StartingAt(x, y);
  46002. };
  46003. return Polygon;
  46004. }());
  46005. BABYLON.Polygon = Polygon;
  46006. var PolygonMeshBuilder = (function () {
  46007. function PolygonMeshBuilder(name, contours, scene) {
  46008. this._points = new PolygonPoints();
  46009. this._outlinepoints = new PolygonPoints();
  46010. this._holes = [];
  46011. this._epoints = new Array();
  46012. this._eholes = new Array();
  46013. this._name = name;
  46014. this._scene = scene;
  46015. var points;
  46016. if (contours instanceof BABYLON.Path2) {
  46017. points = contours.getPoints();
  46018. }
  46019. else {
  46020. points = contours;
  46021. }
  46022. this._addToepoint(points);
  46023. this._points.add(points);
  46024. this._outlinepoints.add(points);
  46025. }
  46026. PolygonMeshBuilder.prototype._addToepoint = function (points) {
  46027. for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {
  46028. var p = points_1[_i];
  46029. this._epoints.push(p.x, p.y);
  46030. }
  46031. };
  46032. PolygonMeshBuilder.prototype.addHole = function (hole) {
  46033. this._points.add(hole);
  46034. var holepoints = new PolygonPoints();
  46035. holepoints.add(hole);
  46036. this._holes.push(holepoints);
  46037. this._eholes.push(this._epoints.length / 2);
  46038. this._addToepoint(hole);
  46039. return this;
  46040. };
  46041. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  46042. var _this = this;
  46043. if (updatable === void 0) { updatable = false; }
  46044. var result = new BABYLON.Mesh(this._name, this._scene);
  46045. var normals = [];
  46046. var positions = [];
  46047. var uvs = [];
  46048. var bounds = this._points.computeBounds();
  46049. this._points.elements.forEach(function (p) {
  46050. normals.push(0, 1.0, 0);
  46051. positions.push(p.x, 0, p.y);
  46052. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  46053. });
  46054. var indices = [];
  46055. var res = Earcut.earcut(this._epoints, this._eholes, 2);
  46056. for (var i = 0; i < res.length; i++) {
  46057. indices.push(res[i]);
  46058. }
  46059. if (depth > 0) {
  46060. var positionscount = (positions.length / 3); //get the current pointcount
  46061. this._points.elements.forEach(function (p) {
  46062. normals.push(0, -1.0, 0);
  46063. positions.push(p.x, -depth, p.y);
  46064. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  46065. });
  46066. var totalCount = indices.length;
  46067. for (var i = 0; i < totalCount; i += 3) {
  46068. var i0 = indices[i + 0];
  46069. var i1 = indices[i + 1];
  46070. var i2 = indices[i + 2];
  46071. indices.push(i2 + positionscount);
  46072. indices.push(i1 + positionscount);
  46073. indices.push(i0 + positionscount);
  46074. }
  46075. //Add the sides
  46076. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  46077. this._holes.forEach(function (hole) {
  46078. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  46079. });
  46080. }
  46081. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  46082. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  46083. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  46084. result.setIndices(indices);
  46085. return result;
  46086. };
  46087. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  46088. var StartIndex = positions.length / 3;
  46089. var ulength = 0;
  46090. for (var i = 0; i < points.elements.length; i++) {
  46091. var p = points.elements[i];
  46092. var p1;
  46093. if ((i + 1) > points.elements.length - 1) {
  46094. p1 = points.elements[0];
  46095. }
  46096. else {
  46097. p1 = points.elements[i + 1];
  46098. }
  46099. positions.push(p.x, 0, p.y);
  46100. positions.push(p.x, -depth, p.y);
  46101. positions.push(p1.x, 0, p1.y);
  46102. positions.push(p1.x, -depth, p1.y);
  46103. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  46104. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  46105. var v3 = v2.subtract(v1);
  46106. var v4 = new BABYLON.Vector3(0, 1, 0);
  46107. var vn = BABYLON.Vector3.Cross(v3, v4);
  46108. vn = vn.normalize();
  46109. uvs.push(ulength / bounds.width, 0);
  46110. uvs.push(ulength / bounds.width, 1);
  46111. ulength += v3.length();
  46112. uvs.push((ulength / bounds.width), 0);
  46113. uvs.push((ulength / bounds.width), 1);
  46114. if (!flip) {
  46115. normals.push(-vn.x, -vn.y, -vn.z);
  46116. normals.push(-vn.x, -vn.y, -vn.z);
  46117. normals.push(-vn.x, -vn.y, -vn.z);
  46118. normals.push(-vn.x, -vn.y, -vn.z);
  46119. indices.push(StartIndex);
  46120. indices.push(StartIndex + 1);
  46121. indices.push(StartIndex + 2);
  46122. indices.push(StartIndex + 1);
  46123. indices.push(StartIndex + 3);
  46124. indices.push(StartIndex + 2);
  46125. }
  46126. else {
  46127. normals.push(vn.x, vn.y, vn.z);
  46128. normals.push(vn.x, vn.y, vn.z);
  46129. normals.push(vn.x, vn.y, vn.z);
  46130. normals.push(vn.x, vn.y, vn.z);
  46131. indices.push(StartIndex);
  46132. indices.push(StartIndex + 2);
  46133. indices.push(StartIndex + 1);
  46134. indices.push(StartIndex + 1);
  46135. indices.push(StartIndex + 2);
  46136. indices.push(StartIndex + 3);
  46137. }
  46138. StartIndex += 4;
  46139. }
  46140. ;
  46141. };
  46142. return PolygonMeshBuilder;
  46143. }());
  46144. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  46145. })(BABYLON || (BABYLON = {}));
  46146. //# sourceMappingURL=babylon.polygonMesh.js.map
  46147. var BABYLON;
  46148. (function (BABYLON) {
  46149. var Octree = (function () {
  46150. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  46151. if (maxDepth === void 0) { maxDepth = 2; }
  46152. this.maxDepth = maxDepth;
  46153. this.dynamicContent = new Array();
  46154. this._maxBlockCapacity = maxBlockCapacity || 64;
  46155. this._selectionContent = new BABYLON.SmartArray(1024);
  46156. this._creationFunc = creationFunc;
  46157. }
  46158. // Methods
  46159. Octree.prototype.update = function (worldMin, worldMax, entries) {
  46160. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  46161. };
  46162. Octree.prototype.addMesh = function (entry) {
  46163. for (var index = 0; index < this.blocks.length; index++) {
  46164. var block = this.blocks[index];
  46165. block.addEntry(entry);
  46166. }
  46167. };
  46168. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  46169. this._selectionContent.reset();
  46170. for (var index = 0; index < this.blocks.length; index++) {
  46171. var block = this.blocks[index];
  46172. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  46173. }
  46174. if (allowDuplicate) {
  46175. this._selectionContent.concat(this.dynamicContent);
  46176. }
  46177. else {
  46178. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  46179. }
  46180. return this._selectionContent;
  46181. };
  46182. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  46183. this._selectionContent.reset();
  46184. for (var index = 0; index < this.blocks.length; index++) {
  46185. var block = this.blocks[index];
  46186. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  46187. }
  46188. if (allowDuplicate) {
  46189. this._selectionContent.concat(this.dynamicContent);
  46190. }
  46191. else {
  46192. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  46193. }
  46194. return this._selectionContent;
  46195. };
  46196. Octree.prototype.intersectsRay = function (ray) {
  46197. this._selectionContent.reset();
  46198. for (var index = 0; index < this.blocks.length; index++) {
  46199. var block = this.blocks[index];
  46200. block.intersectsRay(ray, this._selectionContent);
  46201. }
  46202. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  46203. return this._selectionContent;
  46204. };
  46205. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  46206. target.blocks = new Array();
  46207. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  46208. // Segmenting space
  46209. for (var x = 0; x < 2; x++) {
  46210. for (var y = 0; y < 2; y++) {
  46211. for (var z = 0; z < 2; z++) {
  46212. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  46213. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  46214. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  46215. block.addEntries(entries);
  46216. target.blocks.push(block);
  46217. }
  46218. }
  46219. }
  46220. };
  46221. return Octree;
  46222. }());
  46223. Octree.CreationFuncForMeshes = function (entry, block) {
  46224. if (!entry.isBlocked && entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  46225. block.entries.push(entry);
  46226. }
  46227. };
  46228. Octree.CreationFuncForSubMeshes = function (entry, block) {
  46229. if (entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  46230. block.entries.push(entry);
  46231. }
  46232. };
  46233. BABYLON.Octree = Octree;
  46234. })(BABYLON || (BABYLON = {}));
  46235. //# sourceMappingURL=babylon.octree.js.map
  46236. var BABYLON;
  46237. (function (BABYLON) {
  46238. var OctreeBlock = (function () {
  46239. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  46240. this.entries = new Array();
  46241. this._boundingVectors = new Array();
  46242. this._capacity = capacity;
  46243. this._depth = depth;
  46244. this._maxDepth = maxDepth;
  46245. this._creationFunc = creationFunc;
  46246. this._minPoint = minPoint;
  46247. this._maxPoint = maxPoint;
  46248. this._boundingVectors.push(minPoint.clone());
  46249. this._boundingVectors.push(maxPoint.clone());
  46250. this._boundingVectors.push(minPoint.clone());
  46251. this._boundingVectors[2].x = maxPoint.x;
  46252. this._boundingVectors.push(minPoint.clone());
  46253. this._boundingVectors[3].y = maxPoint.y;
  46254. this._boundingVectors.push(minPoint.clone());
  46255. this._boundingVectors[4].z = maxPoint.z;
  46256. this._boundingVectors.push(maxPoint.clone());
  46257. this._boundingVectors[5].z = minPoint.z;
  46258. this._boundingVectors.push(maxPoint.clone());
  46259. this._boundingVectors[6].x = minPoint.x;
  46260. this._boundingVectors.push(maxPoint.clone());
  46261. this._boundingVectors[7].y = minPoint.y;
  46262. }
  46263. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  46264. // Property
  46265. get: function () {
  46266. return this._capacity;
  46267. },
  46268. enumerable: true,
  46269. configurable: true
  46270. });
  46271. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  46272. get: function () {
  46273. return this._minPoint;
  46274. },
  46275. enumerable: true,
  46276. configurable: true
  46277. });
  46278. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  46279. get: function () {
  46280. return this._maxPoint;
  46281. },
  46282. enumerable: true,
  46283. configurable: true
  46284. });
  46285. // Methods
  46286. OctreeBlock.prototype.addEntry = function (entry) {
  46287. if (this.blocks) {
  46288. for (var index = 0; index < this.blocks.length; index++) {
  46289. var block = this.blocks[index];
  46290. block.addEntry(entry);
  46291. }
  46292. return;
  46293. }
  46294. this._creationFunc(entry, this);
  46295. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  46296. this.createInnerBlocks();
  46297. }
  46298. };
  46299. OctreeBlock.prototype.addEntries = function (entries) {
  46300. for (var index = 0; index < entries.length; index++) {
  46301. var mesh = entries[index];
  46302. this.addEntry(mesh);
  46303. }
  46304. };
  46305. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  46306. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  46307. if (this.blocks) {
  46308. for (var index = 0; index < this.blocks.length; index++) {
  46309. var block = this.blocks[index];
  46310. block.select(frustumPlanes, selection, allowDuplicate);
  46311. }
  46312. return;
  46313. }
  46314. if (allowDuplicate) {
  46315. selection.concat(this.entries);
  46316. }
  46317. else {
  46318. selection.concatWithNoDuplicate(this.entries);
  46319. }
  46320. }
  46321. };
  46322. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  46323. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  46324. if (this.blocks) {
  46325. for (var index = 0; index < this.blocks.length; index++) {
  46326. var block = this.blocks[index];
  46327. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  46328. }
  46329. return;
  46330. }
  46331. if (allowDuplicate) {
  46332. selection.concat(this.entries);
  46333. }
  46334. else {
  46335. selection.concatWithNoDuplicate(this.entries);
  46336. }
  46337. }
  46338. };
  46339. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  46340. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  46341. if (this.blocks) {
  46342. for (var index = 0; index < this.blocks.length; index++) {
  46343. var block = this.blocks[index];
  46344. block.intersectsRay(ray, selection);
  46345. }
  46346. return;
  46347. }
  46348. selection.concatWithNoDuplicate(this.entries);
  46349. }
  46350. };
  46351. OctreeBlock.prototype.createInnerBlocks = function () {
  46352. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  46353. };
  46354. return OctreeBlock;
  46355. }());
  46356. BABYLON.OctreeBlock = OctreeBlock;
  46357. })(BABYLON || (BABYLON = {}));
  46358. //# sourceMappingURL=babylon.octreeBlock.js.map
  46359. var BABYLON;
  46360. (function (BABYLON) {
  46361. var BlurPostProcess = (function (_super) {
  46362. __extends(BlurPostProcess, _super);
  46363. function BlurPostProcess(name, direction, blurWidth, options, camera, samplingMode, engine, reusable) {
  46364. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  46365. var _this = _super.call(this, name, "blur", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable) || this;
  46366. _this.direction = direction;
  46367. _this.blurWidth = blurWidth;
  46368. _this.onApplyObservable.add(function (effect) {
  46369. effect.setFloat2("screenSize", _this.width, _this.height);
  46370. effect.setVector2("direction", _this.direction);
  46371. effect.setFloat("blurWidth", _this.blurWidth);
  46372. });
  46373. return _this;
  46374. }
  46375. return BlurPostProcess;
  46376. }(BABYLON.PostProcess));
  46377. BABYLON.BlurPostProcess = BlurPostProcess;
  46378. })(BABYLON || (BABYLON = {}));
  46379. //# sourceMappingURL=babylon.blurPostProcess.js.map
  46380. var BABYLON;
  46381. (function (BABYLON) {
  46382. var RefractionPostProcess = (function (_super) {
  46383. __extends(RefractionPostProcess, _super);
  46384. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, options, camera, samplingMode, engine, reusable) {
  46385. var _this = _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], options, camera, samplingMode, engine, reusable) || this;
  46386. _this.color = color;
  46387. _this.depth = depth;
  46388. _this.colorLevel = colorLevel;
  46389. _this.onActivateObservable.add(function (cam) {
  46390. _this._refRexture = _this._refRexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  46391. });
  46392. _this.onApplyObservable.add(function (effect) {
  46393. effect.setColor3("baseColor", _this.color);
  46394. effect.setFloat("depth", _this.depth);
  46395. effect.setFloat("colorLevel", _this.colorLevel);
  46396. effect.setTexture("refractionSampler", _this._refRexture);
  46397. });
  46398. return _this;
  46399. }
  46400. // Methods
  46401. RefractionPostProcess.prototype.dispose = function (camera) {
  46402. if (this._refRexture) {
  46403. this._refRexture.dispose();
  46404. }
  46405. _super.prototype.dispose.call(this, camera);
  46406. };
  46407. return RefractionPostProcess;
  46408. }(BABYLON.PostProcess));
  46409. BABYLON.RefractionPostProcess = RefractionPostProcess;
  46410. })(BABYLON || (BABYLON = {}));
  46411. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  46412. var BABYLON;
  46413. (function (BABYLON) {
  46414. var BlackAndWhitePostProcess = (function (_super) {
  46415. __extends(BlackAndWhitePostProcess, _super);
  46416. function BlackAndWhitePostProcess(name, options, camera, samplingMode, engine, reusable) {
  46417. return _super.call(this, name, "blackAndWhite", null, null, options, camera, samplingMode, engine, reusable) || this;
  46418. }
  46419. return BlackAndWhitePostProcess;
  46420. }(BABYLON.PostProcess));
  46421. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  46422. })(BABYLON || (BABYLON = {}));
  46423. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  46424. var BABYLON;
  46425. (function (BABYLON) {
  46426. var ConvolutionPostProcess = (function (_super) {
  46427. __extends(ConvolutionPostProcess, _super);
  46428. function ConvolutionPostProcess(name, kernel, options, camera, samplingMode, engine, reusable) {
  46429. var _this = _super.call(this, name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable) || this;
  46430. _this.kernel = kernel;
  46431. _this.onApply = function (effect) {
  46432. effect.setFloat2("screenSize", _this.width, _this.height);
  46433. effect.setArray("kernel", _this.kernel);
  46434. };
  46435. return _this;
  46436. }
  46437. return ConvolutionPostProcess;
  46438. }(BABYLON.PostProcess));
  46439. // Statics
  46440. // Based on http://en.wikipedia.org/wiki/Kernel_(image_processing)
  46441. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  46442. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  46443. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  46444. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  46445. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  46446. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  46447. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  46448. })(BABYLON || (BABYLON = {}));
  46449. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  46450. var BABYLON;
  46451. (function (BABYLON) {
  46452. var FilterPostProcess = (function (_super) {
  46453. __extends(FilterPostProcess, _super);
  46454. function FilterPostProcess(name, kernelMatrix, options, camera, samplingMode, engine, reusable) {
  46455. var _this = _super.call(this, name, "filter", ["kernelMatrix"], null, options, camera, samplingMode, engine, reusable) || this;
  46456. _this.kernelMatrix = kernelMatrix;
  46457. _this.onApply = function (effect) {
  46458. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  46459. };
  46460. return _this;
  46461. }
  46462. return FilterPostProcess;
  46463. }(BABYLON.PostProcess));
  46464. BABYLON.FilterPostProcess = FilterPostProcess;
  46465. })(BABYLON || (BABYLON = {}));
  46466. //# sourceMappingURL=babylon.filterPostProcess.js.map
  46467. var BABYLON;
  46468. (function (BABYLON) {
  46469. var FxaaPostProcess = (function (_super) {
  46470. __extends(FxaaPostProcess, _super);
  46471. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable) {
  46472. var _this = _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode, engine, reusable) || this;
  46473. _this.onSizeChangedObservable.add(function () {
  46474. _this.texelWidth = 1.0 / _this.width;
  46475. _this.texelHeight = 1.0 / _this.height;
  46476. });
  46477. _this.onApplyObservable.add(function (effect) {
  46478. effect.setFloat2("texelSize", _this.texelWidth, _this.texelHeight);
  46479. });
  46480. return _this;
  46481. }
  46482. return FxaaPostProcess;
  46483. }(BABYLON.PostProcess));
  46484. BABYLON.FxaaPostProcess = FxaaPostProcess;
  46485. })(BABYLON || (BABYLON = {}));
  46486. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  46487. var BABYLON;
  46488. (function (BABYLON) {
  46489. var StereoscopicInterlacePostProcess = (function (_super) {
  46490. __extends(StereoscopicInterlacePostProcess, _super);
  46491. function StereoscopicInterlacePostProcess(name, rigCameras, isStereoscopicHoriz, samplingMode, engine, reusable) {
  46492. var _this = _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined) || this;
  46493. _this._passedProcess = rigCameras[0]._rigPostProcess;
  46494. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  46495. _this.onSizeChangedObservable.add(function () {
  46496. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  46497. });
  46498. _this.onApplyObservable.add(function (effect) {
  46499. effect.setTextureFromPostProcess("camASampler", _this._passedProcess);
  46500. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  46501. });
  46502. return _this;
  46503. }
  46504. return StereoscopicInterlacePostProcess;
  46505. }(BABYLON.PostProcess));
  46506. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  46507. })(BABYLON || (BABYLON = {}));
  46508. //# sourceMappingURL=babylon.stereoscopicInterlacePostProcess.js.map
  46509. var BABYLON;
  46510. (function (BABYLON) {
  46511. var LensFlare = (function () {
  46512. function LensFlare(size, position, color, imgUrl, system) {
  46513. this.size = size;
  46514. this.position = position;
  46515. this.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  46516. this.dispose = function () {
  46517. if (this.texture) {
  46518. this.texture.dispose();
  46519. }
  46520. // Remove from scene
  46521. var index = this._system.lensFlares.indexOf(this);
  46522. this._system.lensFlares.splice(index, 1);
  46523. };
  46524. this.color = color || new BABYLON.Color3(1, 1, 1);
  46525. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  46526. this._system = system;
  46527. system.lensFlares.push(this);
  46528. }
  46529. return LensFlare;
  46530. }());
  46531. BABYLON.LensFlare = LensFlare;
  46532. })(BABYLON || (BABYLON = {}));
  46533. //# sourceMappingURL=babylon.lensFlare.js.map
  46534. var BABYLON;
  46535. (function (BABYLON) {
  46536. var LensFlareSystem = (function () {
  46537. function LensFlareSystem(name, emitter, scene) {
  46538. this.name = name;
  46539. this.lensFlares = new Array();
  46540. this.borderLimit = 300;
  46541. this.viewportBorder = 0;
  46542. this.layerMask = 0x0FFFFFFF;
  46543. this._vertexBuffers = {};
  46544. this._isEnabled = true;
  46545. this._scene = scene;
  46546. this._emitter = emitter;
  46547. this.id = name;
  46548. scene.lensFlareSystems.push(this);
  46549. this.meshesSelectionPredicate = function (m) { return m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0); };
  46550. var engine = scene.getEngine();
  46551. // VBO
  46552. var vertices = [];
  46553. vertices.push(1, 1);
  46554. vertices.push(-1, 1);
  46555. vertices.push(-1, -1);
  46556. vertices.push(1, -1);
  46557. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  46558. // Indices
  46559. var indices = [];
  46560. indices.push(0);
  46561. indices.push(1);
  46562. indices.push(2);
  46563. indices.push(0);
  46564. indices.push(2);
  46565. indices.push(3);
  46566. this._indexBuffer = engine.createIndexBuffer(indices);
  46567. // Effects
  46568. this._effect = engine.createEffect("lensFlare", [BABYLON.VertexBuffer.PositionKind], ["color", "viewportMatrix"], ["textureSampler"], "");
  46569. }
  46570. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  46571. get: function () {
  46572. return this._isEnabled;
  46573. },
  46574. set: function (value) {
  46575. this._isEnabled = value;
  46576. },
  46577. enumerable: true,
  46578. configurable: true
  46579. });
  46580. LensFlareSystem.prototype.getScene = function () {
  46581. return this._scene;
  46582. };
  46583. LensFlareSystem.prototype.getEmitter = function () {
  46584. return this._emitter;
  46585. };
  46586. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  46587. this._emitter = newEmitter;
  46588. };
  46589. LensFlareSystem.prototype.getEmitterPosition = function () {
  46590. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  46591. };
  46592. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  46593. var position = this.getEmitterPosition();
  46594. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  46595. this._positionX = position.x;
  46596. this._positionY = position.y;
  46597. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  46598. if (this.viewportBorder > 0) {
  46599. globalViewport.x -= this.viewportBorder;
  46600. globalViewport.y -= this.viewportBorder;
  46601. globalViewport.width += this.viewportBorder * 2;
  46602. globalViewport.height += this.viewportBorder * 2;
  46603. position.x += this.viewportBorder;
  46604. position.y += this.viewportBorder;
  46605. this._positionX += this.viewportBorder;
  46606. this._positionY += this.viewportBorder;
  46607. }
  46608. if (position.z > 0) {
  46609. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  46610. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  46611. return true;
  46612. }
  46613. return true;
  46614. }
  46615. return false;
  46616. };
  46617. LensFlareSystem.prototype._isVisible = function () {
  46618. if (!this._isEnabled) {
  46619. return false;
  46620. }
  46621. var emitterPosition = this.getEmitterPosition();
  46622. var direction = emitterPosition.subtract(this._scene.activeCamera.globalPosition);
  46623. var distance = direction.length();
  46624. direction.normalize();
  46625. var ray = new BABYLON.Ray(this._scene.activeCamera.globalPosition, direction);
  46626. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  46627. return !pickInfo.hit || pickInfo.distance > distance;
  46628. };
  46629. LensFlareSystem.prototype.render = function () {
  46630. if (!this._effect.isReady())
  46631. return false;
  46632. var engine = this._scene.getEngine();
  46633. var viewport = this._scene.activeCamera.viewport;
  46634. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  46635. // Position
  46636. if (!this.computeEffectivePosition(globalViewport)) {
  46637. return false;
  46638. }
  46639. // Visibility
  46640. if (!this._isVisible()) {
  46641. return false;
  46642. }
  46643. // Intensity
  46644. var awayX;
  46645. var awayY;
  46646. if (this._positionX < this.borderLimit + globalViewport.x) {
  46647. awayX = this.borderLimit + globalViewport.x - this._positionX;
  46648. }
  46649. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  46650. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  46651. }
  46652. else {
  46653. awayX = 0;
  46654. }
  46655. if (this._positionY < this.borderLimit + globalViewport.y) {
  46656. awayY = this.borderLimit + globalViewport.y - this._positionY;
  46657. }
  46658. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  46659. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  46660. }
  46661. else {
  46662. awayY = 0;
  46663. }
  46664. var away = (awayX > awayY) ? awayX : awayY;
  46665. away -= this.viewportBorder;
  46666. if (away > this.borderLimit) {
  46667. away = this.borderLimit;
  46668. }
  46669. var intensity = 1.0 - (away / this.borderLimit);
  46670. if (intensity < 0) {
  46671. return false;
  46672. }
  46673. if (intensity > 1.0) {
  46674. intensity = 1.0;
  46675. }
  46676. if (this.viewportBorder > 0) {
  46677. globalViewport.x += this.viewportBorder;
  46678. globalViewport.y += this.viewportBorder;
  46679. globalViewport.width -= this.viewportBorder * 2;
  46680. globalViewport.height -= this.viewportBorder * 2;
  46681. this._positionX -= this.viewportBorder;
  46682. this._positionY -= this.viewportBorder;
  46683. }
  46684. // Position
  46685. var centerX = globalViewport.x + globalViewport.width / 2;
  46686. var centerY = globalViewport.y + globalViewport.height / 2;
  46687. var distX = centerX - this._positionX;
  46688. var distY = centerY - this._positionY;
  46689. // Effects
  46690. engine.enableEffect(this._effect);
  46691. engine.setState(false);
  46692. engine.setDepthBuffer(false);
  46693. // VBOs
  46694. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  46695. // Flares
  46696. for (var index = 0; index < this.lensFlares.length; index++) {
  46697. var flare = this.lensFlares[index];
  46698. engine.setAlphaMode(flare.alphaMode);
  46699. var x = centerX - (distX * flare.position);
  46700. var y = centerY - (distY * flare.position);
  46701. var cw = flare.size;
  46702. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  46703. var cx = 2 * (x / (globalViewport.width + globalViewport.x * 2)) - 1.0;
  46704. var cy = 1.0 - 2 * (y / (globalViewport.height + globalViewport.y * 2));
  46705. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  46706. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  46707. // Texture
  46708. this._effect.setTexture("textureSampler", flare.texture);
  46709. // Color
  46710. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  46711. // Draw order
  46712. engine.draw(true, 0, 6);
  46713. }
  46714. engine.setDepthBuffer(true);
  46715. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  46716. return true;
  46717. };
  46718. LensFlareSystem.prototype.dispose = function () {
  46719. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  46720. if (vertexBuffer) {
  46721. vertexBuffer.dispose();
  46722. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  46723. }
  46724. if (this._indexBuffer) {
  46725. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  46726. this._indexBuffer = null;
  46727. }
  46728. while (this.lensFlares.length) {
  46729. this.lensFlares[0].dispose();
  46730. }
  46731. // Remove from scene
  46732. var index = this._scene.lensFlareSystems.indexOf(this);
  46733. this._scene.lensFlareSystems.splice(index, 1);
  46734. };
  46735. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  46736. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  46737. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  46738. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  46739. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  46740. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  46741. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  46742. var parsedFlare = parsedLensFlareSystem.flares[index];
  46743. var flare = new BABYLON.LensFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), rootUrl + parsedFlare.textureName, lensFlareSystem);
  46744. }
  46745. return lensFlareSystem;
  46746. };
  46747. LensFlareSystem.prototype.serialize = function () {
  46748. var serializationObject = {};
  46749. serializationObject.id = this.id;
  46750. serializationObject.name = this.name;
  46751. serializationObject.emitterId = this.getEmitter().id;
  46752. serializationObject.borderLimit = this.borderLimit;
  46753. serializationObject.flares = [];
  46754. for (var index = 0; index < this.lensFlares.length; index++) {
  46755. var flare = this.lensFlares[index];
  46756. serializationObject.flares.push({
  46757. size: flare.size,
  46758. position: flare.position,
  46759. color: flare.color.asArray(),
  46760. textureName: BABYLON.Tools.GetFilename(flare.texture.name)
  46761. });
  46762. }
  46763. return serializationObject;
  46764. };
  46765. return LensFlareSystem;
  46766. }());
  46767. BABYLON.LensFlareSystem = LensFlareSystem;
  46768. })(BABYLON || (BABYLON = {}));
  46769. //# sourceMappingURL=babylon.lensFlareSystem.js.map
  46770. var BABYLON;
  46771. (function (BABYLON) {
  46772. // We're mainly based on the logic defined into the FreeCamera code
  46773. var DeviceOrientationCamera = (function (_super) {
  46774. __extends(DeviceOrientationCamera, _super);
  46775. function DeviceOrientationCamera(name, position, scene) {
  46776. var _this = _super.call(this, name, position, scene) || this;
  46777. _this._quaternionCache = new BABYLON.Quaternion();
  46778. _this.inputs.addDeviceOrientation();
  46779. return _this;
  46780. }
  46781. DeviceOrientationCamera.prototype.getClassName = function () {
  46782. return "DeviceOrientationCamera";
  46783. };
  46784. DeviceOrientationCamera.prototype._checkInputs = function () {
  46785. _super.prototype._checkInputs.call(this);
  46786. this._quaternionCache.copyFrom(this.rotationQuaternion);
  46787. if (this._initialQuaternion) {
  46788. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  46789. }
  46790. };
  46791. DeviceOrientationCamera.prototype.resetToCurrentRotation = function (axis) {
  46792. var _this = this;
  46793. if (axis === void 0) { axis = BABYLON.Axis.Y; }
  46794. //can only work if this camera has a rotation quaternion already.
  46795. if (!this.rotationQuaternion)
  46796. return;
  46797. if (!this._initialQuaternion) {
  46798. this._initialQuaternion = new BABYLON.Quaternion();
  46799. }
  46800. this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion);
  46801. ['x', 'y', 'z'].forEach(function (axisName) {
  46802. if (!axis[axisName]) {
  46803. _this._initialQuaternion[axisName] = 0;
  46804. }
  46805. else {
  46806. _this._initialQuaternion[axisName] *= -1;
  46807. }
  46808. });
  46809. this._initialQuaternion.normalize();
  46810. //force rotation update
  46811. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  46812. };
  46813. return DeviceOrientationCamera;
  46814. }(BABYLON.FreeCamera));
  46815. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  46816. })(BABYLON || (BABYLON = {}));
  46817. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  46818. var BABYLON;
  46819. (function (BABYLON) {
  46820. var VRDeviceOrientationFreeCamera = (function (_super) {
  46821. __extends(VRDeviceOrientationFreeCamera, _super);
  46822. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  46823. if (compensateDistortion === void 0) { compensateDistortion = true; }
  46824. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  46825. var _this = _super.call(this, name, position, scene) || this;
  46826. vrCameraMetrics.compensateDistortion = compensateDistortion;
  46827. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  46828. return _this;
  46829. }
  46830. VRDeviceOrientationFreeCamera.prototype.getClassName = function () {
  46831. return "VRDeviceOrientationFreeCamera";
  46832. };
  46833. return VRDeviceOrientationFreeCamera;
  46834. }(BABYLON.DeviceOrientationCamera));
  46835. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  46836. var VRDeviceOrientationArcRotateCamera = (function (_super) {
  46837. __extends(VRDeviceOrientationArcRotateCamera, _super);
  46838. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion, vrCameraMetrics) {
  46839. if (compensateDistortion === void 0) { compensateDistortion = true; }
  46840. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  46841. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  46842. vrCameraMetrics.compensateDistortion = compensateDistortion;
  46843. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  46844. _this.inputs.addVRDeviceOrientation();
  46845. return _this;
  46846. }
  46847. VRDeviceOrientationArcRotateCamera.prototype.getClassName = function () {
  46848. return "VRDeviceOrientationArcRotateCamera";
  46849. };
  46850. return VRDeviceOrientationArcRotateCamera;
  46851. }(BABYLON.ArcRotateCamera));
  46852. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  46853. })(BABYLON || (BABYLON = {}));
  46854. //# sourceMappingURL=babylon.vrDeviceOrientationCamera.js.map
  46855. var BABYLON;
  46856. (function (BABYLON) {
  46857. // We're mainly based on the logic defined into the FreeCamera code
  46858. var UniversalCamera = (function (_super) {
  46859. __extends(UniversalCamera, _super);
  46860. //-- end properties for backward compatibility for inputs
  46861. function UniversalCamera(name, position, scene) {
  46862. var _this = _super.call(this, name, position, scene) || this;
  46863. _this.inputs.addGamepad();
  46864. return _this;
  46865. }
  46866. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  46867. //-- Begin properties for backward compatibility for inputs
  46868. get: function () {
  46869. var gamepad = this.inputs.attached["gamepad"];
  46870. if (gamepad)
  46871. return gamepad.gamepadAngularSensibility;
  46872. },
  46873. set: function (value) {
  46874. var gamepad = this.inputs.attached["gamepad"];
  46875. if (gamepad)
  46876. gamepad.gamepadAngularSensibility = value;
  46877. },
  46878. enumerable: true,
  46879. configurable: true
  46880. });
  46881. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  46882. get: function () {
  46883. var gamepad = this.inputs.attached["gamepad"];
  46884. if (gamepad)
  46885. return gamepad.gamepadMoveSensibility;
  46886. },
  46887. set: function (value) {
  46888. var gamepad = this.inputs.attached["gamepad"];
  46889. if (gamepad)
  46890. gamepad.gamepadMoveSensibility = value;
  46891. },
  46892. enumerable: true,
  46893. configurable: true
  46894. });
  46895. UniversalCamera.prototype.getClassName = function () {
  46896. return "UniversalCamera";
  46897. };
  46898. return UniversalCamera;
  46899. }(BABYLON.TouchCamera));
  46900. BABYLON.UniversalCamera = UniversalCamera;
  46901. })(BABYLON || (BABYLON = {}));
  46902. //# sourceMappingURL=babylon.universalCamera.js.map
  46903. var BABYLON;
  46904. (function (BABYLON) {
  46905. var Gamepads = (function () {
  46906. function Gamepads(ongamedpadconnected) {
  46907. var _this = this;
  46908. this.babylonGamepads = [];
  46909. this.oneGamepadConnected = false;
  46910. this.isMonitoring = false;
  46911. this.gamepadEventSupported = 'GamepadEvent' in window;
  46912. this.gamepadSupportAvailable = (navigator.getGamepads ||
  46913. !!navigator.webkitGetGamepads || !!navigator.msGetGamepads || !!navigator.webkitGamepads);
  46914. this._callbackGamepadConnected = ongamedpadconnected;
  46915. if (this.gamepadSupportAvailable) {
  46916. // Checking if the gamepad connected event is supported (like in Firefox)
  46917. if (this.gamepadEventSupported) {
  46918. this._onGamepadConnectedEvent = function (evt) {
  46919. _this._onGamepadConnected(evt);
  46920. };
  46921. this._onGamepadDisonnectedEvent = function (evt) {
  46922. _this._onGamepadDisconnected(evt);
  46923. };
  46924. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  46925. window.addEventListener('gamepaddisconnected', this._onGamepadDisonnectedEvent, false);
  46926. }
  46927. else {
  46928. this._startMonitoringGamepads();
  46929. }
  46930. }
  46931. }
  46932. Gamepads.prototype.dispose = function () {
  46933. if (Gamepads.gamepadDOMInfo) {
  46934. document.body.removeChild(Gamepads.gamepadDOMInfo);
  46935. }
  46936. if (this._onGamepadConnectedEvent) {
  46937. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  46938. window.removeEventListener('gamepaddisconnected', this._onGamepadDisonnectedEvent, false);
  46939. this._onGamepadConnectedEvent = null;
  46940. this._onGamepadDisonnectedEvent = null;
  46941. }
  46942. };
  46943. Gamepads.prototype._onGamepadConnected = function (evt) {
  46944. var newGamepad = this._addNewGamepad(evt.gamepad);
  46945. if (this._callbackGamepadConnected)
  46946. this._callbackGamepadConnected(newGamepad);
  46947. this._startMonitoringGamepads();
  46948. };
  46949. Gamepads.prototype._addNewGamepad = function (gamepad) {
  46950. if (!this.oneGamepadConnected) {
  46951. this.oneGamepadConnected = true;
  46952. if (Gamepads.gamepadDOMInfo) {
  46953. document.body.removeChild(Gamepads.gamepadDOMInfo);
  46954. Gamepads.gamepadDOMInfo = null;
  46955. }
  46956. }
  46957. var newGamepad;
  46958. var xboxOne = (gamepad.id.search("Xbox One") !== -1);
  46959. if (xboxOne || gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  46960. newGamepad = new Xbox360Pad(gamepad.id, gamepad.index, gamepad, xboxOne);
  46961. }
  46962. else {
  46963. newGamepad = new GenericPad(gamepad.id, gamepad.index, gamepad);
  46964. }
  46965. this.babylonGamepads.push(newGamepad);
  46966. return newGamepad;
  46967. };
  46968. Gamepads.prototype._onGamepadDisconnected = function (evt) {
  46969. // Remove the gamepad from the list of gamepads to monitor.
  46970. for (var i in this.babylonGamepads) {
  46971. if (this.babylonGamepads[i].index == evt.gamepad.index) {
  46972. this.babylonGamepads.splice(+i, 1);
  46973. break;
  46974. }
  46975. }
  46976. // If no gamepads are left, stop the polling loop.
  46977. if (this.babylonGamepads.length == 0) {
  46978. this._stopMonitoringGamepads();
  46979. }
  46980. };
  46981. Gamepads.prototype._startMonitoringGamepads = function () {
  46982. if (!this.isMonitoring) {
  46983. this.isMonitoring = true;
  46984. this._checkGamepadsStatus();
  46985. }
  46986. };
  46987. Gamepads.prototype._stopMonitoringGamepads = function () {
  46988. this.isMonitoring = false;
  46989. };
  46990. Gamepads.prototype._checkGamepadsStatus = function () {
  46991. var _this = this;
  46992. // updating gamepad objects
  46993. this._updateGamepadObjects();
  46994. for (var i in this.babylonGamepads) {
  46995. this.babylonGamepads[i].update();
  46996. }
  46997. if (this.isMonitoring) {
  46998. if (window.requestAnimationFrame) {
  46999. window.requestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  47000. }
  47001. else if (window.mozRequestAnimationFrame) {
  47002. window.mozRequestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  47003. }
  47004. else if (window.webkitRequestAnimationFrame) {
  47005. window.webkitRequestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  47006. }
  47007. }
  47008. };
  47009. // This function is called only on Chrome, which does not yet support
  47010. // connection/disconnection events, but requires you to monitor
  47011. // an array for changes.
  47012. Gamepads.prototype._updateGamepadObjects = function () {
  47013. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  47014. for (var i = 0; i < gamepads.length; i++) {
  47015. if (gamepads[i]) {
  47016. if (!(gamepads[i].index in this.babylonGamepads)) {
  47017. var newGamepad = this._addNewGamepad(gamepads[i]);
  47018. if (this._callbackGamepadConnected) {
  47019. this._callbackGamepadConnected(newGamepad);
  47020. }
  47021. }
  47022. else {
  47023. this.babylonGamepads[i].browserGamepad = gamepads[i];
  47024. }
  47025. }
  47026. }
  47027. };
  47028. return Gamepads;
  47029. }());
  47030. BABYLON.Gamepads = Gamepads;
  47031. var StickValues = (function () {
  47032. function StickValues(x, y) {
  47033. this.x = x;
  47034. this.y = y;
  47035. }
  47036. return StickValues;
  47037. }());
  47038. BABYLON.StickValues = StickValues;
  47039. var Gamepad = (function () {
  47040. function Gamepad(id, index, browserGamepad, leftStickX, leftStickY, rightStickX, rightStickY) {
  47041. if (leftStickX === void 0) { leftStickX = 0; }
  47042. if (leftStickY === void 0) { leftStickY = 1; }
  47043. if (rightStickX === void 0) { rightStickX = 2; }
  47044. if (rightStickY === void 0) { rightStickY = 3; }
  47045. this.id = id;
  47046. this.index = index;
  47047. this.browserGamepad = browserGamepad;
  47048. this._leftStickAxisX = leftStickX;
  47049. this._leftStickAxisY = leftStickY;
  47050. this._rightStickAxisX = rightStickX;
  47051. this._rightStickAxisY = rightStickY;
  47052. if (this.browserGamepad.axes.length >= 2) {
  47053. this._leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  47054. }
  47055. if (this.browserGamepad.axes.length >= 4) {
  47056. this._rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  47057. }
  47058. }
  47059. Gamepad.prototype.onleftstickchanged = function (callback) {
  47060. this._onleftstickchanged = callback;
  47061. };
  47062. Gamepad.prototype.onrightstickchanged = function (callback) {
  47063. this._onrightstickchanged = callback;
  47064. };
  47065. Object.defineProperty(Gamepad.prototype, "leftStick", {
  47066. get: function () {
  47067. return this._leftStick;
  47068. },
  47069. set: function (newValues) {
  47070. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  47071. this._onleftstickchanged(newValues);
  47072. }
  47073. this._leftStick = newValues;
  47074. },
  47075. enumerable: true,
  47076. configurable: true
  47077. });
  47078. Object.defineProperty(Gamepad.prototype, "rightStick", {
  47079. get: function () {
  47080. return this._rightStick;
  47081. },
  47082. set: function (newValues) {
  47083. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  47084. this._onrightstickchanged(newValues);
  47085. }
  47086. this._rightStick = newValues;
  47087. },
  47088. enumerable: true,
  47089. configurable: true
  47090. });
  47091. Gamepad.prototype.update = function () {
  47092. if (this._leftStick) {
  47093. this.leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  47094. }
  47095. if (this._rightStick) {
  47096. this.rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  47097. }
  47098. };
  47099. return Gamepad;
  47100. }());
  47101. BABYLON.Gamepad = Gamepad;
  47102. var GenericPad = (function (_super) {
  47103. __extends(GenericPad, _super);
  47104. function GenericPad(id, index, gamepad) {
  47105. var _this = _super.call(this, id, index, gamepad) || this;
  47106. _this.id = id;
  47107. _this.index = index;
  47108. _this.gamepad = gamepad;
  47109. _this._buttons = new Array(gamepad.buttons.length);
  47110. return _this;
  47111. }
  47112. GenericPad.prototype.onbuttondown = function (callback) {
  47113. this._onbuttondown = callback;
  47114. };
  47115. GenericPad.prototype.onbuttonup = function (callback) {
  47116. this._onbuttonup = callback;
  47117. };
  47118. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  47119. if (newValue !== currentValue) {
  47120. if (this._onbuttondown && newValue === 1) {
  47121. this._onbuttondown(buttonIndex);
  47122. }
  47123. if (this._onbuttonup && newValue === 0) {
  47124. this._onbuttonup(buttonIndex);
  47125. }
  47126. }
  47127. return newValue;
  47128. };
  47129. GenericPad.prototype.update = function () {
  47130. _super.prototype.update.call(this);
  47131. for (var index = 0; index < this._buttons.length; index++) {
  47132. this._buttons[index] = this._setButtonValue(this.gamepad.buttons[index].value, this._buttons[index], index);
  47133. }
  47134. };
  47135. return GenericPad;
  47136. }(Gamepad));
  47137. BABYLON.GenericPad = GenericPad;
  47138. var Xbox360Button;
  47139. (function (Xbox360Button) {
  47140. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  47141. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  47142. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  47143. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  47144. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  47145. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  47146. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  47147. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  47148. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  47149. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  47150. })(Xbox360Button = BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  47151. var Xbox360Dpad;
  47152. (function (Xbox360Dpad) {
  47153. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  47154. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  47155. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  47156. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  47157. })(Xbox360Dpad = BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  47158. var Xbox360Pad = (function (_super) {
  47159. __extends(Xbox360Pad, _super);
  47160. function Xbox360Pad(id, index, gamepad, xboxOne) {
  47161. if (xboxOne === void 0) { xboxOne = false; }
  47162. var _this = _super.call(this, id, index, gamepad, 0, 1, (xboxOne ? 3 : 2), (xboxOne ? 4 : 3)) || this;
  47163. _this._leftTrigger = 0;
  47164. _this._rightTrigger = 0;
  47165. _this._buttonA = 0;
  47166. _this._buttonB = 0;
  47167. _this._buttonX = 0;
  47168. _this._buttonY = 0;
  47169. _this._buttonBack = 0;
  47170. _this._buttonStart = 0;
  47171. _this._buttonLB = 0;
  47172. _this._buttonRB = 0;
  47173. _this._buttonLeftStick = 0;
  47174. _this._buttonRightStick = 0;
  47175. _this._dPadUp = 0;
  47176. _this._dPadDown = 0;
  47177. _this._dPadLeft = 0;
  47178. _this._dPadRight = 0;
  47179. _this._isXboxOnePad = false;
  47180. _this._isXboxOnePad = xboxOne;
  47181. return _this;
  47182. }
  47183. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  47184. this._onlefttriggerchanged = callback;
  47185. };
  47186. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  47187. this._onrighttriggerchanged = callback;
  47188. };
  47189. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  47190. get: function () {
  47191. return this._leftTrigger;
  47192. },
  47193. set: function (newValue) {
  47194. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  47195. this._onlefttriggerchanged(newValue);
  47196. }
  47197. this._leftTrigger = newValue;
  47198. },
  47199. enumerable: true,
  47200. configurable: true
  47201. });
  47202. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  47203. get: function () {
  47204. return this._rightTrigger;
  47205. },
  47206. set: function (newValue) {
  47207. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  47208. this._onrighttriggerchanged(newValue);
  47209. }
  47210. this._rightTrigger = newValue;
  47211. },
  47212. enumerable: true,
  47213. configurable: true
  47214. });
  47215. Xbox360Pad.prototype.onbuttondown = function (callback) {
  47216. this._onbuttondown = callback;
  47217. };
  47218. Xbox360Pad.prototype.onbuttonup = function (callback) {
  47219. this._onbuttonup = callback;
  47220. };
  47221. Xbox360Pad.prototype.ondpaddown = function (callback) {
  47222. this._ondpaddown = callback;
  47223. };
  47224. Xbox360Pad.prototype.ondpadup = function (callback) {
  47225. this._ondpadup = callback;
  47226. };
  47227. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  47228. if (newValue !== currentValue) {
  47229. if (this._onbuttondown && newValue === 1) {
  47230. this._onbuttondown(buttonType);
  47231. }
  47232. if (this._onbuttonup && newValue === 0) {
  47233. this._onbuttonup(buttonType);
  47234. }
  47235. }
  47236. return newValue;
  47237. };
  47238. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  47239. if (newValue !== currentValue) {
  47240. if (this._ondpaddown && newValue === 1) {
  47241. this._ondpaddown(buttonType);
  47242. }
  47243. if (this._ondpadup && newValue === 0) {
  47244. this._ondpadup(buttonType);
  47245. }
  47246. }
  47247. return newValue;
  47248. };
  47249. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  47250. get: function () {
  47251. return this._buttonA;
  47252. },
  47253. set: function (value) {
  47254. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  47255. },
  47256. enumerable: true,
  47257. configurable: true
  47258. });
  47259. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  47260. get: function () {
  47261. return this._buttonB;
  47262. },
  47263. set: function (value) {
  47264. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  47265. },
  47266. enumerable: true,
  47267. configurable: true
  47268. });
  47269. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  47270. get: function () {
  47271. return this._buttonX;
  47272. },
  47273. set: function (value) {
  47274. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  47275. },
  47276. enumerable: true,
  47277. configurable: true
  47278. });
  47279. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  47280. get: function () {
  47281. return this._buttonY;
  47282. },
  47283. set: function (value) {
  47284. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  47285. },
  47286. enumerable: true,
  47287. configurable: true
  47288. });
  47289. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  47290. get: function () {
  47291. return this._buttonStart;
  47292. },
  47293. set: function (value) {
  47294. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  47295. },
  47296. enumerable: true,
  47297. configurable: true
  47298. });
  47299. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  47300. get: function () {
  47301. return this._buttonBack;
  47302. },
  47303. set: function (value) {
  47304. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  47305. },
  47306. enumerable: true,
  47307. configurable: true
  47308. });
  47309. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  47310. get: function () {
  47311. return this._buttonLB;
  47312. },
  47313. set: function (value) {
  47314. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  47315. },
  47316. enumerable: true,
  47317. configurable: true
  47318. });
  47319. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  47320. get: function () {
  47321. return this._buttonRB;
  47322. },
  47323. set: function (value) {
  47324. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  47325. },
  47326. enumerable: true,
  47327. configurable: true
  47328. });
  47329. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  47330. get: function () {
  47331. return this._buttonLeftStick;
  47332. },
  47333. set: function (value) {
  47334. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  47335. },
  47336. enumerable: true,
  47337. configurable: true
  47338. });
  47339. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  47340. get: function () {
  47341. return this._buttonRightStick;
  47342. },
  47343. set: function (value) {
  47344. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  47345. },
  47346. enumerable: true,
  47347. configurable: true
  47348. });
  47349. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  47350. get: function () {
  47351. return this._dPadUp;
  47352. },
  47353. set: function (value) {
  47354. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  47355. },
  47356. enumerable: true,
  47357. configurable: true
  47358. });
  47359. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  47360. get: function () {
  47361. return this._dPadDown;
  47362. },
  47363. set: function (value) {
  47364. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  47365. },
  47366. enumerable: true,
  47367. configurable: true
  47368. });
  47369. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  47370. get: function () {
  47371. return this._dPadLeft;
  47372. },
  47373. set: function (value) {
  47374. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  47375. },
  47376. enumerable: true,
  47377. configurable: true
  47378. });
  47379. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  47380. get: function () {
  47381. return this._dPadRight;
  47382. },
  47383. set: function (value) {
  47384. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  47385. },
  47386. enumerable: true,
  47387. configurable: true
  47388. });
  47389. Xbox360Pad.prototype.update = function () {
  47390. _super.prototype.update.call(this);
  47391. if (this._isXboxOnePad) {
  47392. this.buttonA = this.browserGamepad.buttons[0].value;
  47393. this.buttonB = this.browserGamepad.buttons[1].value;
  47394. this.buttonX = this.browserGamepad.buttons[2].value;
  47395. this.buttonY = this.browserGamepad.buttons[3].value;
  47396. this.buttonLB = this.browserGamepad.buttons[4].value;
  47397. this.buttonRB = this.browserGamepad.buttons[5].value;
  47398. this.leftTrigger = this.browserGamepad.axes[2];
  47399. this.rightTrigger = this.browserGamepad.axes[5];
  47400. this.buttonBack = this.browserGamepad.buttons[9].value;
  47401. this.buttonStart = this.browserGamepad.buttons[8].value;
  47402. this.buttonLeftStick = this.browserGamepad.buttons[6].value;
  47403. this.buttonRightStick = this.browserGamepad.buttons[7].value;
  47404. this.dPadUp = this.browserGamepad.buttons[11].value;
  47405. this.dPadDown = this.browserGamepad.buttons[12].value;
  47406. this.dPadLeft = this.browserGamepad.buttons[13].value;
  47407. this.dPadRight = this.browserGamepad.buttons[14].value;
  47408. }
  47409. else {
  47410. this.buttonA = this.browserGamepad.buttons[0].value;
  47411. this.buttonB = this.browserGamepad.buttons[1].value;
  47412. this.buttonX = this.browserGamepad.buttons[2].value;
  47413. this.buttonY = this.browserGamepad.buttons[3].value;
  47414. this.buttonLB = this.browserGamepad.buttons[4].value;
  47415. this.buttonRB = this.browserGamepad.buttons[5].value;
  47416. this.leftTrigger = this.browserGamepad.buttons[6].value;
  47417. this.rightTrigger = this.browserGamepad.buttons[7].value;
  47418. this.buttonBack = this.browserGamepad.buttons[8].value;
  47419. this.buttonStart = this.browserGamepad.buttons[9].value;
  47420. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  47421. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  47422. this.dPadUp = this.browserGamepad.buttons[12].value;
  47423. this.dPadDown = this.browserGamepad.buttons[13].value;
  47424. this.dPadLeft = this.browserGamepad.buttons[14].value;
  47425. this.dPadRight = this.browserGamepad.buttons[15].value;
  47426. }
  47427. };
  47428. return Xbox360Pad;
  47429. }(Gamepad));
  47430. BABYLON.Xbox360Pad = Xbox360Pad;
  47431. })(BABYLON || (BABYLON = {}));
  47432. //# sourceMappingURL=babylon.gamepads.js.map
  47433. var BABYLON;
  47434. (function (BABYLON) {
  47435. // We're mainly based on the logic defined into the FreeCamera code
  47436. var GamepadCamera = (function (_super) {
  47437. __extends(GamepadCamera, _super);
  47438. //-- end properties for backward compatibility for inputs
  47439. function GamepadCamera(name, position, scene) {
  47440. var _this;
  47441. BABYLON.Tools.Warn("Deprecated. Please use Universal Camera instead.");
  47442. _this = _super.call(this, name, position, scene) || this;
  47443. return _this;
  47444. }
  47445. Object.defineProperty(GamepadCamera.prototype, "gamepadAngularSensibility", {
  47446. //-- Begin properties for backward compatibility for inputs
  47447. get: function () {
  47448. var gamepad = this.inputs.attached["gamepad"];
  47449. if (gamepad)
  47450. return gamepad.gamepadAngularSensibility;
  47451. },
  47452. set: function (value) {
  47453. var gamepad = this.inputs.attached["gamepad"];
  47454. if (gamepad)
  47455. gamepad.gamepadAngularSensibility = value;
  47456. },
  47457. enumerable: true,
  47458. configurable: true
  47459. });
  47460. Object.defineProperty(GamepadCamera.prototype, "gamepadMoveSensibility", {
  47461. get: function () {
  47462. var gamepad = this.inputs.attached["gamepad"];
  47463. if (gamepad)
  47464. return gamepad.gamepadMoveSensibility;
  47465. },
  47466. set: function (value) {
  47467. var gamepad = this.inputs.attached["gamepad"];
  47468. if (gamepad)
  47469. gamepad.gamepadMoveSensibility = value;
  47470. },
  47471. enumerable: true,
  47472. configurable: true
  47473. });
  47474. GamepadCamera.prototype.getClassName = function () {
  47475. return "GamepadCamera";
  47476. };
  47477. return GamepadCamera;
  47478. }(BABYLON.UniversalCamera));
  47479. BABYLON.GamepadCamera = GamepadCamera;
  47480. })(BABYLON || (BABYLON = {}));
  47481. //# sourceMappingURL=babylon.gamepadCamera.js.map
  47482. var BABYLON;
  47483. (function (BABYLON) {
  47484. var Analyser = (function () {
  47485. function Analyser(scene) {
  47486. this.SMOOTHING = 0.75;
  47487. this.FFT_SIZE = 512;
  47488. this.BARGRAPHAMPLITUDE = 256;
  47489. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  47490. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  47491. this._scene = scene;
  47492. this._audioEngine = BABYLON.Engine.audioEngine;
  47493. if (this._audioEngine.canUseWebAudio) {
  47494. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  47495. this._webAudioAnalyser.minDecibels = -140;
  47496. this._webAudioAnalyser.maxDecibels = 0;
  47497. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  47498. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  47499. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  47500. }
  47501. }
  47502. Analyser.prototype.getFrequencyBinCount = function () {
  47503. if (this._audioEngine.canUseWebAudio) {
  47504. return this._webAudioAnalyser.frequencyBinCount;
  47505. }
  47506. else {
  47507. return 0;
  47508. }
  47509. };
  47510. Analyser.prototype.getByteFrequencyData = function () {
  47511. if (this._audioEngine.canUseWebAudio) {
  47512. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  47513. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  47514. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  47515. }
  47516. return this._byteFreqs;
  47517. };
  47518. Analyser.prototype.getByteTimeDomainData = function () {
  47519. if (this._audioEngine.canUseWebAudio) {
  47520. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  47521. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  47522. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  47523. }
  47524. return this._byteTime;
  47525. };
  47526. Analyser.prototype.getFloatFrequencyData = function () {
  47527. if (this._audioEngine.canUseWebAudio) {
  47528. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  47529. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  47530. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  47531. }
  47532. return this._floatFreqs;
  47533. };
  47534. Analyser.prototype.drawDebugCanvas = function () {
  47535. var _this = this;
  47536. if (this._audioEngine.canUseWebAudio) {
  47537. if (!this._debugCanvas) {
  47538. this._debugCanvas = document.createElement("canvas");
  47539. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  47540. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  47541. this._debugCanvas.style.position = "absolute";
  47542. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  47543. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  47544. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  47545. document.body.appendChild(this._debugCanvas);
  47546. this._registerFunc = function () {
  47547. _this.drawDebugCanvas();
  47548. };
  47549. this._scene.registerBeforeRender(this._registerFunc);
  47550. }
  47551. if (this._registerFunc) {
  47552. var workingArray = this.getByteFrequencyData();
  47553. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  47554. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  47555. // Draw the frequency domain chart.
  47556. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  47557. var value = workingArray[i];
  47558. var percent = value / this.BARGRAPHAMPLITUDE;
  47559. var height = this.DEBUGCANVASSIZE.height * percent;
  47560. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  47561. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  47562. var hue = i / this.getFrequencyBinCount() * 360;
  47563. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  47564. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  47565. }
  47566. }
  47567. }
  47568. };
  47569. Analyser.prototype.stopDebugCanvas = function () {
  47570. if (this._debugCanvas) {
  47571. this._scene.unregisterBeforeRender(this._registerFunc);
  47572. this._registerFunc = null;
  47573. document.body.removeChild(this._debugCanvas);
  47574. this._debugCanvas = null;
  47575. this._debugCanvasContext = null;
  47576. }
  47577. };
  47578. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  47579. if (this._audioEngine.canUseWebAudio) {
  47580. inputAudioNode.connect(this._webAudioAnalyser);
  47581. this._webAudioAnalyser.connect(outputAudioNode);
  47582. }
  47583. };
  47584. Analyser.prototype.dispose = function () {
  47585. if (this._audioEngine.canUseWebAudio) {
  47586. this._webAudioAnalyser.disconnect();
  47587. }
  47588. };
  47589. return Analyser;
  47590. }());
  47591. BABYLON.Analyser = Analyser;
  47592. })(BABYLON || (BABYLON = {}));
  47593. //# sourceMappingURL=babylon.analyser.js.map
  47594. var BABYLON;
  47595. (function (BABYLON) {
  47596. var DepthRenderer = (function () {
  47597. function DepthRenderer(scene, type) {
  47598. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  47599. var _this = this;
  47600. this._viewMatrix = BABYLON.Matrix.Zero();
  47601. this._projectionMatrix = BABYLON.Matrix.Zero();
  47602. this._transformMatrix = BABYLON.Matrix.Zero();
  47603. this._worldViewProjection = BABYLON.Matrix.Zero();
  47604. this._scene = scene;
  47605. var engine = scene.getEngine();
  47606. // Render target
  47607. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  47608. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  47609. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  47610. this._depthMap.refreshRate = 1;
  47611. this._depthMap.renderParticles = false;
  47612. this._depthMap.renderList = null;
  47613. // set default depth value to 1.0 (far away)
  47614. this._depthMap.onClearObservable.add(function (engine) {
  47615. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  47616. });
  47617. // Custom render function
  47618. var renderSubMesh = function (subMesh) {
  47619. var mesh = subMesh.getRenderingMesh();
  47620. var scene = _this._scene;
  47621. var engine = scene.getEngine();
  47622. // Culling
  47623. engine.setState(subMesh.getMaterial().backFaceCulling);
  47624. // Managing instances
  47625. var batch = mesh._getInstancesRenderList(subMesh._id);
  47626. if (batch.mustReturn) {
  47627. return;
  47628. }
  47629. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  47630. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  47631. engine.enableEffect(_this._effect);
  47632. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  47633. var material = subMesh.getMaterial();
  47634. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  47635. _this._effect.setFloat("far", scene.activeCamera.maxZ);
  47636. // Alpha test
  47637. if (material && material.needAlphaTesting()) {
  47638. var alphaTexture = material.getAlphaTestTexture();
  47639. _this._effect.setTexture("diffuseSampler", alphaTexture);
  47640. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  47641. }
  47642. // Bones
  47643. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  47644. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  47645. }
  47646. // Draw
  47647. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  47648. }
  47649. };
  47650. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes) {
  47651. var index;
  47652. for (index = 0; index < opaqueSubMeshes.length; index++) {
  47653. renderSubMesh(opaqueSubMeshes.data[index]);
  47654. }
  47655. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  47656. renderSubMesh(alphaTestSubMeshes.data[index]);
  47657. }
  47658. };
  47659. }
  47660. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  47661. var material = subMesh.getMaterial();
  47662. if (material.disableDepthWrite) {
  47663. return false;
  47664. }
  47665. var defines = [];
  47666. var attribs = [BABYLON.VertexBuffer.PositionKind];
  47667. var mesh = subMesh.getMesh();
  47668. var scene = mesh.getScene();
  47669. // Alpha test
  47670. if (material && material.needAlphaTesting()) {
  47671. defines.push("#define ALPHATEST");
  47672. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  47673. attribs.push(BABYLON.VertexBuffer.UVKind);
  47674. defines.push("#define UV1");
  47675. }
  47676. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  47677. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  47678. defines.push("#define UV2");
  47679. }
  47680. }
  47681. // Bones
  47682. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  47683. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  47684. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  47685. if (mesh.numBoneInfluencers > 4) {
  47686. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  47687. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  47688. }
  47689. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  47690. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  47691. }
  47692. else {
  47693. defines.push("#define NUM_BONE_INFLUENCERS 0");
  47694. }
  47695. // Instances
  47696. if (useInstances) {
  47697. defines.push("#define INSTANCES");
  47698. attribs.push("world0");
  47699. attribs.push("world1");
  47700. attribs.push("world2");
  47701. attribs.push("world3");
  47702. }
  47703. // Get correct effect
  47704. var join = defines.join("\n");
  47705. if (this._cachedDefines !== join) {
  47706. this._cachedDefines = join;
  47707. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "far"], ["diffuseSampler"], join);
  47708. }
  47709. return this._effect.isReady();
  47710. };
  47711. DepthRenderer.prototype.getDepthMap = function () {
  47712. return this._depthMap;
  47713. };
  47714. // Methods
  47715. DepthRenderer.prototype.dispose = function () {
  47716. this._depthMap.dispose();
  47717. };
  47718. return DepthRenderer;
  47719. }());
  47720. BABYLON.DepthRenderer = DepthRenderer;
  47721. })(BABYLON || (BABYLON = {}));
  47722. //# sourceMappingURL=babylon.depthRenderer.js.map
  47723. var BABYLON;
  47724. (function (BABYLON) {
  47725. var SSAORenderingPipeline = (function (_super) {
  47726. __extends(SSAORenderingPipeline, _super);
  47727. /**
  47728. * @constructor
  47729. * @param {string} name - The rendering pipeline name
  47730. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  47731. * @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 }
  47732. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  47733. */
  47734. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  47735. var _this = _super.call(this, scene.getEngine(), name) || this;
  47736. // Members
  47737. /**
  47738. * The PassPostProcess id in the pipeline that contains the original scene color
  47739. * @type {string}
  47740. */
  47741. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  47742. /**
  47743. * The SSAO PostProcess id in the pipeline
  47744. * @type {string}
  47745. */
  47746. _this.SSAORenderEffect = "SSAORenderEffect";
  47747. /**
  47748. * The horizontal blur PostProcess id in the pipeline
  47749. * @type {string}
  47750. */
  47751. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  47752. /**
  47753. * The vertical blur PostProcess id in the pipeline
  47754. * @type {string}
  47755. */
  47756. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  47757. /**
  47758. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  47759. * @type {string}
  47760. */
  47761. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  47762. /**
  47763. * The output strength of the SSAO post-process. Default value is 1.0.
  47764. * @type {number}
  47765. */
  47766. _this.totalStrength = 1.0;
  47767. /**
  47768. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  47769. * @type {number}
  47770. */
  47771. _this.radius = 0.0001;
  47772. /**
  47773. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  47774. * Must not be equal to fallOff and superior to fallOff.
  47775. * Default value is 0.975
  47776. * @type {number}
  47777. */
  47778. _this.area = 0.0075;
  47779. /**
  47780. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  47781. * Must not be equal to area and inferior to area.
  47782. * Default value is 0.0
  47783. * @type {number}
  47784. */
  47785. _this.fallOff = 0.000001;
  47786. /**
  47787. * The base color of the SSAO post-process
  47788. * The final result is "base + ssao" between [0, 1]
  47789. * @type {number}
  47790. */
  47791. _this.base = 0.5;
  47792. _this._firstUpdate = true;
  47793. _this._scene = scene;
  47794. // Set up assets
  47795. _this._createRandomTexture();
  47796. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  47797. var ssaoRatio = ratio.ssaoRatio || ratio;
  47798. var combineRatio = ratio.combineRatio || ratio;
  47799. _this._ratio = {
  47800. ssaoRatio: ssaoRatio,
  47801. combineRatio: combineRatio
  47802. };
  47803. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  47804. _this._createSSAOPostProcess(ssaoRatio);
  47805. _this._createBlurPostProcess(ssaoRatio);
  47806. _this._createSSAOCombinePostProcess(combineRatio);
  47807. // Set up pipeline
  47808. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  47809. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  47810. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  47811. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  47812. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  47813. // Finish
  47814. scene.postProcessRenderPipelineManager.addPipeline(_this);
  47815. if (cameras)
  47816. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  47817. return _this;
  47818. }
  47819. // Public Methods
  47820. /**
  47821. * Returns the horizontal blur PostProcess
  47822. * @return {BABYLON.BlurPostProcess} The horizontal blur post-process
  47823. */
  47824. SSAORenderingPipeline.prototype.getBlurHPostProcess = function () {
  47825. BABYLON.Tools.Error("SSAORenderinPipeline.getBlurHPostProcess() is deprecated, no more blur post-process exists");
  47826. return null;
  47827. };
  47828. /**
  47829. * Returns the vertical blur PostProcess
  47830. * @return {BABYLON.BlurPostProcess} The vertical blur post-process
  47831. */
  47832. SSAORenderingPipeline.prototype.getBlurVPostProcess = function () {
  47833. BABYLON.Tools.Error("SSAORenderinPipeline.getBlurVPostProcess() is deprecated, no more blur post-process exists");
  47834. return null;
  47835. };
  47836. /**
  47837. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  47838. */
  47839. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  47840. if (disableDepthRender === void 0) { disableDepthRender = false; }
  47841. for (var i = 0; i < this._scene.cameras.length; i++) {
  47842. var camera = this._scene.cameras[i];
  47843. this._originalColorPostProcess.dispose(camera);
  47844. this._ssaoPostProcess.dispose(camera);
  47845. this._blurHPostProcess.dispose(camera);
  47846. this._blurVPostProcess.dispose(camera);
  47847. this._ssaoCombinePostProcess.dispose(camera);
  47848. }
  47849. this._randomTexture.dispose();
  47850. if (disableDepthRender)
  47851. this._scene.disableDepthRenderer();
  47852. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  47853. _super.prototype.dispose.call(this);
  47854. };
  47855. // Private Methods
  47856. SSAORenderingPipeline.prototype._createBlurPostProcess = function (ratio) {
  47857. var _this = this;
  47858. /*
  47859. var samplerOffsets = [
  47860. -8.0, -6.0, -4.0, -2.0,
  47861. 0.0,
  47862. 2.0, 4.0, 6.0, 8.0
  47863. ];
  47864. */
  47865. var samples = 16;
  47866. var samplerOffsets = [];
  47867. for (var i = -8; i < 8; i++) {
  47868. samplerOffsets.push(i * 2);
  47869. }
  47870. 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");
  47871. this._blurHPostProcess.onApply = function (effect) {
  47872. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width);
  47873. effect.setTexture("depthSampler", _this._depthTexture);
  47874. if (_this._firstUpdate) {
  47875. effect.setArray("samplerOffsets", samplerOffsets);
  47876. }
  47877. };
  47878. 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");
  47879. this._blurVPostProcess.onApply = function (effect) {
  47880. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height);
  47881. effect.setTexture("depthSampler", _this._depthTexture);
  47882. if (_this._firstUpdate) {
  47883. effect.setArray("samplerOffsets", samplerOffsets);
  47884. _this._firstUpdate = false;
  47885. }
  47886. };
  47887. };
  47888. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  47889. var _this = this;
  47890. var numSamples = 16;
  47891. var sampleSphere = [
  47892. 0.5381, 0.1856, -0.4319,
  47893. 0.1379, 0.2486, 0.4430,
  47894. 0.3371, 0.5679, -0.0057,
  47895. -0.6999, -0.0451, -0.0019,
  47896. 0.0689, -0.1598, -0.8547,
  47897. 0.0560, 0.0069, -0.1843,
  47898. -0.0146, 0.1402, 0.0762,
  47899. 0.0100, -0.1924, -0.0344,
  47900. -0.3577, -0.5301, -0.4358,
  47901. -0.3169, 0.1063, 0.0158,
  47902. 0.0103, -0.5869, 0.0046,
  47903. -0.0897, -0.4940, 0.3287,
  47904. 0.7119, -0.0154, -0.0918,
  47905. -0.0533, 0.0596, -0.5411,
  47906. 0.0352, -0.0631, 0.5460,
  47907. -0.4776, 0.2847, -0.0271
  47908. ];
  47909. var samplesFactor = 1.0 / numSamples;
  47910. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  47911. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  47912. "area", "fallOff", "base", "range", "viewport"
  47913. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  47914. var viewport = new BABYLON.Vector2(0, 0);
  47915. this._ssaoPostProcess.onApply = function (effect) {
  47916. if (_this._firstUpdate) {
  47917. effect.setArray3("sampleSphere", sampleSphere);
  47918. effect.setFloat("samplesFactor", samplesFactor);
  47919. effect.setFloat("randTextureTiles", 4.0);
  47920. }
  47921. effect.setFloat("totalStrength", _this.totalStrength);
  47922. effect.setFloat("radius", _this.radius);
  47923. effect.setFloat("area", _this.area);
  47924. effect.setFloat("fallOff", _this.fallOff);
  47925. effect.setFloat("base", _this.base);
  47926. effect.setTexture("textureSampler", _this._depthTexture);
  47927. effect.setTexture("randomSampler", _this._randomTexture);
  47928. };
  47929. };
  47930. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  47931. var _this = this;
  47932. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  47933. this._ssaoCombinePostProcess.onApply = function (effect) {
  47934. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  47935. };
  47936. };
  47937. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  47938. var size = 512;
  47939. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  47940. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  47941. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  47942. var context = this._randomTexture.getContext();
  47943. var rand = function (min, max) {
  47944. return Math.random() * (max - min) + min;
  47945. };
  47946. var randVector = BABYLON.Vector3.Zero();
  47947. for (var x = 0; x < size; x++) {
  47948. for (var y = 0; y < size; y++) {
  47949. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  47950. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  47951. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  47952. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  47953. context.fillRect(x, y, 1, 1);
  47954. }
  47955. }
  47956. this._randomTexture.update(false);
  47957. };
  47958. return SSAORenderingPipeline;
  47959. }(BABYLON.PostProcessRenderPipeline));
  47960. __decorate([
  47961. BABYLON.serialize()
  47962. ], SSAORenderingPipeline.prototype, "totalStrength", void 0);
  47963. __decorate([
  47964. BABYLON.serialize()
  47965. ], SSAORenderingPipeline.prototype, "radius", void 0);
  47966. __decorate([
  47967. BABYLON.serialize()
  47968. ], SSAORenderingPipeline.prototype, "area", void 0);
  47969. __decorate([
  47970. BABYLON.serialize()
  47971. ], SSAORenderingPipeline.prototype, "fallOff", void 0);
  47972. __decorate([
  47973. BABYLON.serialize()
  47974. ], SSAORenderingPipeline.prototype, "base", void 0);
  47975. __decorate([
  47976. BABYLON.serialize()
  47977. ], SSAORenderingPipeline.prototype, "_ratio", void 0);
  47978. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  47979. })(BABYLON || (BABYLON = {}));
  47980. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  47981. var BABYLON;
  47982. (function (BABYLON) {
  47983. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  47984. var VolumetricLightScatteringPostProcess = (function (_super) {
  47985. __extends(VolumetricLightScatteringPostProcess, _super);
  47986. /**
  47987. * @constructor
  47988. * @param {string} name - The post-process name
  47989. * @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)
  47990. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  47991. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  47992. * @param {number} samples - The post-process quality, default 100
  47993. * @param {number} samplingMode - The post-process filtering mode
  47994. * @param {BABYLON.Engine} engine - The babylon engine
  47995. * @param {boolean} reusable - If the post-process is reusable
  47996. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  47997. */
  47998. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  47999. if (samples === void 0) { samples = 100; }
  48000. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  48001. 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;
  48002. _this._screenCoordinates = BABYLON.Vector2.Zero();
  48003. /**
  48004. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  48005. * @type {Vector3}
  48006. */
  48007. _this.customMeshPosition = BABYLON.Vector3.Zero();
  48008. /**
  48009. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  48010. * @type {boolean}
  48011. */
  48012. _this.useCustomMeshPosition = false;
  48013. /**
  48014. * If the post-process should inverse the light scattering direction
  48015. * @type {boolean}
  48016. */
  48017. _this.invert = true;
  48018. /**
  48019. * Array containing the excluded meshes not rendered in the internal pass
  48020. */
  48021. _this.excludedMeshes = new Array();
  48022. /**
  48023. * Controls the overall intensity of the post-process
  48024. * @type {number}
  48025. */
  48026. _this.exposure = 0.3;
  48027. /**
  48028. * Dissipates each sample's contribution in range [0, 1]
  48029. * @type {number}
  48030. */
  48031. _this.decay = 0.96815;
  48032. /**
  48033. * Controls the overall intensity of each sample
  48034. * @type {number}
  48035. */
  48036. _this.weight = 0.58767;
  48037. /**
  48038. * Controls the density of each sample
  48039. * @type {number}
  48040. */
  48041. _this.density = 0.926;
  48042. scene = (camera === null) ? scene : camera.getScene(); // parameter "scene" can be null.
  48043. var engine = scene.getEngine();
  48044. _this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  48045. // Configure mesh
  48046. _this.mesh = (mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene);
  48047. // Configure
  48048. _this._createPass(scene, ratio.passRatio || ratio);
  48049. _this.onActivate = function (camera) {
  48050. if (!_this.isSupported) {
  48051. _this.dispose(camera);
  48052. }
  48053. _this.onActivate = null;
  48054. };
  48055. _this.onApplyObservable.add(function (effect) {
  48056. _this._updateMeshScreenCoordinates(scene);
  48057. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  48058. effect.setFloat("exposure", _this.exposure);
  48059. effect.setFloat("decay", _this.decay);
  48060. effect.setFloat("weight", _this.weight);
  48061. effect.setFloat("density", _this.density);
  48062. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  48063. });
  48064. return _this;
  48065. }
  48066. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  48067. get: function () {
  48068. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  48069. return false;
  48070. },
  48071. set: function (useDiffuseColor) {
  48072. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  48073. },
  48074. enumerable: true,
  48075. configurable: true
  48076. });
  48077. VolumetricLightScatteringPostProcess.prototype.isReady = function (subMesh, useInstances) {
  48078. var mesh = subMesh.getMesh();
  48079. // Render this.mesh as default
  48080. if (mesh === this.mesh) {
  48081. return mesh.material.isReady(mesh);
  48082. }
  48083. var defines = [];
  48084. var attribs = [BABYLON.VertexBuffer.PositionKind];
  48085. var material = subMesh.getMaterial();
  48086. var needUV = false;
  48087. // Alpha test
  48088. if (material) {
  48089. if (material.needAlphaTesting()) {
  48090. defines.push("#define ALPHATEST");
  48091. }
  48092. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  48093. attribs.push(BABYLON.VertexBuffer.UVKind);
  48094. defines.push("#define UV1");
  48095. }
  48096. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  48097. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  48098. defines.push("#define UV2");
  48099. }
  48100. }
  48101. // Bones
  48102. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  48103. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  48104. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  48105. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  48106. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  48107. }
  48108. else {
  48109. defines.push("#define NUM_BONE_INFLUENCERS 0");
  48110. }
  48111. // Instances
  48112. if (useInstances) {
  48113. defines.push("#define INSTANCES");
  48114. attribs.push("world0");
  48115. attribs.push("world1");
  48116. attribs.push("world2");
  48117. attribs.push("world3");
  48118. }
  48119. // Get correct effect
  48120. var join = defines.join("\n");
  48121. if (this._cachedDefines !== join) {
  48122. this._cachedDefines = join;
  48123. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  48124. }
  48125. return this._volumetricLightScatteringPass.isReady();
  48126. };
  48127. /**
  48128. * Sets the new light position for light scattering effect
  48129. * @param {BABYLON.Vector3} The new custom light position
  48130. */
  48131. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  48132. this.customMeshPosition = position;
  48133. };
  48134. /**
  48135. * Returns the light position for light scattering effect
  48136. * @return {BABYLON.Vector3} The custom light position
  48137. */
  48138. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  48139. return this.customMeshPosition;
  48140. };
  48141. /**
  48142. * Disposes the internal assets and detaches the post-process from the camera
  48143. */
  48144. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  48145. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  48146. if (rttIndex !== -1) {
  48147. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  48148. }
  48149. this._volumetricLightScatteringRTT.dispose();
  48150. _super.prototype.dispose.call(this, camera);
  48151. };
  48152. /**
  48153. * Returns the render target texture used by the post-process
  48154. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  48155. */
  48156. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  48157. return this._volumetricLightScatteringRTT;
  48158. };
  48159. // Private methods
  48160. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  48161. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  48162. return true;
  48163. }
  48164. return false;
  48165. };
  48166. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  48167. var _this = this;
  48168. var engine = scene.getEngine();
  48169. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  48170. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  48171. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  48172. this._volumetricLightScatteringRTT.renderList = null;
  48173. this._volumetricLightScatteringRTT.renderParticles = false;
  48174. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  48175. // Custom render function for submeshes
  48176. var renderSubMesh = function (subMesh) {
  48177. var mesh = subMesh.getRenderingMesh();
  48178. if (_this._meshExcluded(mesh)) {
  48179. return;
  48180. }
  48181. var scene = mesh.getScene();
  48182. var engine = scene.getEngine();
  48183. // Culling
  48184. engine.setState(subMesh.getMaterial().backFaceCulling);
  48185. // Managing instances
  48186. var batch = mesh._getInstancesRenderList(subMesh._id);
  48187. if (batch.mustReturn) {
  48188. return;
  48189. }
  48190. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  48191. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  48192. var effect = _this._volumetricLightScatteringPass;
  48193. if (mesh === _this.mesh) {
  48194. effect = subMesh.getMaterial().getEffect();
  48195. }
  48196. engine.enableEffect(effect);
  48197. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  48198. if (mesh === _this.mesh) {
  48199. subMesh.getMaterial().bind(mesh.getWorldMatrix(), mesh);
  48200. }
  48201. else {
  48202. var material = subMesh.getMaterial();
  48203. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  48204. // Alpha test
  48205. if (material && material.needAlphaTesting()) {
  48206. var alphaTexture = material.getAlphaTestTexture();
  48207. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  48208. if (alphaTexture) {
  48209. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  48210. }
  48211. }
  48212. // Bones
  48213. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  48214. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  48215. }
  48216. }
  48217. // Draw
  48218. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  48219. }
  48220. };
  48221. // Render target texture callbacks
  48222. var savedSceneClearColor;
  48223. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  48224. this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function () {
  48225. savedSceneClearColor = scene.clearColor;
  48226. scene.clearColor = sceneClearColor;
  48227. });
  48228. this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function () {
  48229. scene.clearColor = savedSceneClearColor;
  48230. });
  48231. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  48232. var engine = scene.getEngine();
  48233. var index;
  48234. for (index = 0; index < opaqueSubMeshes.length; index++) {
  48235. renderSubMesh(opaqueSubMeshes.data[index]);
  48236. }
  48237. engine.setAlphaTesting(true);
  48238. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  48239. renderSubMesh(alphaTestSubMeshes.data[index]);
  48240. }
  48241. engine.setAlphaTesting(false);
  48242. if (transparentSubMeshes.length) {
  48243. // Sort sub meshes
  48244. for (index = 0; index < transparentSubMeshes.length; index++) {
  48245. var submesh = transparentSubMeshes.data[index];
  48246. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  48247. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  48248. }
  48249. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  48250. sortedArray.sort(function (a, b) {
  48251. // Alpha index first
  48252. if (a._alphaIndex > b._alphaIndex) {
  48253. return 1;
  48254. }
  48255. if (a._alphaIndex < b._alphaIndex) {
  48256. return -1;
  48257. }
  48258. // Then distance to camera
  48259. if (a._distanceToCamera < b._distanceToCamera) {
  48260. return 1;
  48261. }
  48262. if (a._distanceToCamera > b._distanceToCamera) {
  48263. return -1;
  48264. }
  48265. return 0;
  48266. });
  48267. // Render sub meshes
  48268. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  48269. for (index = 0; index < sortedArray.length; index++) {
  48270. renderSubMesh(sortedArray[index]);
  48271. }
  48272. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  48273. }
  48274. };
  48275. };
  48276. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  48277. var transform = scene.getTransformMatrix();
  48278. var meshPosition;
  48279. if (this.useCustomMeshPosition) {
  48280. meshPosition = this.customMeshPosition;
  48281. }
  48282. else if (this.attachedNode) {
  48283. meshPosition = this.attachedNode.position;
  48284. }
  48285. else {
  48286. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  48287. }
  48288. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  48289. this._screenCoordinates.x = pos.x / this._viewPort.width;
  48290. this._screenCoordinates.y = pos.y / this._viewPort.height;
  48291. if (this.invert)
  48292. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  48293. };
  48294. // Static methods
  48295. /**
  48296. * Creates a default mesh for the Volumeric Light Scattering post-process
  48297. * @param {string} The mesh name
  48298. * @param {BABYLON.Scene} The scene where to create the mesh
  48299. * @return {BABYLON.Mesh} the default mesh
  48300. */
  48301. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  48302. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  48303. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  48304. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  48305. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  48306. mesh.material = material;
  48307. return mesh;
  48308. };
  48309. return VolumetricLightScatteringPostProcess;
  48310. }(BABYLON.PostProcess));
  48311. __decorate([
  48312. BABYLON.serializeAsVector3()
  48313. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  48314. __decorate([
  48315. BABYLON.serialize()
  48316. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  48317. __decorate([
  48318. BABYLON.serialize()
  48319. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  48320. __decorate([
  48321. BABYLON.serializeAsMeshReference()
  48322. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  48323. __decorate([
  48324. BABYLON.serialize()
  48325. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  48326. __decorate([
  48327. BABYLON.serialize()
  48328. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  48329. __decorate([
  48330. BABYLON.serialize()
  48331. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  48332. __decorate([
  48333. BABYLON.serialize()
  48334. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  48335. __decorate([
  48336. BABYLON.serialize()
  48337. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  48338. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  48339. })(BABYLON || (BABYLON = {}));
  48340. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  48341. // BABYLON.JS Chromatic Aberration GLSL Shader
  48342. // Author: Olivier Guyot
  48343. // Separates very slightly R, G and B colors on the edges of the screen
  48344. // Inspired by Francois Tarlier & Martins Upitis
  48345. var BABYLON;
  48346. (function (BABYLON) {
  48347. var LensRenderingPipeline = (function (_super) {
  48348. __extends(LensRenderingPipeline, _super);
  48349. /**
  48350. * @constructor
  48351. *
  48352. * Effect parameters are as follow:
  48353. * {
  48354. * chromatic_aberration: number; // from 0 to x (1 for realism)
  48355. * edge_blur: number; // from 0 to x (1 for realism)
  48356. * distortion: number; // from 0 to x (1 for realism)
  48357. * grain_amount: number; // from 0 to 1
  48358. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  48359. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  48360. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  48361. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  48362. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  48363. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  48364. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  48365. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  48366. * }
  48367. * Note: if an effect parameter is unset, effect is disabled
  48368. *
  48369. * @param {string} name - The rendering pipeline name
  48370. * @param {object} parameters - An object containing all parameters (see above)
  48371. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  48372. * @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)
  48373. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  48374. */
  48375. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  48376. if (ratio === void 0) { ratio = 1.0; }
  48377. var _this = _super.call(this, scene.getEngine(), name) || this;
  48378. // Lens effects can be of the following:
  48379. // - chromatic aberration (slight shift of RGB colors)
  48380. // - blur on the edge of the lens
  48381. // - lens distortion
  48382. // - depth-of-field blur & highlights enhancing
  48383. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  48384. // - grain effect (noise or custom texture)
  48385. // Two additional texture samplers are needed:
  48386. // - depth map (for depth-of-field)
  48387. // - grain texture
  48388. /**
  48389. * The chromatic aberration PostProcess id in the pipeline
  48390. * @type {string}
  48391. */
  48392. _this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  48393. /**
  48394. * The highlights enhancing PostProcess id in the pipeline
  48395. * @type {string}
  48396. */
  48397. _this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  48398. /**
  48399. * The depth-of-field PostProcess id in the pipeline
  48400. * @type {string}
  48401. */
  48402. _this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  48403. _this._scene = scene;
  48404. // Fetch texture samplers
  48405. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  48406. if (parameters.grain_texture) {
  48407. _this._grainTexture = parameters.grain_texture;
  48408. }
  48409. else {
  48410. _this._createGrainTexture();
  48411. }
  48412. // save parameters
  48413. _this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  48414. _this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  48415. _this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  48416. _this._distortion = parameters.distortion ? parameters.distortion : 0;
  48417. _this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  48418. _this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  48419. _this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  48420. _this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  48421. _this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  48422. _this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  48423. _this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  48424. // Create effects
  48425. _this._createChromaticAberrationPostProcess(ratio);
  48426. _this._createHighlightsPostProcess(ratio);
  48427. _this._createDepthOfFieldPostProcess(ratio / 4);
  48428. // Set up pipeline
  48429. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  48430. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  48431. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  48432. if (_this._highlightsGain === -1) {
  48433. _this._disableEffect(_this.HighlightsEnhancingEffect, null);
  48434. }
  48435. // Finish
  48436. scene.postProcessRenderPipelineManager.addPipeline(_this);
  48437. if (cameras) {
  48438. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  48439. }
  48440. return _this;
  48441. }
  48442. // public methods (self explanatory)
  48443. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  48444. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  48445. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  48446. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  48447. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  48448. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  48449. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  48450. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  48451. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  48452. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  48453. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  48454. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  48455. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  48456. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  48457. };
  48458. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  48459. this._highlightsPostProcess.updateEffect();
  48460. };
  48461. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  48462. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  48463. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  48464. this._highlightsGain = amount;
  48465. };
  48466. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  48467. if (this._highlightsGain === -1) {
  48468. this._highlightsGain = 1.0;
  48469. }
  48470. this._highlightsThreshold = amount;
  48471. };
  48472. LensRenderingPipeline.prototype.disableHighlights = function () {
  48473. this._highlightsGain = -1;
  48474. };
  48475. /**
  48476. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  48477. */
  48478. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  48479. if (disableDepthRender === void 0) { disableDepthRender = false; }
  48480. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  48481. this._chromaticAberrationPostProcess = undefined;
  48482. this._highlightsPostProcess = undefined;
  48483. this._depthOfFieldPostProcess = undefined;
  48484. this._grainTexture.dispose();
  48485. if (disableDepthRender)
  48486. this._scene.disableDepthRenderer();
  48487. };
  48488. // colors shifting and distortion
  48489. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  48490. var _this = this;
  48491. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height"], // uniforms
  48492. [], // samplers
  48493. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  48494. this._chromaticAberrationPostProcess.onApply = function (effect) {
  48495. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  48496. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  48497. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  48498. };
  48499. };
  48500. // highlights enhancing
  48501. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  48502. var _this = this;
  48503. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  48504. [], // samplers
  48505. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  48506. this._highlightsPostProcess.onApply = function (effect) {
  48507. effect.setFloat('gain', _this._highlightsGain);
  48508. effect.setFloat('threshold', _this._highlightsThreshold);
  48509. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  48510. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  48511. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  48512. };
  48513. };
  48514. // colors shifting and distortion
  48515. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  48516. var _this = this;
  48517. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  48518. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  48519. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  48520. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  48521. this._depthOfFieldPostProcess.onApply = function (effect) {
  48522. effect.setTexture("depthSampler", _this._depthTexture);
  48523. effect.setTexture("grainSampler", _this._grainTexture);
  48524. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  48525. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  48526. effect.setFloat('grain_amount', _this._grainAmount);
  48527. effect.setBool('blur_noise', _this._blurNoise);
  48528. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  48529. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  48530. effect.setFloat('distortion', _this._distortion);
  48531. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  48532. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  48533. effect.setFloat('aperture', _this._dofAperture);
  48534. effect.setFloat('darken', _this._dofDarken);
  48535. effect.setFloat('edge_blur', _this._edgeBlur);
  48536. effect.setBool('highlights', (_this._highlightsGain !== -1));
  48537. effect.setFloat('near', _this._scene.activeCamera.minZ);
  48538. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  48539. };
  48540. };
  48541. // creates a black and white random noise texture, 512x512
  48542. LensRenderingPipeline.prototype._createGrainTexture = function () {
  48543. var size = 512;
  48544. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  48545. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  48546. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  48547. var context = this._grainTexture.getContext();
  48548. var rand = function (min, max) {
  48549. return Math.random() * (max - min) + min;
  48550. };
  48551. var value;
  48552. for (var x = 0; x < size; x++) {
  48553. for (var y = 0; y < size; y++) {
  48554. value = Math.floor(rand(0.42, 0.58) * 255);
  48555. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  48556. context.fillRect(x, y, 1, 1);
  48557. }
  48558. }
  48559. this._grainTexture.update(false);
  48560. };
  48561. return LensRenderingPipeline;
  48562. }(BABYLON.PostProcessRenderPipeline));
  48563. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  48564. })(BABYLON || (BABYLON = {}));
  48565. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map
  48566. //
  48567. // This post-process allows the modification of rendered colors by using
  48568. // a 'look-up table' (LUT). This effect is also called Color Grading.
  48569. //
  48570. // The object needs to be provided an url to a texture containing the color
  48571. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  48572. // Use an image editing software to tweak the LUT to match your needs.
  48573. //
  48574. // For an example of a color LUT, see here:
  48575. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  48576. // For explanations on color grading, see here:
  48577. // http://udn.epicgames.com/Three/ColorGrading.html
  48578. //
  48579. var BABYLON;
  48580. (function (BABYLON) {
  48581. var ColorCorrectionPostProcess = (function (_super) {
  48582. __extends(ColorCorrectionPostProcess, _super);
  48583. function ColorCorrectionPostProcess(name, colorTableUrl, options, camera, samplingMode, engine, reusable) {
  48584. var _this = _super.call(this, name, 'colorCorrection', null, ['colorTable'], options, camera, samplingMode, engine, reusable) || this;
  48585. _this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  48586. _this._colorTableTexture.anisotropicFilteringLevel = 1;
  48587. _this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  48588. _this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  48589. _this.onApply = function (effect) {
  48590. effect.setTexture("colorTable", _this._colorTableTexture);
  48591. };
  48592. return _this;
  48593. }
  48594. return ColorCorrectionPostProcess;
  48595. }(BABYLON.PostProcess));
  48596. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  48597. })(BABYLON || (BABYLON = {}));
  48598. //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.map
  48599. var BABYLON;
  48600. (function (BABYLON) {
  48601. var AnaglyphFreeCamera = (function (_super) {
  48602. __extends(AnaglyphFreeCamera, _super);
  48603. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  48604. var _this = _super.call(this, name, position, scene) || this;
  48605. _this.interaxialDistance = interaxialDistance;
  48606. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  48607. return _this;
  48608. }
  48609. AnaglyphFreeCamera.prototype.getClassName = function () {
  48610. return "AnaglyphFreeCamera";
  48611. };
  48612. return AnaglyphFreeCamera;
  48613. }(BABYLON.FreeCamera));
  48614. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  48615. var AnaglyphArcRotateCamera = (function (_super) {
  48616. __extends(AnaglyphArcRotateCamera, _super);
  48617. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  48618. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  48619. _this.interaxialDistance = interaxialDistance;
  48620. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  48621. return _this;
  48622. }
  48623. AnaglyphArcRotateCamera.prototype.getClassName = function () {
  48624. return "AnaglyphArcRotateCamera";
  48625. };
  48626. return AnaglyphArcRotateCamera;
  48627. }(BABYLON.ArcRotateCamera));
  48628. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  48629. var AnaglyphGamepadCamera = (function (_super) {
  48630. __extends(AnaglyphGamepadCamera, _super);
  48631. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  48632. var _this = _super.call(this, name, position, scene) || this;
  48633. _this.interaxialDistance = interaxialDistance;
  48634. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  48635. return _this;
  48636. }
  48637. AnaglyphGamepadCamera.prototype.getClassName = function () {
  48638. return "AnaglyphGamepadCamera";
  48639. };
  48640. return AnaglyphGamepadCamera;
  48641. }(BABYLON.GamepadCamera));
  48642. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  48643. var AnaglyphUniversalCamera = (function (_super) {
  48644. __extends(AnaglyphUniversalCamera, _super);
  48645. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  48646. var _this = _super.call(this, name, position, scene) || this;
  48647. _this.interaxialDistance = interaxialDistance;
  48648. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  48649. return _this;
  48650. }
  48651. AnaglyphUniversalCamera.prototype.getClassName = function () {
  48652. return "AnaglyphUniversalCamera";
  48653. };
  48654. return AnaglyphUniversalCamera;
  48655. }(BABYLON.UniversalCamera));
  48656. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  48657. var StereoscopicFreeCamera = (function (_super) {
  48658. __extends(StereoscopicFreeCamera, _super);
  48659. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  48660. var _this = _super.call(this, name, position, scene) || this;
  48661. _this.interaxialDistance = interaxialDistance;
  48662. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  48663. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  48664. return _this;
  48665. }
  48666. StereoscopicFreeCamera.prototype.getClassName = function () {
  48667. return "StereoscopicFreeCamera";
  48668. };
  48669. return StereoscopicFreeCamera;
  48670. }(BABYLON.FreeCamera));
  48671. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  48672. var StereoscopicArcRotateCamera = (function (_super) {
  48673. __extends(StereoscopicArcRotateCamera, _super);
  48674. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  48675. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  48676. _this.interaxialDistance = interaxialDistance;
  48677. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  48678. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  48679. return _this;
  48680. }
  48681. StereoscopicArcRotateCamera.prototype.getClassName = function () {
  48682. return "StereoscopicArcRotateCamera";
  48683. };
  48684. return StereoscopicArcRotateCamera;
  48685. }(BABYLON.ArcRotateCamera));
  48686. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  48687. var StereoscopicGamepadCamera = (function (_super) {
  48688. __extends(StereoscopicGamepadCamera, _super);
  48689. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  48690. var _this = _super.call(this, name, position, scene) || this;
  48691. _this.interaxialDistance = interaxialDistance;
  48692. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  48693. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  48694. return _this;
  48695. }
  48696. StereoscopicGamepadCamera.prototype.getClassName = function () {
  48697. return "StereoscopicGamepadCamera";
  48698. };
  48699. return StereoscopicGamepadCamera;
  48700. }(BABYLON.GamepadCamera));
  48701. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  48702. var StereoscopicUniversalCamera = (function (_super) {
  48703. __extends(StereoscopicUniversalCamera, _super);
  48704. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  48705. var _this = _super.call(this, name, position, scene) || this;
  48706. _this.interaxialDistance = interaxialDistance;
  48707. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  48708. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  48709. return _this;
  48710. }
  48711. StereoscopicUniversalCamera.prototype.getClassName = function () {
  48712. return "StereoscopicUniversalCamera";
  48713. };
  48714. return StereoscopicUniversalCamera;
  48715. }(BABYLON.UniversalCamera));
  48716. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  48717. })(BABYLON || (BABYLON = {}));
  48718. //# sourceMappingURL=babylon.stereoscopicCameras.js.map
  48719. var BABYLON;
  48720. (function (BABYLON) {
  48721. var HolographicCamera = (function (_super) {
  48722. __extends(HolographicCamera, _super);
  48723. function HolographicCamera(name, scene) {
  48724. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  48725. scene.clearColor = new BABYLON.Color4(0, 0, 0, 0);
  48726. _this._holographicViewMatrix = new BABYLON.Matrix();
  48727. _this._identityProjection = BABYLON.Matrix.Identity();
  48728. _this._scriptProjection = BABYLON.Matrix.Transpose(BABYLON.Matrix.PerspectiveFovLH(30, window.innerWidth / window.innerHeight, 1, 20));
  48729. _this._scriptViewProjection = BABYLON.Matrix.Identity();
  48730. _this.fov = 30;
  48731. _this.minZ = 1.0;
  48732. _this.maxZ = 20;
  48733. _this.mode = BABYLON.Camera.PERSPECTIVE_CAMERA;
  48734. _this.isIntermediate = false;
  48735. _this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  48736. _this.layerMask = 0x0FFFFFFF;
  48737. _this.fovMode = BABYLON.Camera.FOVMODE_VERTICAL_FIXED;
  48738. _this.cameraRigMode = BABYLON.Camera.RIG_MODE_NONE;
  48739. var self = _this;
  48740. _this._onBeforeRenderObserver = scene.onBeforeRenderObservable.add(function (scene) {
  48741. self._holographicViewMatrix.m = window.getViewMatrix();
  48742. self.setViewMatrix(self._holographicViewMatrix);
  48743. var position = window.getCameraPositionVector();
  48744. self.position.copyFromFloats(-position[0], position[1], -position[2]);
  48745. });
  48746. _this._onBeforeCameraRenderObserver = scene.onBeforeCameraRenderObservable.add(function () {
  48747. if (scene.frustumPlanes) {
  48748. self.getFrustumPlanesToRef(scene.frustumPlanes);
  48749. }
  48750. });
  48751. scene.addCamera(_this);
  48752. if (!scene.activeCamera) {
  48753. scene.activeCamera = _this;
  48754. }
  48755. return _this;
  48756. }
  48757. HolographicCamera.prototype.getTypeName = function () {
  48758. return "HolographicCamera";
  48759. };
  48760. ;
  48761. HolographicCamera.prototype.getProjectionMatrix = function () {
  48762. return this._identityProjection;
  48763. };
  48764. ;
  48765. HolographicCamera.prototype.getViewMatrix = function () {
  48766. return this._holographicViewMatrix;
  48767. };
  48768. ;
  48769. HolographicCamera.prototype.setViewMatrix = function (view) {
  48770. this._holographicViewMatrix = view;
  48771. view.m[0] = -view.m[0];
  48772. view.m[1] = -view.m[1];
  48773. view.m[2] = -view.m[2];
  48774. view.m[3] = -view.m[3];
  48775. view.m[8] = -view.m[8];
  48776. view.m[9] = -view.m[9];
  48777. view.m[10] = -view.m[10];
  48778. view.m[11] = -view.m[11];
  48779. };
  48780. ;
  48781. HolographicCamera.prototype._initCache = function () { };
  48782. ;
  48783. HolographicCamera.prototype._updateCache = function () { };
  48784. ;
  48785. HolographicCamera.prototype._updateFromScene = function () { };
  48786. ;
  48787. // Synchronized
  48788. HolographicCamera.prototype._isSynchronizedViewMatrix = function () {
  48789. return true;
  48790. };
  48791. ;
  48792. HolographicCamera.prototype._isSynchronizedProjectionMatrix = function () {
  48793. return true;
  48794. };
  48795. ;
  48796. HolographicCamera.prototype.getFrustumPlanesToRef = function (result) {
  48797. this._holographicViewMatrix.multiplyToRef(this._scriptProjection, this._scriptViewProjection);
  48798. BABYLON.Frustum.GetPlanesToRef(this._scriptViewProjection, result);
  48799. return result;
  48800. };
  48801. ;
  48802. HolographicCamera.prototype.dispose = function () {
  48803. this.getScene().onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  48804. this.getScene().onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  48805. _super.prototype.dispose.call(this);
  48806. };
  48807. return HolographicCamera;
  48808. }(BABYLON.Camera));
  48809. BABYLON.HolographicCamera = HolographicCamera;
  48810. })(BABYLON || (BABYLON = {}));
  48811. //# sourceMappingURL=babylon.holographicCamera.js.map
  48812. var BABYLON;
  48813. (function (BABYLON) {
  48814. var HDRRenderingPipeline = (function (_super) {
  48815. __extends(HDRRenderingPipeline, _super);
  48816. /**
  48817. * @constructor
  48818. * @param {string} name - The rendering pipeline name
  48819. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  48820. * @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)
  48821. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  48822. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  48823. */
  48824. function HDRRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  48825. if (originalPostProcess === void 0) { originalPostProcess = null; }
  48826. var _this = _super.call(this, scene.getEngine(), name) || this;
  48827. /**
  48828. * Public members
  48829. */
  48830. // Gaussian Blur
  48831. /**
  48832. * Gaussian blur coefficient
  48833. * @type {number}
  48834. */
  48835. _this.gaussCoeff = 0.3;
  48836. /**
  48837. * Gaussian blur mean
  48838. * @type {number}
  48839. */
  48840. _this.gaussMean = 1.0;
  48841. /**
  48842. * Gaussian blur standard deviation
  48843. * @type {number}
  48844. */
  48845. _this.gaussStandDev = 0.8;
  48846. /**
  48847. * Gaussian blur multiplier. Multiplies the blur effect
  48848. * @type {number}
  48849. */
  48850. _this.gaussMultiplier = 4.0;
  48851. // HDR
  48852. /**
  48853. * Exposure, controls the overall intensity of the pipeline
  48854. * @type {number}
  48855. */
  48856. _this.exposure = 1.0;
  48857. /**
  48858. * Minimum luminance that the post-process can output. Luminance is >= 0
  48859. * @type {number}
  48860. */
  48861. _this.minimumLuminance = 1.0;
  48862. /**
  48863. * Maximum luminance that the post-process can output. Must be suprerior to minimumLuminance
  48864. * @type {number}
  48865. */
  48866. _this.maximumLuminance = 1e20;
  48867. /**
  48868. * Increase rate for luminance: eye adaptation speed to dark
  48869. * @type {number}
  48870. */
  48871. _this.luminanceIncreaserate = 0.5;
  48872. /**
  48873. * Decrease rate for luminance: eye adaptation speed to bright
  48874. * @type {number}
  48875. */
  48876. _this.luminanceDecreaseRate = 0.5;
  48877. // Bright pass
  48878. /**
  48879. * Minimum luminance needed to compute HDR
  48880. * @type {number}
  48881. */
  48882. _this.brightThreshold = 0.8;
  48883. _this._needUpdate = true;
  48884. _this._scene = scene;
  48885. // Bright pass
  48886. _this._createBrightPassPostProcess(scene, ratio);
  48887. // Down sample X4
  48888. _this._createDownSampleX4PostProcess(scene, ratio);
  48889. // Create gaussian blur post-processes
  48890. _this._createGaussianBlurPostProcess(scene, ratio);
  48891. // Texture adder
  48892. _this._createTextureAdderPostProcess(scene, ratio);
  48893. // Luminance generator
  48894. _this._createLuminanceGeneratorPostProcess(scene);
  48895. // HDR
  48896. _this._createHDRPostProcess(scene, ratio);
  48897. // Pass postprocess
  48898. if (originalPostProcess === null) {
  48899. _this._originalPostProcess = new BABYLON.PassPostProcess("hdr", ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  48900. }
  48901. else {
  48902. _this._originalPostProcess = originalPostProcess;
  48903. }
  48904. // Configure pipeline
  48905. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this._originalPostProcess; }, true));
  48906. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this._brightPassPostProcess; }, true));
  48907. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this._downSampleX4PostProcess; }, true));
  48908. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurH", function () { return _this._guassianBlurHPostProcess; }, true));
  48909. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurV", function () { return _this._guassianBlurVPostProcess; }, true));
  48910. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this._textureAdderPostProcess; }, true));
  48911. var addDownSamplerPostProcess = function (id) {
  48912. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampler" + id, function () { return _this._downSamplePostProcesses[id]; }, true));
  48913. };
  48914. for (var i = HDRRenderingPipeline.LUM_STEPS - 1; i >= 0; i--) {
  48915. addDownSamplerPostProcess(i);
  48916. }
  48917. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this._hdrPostProcess; }, true));
  48918. // Finish
  48919. scene.postProcessRenderPipelineManager.addPipeline(_this);
  48920. if (cameras !== null) {
  48921. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  48922. }
  48923. _this.update();
  48924. return _this;
  48925. }
  48926. /**
  48927. * Tells the pipeline to update its post-processes
  48928. */
  48929. HDRRenderingPipeline.prototype.update = function () {
  48930. this._needUpdate = true;
  48931. };
  48932. /**
  48933. * Returns the current calculated luminance
  48934. */
  48935. HDRRenderingPipeline.prototype.getCurrentLuminance = function () {
  48936. return this._hdrCurrentLuminance;
  48937. };
  48938. /**
  48939. * Returns the currently drawn luminance
  48940. */
  48941. HDRRenderingPipeline.prototype.getOutputLuminance = function () {
  48942. return this._hdrOutputLuminance;
  48943. };
  48944. /**
  48945. * Releases the rendering pipeline and its internal effects. Detaches pipeline from cameras
  48946. */
  48947. HDRRenderingPipeline.prototype.dispose = function () {
  48948. for (var i = 0; i < this._scene.cameras.length; i++) {
  48949. var camera = this._scene.cameras[i];
  48950. this._originalPostProcess.dispose(camera);
  48951. this._brightPassPostProcess.dispose(camera);
  48952. this._downSampleX4PostProcess.dispose(camera);
  48953. this._guassianBlurHPostProcess.dispose(camera);
  48954. this._guassianBlurVPostProcess.dispose(camera);
  48955. this._textureAdderPostProcess.dispose(camera);
  48956. for (var j = HDRRenderingPipeline.LUM_STEPS - 1; j >= 0; j--) {
  48957. this._downSamplePostProcesses[j].dispose(camera);
  48958. }
  48959. this._hdrPostProcess.dispose(camera);
  48960. }
  48961. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  48962. _super.prototype.dispose.call(this);
  48963. };
  48964. /**
  48965. * Creates the HDR post-process and computes the luminance adaptation
  48966. */
  48967. HDRRenderingPipeline.prototype._createHDRPostProcess = function (scene, ratio) {
  48968. var _this = this;
  48969. var hdrLastLuminance = 0.0;
  48970. this._hdrOutputLuminance = -1.0;
  48971. this._hdrCurrentLuminance = 1.0;
  48972. this._hdrPostProcess = new BABYLON.PostProcess("hdr", "hdr", ["exposure", "avgLuminance"], ["otherSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define HDR");
  48973. this._hdrPostProcess.onApply = function (effect) {
  48974. if (_this._hdrOutputLuminance < 0.0) {
  48975. _this._hdrOutputLuminance = _this._hdrCurrentLuminance;
  48976. }
  48977. else {
  48978. var dt = (hdrLastLuminance - (hdrLastLuminance + scene.getEngine().getDeltaTime())) / 1000.0;
  48979. if (_this._hdrCurrentLuminance < _this._hdrOutputLuminance + _this.luminanceDecreaseRate * dt) {
  48980. _this._hdrOutputLuminance += _this.luminanceDecreaseRate * dt;
  48981. }
  48982. else if (_this._hdrCurrentLuminance > _this._hdrOutputLuminance - _this.luminanceIncreaserate * dt) {
  48983. _this._hdrOutputLuminance -= _this.luminanceIncreaserate * dt;
  48984. }
  48985. else {
  48986. _this._hdrOutputLuminance = _this._hdrCurrentLuminance;
  48987. }
  48988. }
  48989. _this._hdrOutputLuminance = BABYLON.MathTools.Clamp(_this._hdrOutputLuminance, _this.minimumLuminance, _this.maximumLuminance);
  48990. hdrLastLuminance += scene.getEngine().getDeltaTime();
  48991. effect.setTextureFromPostProcess("textureSampler", _this._textureAdderPostProcess);
  48992. effect.setTextureFromPostProcess("otherSampler", _this._originalPostProcess);
  48993. effect.setFloat("exposure", _this.exposure);
  48994. effect.setFloat("avgLuminance", _this._hdrOutputLuminance);
  48995. _this._needUpdate = false;
  48996. };
  48997. };
  48998. /**
  48999. * Texture Adder post-process
  49000. */
  49001. HDRRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  49002. var _this = this;
  49003. this._textureAdderPostProcess = new BABYLON.PostProcess("hdr", "hdr", [], ["otherSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define TEXTURE_ADDER");
  49004. this._textureAdderPostProcess.onApply = function (effect) {
  49005. effect.setTextureFromPostProcess("otherSampler", _this._originalPostProcess);
  49006. };
  49007. };
  49008. /**
  49009. * Down sample X4 post-process
  49010. */
  49011. HDRRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  49012. var _this = this;
  49013. var downSampleX4Offsets = new Array(32);
  49014. this._downSampleX4PostProcess = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets"], [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define DOWN_SAMPLE_X4");
  49015. this._downSampleX4PostProcess.onApply = function (effect) {
  49016. if (_this._needUpdate) {
  49017. var id = 0;
  49018. for (var i = -2; i < 2; i++) {
  49019. for (var j = -2; j < 2; j++) {
  49020. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / _this._downSampleX4PostProcess.width);
  49021. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / _this._downSampleX4PostProcess.height);
  49022. id += 2;
  49023. }
  49024. }
  49025. }
  49026. effect.setArray2("dsOffsets", downSampleX4Offsets);
  49027. };
  49028. };
  49029. /**
  49030. * Bright pass post-process
  49031. */
  49032. HDRRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  49033. var _this = this;
  49034. var brightOffsets = new Array(8);
  49035. var brightPassCallback = function (effect) {
  49036. if (_this._needUpdate) {
  49037. var sU = (1.0 / _this._brightPassPostProcess.width);
  49038. var sV = (1.0 / _this._brightPassPostProcess.height);
  49039. brightOffsets[0] = -0.5 * sU;
  49040. brightOffsets[1] = 0.5 * sV;
  49041. brightOffsets[2] = 0.5 * sU;
  49042. brightOffsets[3] = 0.5 * sV;
  49043. brightOffsets[4] = -0.5 * sU;
  49044. brightOffsets[5] = -0.5 * sV;
  49045. brightOffsets[6] = 0.5 * sU;
  49046. brightOffsets[7] = -0.5 * sV;
  49047. }
  49048. effect.setArray2("dsOffsets", brightOffsets);
  49049. effect.setFloat("brightThreshold", _this.brightThreshold);
  49050. };
  49051. this._brightPassPostProcess = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets", "brightThreshold"], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define BRIGHT_PASS");
  49052. this._brightPassPostProcess.onApply = brightPassCallback;
  49053. };
  49054. /**
  49055. * Luminance generator. Creates the luminance post-process and down sample post-processes
  49056. */
  49057. HDRRenderingPipeline.prototype._createLuminanceGeneratorPostProcess = function (scene) {
  49058. var _this = this;
  49059. var lumSteps = HDRRenderingPipeline.LUM_STEPS;
  49060. var luminanceOffsets = new Array(8);
  49061. var downSampleOffsets = new Array(18);
  49062. var halfDestPixelSize;
  49063. this._downSamplePostProcesses = new Array(lumSteps);
  49064. // Utils for luminance
  49065. var luminanceUpdateSourceOffsets = function (width, height) {
  49066. var sU = (1.0 / width);
  49067. var sV = (1.0 / height);
  49068. luminanceOffsets[0] = -0.5 * sU;
  49069. luminanceOffsets[1] = 0.5 * sV;
  49070. luminanceOffsets[2] = 0.5 * sU;
  49071. luminanceOffsets[3] = 0.5 * sV;
  49072. luminanceOffsets[4] = -0.5 * sU;
  49073. luminanceOffsets[5] = -0.5 * sV;
  49074. luminanceOffsets[6] = 0.5 * sU;
  49075. luminanceOffsets[7] = -0.5 * sV;
  49076. };
  49077. var luminanceUpdateDestOffsets = function (width, height) {
  49078. var id = 0;
  49079. for (var x = -1; x < 2; x++) {
  49080. for (var y = -1; y < 2; y++) {
  49081. downSampleOffsets[id] = (x) / width;
  49082. downSampleOffsets[id + 1] = (y) / height;
  49083. id += 2;
  49084. }
  49085. }
  49086. };
  49087. // Luminance callback
  49088. var luminanceCallback = function (effect) {
  49089. if (_this._needUpdate) {
  49090. luminanceUpdateSourceOffsets(_this._textureAdderPostProcess.width, _this._textureAdderPostProcess.height);
  49091. }
  49092. effect.setTextureFromPostProcess("textureSampler", _this._textureAdderPostProcess);
  49093. effect.setArray2("lumOffsets", luminanceOffsets);
  49094. };
  49095. // Down sample callbacks
  49096. var downSampleCallback = function (indice) {
  49097. var i = indice;
  49098. return function (effect) {
  49099. luminanceUpdateSourceOffsets(_this._downSamplePostProcesses[i].width, _this._downSamplePostProcesses[i].height);
  49100. luminanceUpdateDestOffsets(_this._downSamplePostProcesses[i].width, _this._downSamplePostProcesses[i].height);
  49101. halfDestPixelSize = 0.5 / _this._downSamplePostProcesses[i].width;
  49102. effect.setTextureFromPostProcess("textureSampler", _this._downSamplePostProcesses[i + 1]);
  49103. effect.setFloat("halfDestPixelSize", halfDestPixelSize);
  49104. effect.setArray2("dsOffsets", downSampleOffsets);
  49105. };
  49106. };
  49107. var downSampleAfterRenderCallback = function (effect) {
  49108. // Unpack result
  49109. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  49110. 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);
  49111. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  49112. };
  49113. // Create luminance post-process
  49114. var ratio = { width: Math.pow(3, lumSteps - 1), height: Math.pow(3, lumSteps - 1) };
  49115. 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);
  49116. this._downSamplePostProcesses[lumSteps - 1].onApply = luminanceCallback;
  49117. // Create down sample post-processes
  49118. for (var i = lumSteps - 2; i >= 0; i--) {
  49119. var length = Math.pow(3, i);
  49120. ratio = { width: length, height: length };
  49121. var defines = "#define DOWN_SAMPLE\n";
  49122. if (i === 0) {
  49123. defines += "#define FINAL_DOWN_SAMPLE\n"; // To pack the result
  49124. }
  49125. this._downSamplePostProcesses[i] = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets", "halfDestPixelSize"], [], ratio, null, BABYLON.Texture.NEAREST_SAMPLINGMODE, scene.getEngine(), false, defines, BABYLON.Engine.TEXTURETYPE_FLOAT);
  49126. this._downSamplePostProcesses[i].onApply = downSampleCallback(i);
  49127. if (i === 0) {
  49128. this._downSamplePostProcesses[i].onAfterRender = downSampleAfterRenderCallback;
  49129. }
  49130. }
  49131. };
  49132. /**
  49133. * Gaussian blur post-processes. Horizontal and Vertical
  49134. */
  49135. HDRRenderingPipeline.prototype._createGaussianBlurPostProcess = function (scene, ratio) {
  49136. var _this = this;
  49137. var blurOffsetsW = new Array(9);
  49138. var blurOffsetsH = new Array(9);
  49139. var blurWeights = new Array(9);
  49140. var uniforms = ["blurOffsets", "blurWeights", "multiplier"];
  49141. // Utils for gaussian blur
  49142. var calculateBlurOffsets = function (height) {
  49143. var lastOutputDimensions = {
  49144. width: scene.getEngine().getRenderWidth(),
  49145. height: scene.getEngine().getRenderHeight()
  49146. };
  49147. for (var i = 0; i < 9; i++) {
  49148. var value = (i - 4.0) * (1.0 / (height === true ? lastOutputDimensions.height : lastOutputDimensions.width));
  49149. if (height) {
  49150. blurOffsetsH[i] = value;
  49151. }
  49152. else {
  49153. blurOffsetsW[i] = value;
  49154. }
  49155. }
  49156. };
  49157. var calculateWeights = function () {
  49158. var x = 0.0;
  49159. for (var i = 0; i < 9; i++) {
  49160. x = (i - 4.0) / 4.0;
  49161. 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));
  49162. }
  49163. };
  49164. // Callback
  49165. var gaussianBlurCallback = function (height) {
  49166. return function (effect) {
  49167. if (_this._needUpdate) {
  49168. calculateWeights();
  49169. calculateBlurOffsets(height);
  49170. }
  49171. effect.setArray("blurOffsets", height ? blurOffsetsH : blurOffsetsW);
  49172. effect.setArray("blurWeights", blurWeights);
  49173. effect.setFloat("multiplier", _this.gaussMultiplier);
  49174. };
  49175. };
  49176. // Create horizontal gaussian blur post-processes
  49177. this._guassianBlurHPostProcess = new BABYLON.PostProcess("hdr", "hdr", uniforms, [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define GAUSSIAN_BLUR_H");
  49178. this._guassianBlurHPostProcess.onApply = gaussianBlurCallback(false);
  49179. // Create vertical gaussian blur post-process
  49180. this._guassianBlurVPostProcess = new BABYLON.PostProcess("hdr", "hdr", uniforms, [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define GAUSSIAN_BLUR_V");
  49181. this._guassianBlurVPostProcess.onApply = gaussianBlurCallback(true);
  49182. };
  49183. return HDRRenderingPipeline;
  49184. }(BABYLON.PostProcessRenderPipeline));
  49185. // Luminance generator
  49186. HDRRenderingPipeline.LUM_STEPS = 6;
  49187. BABYLON.HDRRenderingPipeline = HDRRenderingPipeline;
  49188. })(BABYLON || (BABYLON = {}));
  49189. //# sourceMappingURL=babylon.hdrRenderingPipeline.js.map
  49190. var BABYLON;
  49191. (function (BABYLON) {
  49192. var FaceAdjacencies = (function () {
  49193. function FaceAdjacencies() {
  49194. this.edges = new Array();
  49195. this.edgesConnectedCount = 0;
  49196. }
  49197. return FaceAdjacencies;
  49198. }());
  49199. var EdgesRenderer = (function () {
  49200. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  49201. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  49202. if (epsilon === void 0) { epsilon = 0.95; }
  49203. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  49204. this.edgesWidthScalerForOrthographic = 1000.0;
  49205. this.edgesWidthScalerForPerspective = 50.0;
  49206. this._linesPositions = new Array();
  49207. this._linesNormals = new Array();
  49208. this._linesIndices = new Array();
  49209. this._buffers = {};
  49210. this._checkVerticesInsteadOfIndices = false;
  49211. this._source = source;
  49212. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  49213. this._epsilon = epsilon;
  49214. this._prepareRessources();
  49215. this._generateEdgesLines();
  49216. }
  49217. EdgesRenderer.prototype._prepareRessources = function () {
  49218. if (this._lineShader) {
  49219. return;
  49220. }
  49221. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  49222. attributes: ["position", "normal"],
  49223. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  49224. });
  49225. this._lineShader.disableDepthWrite = true;
  49226. this._lineShader.backFaceCulling = false;
  49227. };
  49228. EdgesRenderer.prototype.dispose = function () {
  49229. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  49230. if (buffer) {
  49231. buffer.dispose();
  49232. this._buffers[BABYLON.VertexBuffer.PositionKind] = null;
  49233. }
  49234. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  49235. if (buffer) {
  49236. buffer.dispose();
  49237. this._buffers[BABYLON.VertexBuffer.NormalKind] = null;
  49238. }
  49239. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  49240. this._lineShader.dispose();
  49241. };
  49242. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  49243. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  49244. return 0;
  49245. }
  49246. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  49247. return 1;
  49248. }
  49249. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  49250. return 2;
  49251. }
  49252. return -1;
  49253. };
  49254. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  49255. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  49256. return 0;
  49257. }
  49258. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  49259. return 1;
  49260. }
  49261. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  49262. return 2;
  49263. }
  49264. return -1;
  49265. };
  49266. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  49267. var needToCreateLine;
  49268. if (edge === undefined) {
  49269. needToCreateLine = true;
  49270. }
  49271. else {
  49272. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  49273. needToCreateLine = dotProduct < this._epsilon;
  49274. }
  49275. if (needToCreateLine) {
  49276. var offset = this._linesPositions.length / 3;
  49277. var normal = p0.subtract(p1);
  49278. normal.normalize();
  49279. // Positions
  49280. this._linesPositions.push(p0.x);
  49281. this._linesPositions.push(p0.y);
  49282. this._linesPositions.push(p0.z);
  49283. this._linesPositions.push(p0.x);
  49284. this._linesPositions.push(p0.y);
  49285. this._linesPositions.push(p0.z);
  49286. this._linesPositions.push(p1.x);
  49287. this._linesPositions.push(p1.y);
  49288. this._linesPositions.push(p1.z);
  49289. this._linesPositions.push(p1.x);
  49290. this._linesPositions.push(p1.y);
  49291. this._linesPositions.push(p1.z);
  49292. // Normals
  49293. this._linesNormals.push(p1.x);
  49294. this._linesNormals.push(p1.y);
  49295. this._linesNormals.push(p1.z);
  49296. this._linesNormals.push(-1);
  49297. this._linesNormals.push(p1.x);
  49298. this._linesNormals.push(p1.y);
  49299. this._linesNormals.push(p1.z);
  49300. this._linesNormals.push(1);
  49301. this._linesNormals.push(p0.x);
  49302. this._linesNormals.push(p0.y);
  49303. this._linesNormals.push(p0.z);
  49304. this._linesNormals.push(-1);
  49305. this._linesNormals.push(p0.x);
  49306. this._linesNormals.push(p0.y);
  49307. this._linesNormals.push(p0.z);
  49308. this._linesNormals.push(1);
  49309. // Indices
  49310. this._linesIndices.push(offset);
  49311. this._linesIndices.push(offset + 1);
  49312. this._linesIndices.push(offset + 2);
  49313. this._linesIndices.push(offset);
  49314. this._linesIndices.push(offset + 2);
  49315. this._linesIndices.push(offset + 3);
  49316. }
  49317. };
  49318. EdgesRenderer.prototype._generateEdgesLines = function () {
  49319. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  49320. var indices = this._source.getIndices();
  49321. // First let's find adjacencies
  49322. var adjacencies = new Array();
  49323. var faceNormals = new Array();
  49324. var index;
  49325. var faceAdjacencies;
  49326. // Prepare faces
  49327. for (index = 0; index < indices.length; index += 3) {
  49328. faceAdjacencies = new FaceAdjacencies();
  49329. var p0Index = indices[index];
  49330. var p1Index = indices[index + 1];
  49331. var p2Index = indices[index + 2];
  49332. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  49333. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  49334. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  49335. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  49336. faceNormal.normalize();
  49337. faceNormals.push(faceNormal);
  49338. adjacencies.push(faceAdjacencies);
  49339. }
  49340. // Scan
  49341. for (index = 0; index < adjacencies.length; index++) {
  49342. faceAdjacencies = adjacencies[index];
  49343. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  49344. var otherFaceAdjacencies = adjacencies[otherIndex];
  49345. if (faceAdjacencies.edgesConnectedCount === 3) {
  49346. break;
  49347. }
  49348. if (otherFaceAdjacencies.edgesConnectedCount === 3) {
  49349. continue;
  49350. }
  49351. var otherP0 = indices[otherIndex * 3];
  49352. var otherP1 = indices[otherIndex * 3 + 1];
  49353. var otherP2 = indices[otherIndex * 3 + 2];
  49354. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  49355. var otherEdgeIndex;
  49356. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  49357. continue;
  49358. }
  49359. switch (edgeIndex) {
  49360. case 0:
  49361. if (this._checkVerticesInsteadOfIndices) {
  49362. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  49363. }
  49364. else {
  49365. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  49366. }
  49367. break;
  49368. case 1:
  49369. if (this._checkVerticesInsteadOfIndices) {
  49370. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  49371. }
  49372. else {
  49373. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  49374. }
  49375. break;
  49376. case 2:
  49377. if (this._checkVerticesInsteadOfIndices) {
  49378. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  49379. }
  49380. else {
  49381. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  49382. }
  49383. break;
  49384. }
  49385. if (otherEdgeIndex === -1) {
  49386. continue;
  49387. }
  49388. faceAdjacencies.edges[edgeIndex] = otherIndex;
  49389. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  49390. faceAdjacencies.edgesConnectedCount++;
  49391. otherFaceAdjacencies.edgesConnectedCount++;
  49392. if (faceAdjacencies.edgesConnectedCount === 3) {
  49393. break;
  49394. }
  49395. }
  49396. }
  49397. }
  49398. // Create lines
  49399. for (index = 0; index < adjacencies.length; index++) {
  49400. // 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
  49401. var current = adjacencies[index];
  49402. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  49403. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  49404. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  49405. }
  49406. // Merge into a single mesh
  49407. var engine = this._source.getScene().getEngine();
  49408. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  49409. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  49410. this._ib = engine.createIndexBuffer(this._linesIndices);
  49411. this._indicesCount = this._linesIndices.length;
  49412. };
  49413. EdgesRenderer.prototype.render = function () {
  49414. if (!this._lineShader.isReady()) {
  49415. return;
  49416. }
  49417. var scene = this._source.getScene();
  49418. var engine = scene.getEngine();
  49419. this._lineShader._preBind();
  49420. // VBOs
  49421. engine.bindBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  49422. scene.resetCachedMaterial();
  49423. this._lineShader.setColor4("color", this._source.edgesColor);
  49424. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  49425. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  49426. }
  49427. else {
  49428. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  49429. }
  49430. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  49431. this._lineShader.bind(this._source.getWorldMatrix());
  49432. // Draw order
  49433. engine.draw(true, 0, this._indicesCount);
  49434. this._lineShader.unbind();
  49435. engine.setDepthWrite(true);
  49436. };
  49437. return EdgesRenderer;
  49438. }());
  49439. BABYLON.EdgesRenderer = EdgesRenderer;
  49440. })(BABYLON || (BABYLON = {}));
  49441. //# sourceMappingURL=babylon.edgesRenderer.js.map
  49442. var BABYLON;
  49443. (function (BABYLON) {
  49444. var TonemappingOperator;
  49445. (function (TonemappingOperator) {
  49446. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  49447. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  49448. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  49449. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  49450. })(TonemappingOperator = BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  49451. ;
  49452. var TonemapPostProcess = (function (_super) {
  49453. __extends(TonemapPostProcess, _super);
  49454. function TonemapPostProcess(name, _operator, exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  49455. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  49456. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  49457. var _this = _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, defines, textureFormat) || this;
  49458. _this._operator = _operator;
  49459. _this.exposureAdjustment = exposureAdjustment;
  49460. var defines = "#define ";
  49461. if (_this._operator === TonemappingOperator.Hable)
  49462. defines += "HABLE_TONEMAPPING";
  49463. else if (_this._operator === TonemappingOperator.Reinhard)
  49464. defines += "REINHARD_TONEMAPPING";
  49465. else if (_this._operator === TonemappingOperator.HejiDawson)
  49466. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  49467. else if (_this._operator === TonemappingOperator.Photographic)
  49468. defines += "PHOTOGRAPHIC_TONEMAPPING";
  49469. //sadly a second call to create the effect.
  49470. _this.updateEffect(defines);
  49471. _this.onApply = function (effect) {
  49472. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  49473. };
  49474. return _this;
  49475. }
  49476. return TonemapPostProcess;
  49477. }(BABYLON.PostProcess));
  49478. BABYLON.TonemapPostProcess = TonemapPostProcess;
  49479. })(BABYLON || (BABYLON = {}));
  49480. //# sourceMappingURL=babylon.tonemapPostProcess.js.map
  49481. var BABYLON;
  49482. (function (BABYLON) {
  49483. var ReflectionProbe = (function () {
  49484. function ReflectionProbe(name, size, scene, generateMipMaps) {
  49485. if (generateMipMaps === void 0) { generateMipMaps = true; }
  49486. var _this = this;
  49487. this.name = name;
  49488. this._viewMatrix = BABYLON.Matrix.Identity();
  49489. this._target = BABYLON.Vector3.Zero();
  49490. this._add = BABYLON.Vector3.Zero();
  49491. this.invertYAxis = false;
  49492. this.position = BABYLON.Vector3.Zero();
  49493. this._scene = scene;
  49494. this._scene.reflectionProbes.push(this);
  49495. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  49496. this._renderTargetTexture.onBeforeRenderObservable.add(function (faceIndex) {
  49497. switch (faceIndex) {
  49498. case 0:
  49499. _this._add.copyFromFloats(1, 0, 0);
  49500. break;
  49501. case 1:
  49502. _this._add.copyFromFloats(-1, 0, 0);
  49503. break;
  49504. case 2:
  49505. _this._add.copyFromFloats(0, _this.invertYAxis ? 1 : -1, 0);
  49506. break;
  49507. case 3:
  49508. _this._add.copyFromFloats(0, _this.invertYAxis ? -1 : 1, 0);
  49509. break;
  49510. case 4:
  49511. _this._add.copyFromFloats(0, 0, 1);
  49512. break;
  49513. case 5:
  49514. _this._add.copyFromFloats(0, 0, -1);
  49515. break;
  49516. }
  49517. if (_this._attachedMesh) {
  49518. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  49519. }
  49520. _this.position.addToRef(_this._add, _this._target);
  49521. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  49522. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  49523. });
  49524. this._renderTargetTexture.onAfterUnbindObservable.add(function () {
  49525. scene.updateTransformMatrix(true);
  49526. });
  49527. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  49528. }
  49529. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  49530. get: function () {
  49531. return this._renderTargetTexture.refreshRate;
  49532. },
  49533. set: function (value) {
  49534. this._renderTargetTexture.refreshRate = value;
  49535. },
  49536. enumerable: true,
  49537. configurable: true
  49538. });
  49539. ReflectionProbe.prototype.getScene = function () {
  49540. return this._scene;
  49541. };
  49542. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  49543. get: function () {
  49544. return this._renderTargetTexture;
  49545. },
  49546. enumerable: true,
  49547. configurable: true
  49548. });
  49549. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  49550. get: function () {
  49551. return this._renderTargetTexture.renderList;
  49552. },
  49553. enumerable: true,
  49554. configurable: true
  49555. });
  49556. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  49557. this._attachedMesh = mesh;
  49558. };
  49559. ReflectionProbe.prototype.dispose = function () {
  49560. var index = this._scene.reflectionProbes.indexOf(this);
  49561. if (index !== -1) {
  49562. // Remove from the scene if found
  49563. this._scene.reflectionProbes.splice(index, 1);
  49564. }
  49565. if (this._renderTargetTexture) {
  49566. this._renderTargetTexture.dispose();
  49567. this._renderTargetTexture = null;
  49568. }
  49569. };
  49570. return ReflectionProbe;
  49571. }());
  49572. BABYLON.ReflectionProbe = ReflectionProbe;
  49573. })(BABYLON || (BABYLON = {}));
  49574. //# sourceMappingURL=babylon.reflectionProbe.js.map
  49575. var BABYLON;
  49576. (function (BABYLON) {
  49577. var SolidParticle = (function () {
  49578. /**
  49579. * Creates a Solid Particle object.
  49580. * Don't create particles manually, use instead the Solid Particle System internal tools like _addParticle()
  49581. * `particleIndex` (integer) is the particle index in the Solid Particle System pool. It's also the particle identifier.
  49582. * `positionIndex` (integer) is the starting index of the particle vertices in the SPS "positions" array.
  49583. * `model` (ModelShape) is a reference to the model shape on what the particle is designed.
  49584. * `shapeId` (integer) is the model shape identifier in the SPS.
  49585. * `idxInShape` (integer) is the index of the particle in the current model (ex: the 10th box of addShape(box, 30))
  49586. * `modelBoundingInfo` is the reference to the model BoundingInfo used for intersection computations.
  49587. */
  49588. function SolidParticle(particleIndex, positionIndex, model, shapeId, idxInShape, sps, modelBoundingInfo) {
  49589. this.idx = 0; // particle global index
  49590. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0); // color
  49591. this.position = BABYLON.Vector3.Zero(); // position
  49592. this.rotation = BABYLON.Vector3.Zero(); // rotation
  49593. this.scaling = new BABYLON.Vector3(1.0, 1.0, 1.0); // scaling
  49594. this.uvs = new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0); // uvs
  49595. this.velocity = BABYLON.Vector3.Zero(); // velocity
  49596. this.alive = true; // alive
  49597. this.isVisible = true; // visibility
  49598. this._pos = 0; // index of this particle in the global "positions" array
  49599. this.shapeId = 0; // model shape id
  49600. this.idxInShape = 0; // index of the particle in its shape id
  49601. this.idx = particleIndex;
  49602. this._pos = positionIndex;
  49603. this._model = model;
  49604. this.shapeId = shapeId;
  49605. this.idxInShape = idxInShape;
  49606. this._sps = sps;
  49607. if (modelBoundingInfo) {
  49608. this._modelBoundingInfo = modelBoundingInfo;
  49609. this._boundingInfo = new BABYLON.BoundingInfo(modelBoundingInfo.minimum, modelBoundingInfo.maximum);
  49610. }
  49611. }
  49612. Object.defineProperty(SolidParticle.prototype, "scale", {
  49613. /**
  49614. * legacy support, changed scale to scaling
  49615. */
  49616. get: function () {
  49617. return this.scaling;
  49618. },
  49619. set: function (scale) {
  49620. this.scaling = scale;
  49621. },
  49622. enumerable: true,
  49623. configurable: true
  49624. });
  49625. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  49626. /**
  49627. * legacy support, changed quaternion to rotationQuaternion
  49628. */
  49629. get: function () {
  49630. return this.rotationQuaternion;
  49631. },
  49632. set: function (q) {
  49633. this.rotationQuaternion = q;
  49634. },
  49635. enumerable: true,
  49636. configurable: true
  49637. });
  49638. /**
  49639. * Returns a boolean. True if the particle intersects another particle or another mesh, else false.
  49640. * The intersection is computed on the particle bounding sphere and Axis Aligned Bounding Box (AABB)
  49641. * `target` is the object (solid particle or mesh) what the intersection is computed against.
  49642. */
  49643. SolidParticle.prototype.intersectsMesh = function (target) {
  49644. if (!this._boundingInfo || !target._boundingInfo) {
  49645. return false;
  49646. }
  49647. if (this._sps._bSphereOnly) {
  49648. return BABYLON.BoundingSphere.Intersects(this._boundingInfo.boundingSphere, target._boundingInfo.boundingSphere);
  49649. }
  49650. return this._boundingInfo.intersects(target._boundingInfo, false);
  49651. };
  49652. return SolidParticle;
  49653. }());
  49654. BABYLON.SolidParticle = SolidParticle;
  49655. var ModelShape = (function () {
  49656. /**
  49657. * 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.
  49658. * SPS internal tool, don't use it manually.
  49659. */
  49660. function ModelShape(id, shape, shapeUV, posFunction, vtxFunction) {
  49661. this.shapeID = id;
  49662. this._shape = shape;
  49663. this._shapeUV = shapeUV;
  49664. this._positionFunction = posFunction;
  49665. this._vertexFunction = vtxFunction;
  49666. }
  49667. return ModelShape;
  49668. }());
  49669. BABYLON.ModelShape = ModelShape;
  49670. })(BABYLON || (BABYLON = {}));
  49671. //# sourceMappingURL=babylon.solidParticle.js.map
  49672. var BABYLON;
  49673. (function (BABYLON) {
  49674. /**
  49675. * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System
  49676. */
  49677. var SolidParticleSystem = (function () {
  49678. /**
  49679. * Creates a SPS (Solid Particle System) object.
  49680. * `name` (String) is the SPS name, this will be the underlying mesh name.
  49681. * `scene` (Scene) is the scene in which the SPS is added.
  49682. * `updatable` (optional boolean, default true) : if the SPS must be updatable or immutable.
  49683. * `isPickable` (optional boolean, default false) : if the solid particles must be pickable.
  49684. * `particleIntersection` (optional boolean, default false) : if the solid particle intersections must be computed.
  49685. * `boundingSphereOnly` (optional boolean, default false) : if the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster).
  49686. * `bSphereRadiusFactor` (optional float, default 1.0) : a number to multiply the boundind sphere radius by in order to reduce it for instance.
  49687. * Example : bSphereRadiusFactor = 1.0 / Math.sqrt(3.0) => the bounding sphere exactly matches a spherical mesh.
  49688. */
  49689. function SolidParticleSystem(name, scene, options) {
  49690. // public members
  49691. /**
  49692. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  49693. * Example : var p = SPS.particles[i];
  49694. */
  49695. this.particles = new Array();
  49696. /**
  49697. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  49698. */
  49699. this.nbParticles = 0;
  49700. /**
  49701. * If the particles must ever face the camera (default false). Useful for planar particles.
  49702. */
  49703. this.billboard = false;
  49704. /**
  49705. * Recompute normals when adding a shape
  49706. */
  49707. this.recomputeNormals = true;
  49708. /**
  49709. * This a counter ofr your own usage. It's not set by any SPS functions.
  49710. */
  49711. this.counter = 0;
  49712. /**
  49713. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  49714. * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns
  49715. */
  49716. this.vars = {};
  49717. this._positions = new Array();
  49718. this._indices = new Array();
  49719. this._normals = new Array();
  49720. this._colors = new Array();
  49721. this._uvs = new Array();
  49722. this._index = 0; // indices index
  49723. this._updatable = true;
  49724. this._pickable = false;
  49725. this._isVisibilityBoxLocked = false;
  49726. this._alwaysVisible = false;
  49727. this._shapeCounter = 0;
  49728. this._copy = new BABYLON.SolidParticle(null, null, null, null, null, null);
  49729. this._color = new BABYLON.Color4(0, 0, 0, 0);
  49730. this._computeParticleColor = true;
  49731. this._computeParticleTexture = true;
  49732. this._computeParticleRotation = true;
  49733. this._computeParticleVertex = false;
  49734. this._computeBoundingBox = false;
  49735. this._cam_axisZ = BABYLON.Vector3.Zero();
  49736. this._cam_axisY = BABYLON.Vector3.Zero();
  49737. this._cam_axisX = BABYLON.Vector3.Zero();
  49738. this._axisX = BABYLON.Axis.X;
  49739. this._axisY = BABYLON.Axis.Y;
  49740. this._axisZ = BABYLON.Axis.Z;
  49741. this._camDir = BABYLON.Vector3.Zero();
  49742. this._rotMatrix = new BABYLON.Matrix();
  49743. this._invertMatrix = new BABYLON.Matrix();
  49744. this._rotated = BABYLON.Vector3.Zero();
  49745. this._quaternion = new BABYLON.Quaternion();
  49746. this._vertex = BABYLON.Vector3.Zero();
  49747. this._normal = BABYLON.Vector3.Zero();
  49748. this._yaw = 0.0;
  49749. this._pitch = 0.0;
  49750. this._roll = 0.0;
  49751. this._halfroll = 0.0;
  49752. this._halfpitch = 0.0;
  49753. this._halfyaw = 0.0;
  49754. this._sinRoll = 0.0;
  49755. this._cosRoll = 0.0;
  49756. this._sinPitch = 0.0;
  49757. this._cosPitch = 0.0;
  49758. this._sinYaw = 0.0;
  49759. this._cosYaw = 0.0;
  49760. this._w = 0.0;
  49761. this._minimum = BABYLON.Tmp.Vector3[0];
  49762. this._maximum = BABYLON.Tmp.Vector3[1];
  49763. this._scale = BABYLON.Tmp.Vector3[2];
  49764. this._translation = BABYLON.Tmp.Vector3[3];
  49765. this._minBbox = BABYLON.Tmp.Vector3[4];
  49766. this._maxBbox = BABYLON.Tmp.Vector3[5];
  49767. this._particlesIntersect = false;
  49768. this._bSphereOnly = false;
  49769. this._bSphereRadiusFactor = 1.0;
  49770. this.name = name;
  49771. this._scene = scene;
  49772. this._camera = scene.activeCamera;
  49773. this._pickable = options ? options.isPickable : false;
  49774. this._particlesIntersect = options ? options.particleIntersection : false;
  49775. this._bSphereOnly = options ? options.boundingSphereOnly : false;
  49776. this._bSphereRadiusFactor = (options && options.bSphereRadiusFactor) ? options.bSphereRadiusFactor : 1.0;
  49777. if (options && options.updatable) {
  49778. this._updatable = options.updatable;
  49779. }
  49780. else {
  49781. this._updatable = true;
  49782. }
  49783. if (this._pickable) {
  49784. this.pickedParticles = [];
  49785. }
  49786. }
  49787. /**
  49788. * Builds the SPS underlying mesh. Returns a standard Mesh.
  49789. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  49790. */
  49791. SolidParticleSystem.prototype.buildMesh = function () {
  49792. if (this.nbParticles === 0) {
  49793. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  49794. this.addShape(triangle, 1);
  49795. triangle.dispose();
  49796. }
  49797. this._positions32 = new Float32Array(this._positions);
  49798. this._uvs32 = new Float32Array(this._uvs);
  49799. this._colors32 = new Float32Array(this._colors);
  49800. if (this.recomputeNormals) {
  49801. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices, this._normals);
  49802. }
  49803. this._normals32 = new Float32Array(this._normals);
  49804. this._fixedNormal32 = new Float32Array(this._normals);
  49805. var vertexData = new BABYLON.VertexData();
  49806. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  49807. vertexData.indices = this._indices;
  49808. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  49809. if (this._uvs32) {
  49810. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  49811. ;
  49812. }
  49813. if (this._colors32) {
  49814. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  49815. }
  49816. var mesh = new BABYLON.Mesh(this.name, this._scene);
  49817. vertexData.applyToMesh(mesh, this._updatable);
  49818. this.mesh = mesh;
  49819. this.mesh.isPickable = this._pickable;
  49820. // free memory
  49821. this._positions = null;
  49822. this._normals = null;
  49823. this._uvs = null;
  49824. this._colors = null;
  49825. if (!this._updatable) {
  49826. this.particles.length = 0;
  49827. }
  49828. return mesh;
  49829. };
  49830. /**
  49831. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  49832. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  49833. * Thus the particles generated from `digest()` have their property `position` set yet.
  49834. * `mesh` ( Mesh ) is the mesh to be digested
  49835. * `facetNb` (optional integer, default 1) is the number of mesh facets per particle, this parameter is overriden by the parameter `number` if any
  49836. * `delta` (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  49837. * `number` (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  49838. */
  49839. SolidParticleSystem.prototype.digest = function (mesh, options) {
  49840. var size = (options && options.facetNb) || 1;
  49841. var number = (options && options.number);
  49842. var delta = (options && options.delta) || 0;
  49843. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  49844. var meshInd = mesh.getIndices();
  49845. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  49846. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  49847. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  49848. var f = 0; // facet counter
  49849. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  49850. // compute size from number
  49851. if (number) {
  49852. number = (number > totalFacets) ? totalFacets : number;
  49853. size = Math.round(totalFacets / number);
  49854. delta = 0;
  49855. }
  49856. else {
  49857. size = (size > totalFacets) ? totalFacets : size;
  49858. }
  49859. var facetPos = []; // submesh positions
  49860. var facetInd = []; // submesh indices
  49861. var facetUV = []; // submesh UV
  49862. var facetCol = []; // submesh colors
  49863. var barycenter = BABYLON.Tmp.Vector3[0];
  49864. var rand;
  49865. var sizeO = size;
  49866. while (f < totalFacets) {
  49867. size = sizeO + Math.floor((1 + delta) * Math.random());
  49868. if (f > totalFacets - size) {
  49869. size = totalFacets - f;
  49870. }
  49871. // reset temp arrays
  49872. facetPos.length = 0;
  49873. facetInd.length = 0;
  49874. facetUV.length = 0;
  49875. facetCol.length = 0;
  49876. // iterate over "size" facets
  49877. var fi = 0;
  49878. for (var j = f * 3; j < (f + size) * 3; j++) {
  49879. facetInd.push(fi);
  49880. var i = meshInd[j];
  49881. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  49882. if (meshUV) {
  49883. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  49884. }
  49885. if (meshCol) {
  49886. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  49887. }
  49888. fi++;
  49889. }
  49890. // create a model shape for each single particle
  49891. var idx = this.nbParticles;
  49892. var shape = this._posToShape(facetPos);
  49893. var shapeUV = this._uvsToShapeUV(facetUV);
  49894. // compute the barycenter of the shape
  49895. var v;
  49896. for (v = 0; v < shape.length; v++) {
  49897. barycenter.addInPlace(shape[v]);
  49898. }
  49899. barycenter.scaleInPlace(1 / shape.length);
  49900. // shift the shape from its barycenter to the origin
  49901. for (v = 0; v < shape.length; v++) {
  49902. shape[v].subtractInPlace(barycenter);
  49903. }
  49904. var bInfo;
  49905. if (this._particlesIntersect) {
  49906. bInfo = new BABYLON.BoundingInfo(barycenter, barycenter);
  49907. }
  49908. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, shapeUV, null, null);
  49909. // add the particle in the SPS
  49910. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, meshNor, this._normals, idx, 0, null);
  49911. this._addParticle(idx, this._positions.length, modelShape, this._shapeCounter, 0, bInfo);
  49912. // initialize the particle position
  49913. this.particles[this.nbParticles].position.addInPlace(barycenter);
  49914. this._index += shape.length;
  49915. idx++;
  49916. this.nbParticles++;
  49917. this._shapeCounter++;
  49918. f += size;
  49919. }
  49920. return this;
  49921. };
  49922. //reset copy
  49923. SolidParticleSystem.prototype._resetCopy = function () {
  49924. this._copy.position.x = 0;
  49925. this._copy.position.y = 0;
  49926. this._copy.position.z = 0;
  49927. this._copy.rotation.x = 0;
  49928. this._copy.rotation.y = 0;
  49929. this._copy.rotation.z = 0;
  49930. this._copy.rotationQuaternion = null;
  49931. this._copy.scaling.x = 1;
  49932. this._copy.scaling.y = 1;
  49933. this._copy.scaling.z = 1;
  49934. this._copy.uvs.x = 0;
  49935. this._copy.uvs.y = 0;
  49936. this._copy.uvs.z = 1;
  49937. this._copy.uvs.w = 1;
  49938. this._copy.color = null;
  49939. };
  49940. // _meshBuilder : inserts the shape model in the global SPS mesh
  49941. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, meshNor, normals, idx, idxInShape, options) {
  49942. var i;
  49943. var u = 0;
  49944. var c = 0;
  49945. var n = 0;
  49946. this._resetCopy();
  49947. if (options && options.positionFunction) {
  49948. options.positionFunction(this._copy, idx, idxInShape);
  49949. }
  49950. if (this._copy.rotationQuaternion) {
  49951. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  49952. }
  49953. else {
  49954. this._yaw = this._copy.rotation.y;
  49955. this._pitch = this._copy.rotation.x;
  49956. this._roll = this._copy.rotation.z;
  49957. this._quaternionRotationYPR();
  49958. }
  49959. this._quaternionToRotationMatrix();
  49960. for (i = 0; i < shape.length; i++) {
  49961. this._vertex.x = shape[i].x;
  49962. this._vertex.y = shape[i].y;
  49963. this._vertex.z = shape[i].z;
  49964. if (options && options.vertexFunction) {
  49965. options.vertexFunction(this._copy, this._vertex, i);
  49966. }
  49967. this._vertex.x *= this._copy.scaling.x;
  49968. this._vertex.y *= this._copy.scaling.y;
  49969. this._vertex.z *= this._copy.scaling.z;
  49970. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  49971. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  49972. if (meshUV) {
  49973. 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);
  49974. u += 2;
  49975. }
  49976. if (this._copy.color) {
  49977. this._color = this._copy.color;
  49978. }
  49979. else if (meshCol && meshCol[c] !== undefined) {
  49980. this._color.r = meshCol[c];
  49981. this._color.g = meshCol[c + 1];
  49982. this._color.b = meshCol[c + 2];
  49983. this._color.a = meshCol[c + 3];
  49984. }
  49985. else {
  49986. this._color.r = 1;
  49987. this._color.g = 1;
  49988. this._color.b = 1;
  49989. this._color.a = 1;
  49990. }
  49991. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  49992. c += 4;
  49993. if (!this.recomputeNormals && meshNor) {
  49994. this._normal.x = meshNor[n];
  49995. this._normal.y = meshNor[n + 1];
  49996. this._normal.z = meshNor[n + 2];
  49997. BABYLON.Vector3.TransformCoordinatesToRef(this._normal, this._rotMatrix, this._normal);
  49998. normals.push(this._normal.x, this._normal.y, this._normal.z);
  49999. n += 3;
  50000. }
  50001. }
  50002. for (i = 0; i < meshInd.length; i++) {
  50003. indices.push(p + meshInd[i]);
  50004. }
  50005. if (this._pickable) {
  50006. var nbfaces = meshInd.length / 3;
  50007. for (i = 0; i < nbfaces; i++) {
  50008. this.pickedParticles.push({ idx: idx, faceId: i });
  50009. }
  50010. }
  50011. };
  50012. // returns a shape array from positions array
  50013. SolidParticleSystem.prototype._posToShape = function (positions) {
  50014. var shape = [];
  50015. for (var i = 0; i < positions.length; i += 3) {
  50016. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  50017. }
  50018. return shape;
  50019. };
  50020. // returns a shapeUV array from a Vector4 uvs
  50021. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  50022. var shapeUV = [];
  50023. if (uvs) {
  50024. for (var i = 0; i < uvs.length; i++)
  50025. shapeUV.push(uvs[i]);
  50026. }
  50027. return shapeUV;
  50028. };
  50029. // adds a new particle object in the particles array
  50030. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, model, shapeId, idxInShape, bInfo) {
  50031. this.particles.push(new BABYLON.SolidParticle(idx, idxpos, model, shapeId, idxInShape, this, bInfo));
  50032. };
  50033. /**
  50034. * Adds some particles to the SPS from the model shape. Returns the shape id.
  50035. * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps
  50036. * `mesh` is any Mesh object that will be used as a model for the solid particles.
  50037. * `nb` (positive integer) the number of particles to be created from this model
  50038. * `positionFunction` is an optional javascript function to called for each particle on SPS creation.
  50039. * `vertexFunction` is an optional javascript function to called for each vertex of each particle on SPS creation
  50040. */
  50041. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  50042. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  50043. var meshInd = mesh.getIndices();
  50044. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  50045. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  50046. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  50047. var bbInfo;
  50048. if (this._particlesIntersect) {
  50049. bbInfo = mesh.getBoundingInfo();
  50050. }
  50051. var shape = this._posToShape(meshPos);
  50052. var shapeUV = this._uvsToShapeUV(meshUV);
  50053. var posfunc = options ? options.positionFunction : null;
  50054. var vtxfunc = options ? options.vertexFunction : null;
  50055. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, shapeUV, posfunc, vtxfunc);
  50056. // particles
  50057. var idx = this.nbParticles;
  50058. for (var i = 0; i < nb; i++) {
  50059. this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, meshNor, this._normals, idx, i, options);
  50060. if (this._updatable) {
  50061. this._addParticle(idx, this._positions.length, modelShape, this._shapeCounter, i, bbInfo);
  50062. }
  50063. this._index += shape.length;
  50064. idx++;
  50065. }
  50066. this.nbParticles += nb;
  50067. this._shapeCounter++;
  50068. return this._shapeCounter - 1;
  50069. };
  50070. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  50071. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  50072. this._resetCopy();
  50073. if (particle._model._positionFunction) {
  50074. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  50075. }
  50076. if (this._copy.rotationQuaternion) {
  50077. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  50078. }
  50079. else {
  50080. this._yaw = this._copy.rotation.y;
  50081. this._pitch = this._copy.rotation.x;
  50082. this._roll = this._copy.rotation.z;
  50083. this._quaternionRotationYPR();
  50084. }
  50085. this._quaternionToRotationMatrix();
  50086. this._shape = particle._model._shape;
  50087. for (var pt = 0; pt < this._shape.length; pt++) {
  50088. this._vertex.x = this._shape[pt].x;
  50089. this._vertex.y = this._shape[pt].y;
  50090. this._vertex.z = this._shape[pt].z;
  50091. if (particle._model._vertexFunction) {
  50092. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  50093. }
  50094. this._vertex.x *= this._copy.scaling.x;
  50095. this._vertex.y *= this._copy.scaling.y;
  50096. this._vertex.z *= this._copy.scaling.z;
  50097. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  50098. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  50099. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  50100. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  50101. }
  50102. particle.position.x = 0.0;
  50103. particle.position.y = 0.0;
  50104. particle.position.z = 0.0;
  50105. particle.rotation.x = 0.0;
  50106. particle.rotation.y = 0.0;
  50107. particle.rotation.z = 0.0;
  50108. particle.rotationQuaternion = null;
  50109. particle.scaling.x = 1.0;
  50110. particle.scaling.y = 1.0;
  50111. particle.scaling.z = 1.0;
  50112. };
  50113. /**
  50114. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  50115. */
  50116. SolidParticleSystem.prototype.rebuildMesh = function () {
  50117. for (var p = 0; p < this.particles.length; p++) {
  50118. this._rebuildParticle(this.particles[p]);
  50119. }
  50120. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  50121. };
  50122. /**
  50123. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  50124. * This method calls `updateParticle()` for each particle of the SPS.
  50125. * For an animated SPS, it is usually called within the render loop.
  50126. * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_
  50127. * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_
  50128. * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_
  50129. */
  50130. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  50131. if (start === void 0) { start = 0; }
  50132. if (end === void 0) { end = this.nbParticles - 1; }
  50133. if (update === void 0) { update = true; }
  50134. if (!this._updatable) {
  50135. return;
  50136. }
  50137. // custom beforeUpdate
  50138. this.beforeUpdateParticles(start, end, update);
  50139. this._cam_axisX.x = 1.0;
  50140. this._cam_axisX.y = 0.0;
  50141. this._cam_axisX.z = 0.0;
  50142. this._cam_axisY.x = 0.0;
  50143. this._cam_axisY.y = 1.0;
  50144. this._cam_axisY.z = 0.0;
  50145. this._cam_axisZ.x = 0.0;
  50146. this._cam_axisZ.y = 0.0;
  50147. this._cam_axisZ.z = 1.0;
  50148. // if the particles will always face the camera
  50149. if (this.billboard) {
  50150. // compute the camera position and un-rotate it by the current mesh rotation
  50151. if (this.mesh._worldMatrix.decompose(this._scale, this._quaternion, this._translation)) {
  50152. this._quaternionToRotationMatrix();
  50153. this._rotMatrix.invertToRef(this._invertMatrix);
  50154. this._camera._currentTarget.subtractToRef(this._camera.globalPosition, this._camDir);
  50155. BABYLON.Vector3.TransformCoordinatesToRef(this._camDir, this._invertMatrix, this._cam_axisZ);
  50156. this._cam_axisZ.normalize();
  50157. // set two orthogonal vectors (_cam_axisX and and _cam_axisY) to the rotated camDir axis (_cam_axisZ)
  50158. BABYLON.Vector3.CrossToRef(this._cam_axisZ, this._axisX, this._cam_axisY);
  50159. BABYLON.Vector3.CrossToRef(this._cam_axisY, this._cam_axisZ, this._cam_axisX);
  50160. this._cam_axisY.normalize();
  50161. this._cam_axisX.normalize();
  50162. }
  50163. }
  50164. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  50165. var idx = 0; // current position index in the global array positions32
  50166. var index = 0; // position start index in the global array positions32 of the current particle
  50167. var colidx = 0; // current color index in the global array colors32
  50168. var colorIndex = 0; // color start index in the global array colors32 of the current particle
  50169. var uvidx = 0; // current uv index in the global array uvs32
  50170. var uvIndex = 0; // uv start index in the global array uvs32 of the current particle
  50171. var pt = 0; // current index in the particle model shape
  50172. if (this.mesh.isFacetDataEnabled) {
  50173. this._computeBoundingBox = true;
  50174. }
  50175. if (this._computeBoundingBox) {
  50176. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  50177. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  50178. }
  50179. // particle loop
  50180. end = (end > this.nbParticles - 1) ? this.nbParticles - 1 : end;
  50181. for (var p = start; p <= end; p++) {
  50182. this._particle = this.particles[p];
  50183. this._shape = this._particle._model._shape;
  50184. this._shapeUV = this._particle._model._shapeUV;
  50185. // call to custom user function to update the particle properties
  50186. this.updateParticle(this._particle);
  50187. if (this._particle.isVisible) {
  50188. // particle rotation matrix
  50189. if (this.billboard) {
  50190. this._particle.rotation.x = 0.0;
  50191. this._particle.rotation.y = 0.0;
  50192. }
  50193. if (this._computeParticleRotation || this.billboard) {
  50194. if (this._particle.rotationQuaternion) {
  50195. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  50196. }
  50197. else {
  50198. this._yaw = this._particle.rotation.y;
  50199. this._pitch = this._particle.rotation.x;
  50200. this._roll = this._particle.rotation.z;
  50201. this._quaternionRotationYPR();
  50202. }
  50203. this._quaternionToRotationMatrix();
  50204. }
  50205. // particle vertex loop
  50206. for (pt = 0; pt < this._shape.length; pt++) {
  50207. idx = index + pt * 3;
  50208. colidx = colorIndex + pt * 4;
  50209. uvidx = uvIndex + pt * 2;
  50210. this._vertex.x = this._shape[pt].x;
  50211. this._vertex.y = this._shape[pt].y;
  50212. this._vertex.z = this._shape[pt].z;
  50213. if (this._computeParticleVertex) {
  50214. this.updateParticleVertex(this._particle, this._vertex, pt);
  50215. }
  50216. // positions
  50217. this._vertex.x *= this._particle.scaling.x;
  50218. this._vertex.y *= this._particle.scaling.y;
  50219. this._vertex.z *= this._particle.scaling.z;
  50220. 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];
  50221. 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;
  50222. 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;
  50223. 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;
  50224. 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;
  50225. 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;
  50226. 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;
  50227. if (this._computeBoundingBox) {
  50228. if (this._positions32[idx] < this._minimum.x) {
  50229. this._minimum.x = this._positions32[idx];
  50230. }
  50231. if (this._positions32[idx] > this._maximum.x) {
  50232. this._maximum.x = this._positions32[idx];
  50233. }
  50234. if (this._positions32[idx + 1] < this._minimum.y) {
  50235. this._minimum.y = this._positions32[idx + 1];
  50236. }
  50237. if (this._positions32[idx + 1] > this._maximum.y) {
  50238. this._maximum.y = this._positions32[idx + 1];
  50239. }
  50240. if (this._positions32[idx + 2] < this._minimum.z) {
  50241. this._minimum.z = this._positions32[idx + 2];
  50242. }
  50243. if (this._positions32[idx + 2] > this._maximum.z) {
  50244. this._maximum.z = this._positions32[idx + 2];
  50245. }
  50246. }
  50247. // normals : if the particles can't be morphed then just rotate the normals, what is much more faster than ComputeNormals()
  50248. if (!this._computeParticleVertex) {
  50249. this._normal.x = this._fixedNormal32[idx];
  50250. this._normal.y = this._fixedNormal32[idx + 1];
  50251. this._normal.z = this._fixedNormal32[idx + 2];
  50252. this._w = (this._normal.x * this._rotMatrix.m[3]) + (this._normal.y * this._rotMatrix.m[7]) + (this._normal.z * this._rotMatrix.m[11]) + this._rotMatrix.m[15];
  50253. 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]) / this._w;
  50254. 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]) / this._w;
  50255. 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]) / this._w;
  50256. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  50257. 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;
  50258. 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;
  50259. }
  50260. if (this._computeParticleColor) {
  50261. this._colors32[colidx] = this._particle.color.r;
  50262. this._colors32[colidx + 1] = this._particle.color.g;
  50263. this._colors32[colidx + 2] = this._particle.color.b;
  50264. this._colors32[colidx + 3] = this._particle.color.a;
  50265. }
  50266. if (this._computeParticleTexture) {
  50267. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  50268. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  50269. }
  50270. }
  50271. }
  50272. else {
  50273. for (pt = 0; pt < this._shape.length; pt++) {
  50274. idx = index + pt * 3;
  50275. colidx = colorIndex + pt * 4;
  50276. uvidx = uvIndex + pt * 2;
  50277. this._positions32[idx] = this._camera.position.x;
  50278. this._positions32[idx + 1] = this._camera.position.y;
  50279. this._positions32[idx + 2] = this._camera.position.z;
  50280. this._normals32[idx] = 0.0;
  50281. this._normals32[idx + 1] = 0.0;
  50282. this._normals32[idx + 2] = 0.0;
  50283. if (this._computeParticleColor) {
  50284. this._colors32[colidx] = this._particle.color.r;
  50285. this._colors32[colidx + 1] = this._particle.color.g;
  50286. this._colors32[colidx + 2] = this._particle.color.b;
  50287. this._colors32[colidx + 3] = this._particle.color.a;
  50288. }
  50289. if (this._computeParticleTexture) {
  50290. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  50291. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  50292. }
  50293. }
  50294. }
  50295. // if the particle intersections must be computed : update the bbInfo
  50296. if (this._particlesIntersect) {
  50297. var bInfo = this._particle._boundingInfo;
  50298. var bBox = bInfo.boundingBox;
  50299. var bSphere = bInfo.boundingSphere;
  50300. if (!this._bSphereOnly) {
  50301. // place, scale and rotate the particle bbox within the SPS local system, then update it
  50302. for (var b = 0; b < bBox.vectors.length; b++) {
  50303. this._vertex.x = this._particle._modelBoundingInfo.boundingBox.vectors[b].x * this._particle.scaling.x;
  50304. this._vertex.y = this._particle._modelBoundingInfo.boundingBox.vectors[b].y * this._particle.scaling.y;
  50305. this._vertex.z = this._particle._modelBoundingInfo.boundingBox.vectors[b].z * this._particle.scaling.z;
  50306. 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];
  50307. 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;
  50308. 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;
  50309. 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;
  50310. 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;
  50311. 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;
  50312. 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;
  50313. }
  50314. bBox._update(this.mesh._worldMatrix);
  50315. }
  50316. // place and scale the particle bouding sphere in the SPS local system, then update it
  50317. this._minBbox.x = this._particle._modelBoundingInfo.minimum.x * this._particle.scaling.x;
  50318. this._minBbox.y = this._particle._modelBoundingInfo.minimum.y * this._particle.scaling.y;
  50319. this._minBbox.z = this._particle._modelBoundingInfo.minimum.z * this._particle.scaling.z;
  50320. this._maxBbox.x = this._particle._modelBoundingInfo.maximum.x * this._particle.scaling.x;
  50321. this._maxBbox.y = this._particle._modelBoundingInfo.maximum.y * this._particle.scaling.y;
  50322. this._maxBbox.z = this._particle._modelBoundingInfo.maximum.z * this._particle.scaling.z;
  50323. bSphere.center.x = this._particle.position.x + (this._minBbox.x + this._maxBbox.x) * 0.5;
  50324. bSphere.center.y = this._particle.position.y + (this._minBbox.y + this._maxBbox.y) * 0.5;
  50325. bSphere.center.z = this._particle.position.z + (this._minBbox.z + this._maxBbox.z) * 0.5;
  50326. 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));
  50327. bSphere._update(this.mesh._worldMatrix);
  50328. }
  50329. // increment indexes for the next particle
  50330. index = idx + 3;
  50331. colorIndex = colidx + 4;
  50332. uvIndex = uvidx + 2;
  50333. }
  50334. // if the VBO must be updated
  50335. if (update) {
  50336. if (this._computeParticleColor) {
  50337. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  50338. }
  50339. if (this._computeParticleTexture) {
  50340. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  50341. }
  50342. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  50343. if (!this.mesh.areNormalsFrozen || this.mesh.isFacetDataEnabled) {
  50344. if (this._computeParticleVertex || this.mesh.isFacetDataEnabled) {
  50345. // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]
  50346. var params = this.mesh.isFacetDataEnabled ? this.mesh.getFacetDataParameters() : null;
  50347. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices, this._normals32, params);
  50348. for (var i = 0; i < this._normals32.length; i++) {
  50349. this._fixedNormal32[i] = this._normals32[i];
  50350. }
  50351. }
  50352. if (!this.mesh.areNormalsFrozen) {
  50353. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  50354. }
  50355. }
  50356. }
  50357. if (this._computeBoundingBox) {
  50358. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  50359. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  50360. }
  50361. this.afterUpdateParticles(start, end, update);
  50362. };
  50363. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  50364. this._halfroll = this._roll * 0.5;
  50365. this._halfpitch = this._pitch * 0.5;
  50366. this._halfyaw = this._yaw * 0.5;
  50367. this._sinRoll = Math.sin(this._halfroll);
  50368. this._cosRoll = Math.cos(this._halfroll);
  50369. this._sinPitch = Math.sin(this._halfpitch);
  50370. this._cosPitch = Math.cos(this._halfpitch);
  50371. this._sinYaw = Math.sin(this._halfyaw);
  50372. this._cosYaw = Math.cos(this._halfyaw);
  50373. this._quaternion.x = (this._cosYaw * this._sinPitch * this._cosRoll) + (this._sinYaw * this._cosPitch * this._sinRoll);
  50374. this._quaternion.y = (this._sinYaw * this._cosPitch * this._cosRoll) - (this._cosYaw * this._sinPitch * this._sinRoll);
  50375. this._quaternion.z = (this._cosYaw * this._cosPitch * this._sinRoll) - (this._sinYaw * this._sinPitch * this._cosRoll);
  50376. this._quaternion.w = (this._cosYaw * this._cosPitch * this._cosRoll) + (this._sinYaw * this._sinPitch * this._sinRoll);
  50377. };
  50378. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  50379. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  50380. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  50381. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  50382. this._rotMatrix.m[3] = 0;
  50383. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  50384. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  50385. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  50386. this._rotMatrix.m[7] = 0;
  50387. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  50388. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  50389. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  50390. this._rotMatrix.m[11] = 0;
  50391. this._rotMatrix.m[12] = 0;
  50392. this._rotMatrix.m[13] = 0;
  50393. this._rotMatrix.m[14] = 0;
  50394. this._rotMatrix.m[15] = 1.0;
  50395. };
  50396. /**
  50397. * Disposes the SPS
  50398. */
  50399. SolidParticleSystem.prototype.dispose = function () {
  50400. this.mesh.dispose();
  50401. this.vars = null;
  50402. // drop references to internal big arrays for the GC
  50403. this._positions = null;
  50404. this._indices = null;
  50405. this._normals = null;
  50406. this._uvs = null;
  50407. this._colors = null;
  50408. this._positions32 = null;
  50409. this._normals32 = null;
  50410. this._fixedNormal32 = null;
  50411. this._uvs32 = null;
  50412. this._colors32 = null;
  50413. this.pickedParticles = null;
  50414. };
  50415. /**
  50416. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  50417. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  50418. */
  50419. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  50420. if (!this._isVisibilityBoxLocked) {
  50421. this.mesh.refreshBoundingInfo();
  50422. }
  50423. };
  50424. /**
  50425. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  50426. * @param size the size (float) of the visibility box
  50427. * note : this doesn't lock the SPS mesh bounding box.
  50428. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  50429. */
  50430. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  50431. var vis = size / 2;
  50432. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  50433. };
  50434. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  50435. // getter and setter
  50436. get: function () {
  50437. return this._alwaysVisible;
  50438. },
  50439. /**
  50440. * Sets the SPS as always visible or not
  50441. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  50442. */
  50443. set: function (val) {
  50444. this._alwaysVisible = val;
  50445. this.mesh.alwaysSelectAsActiveMesh = val;
  50446. },
  50447. enumerable: true,
  50448. configurable: true
  50449. });
  50450. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  50451. get: function () {
  50452. return this._isVisibilityBoxLocked;
  50453. },
  50454. /**
  50455. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  50456. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  50457. */
  50458. set: function (val) {
  50459. this._isVisibilityBoxLocked = val;
  50460. this.mesh.getBoundingInfo().isLocked = val;
  50461. },
  50462. enumerable: true,
  50463. configurable: true
  50464. });
  50465. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  50466. // getters
  50467. get: function () {
  50468. return this._computeParticleRotation;
  50469. },
  50470. // Optimizer setters
  50471. /**
  50472. * Tells to `setParticles()` to compute the particle rotations or not.
  50473. * Default value : true. The SPS is faster when it's set to false.
  50474. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  50475. */
  50476. set: function (val) {
  50477. this._computeParticleRotation = val;
  50478. },
  50479. enumerable: true,
  50480. configurable: true
  50481. });
  50482. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  50483. get: function () {
  50484. return this._computeParticleColor;
  50485. },
  50486. /**
  50487. * Tells to `setParticles()` to compute the particle colors or not.
  50488. * Default value : true. The SPS is faster when it's set to false.
  50489. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  50490. */
  50491. set: function (val) {
  50492. this._computeParticleColor = val;
  50493. },
  50494. enumerable: true,
  50495. configurable: true
  50496. });
  50497. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  50498. get: function () {
  50499. return this._computeParticleTexture;
  50500. },
  50501. /**
  50502. * Tells to `setParticles()` to compute the particle textures or not.
  50503. * Default value : true. The SPS is faster when it's set to false.
  50504. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  50505. */
  50506. set: function (val) {
  50507. this._computeParticleTexture = val;
  50508. },
  50509. enumerable: true,
  50510. configurable: true
  50511. });
  50512. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  50513. get: function () {
  50514. return this._computeParticleVertex;
  50515. },
  50516. /**
  50517. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  50518. * Default value : false. The SPS is faster when it's set to false.
  50519. * Note : the particle custom vertex positions aren't stored values.
  50520. */
  50521. set: function (val) {
  50522. this._computeParticleVertex = val;
  50523. },
  50524. enumerable: true,
  50525. configurable: true
  50526. });
  50527. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  50528. get: function () {
  50529. return this._computeBoundingBox;
  50530. },
  50531. /**
  50532. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  50533. */
  50534. set: function (val) {
  50535. this._computeBoundingBox = val;
  50536. },
  50537. enumerable: true,
  50538. configurable: true
  50539. });
  50540. // =======================================================================
  50541. // Particle behavior logic
  50542. // these following methods may be overwritten by the user to fit his needs
  50543. /**
  50544. * This function does nothing. It may be overwritten to set all the particle first values.
  50545. * The SPS doesn't call this function, you may have to call it by your own.
  50546. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  50547. */
  50548. SolidParticleSystem.prototype.initParticles = function () {
  50549. };
  50550. /**
  50551. * This function does nothing. It may be overwritten to recycle a particle.
  50552. * The SPS doesn't call this function, you may have to call it by your own.
  50553. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  50554. */
  50555. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  50556. return particle;
  50557. };
  50558. /**
  50559. * Updates a particle : this function should be overwritten by the user.
  50560. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  50561. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  50562. * ex : just set a particle position or velocity and recycle conditions
  50563. */
  50564. SolidParticleSystem.prototype.updateParticle = function (particle) {
  50565. return particle;
  50566. };
  50567. /**
  50568. * Updates a vertex of a particle : it can be overwritten by the user.
  50569. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  50570. * @param particle the current particle
  50571. * @param vertex the current index of the current particle
  50572. * @param pt the index of the current vertex in the particle shape
  50573. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape
  50574. * ex : just set a vertex particle position
  50575. */
  50576. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  50577. return vertex;
  50578. };
  50579. /**
  50580. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  50581. * This does nothing and may be overwritten by the user.
  50582. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  50583. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  50584. * @param update the boolean update value actually passed to setParticles()
  50585. */
  50586. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  50587. };
  50588. /**
  50589. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  50590. * This will be passed three parameters.
  50591. * This does nothing and may be overwritten by the user.
  50592. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  50593. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  50594. * @param update the boolean update value actually passed to setParticles()
  50595. */
  50596. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  50597. };
  50598. return SolidParticleSystem;
  50599. }());
  50600. BABYLON.SolidParticleSystem = SolidParticleSystem;
  50601. })(BABYLON || (BABYLON = {}));
  50602. //# sourceMappingURL=babylon.solidParticleSystem.js.map
  50603. var BABYLON;
  50604. (function (BABYLON) {
  50605. var Internals;
  50606. (function (Internals) {
  50607. var FileFaceOrientation = (function () {
  50608. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  50609. this.name = name;
  50610. this.worldAxisForNormal = worldAxisForNormal;
  50611. this.worldAxisForFileX = worldAxisForFileX;
  50612. this.worldAxisForFileY = worldAxisForFileY;
  50613. }
  50614. return FileFaceOrientation;
  50615. }());
  50616. ;
  50617. /**
  50618. * Helper class dealing with the extraction of spherical polynomial dataArray
  50619. * from a cube map.
  50620. */
  50621. var CubeMapToSphericalPolynomialTools = (function () {
  50622. function CubeMapToSphericalPolynomialTools() {
  50623. }
  50624. /**
  50625. * Converts a cubemap to the according Spherical Polynomial data.
  50626. * This extracts the first 3 orders only as they are the only one used in the lighting.
  50627. *
  50628. * @param cubeInfo The Cube map to extract the information from.
  50629. * @return The Spherical Polynomial data.
  50630. */
  50631. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  50632. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  50633. var totalSolidAngle = 0.0;
  50634. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  50635. var du = 2.0 / cubeInfo.size;
  50636. var dv = du;
  50637. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  50638. var minUV = du * 0.5 - 1.0;
  50639. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  50640. var fileFace = this.FileFaces[faceIndex];
  50641. var dataArray = cubeInfo[fileFace.name];
  50642. var v = minUV;
  50643. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  50644. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  50645. // Because SP is still linear, so summation is fine in that basis.
  50646. for (var y = 0; y < cubeInfo.size; y++) {
  50647. var u = minUV;
  50648. for (var x = 0; x < cubeInfo.size; x++) {
  50649. // World direction (not normalised)
  50650. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  50651. worldDirection.normalize();
  50652. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  50653. if (1) {
  50654. var r = dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0];
  50655. var g = dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1];
  50656. var b = dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2];
  50657. var color = new BABYLON.Color3(r, g, b);
  50658. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  50659. }
  50660. else {
  50661. if (faceIndex == 0) {
  50662. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 1;
  50663. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 0;
  50664. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 0;
  50665. }
  50666. else if (faceIndex == 1) {
  50667. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 0;
  50668. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 1;
  50669. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 0;
  50670. }
  50671. else if (faceIndex == 2) {
  50672. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 0;
  50673. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 0;
  50674. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 1;
  50675. }
  50676. else if (faceIndex == 3) {
  50677. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 1;
  50678. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 1;
  50679. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 0;
  50680. }
  50681. else if (faceIndex == 4) {
  50682. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 1;
  50683. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 0;
  50684. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 1;
  50685. }
  50686. else if (faceIndex == 5) {
  50687. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 0;
  50688. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 1;
  50689. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 1;
  50690. }
  50691. 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]);
  50692. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  50693. }
  50694. totalSolidAngle += deltaSolidAngle;
  50695. u += du;
  50696. }
  50697. v += dv;
  50698. }
  50699. }
  50700. var correctSolidAngle = 4.0 * Math.PI; // Solid angle for entire sphere is 4*pi
  50701. var correction = correctSolidAngle / totalSolidAngle;
  50702. sphericalHarmonics.scale(correction);
  50703. // Additionally scale by pi -- audit needed
  50704. sphericalHarmonics.scale(1.0 / Math.PI);
  50705. return BABYLON.SphericalPolynomial.getSphericalPolynomialFromHarmonics(sphericalHarmonics);
  50706. };
  50707. return CubeMapToSphericalPolynomialTools;
  50708. }());
  50709. CubeMapToSphericalPolynomialTools.FileFaces = [
  50710. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  50711. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  50712. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  50713. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  50714. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  50715. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  50716. ];
  50717. Internals.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  50718. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  50719. })(BABYLON || (BABYLON = {}));
  50720. //# sourceMappingURL=babylon.tools.cubemapToSphericalPolynomial.js.map
  50721. var BABYLON;
  50722. (function (BABYLON) {
  50723. var Internals;
  50724. (function (Internals) {
  50725. /**
  50726. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  50727. */
  50728. var PanoramaToCubeMapTools = (function () {
  50729. function PanoramaToCubeMapTools() {
  50730. }
  50731. /**
  50732. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  50733. *
  50734. * @param float32Array The source data.
  50735. * @param inputWidth The width of the input panorama.
  50736. * @param inputhHeight The height of the input panorama.
  50737. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  50738. * @return The cubemap data
  50739. */
  50740. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  50741. if (!float32Array) {
  50742. throw "ConvertPanoramaToCubemap: input cannot be null";
  50743. }
  50744. if (float32Array.length != inputWidth * inputHeight * 3) {
  50745. throw "ConvertPanoramaToCubemap: input size is wrong";
  50746. }
  50747. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  50748. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  50749. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  50750. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  50751. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  50752. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  50753. return {
  50754. front: textureFront,
  50755. back: textureBack,
  50756. left: textureLeft,
  50757. right: textureRight,
  50758. up: textureUp,
  50759. down: textureDown,
  50760. size: size
  50761. };
  50762. };
  50763. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  50764. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  50765. var textureArray = new Float32Array(buffer);
  50766. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  50767. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  50768. var dy = 1 / texSize;
  50769. var fy = 0;
  50770. for (var y = 0; y < texSize; y++) {
  50771. var xv1 = faceData[0];
  50772. var xv2 = faceData[2];
  50773. for (var x = 0; x < texSize; x++) {
  50774. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  50775. v.normalize();
  50776. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  50777. // 3 channels per pixels
  50778. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  50779. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  50780. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  50781. xv1 = xv1.add(rotDX1);
  50782. xv2 = xv2.add(rotDX2);
  50783. }
  50784. fy += dy;
  50785. }
  50786. return textureArray;
  50787. };
  50788. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  50789. var theta = Math.atan2(vDir.z, vDir.x);
  50790. var phi = Math.acos(vDir.y);
  50791. while (theta < -Math.PI)
  50792. theta += 2 * Math.PI;
  50793. while (theta > Math.PI)
  50794. theta -= 2 * Math.PI;
  50795. var dx = theta / Math.PI;
  50796. var dy = phi / Math.PI;
  50797. // recenter.
  50798. dx = dx * 0.5 + 0.5;
  50799. var px = Math.round(dx * inputWidth);
  50800. if (px < 0)
  50801. px = 0;
  50802. else if (px >= inputWidth)
  50803. px = inputWidth - 1;
  50804. var py = Math.round(dy * inputHeight);
  50805. if (py < 0)
  50806. py = 0;
  50807. else if (py >= inputHeight)
  50808. py = inputHeight - 1;
  50809. var inputY = (inputHeight - py - 1);
  50810. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  50811. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  50812. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  50813. return {
  50814. r: r,
  50815. g: g,
  50816. b: b
  50817. };
  50818. };
  50819. return PanoramaToCubeMapTools;
  50820. }());
  50821. PanoramaToCubeMapTools.FACE_FRONT = [
  50822. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  50823. new BABYLON.Vector3(1.0, -1.0, -1.0),
  50824. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  50825. new BABYLON.Vector3(1.0, 1.0, -1.0)
  50826. ];
  50827. PanoramaToCubeMapTools.FACE_BACK = [
  50828. new BABYLON.Vector3(1.0, -1.0, 1.0),
  50829. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  50830. new BABYLON.Vector3(1.0, 1.0, 1.0),
  50831. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  50832. ];
  50833. PanoramaToCubeMapTools.FACE_RIGHT = [
  50834. new BABYLON.Vector3(1.0, -1.0, -1.0),
  50835. new BABYLON.Vector3(1.0, -1.0, 1.0),
  50836. new BABYLON.Vector3(1.0, 1.0, -1.0),
  50837. new BABYLON.Vector3(1.0, 1.0, 1.0)
  50838. ];
  50839. PanoramaToCubeMapTools.FACE_LEFT = [
  50840. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  50841. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  50842. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  50843. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  50844. ];
  50845. PanoramaToCubeMapTools.FACE_DOWN = [
  50846. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  50847. new BABYLON.Vector3(1.0, 1.0, -1.0),
  50848. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  50849. new BABYLON.Vector3(1.0, 1.0, 1.0)
  50850. ];
  50851. PanoramaToCubeMapTools.FACE_UP = [
  50852. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  50853. new BABYLON.Vector3(1.0, -1.0, 1.0),
  50854. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  50855. new BABYLON.Vector3(1.0, -1.0, -1.0)
  50856. ];
  50857. Internals.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  50858. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  50859. })(BABYLON || (BABYLON = {}));
  50860. //# sourceMappingURL=babylon.tools.panoramaToCubemap.js.map
  50861. var BABYLON;
  50862. (function (BABYLON) {
  50863. var Internals;
  50864. (function (Internals) {
  50865. ;
  50866. /**
  50867. * This groups tools to convert HDR texture to native colors array.
  50868. */
  50869. var HDRTools = (function () {
  50870. function HDRTools() {
  50871. }
  50872. HDRTools.Ldexp = function (mantissa, exponent) {
  50873. if (exponent > 1023) {
  50874. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  50875. }
  50876. if (exponent < -1074) {
  50877. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  50878. }
  50879. return mantissa * Math.pow(2, exponent);
  50880. };
  50881. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  50882. if (exponent > 0) {
  50883. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  50884. float32array[index + 0] = red * exponent;
  50885. float32array[index + 1] = green * exponent;
  50886. float32array[index + 2] = blue * exponent;
  50887. }
  50888. else {
  50889. float32array[index + 0] = 0;
  50890. float32array[index + 1] = 0;
  50891. float32array[index + 2] = 0;
  50892. }
  50893. };
  50894. HDRTools.readStringLine = function (uint8array, startIndex) {
  50895. var line = "";
  50896. var character = "";
  50897. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  50898. character = String.fromCharCode(uint8array[i]);
  50899. if (character == "\n") {
  50900. break;
  50901. }
  50902. line += character;
  50903. }
  50904. return line;
  50905. };
  50906. /**
  50907. * Reads header information from an RGBE texture stored in a native array.
  50908. * More information on this format are available here:
  50909. * https://en.wikipedia.org/wiki/RGBE_image_format
  50910. *
  50911. * @param uint8array The binary file stored in native array.
  50912. * @return The header information.
  50913. */
  50914. HDRTools.RGBE_ReadHeader = function (uint8array) {
  50915. var height = 0;
  50916. var width = 0;
  50917. var line = this.readStringLine(uint8array, 0);
  50918. if (line[0] != '#' || line[1] != '?') {
  50919. throw "Bad HDR Format.";
  50920. }
  50921. var endOfHeader = false;
  50922. var findFormat = false;
  50923. var lineIndex = 0;
  50924. do {
  50925. lineIndex += (line.length + 1);
  50926. line = this.readStringLine(uint8array, lineIndex);
  50927. if (line == "FORMAT=32-bit_rle_rgbe") {
  50928. findFormat = true;
  50929. }
  50930. else if (line.length == 0) {
  50931. endOfHeader = true;
  50932. }
  50933. } while (!endOfHeader);
  50934. if (!findFormat) {
  50935. throw "HDR Bad header format, unsupported FORMAT";
  50936. }
  50937. lineIndex += (line.length + 1);
  50938. line = this.readStringLine(uint8array, lineIndex);
  50939. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  50940. var match = sizeRegexp.exec(line);
  50941. // TODO. Support +Y and -X if needed.
  50942. if (match.length < 3) {
  50943. throw "HDR Bad header format, no size";
  50944. }
  50945. width = parseInt(match[2]);
  50946. height = parseInt(match[1]);
  50947. if (width < 8 || width > 0x7fff) {
  50948. throw "HDR Bad header format, unsupported size";
  50949. }
  50950. lineIndex += (line.length + 1);
  50951. return {
  50952. height: height,
  50953. width: width,
  50954. dataPosition: lineIndex
  50955. };
  50956. };
  50957. /**
  50958. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  50959. * This RGBE texture needs to store the information as a panorama.
  50960. *
  50961. * More information on this format are available here:
  50962. * https://en.wikipedia.org/wiki/RGBE_image_format
  50963. *
  50964. * @param buffer The binary file stored in an array buffer.
  50965. * @param size The expected size of the extracted cubemap.
  50966. * @return The Cube Map information.
  50967. */
  50968. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  50969. var uint8array = new Uint8Array(buffer);
  50970. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  50971. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  50972. var cubeMapData = Internals.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  50973. return cubeMapData;
  50974. };
  50975. /**
  50976. * Returns the pixels data extracted from an RGBE texture.
  50977. * This pixels will be stored left to right up to down in the R G B order in one array.
  50978. *
  50979. * More information on this format are available here:
  50980. * https://en.wikipedia.org/wiki/RGBE_image_format
  50981. *
  50982. * @param uint8array The binary file stored in an array buffer.
  50983. * @param hdrInfo The header information of the file.
  50984. * @return The pixels data in RGB right to left up to down order.
  50985. */
  50986. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  50987. // Keep for multi format supports.
  50988. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  50989. };
  50990. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  50991. var num_scanlines = hdrInfo.height;
  50992. var scanline_width = hdrInfo.width;
  50993. var a, b, c, d, count;
  50994. var dataIndex = hdrInfo.dataPosition;
  50995. var index = 0, endIndex = 0, i = 0;
  50996. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  50997. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  50998. // 3 channels of 4 bytes per pixel in float.
  50999. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  51000. var resultArray = new Float32Array(resultBuffer);
  51001. // read in each successive scanline
  51002. while (num_scanlines > 0) {
  51003. a = uint8array[dataIndex++];
  51004. b = uint8array[dataIndex++];
  51005. c = uint8array[dataIndex++];
  51006. d = uint8array[dataIndex++];
  51007. if (a != 2 || b != 2 || (c & 0x80)) {
  51008. // this file is not run length encoded
  51009. throw "HDR Bad header format, not RLE";
  51010. }
  51011. if (((c << 8) | d) != scanline_width) {
  51012. throw "HDR Bad header format, wrong scan line width";
  51013. }
  51014. index = 0;
  51015. // read each of the four channels for the scanline into the buffer
  51016. for (i = 0; i < 4; i++) {
  51017. endIndex = (i + 1) * scanline_width;
  51018. while (index < endIndex) {
  51019. a = uint8array[dataIndex++];
  51020. b = uint8array[dataIndex++];
  51021. if (a > 128) {
  51022. // a run of the same value
  51023. count = a - 128;
  51024. if ((count == 0) || (count > endIndex - index)) {
  51025. throw "HDR Bad Format, bad scanline data (run)";
  51026. }
  51027. while (count-- > 0) {
  51028. scanLineArray[index++] = b;
  51029. }
  51030. }
  51031. else {
  51032. // a non-run
  51033. count = a;
  51034. if ((count == 0) || (count > endIndex - index)) {
  51035. throw "HDR Bad Format, bad scanline data (non-run)";
  51036. }
  51037. scanLineArray[index++] = b;
  51038. if (--count > 0) {
  51039. for (var j = 0; j < count; j++) {
  51040. scanLineArray[index++] = uint8array[dataIndex++];
  51041. }
  51042. }
  51043. }
  51044. }
  51045. }
  51046. // now convert data from buffer into floats
  51047. for (i = 0; i < scanline_width; i++) {
  51048. a = scanLineArray[i];
  51049. b = scanLineArray[i + scanline_width];
  51050. c = scanLineArray[i + 2 * scanline_width];
  51051. d = scanLineArray[i + 3 * scanline_width];
  51052. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  51053. }
  51054. num_scanlines--;
  51055. }
  51056. return resultArray;
  51057. };
  51058. return HDRTools;
  51059. }());
  51060. Internals.HDRTools = HDRTools;
  51061. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  51062. })(BABYLON || (BABYLON = {}));
  51063. //# sourceMappingURL=babylon.tools.hdr.js.map
  51064. //_______________________________________________________________
  51065. // Extracted from CubeMapGen:
  51066. // https://code.google.com/archive/p/cubemapgen/
  51067. //
  51068. // Following https://seblagarde.wordpress.com/2012/06/10/amd-cubemapgen-for-physically-based-rendering/
  51069. //_______________________________________________________________
  51070. var BABYLON;
  51071. (function (BABYLON) {
  51072. var Internals;
  51073. (function (Internals) {
  51074. /**
  51075. * The bounding box information used during the conversion process.
  51076. */
  51077. var CMGBoundinBox = (function () {
  51078. function CMGBoundinBox() {
  51079. this.min = new BABYLON.Vector3(0, 0, 0);
  51080. this.max = new BABYLON.Vector3(0, 0, 0);
  51081. this.clear();
  51082. }
  51083. CMGBoundinBox.prototype.clear = function () {
  51084. this.min.x = CMGBoundinBox.MAX;
  51085. this.min.y = CMGBoundinBox.MAX;
  51086. this.min.z = CMGBoundinBox.MAX;
  51087. this.max.x = CMGBoundinBox.MIN;
  51088. this.max.y = CMGBoundinBox.MIN;
  51089. this.max.z = CMGBoundinBox.MIN;
  51090. };
  51091. CMGBoundinBox.prototype.augment = function (x, y, z) {
  51092. this.min.x = Math.min(this.min.x, x);
  51093. this.min.y = Math.min(this.min.y, y);
  51094. this.min.z = Math.min(this.min.z, z);
  51095. this.max.x = Math.max(this.max.x, x);
  51096. this.max.y = Math.max(this.max.y, y);
  51097. this.max.z = Math.max(this.max.z, z);
  51098. };
  51099. CMGBoundinBox.prototype.clampMin = function (x, y, z) {
  51100. this.min.x = Math.max(this.min.x, x);
  51101. this.min.y = Math.max(this.min.y, y);
  51102. this.min.z = Math.max(this.min.z, z);
  51103. };
  51104. CMGBoundinBox.prototype.clampMax = function (x, y, z) {
  51105. this.max.x = Math.min(this.max.x, x);
  51106. this.max.y = Math.min(this.max.y, y);
  51107. this.max.z = Math.min(this.max.z, z);
  51108. };
  51109. CMGBoundinBox.prototype.empty = function () {
  51110. if ((this.min.x > this.max.y) ||
  51111. (this.min.y > this.max.y) ||
  51112. (this.min.z > this.max.y)) {
  51113. return true;
  51114. }
  51115. else {
  51116. return false;
  51117. }
  51118. };
  51119. return CMGBoundinBox;
  51120. }());
  51121. CMGBoundinBox.MAX = Number.MAX_VALUE;
  51122. CMGBoundinBox.MIN = Number.MIN_VALUE;
  51123. /**
  51124. * Helper class to PreProcess a cubemap in order to generate mipmap according to the level of blur
  51125. * required by the glossinees of a material.
  51126. *
  51127. * This only supports the cosine drop power as well as Warp fixup generation method.
  51128. *
  51129. * This is using the process from CubeMapGen described here:
  51130. * https://seblagarde.wordpress.com/2012/06/10/amd-cubemapgen-for-physically-based-rendering/
  51131. */
  51132. var PMREMGenerator = (function () {
  51133. /**
  51134. * Constructor of the generator.
  51135. *
  51136. * @param input The different faces data from the original cubemap in the order X+ X- Y+ Y- Z+ Z-
  51137. * @param inputSize The size of the cubemap faces
  51138. * @param outputSize The size of the output cubemap faces
  51139. * @param maxNumMipLevels The max number of mip map to generate (0 means all)
  51140. * @param numChannels The number of channels stored in the cubemap (3 for RBGE for instance)
  51141. * @param isFloat Specifies if the input texture is in float or int (hdr is usually in float)
  51142. * @param specularPower The max specular level of the desired cubemap
  51143. * @param cosinePowerDropPerMip The amount of drop the specular power will follow on each mip
  51144. * @param excludeBase Specifies wether to process the level 0 (original level) or not
  51145. * @param fixup Specifies wether to apply the edge fixup algorythm or not
  51146. */
  51147. function PMREMGenerator(input, inputSize, outputSize, maxNumMipLevels, numChannels, isFloat, specularPower, cosinePowerDropPerMip, excludeBase, fixup) {
  51148. this.input = input;
  51149. this.inputSize = inputSize;
  51150. this.outputSize = outputSize;
  51151. this.maxNumMipLevels = maxNumMipLevels;
  51152. this.numChannels = numChannels;
  51153. this.isFloat = isFloat;
  51154. this.specularPower = specularPower;
  51155. this.cosinePowerDropPerMip = cosinePowerDropPerMip;
  51156. this.excludeBase = excludeBase;
  51157. this.fixup = fixup;
  51158. this._outputSurface = [];
  51159. this._numMipLevels = 0;
  51160. }
  51161. /**
  51162. * Launches the filter process and return the result.
  51163. *
  51164. * @return the filter cubemap in the form mip0 [faces1..6] .. mipN [faces1..6]
  51165. */
  51166. PMREMGenerator.prototype.filterCubeMap = function () {
  51167. // Init cubemap processor
  51168. this.init();
  51169. // Filters the cubemap
  51170. this.filterCubeMapMipChain();
  51171. // Returns the filtered mips.
  51172. return this._outputSurface;
  51173. };
  51174. PMREMGenerator.prototype.init = function () {
  51175. var i;
  51176. var j;
  51177. var mipLevelSize;
  51178. //if nax num mip levels is set to 0, set it to generate the entire mip chain
  51179. if (this.maxNumMipLevels == 0) {
  51180. this.maxNumMipLevels = PMREMGenerator.CP_MAX_MIPLEVELS;
  51181. }
  51182. //first miplevel size
  51183. mipLevelSize = this.outputSize;
  51184. //Iterate over mip chain, and init ArrayBufferView for mip-chain
  51185. for (j = 0; j < this.maxNumMipLevels; j++) {
  51186. this._outputSurface.length++;
  51187. this._outputSurface[j] = [];
  51188. //Iterate over faces for output images
  51189. for (i = 0; i < 6; i++) {
  51190. this._outputSurface[j].length++;
  51191. // Initializes a new array for the output.
  51192. if (this.isFloat) {
  51193. this._outputSurface[j][i] = new Float32Array(mipLevelSize * mipLevelSize * this.numChannels);
  51194. }
  51195. else {
  51196. this._outputSurface[j][i] = new Uint32Array(mipLevelSize * mipLevelSize * this.numChannels);
  51197. }
  51198. }
  51199. //next mip level is half size
  51200. mipLevelSize >>= 1;
  51201. this._numMipLevels++;
  51202. //terminate if mip chain becomes too small
  51203. if (mipLevelSize == 0) {
  51204. this.maxNumMipLevels = j;
  51205. return;
  51206. }
  51207. }
  51208. };
  51209. //--------------------------------------------------------------------------------------
  51210. //Cube map filtering and mip chain generation.
  51211. // the cube map filtereing is specified using a number of parameters:
  51212. // Filtering per miplevel is specified using 2D cone angle (in degrees) that
  51213. // indicates the region of the hemisphere to filter over for each tap.
  51214. //
  51215. // Note that the top mip level is also a filtered version of the original input images
  51216. // as well in order to create mip chains for diffuse environment illumination.
  51217. // The cone angle for the top level is specified by a_BaseAngle. This can be used to
  51218. // generate mipchains used to store the resutls of preintegration across the hemisphere.
  51219. //
  51220. // Then the mip angle used to genreate the next level of the mip chain from the first level
  51221. // is a_InitialMipAngle
  51222. //
  51223. // The angle for the subsequent levels of the mip chain are specified by their parents
  51224. // filtering angle and a per-level scale and bias
  51225. // newAngle = oldAngle * a_MipAnglePerLevelScale;
  51226. //
  51227. //--------------------------------------------------------------------------------------
  51228. PMREMGenerator.prototype.filterCubeMapMipChain = function () {
  51229. // First, take count of the lighting model to modify SpecularPower
  51230. // 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;
  51231. // var refSpecularPower = this.specularPower; // Only Phong BRDF yet. This explains the line below using this.specularpower.
  51232. //Cone angle start (for generating subsequent mip levels)
  51233. var currentSpecularPower = this.specularPower;
  51234. //Build filter lookup tables based on the source miplevel size
  51235. this.precomputeFilterLookupTables(this.inputSize);
  51236. // Note that we need to filter the first level before generating mipmap
  51237. // So LevelIndex == 0 is base filtering hen LevelIndex > 0 is mipmap generation
  51238. for (var levelIndex = 0; levelIndex < this._numMipLevels; levelIndex++) {
  51239. // TODO : Write a function to copy and scale the base mipmap in output
  51240. // I am just lazy here and just put a high specular power value, and do some if.
  51241. if (this.excludeBase && (levelIndex == 0)) {
  51242. // 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).
  51243. currentSpecularPower = 100000.0;
  51244. }
  51245. // Special case for cosine power mipmap chain. For quality requirement, we always process the current mipmap from the top mipmap
  51246. var srcCubeImage = this.input;
  51247. var dstCubeImage = this._outputSurface[levelIndex];
  51248. var dstSize = this.outputSize >> levelIndex;
  51249. // Compute required angle.
  51250. var angle = this.getBaseFilterAngle(currentSpecularPower);
  51251. // filter cube surfaces
  51252. this.filterCubeSurfaces(srcCubeImage, this.inputSize, dstCubeImage, dstSize, angle, currentSpecularPower);
  51253. // fix seams
  51254. if (this.fixup) {
  51255. this.fixupCubeEdges(dstCubeImage, dstSize);
  51256. }
  51257. // Decrease the specular power to generate the mipmap chain
  51258. // TODO : Use another method for Exclude (see first comment at start of the function
  51259. if (this.excludeBase && (levelIndex == 0)) {
  51260. currentSpecularPower = this.specularPower;
  51261. }
  51262. currentSpecularPower *= this.cosinePowerDropPerMip;
  51263. }
  51264. };
  51265. //--------------------------------------------------------------------------------------
  51266. // This function return the BaseFilterAngle require by PMREMGenerator to its FilterExtends
  51267. // It allow to optimize the texel to access base on the specular power.
  51268. //--------------------------------------------------------------------------------------
  51269. PMREMGenerator.prototype.getBaseFilterAngle = function (cosinePower) {
  51270. // We want to find the alpha such that:
  51271. // cos(alpha)^cosinePower = epsilon
  51272. // That's: acos(epsilon^(1/cosinePower))
  51273. var threshold = 0.000001; // Empirical threshold (Work perfectly, didn't check for a more big number, may get some performance and still god approximation)
  51274. var angle = 180.0;
  51275. angle = Math.acos(Math.pow(threshold, 1.0 / cosinePower));
  51276. angle *= 180.0 / Math.PI; // Convert to degree
  51277. angle *= 2.0; // * 2.0f because PMREMGenerator divide by 2 later
  51278. return angle;
  51279. };
  51280. //--------------------------------------------------------------------------------------
  51281. //Builds the following lookup tables prior to filtering:
  51282. // -normalizer cube map
  51283. // -tap weight lookup table
  51284. //
  51285. //--------------------------------------------------------------------------------------
  51286. PMREMGenerator.prototype.precomputeFilterLookupTables = function (srcCubeMapWidth) {
  51287. var srcTexelAngle;
  51288. var iCubeFace;
  51289. //clear pre-existing normalizer cube map
  51290. this._normCubeMap = [];
  51291. //Normalized vectors per cubeface and per-texel solid angle
  51292. this.buildNormalizerSolidAngleCubemap(srcCubeMapWidth);
  51293. };
  51294. //--------------------------------------------------------------------------------------
  51295. //Builds a normalizer cubemap, with the texels solid angle stored in the fourth component
  51296. //
  51297. //Takes in a cube face size, and an array of 6 surfaces to write the cube faces into
  51298. //
  51299. //Note that this normalizer cube map stores the vectors in unbiased -1 to 1 range.
  51300. // if _bx2 style scaled and biased vectors are needed, uncomment the SCALE and BIAS
  51301. // below
  51302. //--------------------------------------------------------------------------------------
  51303. PMREMGenerator.prototype.buildNormalizerSolidAngleCubemap = function (size) {
  51304. var iCubeFace;
  51305. var u;
  51306. var v;
  51307. //iterate over cube faces
  51308. for (iCubeFace = 0; iCubeFace < 6; iCubeFace++) {
  51309. //First three channels for norm cube, and last channel for solid angle
  51310. this._normCubeMap.push(new Float32Array(size * size * 4));
  51311. //fast texture walk, build normalizer cube map
  51312. var facesData = this.input[iCubeFace];
  51313. for (v = 0; v < size; v++) {
  51314. for (u = 0; u < size; u++) {
  51315. var vect = this.texelCoordToVect(iCubeFace, u, v, size, this.fixup);
  51316. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 0] = vect.x;
  51317. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 1] = vect.y;
  51318. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 2] = vect.z;
  51319. var solidAngle = this.texelCoordSolidAngle(iCubeFace, u, v, size);
  51320. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 4] = solidAngle;
  51321. }
  51322. }
  51323. }
  51324. };
  51325. //--------------------------------------------------------------------------------------
  51326. // Convert cubemap face texel coordinates and face idx to 3D vector
  51327. // note the U and V coords are integer coords and range from 0 to size-1
  51328. // this routine can be used to generate a normalizer cube map
  51329. //--------------------------------------------------------------------------------------
  51330. // SL BEGIN
  51331. PMREMGenerator.prototype.texelCoordToVect = function (faceIdx, u, v, size, fixup) {
  51332. var nvcU;
  51333. var nvcV;
  51334. var tempVec;
  51335. // Change from original AMD code
  51336. // transform from [0..res - 1] to [- (1 - 1 / res) .. (1 - 1 / res)]
  51337. // + 0.5f is for texel center addressing
  51338. nvcU = (2.0 * (u + 0.5) / size) - 1.0;
  51339. nvcV = (2.0 * (v + 0.5) / size) - 1.0;
  51340. // warp fixup
  51341. if (fixup && size > 1) {
  51342. // Code from Nvtt : http://code.google.com/p/nvidia-texture-tools/source/browse/trunk/src/nvtt/CubeSurface.cpp
  51343. var a = Math.pow(size, 2.0) / Math.pow(size - 1, 3.0);
  51344. nvcU = a * Math.pow(nvcU, 3) + nvcU;
  51345. nvcV = a * Math.pow(nvcV, 3) + nvcV;
  51346. }
  51347. // Get current vector
  51348. // generate x,y,z vector (xform 2d NVC coord to 3D vector)
  51349. // U contribution
  51350. var UVec = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_UDIR];
  51351. PMREMGenerator._vectorTemp.x = UVec[0] * nvcU;
  51352. PMREMGenerator._vectorTemp.y = UVec[1] * nvcU;
  51353. PMREMGenerator._vectorTemp.z = UVec[2] * nvcU;
  51354. // V contribution and Sum
  51355. var VVec = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_VDIR];
  51356. PMREMGenerator._vectorTemp.x += VVec[0] * nvcV;
  51357. PMREMGenerator._vectorTemp.y += VVec[1] * nvcV;
  51358. PMREMGenerator._vectorTemp.z += VVec[2] * nvcV;
  51359. //add face axis
  51360. var faceAxis = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_FACEAXIS];
  51361. PMREMGenerator._vectorTemp.x += faceAxis[0];
  51362. PMREMGenerator._vectorTemp.y += faceAxis[1];
  51363. PMREMGenerator._vectorTemp.z += faceAxis[2];
  51364. //normalize vector
  51365. PMREMGenerator._vectorTemp.normalize();
  51366. return PMREMGenerator._vectorTemp;
  51367. };
  51368. //--------------------------------------------------------------------------------------
  51369. // Convert 3D vector to cubemap face texel coordinates and face idx
  51370. // note the U and V coords are integer coords and range from 0 to size-1
  51371. // this routine can be used to generate a normalizer cube map
  51372. //
  51373. // returns face IDX and texel coords
  51374. //--------------------------------------------------------------------------------------
  51375. // SL BEGIN
  51376. /*
  51377. Mapping Texture Coordinates to Cube Map Faces
  51378. Because there are multiple faces, the mapping of texture coordinates to positions on cube map faces
  51379. is more complicated than the other texturing targets. The EXT_texture_cube_map extension is purposefully
  51380. designed to be consistent with DirectX 7's cube map arrangement. This is also consistent with the cube
  51381. map arrangement in Pixar's RenderMan package.
  51382. For cube map texturing, the (s,t,r) texture coordinates are treated as a direction vector (rx,ry,rz)
  51383. emanating from the center of a cube. (The q coordinate can be ignored since it merely scales the vector
  51384. without affecting the direction.) At texture application time, the interpolated per-fragment (s,t,r)
  51385. selects one of the cube map face's 2D mipmap sets based on the largest magnitude coordinate direction
  51386. the major axis direction). The target column in the table below explains how the major axis direction
  51387. maps to the 2D image of a particular cube map target.
  51388. major axis
  51389. direction target sc tc ma
  51390. ---------- --------------------------------- --- --- ---
  51391. +rx GL_TEXTURE_CUBE_MAP_POSITIVE_X_EXT -rz -ry rx
  51392. -rx GL_TEXTURE_CUBE_MAP_NEGATIVE_X_EXT +rz -ry rx
  51393. +ry GL_TEXTURE_CUBE_MAP_POSITIVE_Y_EXT +rx +rz ry
  51394. -ry GL_TEXTURE_CUBE_MAP_NEGATIVE_Y_EXT +rx -rz ry
  51395. +rz GL_TEXTURE_CUBE_MAP_POSITIVE_Z_EXT +rx -ry rz
  51396. -rz GL_TEXTURE_CUBE_MAP_NEGATIVE_Z_EXT -rx -ry rz
  51397. Using the sc, tc, and ma determined by the major axis direction as specified in the table above,
  51398. an updated (s,t) is calculated as follows
  51399. s = ( sc/|ma| + 1 ) / 2
  51400. t = ( tc/|ma| + 1 ) / 2
  51401. If |ma| is zero or very nearly zero, the results of the above two equations need not be defined
  51402. (though the result may not lead to GL interruption or termination). Once the cube map face's 2D mipmap
  51403. set and (s,t) is determined, texture fetching and filtering proceeds like standard OpenGL 2D texturing.
  51404. */
  51405. // Note this method return U and V in range from 0 to size-1
  51406. // SL END
  51407. // Store the information in vector3 for convenience (faceindex, u, v)
  51408. PMREMGenerator.prototype.vectToTexelCoord = function (x, y, z, size) {
  51409. var maxCoord;
  51410. var faceIdx;
  51411. //absolute value 3
  51412. var absX = Math.abs(x);
  51413. var absY = Math.abs(y);
  51414. var absZ = Math.abs(z);
  51415. if (absX >= absY && absX >= absZ) {
  51416. maxCoord = absX;
  51417. if (x >= 0) {
  51418. faceIdx = PMREMGenerator.CP_FACE_X_POS;
  51419. }
  51420. else {
  51421. faceIdx = PMREMGenerator.CP_FACE_X_NEG;
  51422. }
  51423. }
  51424. else if (absY >= absX && absY >= absZ) {
  51425. maxCoord = absY;
  51426. if (y >= 0) {
  51427. faceIdx = PMREMGenerator.CP_FACE_Y_POS;
  51428. }
  51429. else {
  51430. faceIdx = PMREMGenerator.CP_FACE_Y_NEG;
  51431. }
  51432. }
  51433. else {
  51434. maxCoord = absZ;
  51435. if (z >= 0) {
  51436. faceIdx = PMREMGenerator.CP_FACE_Z_POS;
  51437. }
  51438. else {
  51439. faceIdx = PMREMGenerator.CP_FACE_Z_NEG;
  51440. }
  51441. }
  51442. //divide through by max coord so face vector lies on cube face
  51443. var scale = 1 / maxCoord;
  51444. x *= scale;
  51445. y *= scale;
  51446. z *= scale;
  51447. var temp = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_UDIR];
  51448. var nvcU = temp[0] * x + temp[1] * y + temp[2] * z;
  51449. temp = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_VDIR];
  51450. var nvcV = temp[0] * x + temp[1] * y + temp[2] * z;
  51451. // Modify original AMD code to return value from 0 to Size - 1
  51452. var u = Math.floor((size - 1) * 0.5 * (nvcU + 1.0));
  51453. var v = Math.floor((size - 1) * 0.5 * (nvcV + 1.0));
  51454. PMREMGenerator._vectorTemp.x = faceIdx;
  51455. PMREMGenerator._vectorTemp.y = u;
  51456. PMREMGenerator._vectorTemp.z = v;
  51457. return PMREMGenerator._vectorTemp;
  51458. };
  51459. //--------------------------------------------------------------------------------------
  51460. //Original code from Ignacio CastaÒo
  51461. // This formula is from Manne ÷hrstrˆm's thesis.
  51462. // Take two coordiantes in the range [-1, 1] that define a portion of a
  51463. // cube face and return the area of the projection of that portion on the
  51464. // surface of the sphere.
  51465. //--------------------------------------------------------------------------------------
  51466. PMREMGenerator.prototype.areaElement = function (x, y) {
  51467. return Math.atan2(x * y, Math.sqrt(x * x + y * y + 1));
  51468. };
  51469. PMREMGenerator.prototype.texelCoordSolidAngle = function (faceIdx, u, v, size) {
  51470. // transform from [0..res - 1] to [- (1 - 1 / res) .. (1 - 1 / res)]
  51471. // (+ 0.5f is for texel center addressing)
  51472. u = (2.0 * (u + 0.5) / size) - 1.0;
  51473. v = (2.0 * (v + 0.5) / size) - 1.0;
  51474. // Shift from a demi texel, mean 1.0f / a_Size with U and V in [-1..1]
  51475. var invResolution = 1.0 / size;
  51476. // U and V are the -1..1 texture coordinate on the current face.
  51477. // Get projected area for this texel
  51478. var x0 = u - invResolution;
  51479. var y0 = v - invResolution;
  51480. var x1 = u + invResolution;
  51481. var y1 = v + invResolution;
  51482. var solidAngle = this.areaElement(x0, y0) - this.areaElement(x0, y1) - this.areaElement(x1, y0) + this.areaElement(x1, y1);
  51483. return solidAngle;
  51484. };
  51485. //--------------------------------------------------------------------------------------
  51486. //The key to the speed of these filtering routines is to quickly define a per-face
  51487. // bounding box of pixels which enclose all the taps in the filter kernel efficiently.
  51488. // Later these pixels are selectively processed based on their dot products to see if
  51489. // they reside within the filtering cone.
  51490. //
  51491. //This is done by computing the smallest per-texel angle to get a conservative estimate
  51492. // of the number of texels needed to be covered in width and height order to filter the
  51493. // region. the bounding box for the center taps face is defined first, and if the
  51494. // filtereing region bleeds onto the other faces, bounding boxes for the other faces are
  51495. // defined next
  51496. //--------------------------------------------------------------------------------------
  51497. PMREMGenerator.prototype.filterCubeSurfaces = function (srcCubeMap, srcSize, dstCubeMap, dstSize, filterConeAngle, specularPower) {
  51498. // note that pixels within these regions may be rejected
  51499. // based on the anlge
  51500. var iCubeFace;
  51501. var u;
  51502. var v;
  51503. // bounding box per face to specify region to process
  51504. var filterExtents = [];
  51505. for (iCubeFace = 0; iCubeFace < 6; iCubeFace++) {
  51506. filterExtents.push(new CMGBoundinBox());
  51507. }
  51508. // min angle a src texel can cover (in degrees)
  51509. var srcTexelAngle = (180.0 / (Math.PI) * Math.atan2(1.0, srcSize));
  51510. // angle about center tap to define filter cone
  51511. // filter angle is 1/2 the cone angle
  51512. var filterAngle = filterConeAngle / 2.0;
  51513. //ensure filter angle is larger than a texel
  51514. if (filterAngle < srcTexelAngle) {
  51515. filterAngle = srcTexelAngle;
  51516. }
  51517. //ensure filter cone is always smaller than the hemisphere
  51518. if (filterAngle > 90.0) {
  51519. filterAngle = 90.0;
  51520. }
  51521. // the maximum number of texels in 1D the filter cone angle will cover
  51522. // used to determine bounding box size for filter extents
  51523. var filterSize = Math.ceil(filterAngle / srcTexelAngle);
  51524. // ensure conservative region always covers at least one texel
  51525. if (filterSize < 1) {
  51526. filterSize = 1;
  51527. }
  51528. // dotProdThresh threshold based on cone angle to determine whether or not taps
  51529. // reside within the cone angle
  51530. var dotProdThresh = Math.cos((Math.PI / 180.0) * filterAngle);
  51531. // process required faces
  51532. for (iCubeFace = 0; iCubeFace < 6; iCubeFace++) {
  51533. //iterate over dst cube map face texel
  51534. for (v = 0; v < dstSize; v++) {
  51535. for (u = 0; u < dstSize; u++) {
  51536. //get center tap direction
  51537. var centerTapDir = this.texelCoordToVect(iCubeFace, u, v, dstSize, this.fixup).clone();
  51538. //clear old per-face filter extents
  51539. this.clearFilterExtents(filterExtents);
  51540. //define per-face filter extents
  51541. this.determineFilterExtents(centerTapDir, srcSize, filterSize, filterExtents);
  51542. //perform filtering of src faces using filter extents
  51543. var vect = this.processFilterExtents(centerTapDir, dotProdThresh, filterExtents, srcCubeMap, srcSize, specularPower);
  51544. dstCubeMap[iCubeFace][(v * dstSize + u) * this.numChannels + 0] = vect.x;
  51545. dstCubeMap[iCubeFace][(v * dstSize + u) * this.numChannels + 1] = vect.y;
  51546. dstCubeMap[iCubeFace][(v * dstSize + u) * this.numChannels + 2] = vect.z;
  51547. }
  51548. }
  51549. }
  51550. };
  51551. //--------------------------------------------------------------------------------------
  51552. //Clear filter extents for the 6 cube map faces
  51553. //--------------------------------------------------------------------------------------
  51554. PMREMGenerator.prototype.clearFilterExtents = function (filterExtents) {
  51555. for (var iCubeFaces = 0; iCubeFaces < 6; iCubeFaces++) {
  51556. filterExtents[iCubeFaces].clear();
  51557. }
  51558. };
  51559. //--------------------------------------------------------------------------------------
  51560. //Define per-face bounding box filter extents
  51561. //
  51562. // These define conservative texel regions in each of the faces the filter can possibly
  51563. // process. When the pixels in the regions are actually processed, the dot product
  51564. // between the tap vector and the center tap vector is used to determine the weight of
  51565. // the tap and whether or not the tap is within the cone.
  51566. //
  51567. //--------------------------------------------------------------------------------------
  51568. PMREMGenerator.prototype.determineFilterExtents = function (centerTapDir, srcSize, bboxSize, filterExtents) {
  51569. //neighboring face and bleed over amount, and width of BBOX for
  51570. // left, right, top, and bottom edges of this face
  51571. var bleedOverAmount = [0, 0, 0, 0];
  51572. var bleedOverBBoxMin = [0, 0, 0, 0];
  51573. var bleedOverBBoxMax = [0, 0, 0, 0];
  51574. var neighborFace;
  51575. var neighborEdge;
  51576. var oppositeFaceIdx;
  51577. //get face idx, and u, v info from center tap dir
  51578. var result = this.vectToTexelCoord(centerTapDir.x, centerTapDir.y, centerTapDir.z, srcSize);
  51579. var faceIdx = result.x;
  51580. var u = result.y;
  51581. var v = result.z;
  51582. //define bbox size within face
  51583. filterExtents[faceIdx].augment(u - bboxSize, v - bboxSize, 0);
  51584. filterExtents[faceIdx].augment(u + bboxSize, v + bboxSize, 0);
  51585. filterExtents[faceIdx].clampMin(0, 0, 0);
  51586. filterExtents[faceIdx].clampMax(srcSize - 1, srcSize - 1, 0);
  51587. //u and v extent in face corresponding to center tap
  51588. var minU = filterExtents[faceIdx].min.x;
  51589. var minV = filterExtents[faceIdx].min.y;
  51590. var maxU = filterExtents[faceIdx].max.x;
  51591. var maxV = filterExtents[faceIdx].max.y;
  51592. //bleed over amounts for face across u=0 edge (left)
  51593. bleedOverAmount[0] = (bboxSize - u);
  51594. bleedOverBBoxMin[0] = minV;
  51595. bleedOverBBoxMax[0] = maxV;
  51596. //bleed over amounts for face across u=1 edge (right)
  51597. bleedOverAmount[1] = (u + bboxSize) - (srcSize - 1);
  51598. bleedOverBBoxMin[1] = minV;
  51599. bleedOverBBoxMax[1] = maxV;
  51600. //bleed over to face across v=0 edge (up)
  51601. bleedOverAmount[2] = (bboxSize - v);
  51602. bleedOverBBoxMin[2] = minU;
  51603. bleedOverBBoxMax[2] = maxU;
  51604. //bleed over to face across v=1 edge (down)
  51605. bleedOverAmount[3] = (v + bboxSize) - (srcSize - 1);
  51606. bleedOverBBoxMin[3] = minU;
  51607. bleedOverBBoxMax[3] = maxU;
  51608. //compute bleed over regions in neighboring faces
  51609. for (var i = 0; i < 4; i++) {
  51610. if (bleedOverAmount[i] > 0) {
  51611. neighborFace = PMREMGenerator._sgCubeNgh[faceIdx][i][0];
  51612. neighborEdge = PMREMGenerator._sgCubeNgh[faceIdx][i][1];
  51613. //For certain types of edge abutments, the bleedOverBBoxMin, and bleedOverBBoxMax need to
  51614. // be flipped: the cases are
  51615. // if a left edge mates with a left or bottom edge on the neighbor
  51616. // if a top edge mates with a top or right edge on the neighbor
  51617. // if a right edge mates with a right or top edge on the neighbor
  51618. // if a bottom edge mates with a bottom or left edge on the neighbor
  51619. //Seeing as the edges are enumerated as follows
  51620. // left =0
  51621. // right =1
  51622. // top =2
  51623. // bottom =3
  51624. //
  51625. // so if the edge enums are the same, or the sum of the enums == 3,
  51626. // the bbox needs to be flipped
  51627. if ((i == neighborEdge) || ((i + neighborEdge) == 3)) {
  51628. bleedOverBBoxMin[i] = (srcSize - 1) - bleedOverBBoxMin[i];
  51629. bleedOverBBoxMax[i] = (srcSize - 1) - bleedOverBBoxMax[i];
  51630. }
  51631. //The way the bounding box is extended onto the neighboring face
  51632. // depends on which edge of neighboring face abuts with this one
  51633. switch (PMREMGenerator._sgCubeNgh[faceIdx][i][1]) {
  51634. case PMREMGenerator.CP_EDGE_LEFT:
  51635. filterExtents[neighborFace].augment(0, bleedOverBBoxMin[i], 0);
  51636. filterExtents[neighborFace].augment(bleedOverAmount[i], bleedOverBBoxMax[i], 0);
  51637. break;
  51638. case PMREMGenerator.CP_EDGE_RIGHT:
  51639. filterExtents[neighborFace].augment((srcSize - 1), bleedOverBBoxMin[i], 0);
  51640. filterExtents[neighborFace].augment((srcSize - 1) - bleedOverAmount[i], bleedOverBBoxMax[i], 0);
  51641. break;
  51642. case PMREMGenerator.CP_EDGE_TOP:
  51643. filterExtents[neighborFace].augment(bleedOverBBoxMin[i], 0, 0);
  51644. filterExtents[neighborFace].augment(bleedOverBBoxMax[i], bleedOverAmount[i], 0);
  51645. break;
  51646. case PMREMGenerator.CP_EDGE_BOTTOM:
  51647. filterExtents[neighborFace].augment(bleedOverBBoxMin[i], (srcSize - 1), 0);
  51648. filterExtents[neighborFace].augment(bleedOverBBoxMax[i], (srcSize - 1) - bleedOverAmount[i], 0);
  51649. break;
  51650. }
  51651. //clamp filter extents in non-center tap faces to remain within surface
  51652. filterExtents[neighborFace].clampMin(0, 0, 0);
  51653. filterExtents[neighborFace].clampMax(srcSize - 1, srcSize - 1, 0);
  51654. }
  51655. //If the bleed over amount bleeds past the adjacent face onto the opposite face
  51656. // from the center tap face, then process the opposite face entirely for now.
  51657. //Note that the cases in which this happens, what usually happens is that
  51658. // more than one edge bleeds onto the opposite face, and the bounding box
  51659. // encompasses the entire cube map face.
  51660. if (bleedOverAmount[i] > srcSize) {
  51661. //determine opposite face
  51662. switch (faceIdx) {
  51663. case PMREMGenerator.CP_FACE_X_POS:
  51664. oppositeFaceIdx = PMREMGenerator.CP_FACE_X_NEG;
  51665. break;
  51666. case PMREMGenerator.CP_FACE_X_NEG:
  51667. oppositeFaceIdx = PMREMGenerator.CP_FACE_X_POS;
  51668. break;
  51669. case PMREMGenerator.CP_FACE_Y_POS:
  51670. oppositeFaceIdx = PMREMGenerator.CP_FACE_Y_NEG;
  51671. break;
  51672. case PMREMGenerator.CP_FACE_Y_NEG:
  51673. oppositeFaceIdx = PMREMGenerator.CP_FACE_Y_POS;
  51674. break;
  51675. case PMREMGenerator.CP_FACE_Z_POS:
  51676. oppositeFaceIdx = PMREMGenerator.CP_FACE_Z_NEG;
  51677. break;
  51678. case PMREMGenerator.CP_FACE_Z_NEG:
  51679. oppositeFaceIdx = PMREMGenerator.CP_FACE_Z_POS;
  51680. break;
  51681. default:
  51682. break;
  51683. }
  51684. //just encompass entire face for now
  51685. filterExtents[oppositeFaceIdx].augment(0, 0, 0);
  51686. filterExtents[oppositeFaceIdx].augment((srcSize - 1), (srcSize - 1), 0);
  51687. }
  51688. }
  51689. };
  51690. //--------------------------------------------------------------------------------------
  51691. //ProcessFilterExtents
  51692. // Process bounding box in each cube face
  51693. //
  51694. //--------------------------------------------------------------------------------------
  51695. PMREMGenerator.prototype.processFilterExtents = function (centerTapDir, dotProdThresh, filterExtents, srcCubeMap, srcSize, specularPower) {
  51696. //accumulators are 64-bit floats in order to have the precision needed
  51697. // over a summation of a large number of pixels
  51698. var dstAccum = [0, 0, 0, 0];
  51699. var weightAccum = 0;
  51700. var k = 0;
  51701. var nSrcChannels = this.numChannels;
  51702. // norm cube map and srcCubeMap have same face width
  51703. var faceWidth = srcSize;
  51704. //amount to add to pointer to move to next scanline in images
  51705. var normCubePitch = faceWidth * 4; // 4 channels in normCubeMap.
  51706. var srcCubePitch = faceWidth * this.numChannels; // numChannels correponds to the cubemap number of channel
  51707. var IsPhongBRDF = 1; // Only works in Phong BRDF yet.
  51708. //(a_LightingModel == CP_LIGHTINGMODEL_PHONG_BRDF || a_LightingModel == CP_LIGHTINGMODEL_BLINN_BRDF) ? 1 : 0; // This value will be added to the specular power
  51709. // iterate over cubefaces
  51710. for (var iFaceIdx = 0; iFaceIdx < 6; iFaceIdx++) {
  51711. //if bbox is non empty
  51712. if (!filterExtents[iFaceIdx].empty()) {
  51713. var uStart = filterExtents[iFaceIdx].min.x;
  51714. var vStart = filterExtents[iFaceIdx].min.y;
  51715. var uEnd = filterExtents[iFaceIdx].max.x;
  51716. var vEnd = filterExtents[iFaceIdx].max.y;
  51717. var startIndexNormCubeMap = (4 * ((vStart * faceWidth) + uStart));
  51718. var startIndexSrcCubeMap = (this.numChannels * ((vStart * faceWidth) + uStart));
  51719. //note that <= is used to ensure filter extents always encompass at least one pixel if bbox is non empty
  51720. for (var v = vStart; v <= vEnd; v++) {
  51721. var normCubeRowWalk = 0;
  51722. var srcCubeRowWalk = 0;
  51723. for (var u = uStart; u <= uEnd; u++) {
  51724. //pointer to direction in cube map associated with texel
  51725. var texelVectX = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 0];
  51726. var texelVectY = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 1];
  51727. var texelVectZ = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 2];
  51728. //check dot product to see if texel is within cone
  51729. var tapDotProd = texelVectX * centerTapDir.x +
  51730. texelVectY * centerTapDir.y +
  51731. texelVectZ * centerTapDir.z;
  51732. if (tapDotProd >= dotProdThresh && tapDotProd > 0.0) {
  51733. //solid angle stored in 4th channel of normalizer/solid angle cube map
  51734. var weight = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 3];
  51735. // Here we decide if we use a Phong/Blinn or a Phong/Blinn BRDF.
  51736. // Phong/Blinn BRDF is just the Phong/Blinn model multiply by the cosine of the lambert law
  51737. // so just adding one to specularpower do the trick.
  51738. weight *= Math.pow(tapDotProd, (specularPower + IsPhongBRDF));
  51739. //iterate over channels
  51740. for (k = 0; k < nSrcChannels; k++) {
  51741. dstAccum[k] += weight * srcCubeMap[iFaceIdx][startIndexSrcCubeMap + srcCubeRowWalk];
  51742. srcCubeRowWalk++;
  51743. }
  51744. weightAccum += weight; //accumulate weight
  51745. }
  51746. else {
  51747. //step across source pixel
  51748. srcCubeRowWalk += nSrcChannels;
  51749. }
  51750. normCubeRowWalk += 4; // 4 channels per norm cube map.
  51751. }
  51752. startIndexNormCubeMap += normCubePitch;
  51753. startIndexSrcCubeMap += srcCubePitch;
  51754. }
  51755. }
  51756. }
  51757. //divide through by weights if weight is non zero
  51758. if (weightAccum != 0.0) {
  51759. PMREMGenerator._vectorTemp.x = (dstAccum[0] / weightAccum);
  51760. PMREMGenerator._vectorTemp.y = (dstAccum[1] / weightAccum);
  51761. PMREMGenerator._vectorTemp.z = (dstAccum[2] / weightAccum);
  51762. if (this.numChannels > 3) {
  51763. PMREMGenerator._vectorTemp.w = (dstAccum[3] / weightAccum);
  51764. }
  51765. }
  51766. else {
  51767. // otherwise sample nearest
  51768. // get face idx and u, v texel coordinate in face
  51769. var coord = this.vectToTexelCoord(centerTapDir.x, centerTapDir.y, centerTapDir.z, srcSize).clone();
  51770. PMREMGenerator._vectorTemp.x = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 0];
  51771. PMREMGenerator._vectorTemp.y = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 1];
  51772. PMREMGenerator._vectorTemp.z = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 2];
  51773. if (this.numChannels > 3) {
  51774. PMREMGenerator._vectorTemp.z = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 3];
  51775. }
  51776. }
  51777. return PMREMGenerator._vectorTemp;
  51778. };
  51779. //--------------------------------------------------------------------------------------
  51780. // Fixup cube edges
  51781. //
  51782. // average texels on cube map faces across the edges
  51783. // WARP/BENT Method Only.
  51784. //--------------------------------------------------------------------------------------
  51785. PMREMGenerator.prototype.fixupCubeEdges = function (cubeMap, cubeMapSize) {
  51786. var k;
  51787. var j;
  51788. var i;
  51789. var iFace;
  51790. var iCorner = 0;
  51791. var cornerNumPtrs = [0, 0, 0, 0, 0, 0, 0, 0]; //indexed by corner and face idx
  51792. var faceCornerStartIndicies = [[], [], [], []]; //corner pointers for face keeping track of the face they belong to.
  51793. // note that if functionality to filter across the three texels for each corner, then
  51794. //indexed by corner and face idx. the array contains the face the start points belongs to.
  51795. var cornerPtr = [
  51796. [[], [], []],
  51797. [[], [], []],
  51798. [[], [], []],
  51799. [[], [], []],
  51800. [[], [], []],
  51801. [[], [], []],
  51802. [[], [], []],
  51803. [[], [], []]
  51804. ];
  51805. //if there is no fixup, or fixup width = 0, do nothing
  51806. if (cubeMapSize < 1) {
  51807. return;
  51808. }
  51809. //special case 1x1 cubemap, average face colors
  51810. if (cubeMapSize == 1) {
  51811. //iterate over channels
  51812. for (k = 0; k < this.numChannels; k++) {
  51813. var accum = 0.0;
  51814. //iterate over faces to accumulate face colors
  51815. for (iFace = 0; iFace < 6; iFace++) {
  51816. accum += cubeMap[iFace][k];
  51817. }
  51818. //compute average over 6 face colors
  51819. accum /= 6.0;
  51820. //iterate over faces to distribute face colors
  51821. for (iFace = 0; iFace < 6; iFace++) {
  51822. cubeMap[iFace][k] = accum;
  51823. }
  51824. }
  51825. return;
  51826. }
  51827. //iterate over faces to collect list of corner texel pointers
  51828. for (iFace = 0; iFace < 6; iFace++) {
  51829. //the 4 corner pointers for this face
  51830. faceCornerStartIndicies[0] = [iFace, 0];
  51831. faceCornerStartIndicies[1] = [iFace, ((cubeMapSize - 1) * this.numChannels)];
  51832. faceCornerStartIndicies[2] = [iFace, ((cubeMapSize) * (cubeMapSize - 1) * this.numChannels)];
  51833. faceCornerStartIndicies[3] = [iFace, ((((cubeMapSize) * (cubeMapSize - 1)) + (cubeMapSize - 1)) * this.numChannels)];
  51834. //iterate over face corners to collect cube corner pointers
  51835. for (iCorner = 0; iCorner < 4; iCorner++) {
  51836. var corner = PMREMGenerator._sgCubeCornerList[iFace][iCorner];
  51837. cornerPtr[corner][cornerNumPtrs[corner]] = faceCornerStartIndicies[iCorner];
  51838. cornerNumPtrs[corner]++;
  51839. }
  51840. }
  51841. //iterate over corners to average across corner tap values
  51842. for (iCorner = 0; iCorner < 8; iCorner++) {
  51843. for (k = 0; k < this.numChannels; k++) {
  51844. var cornerTapAccum = 0.0;
  51845. //iterate over corner texels and average results
  51846. for (i = 0; i < 3; i++) {
  51847. cornerTapAccum += cubeMap[cornerPtr[iCorner][i][0]][cornerPtr[iCorner][i][1] + k]; // Get in the cube map face the start point + channel.
  51848. }
  51849. //divide by 3 to compute average of corner tap values
  51850. cornerTapAccum *= (1.0 / 3.0);
  51851. //iterate over corner texels and average results
  51852. for (i = 0; i < 3; i++) {
  51853. cubeMap[cornerPtr[iCorner][i][0]][cornerPtr[iCorner][i][1] + k] = cornerTapAccum;
  51854. }
  51855. }
  51856. }
  51857. //iterate over the twelve edges of the cube to average across edges
  51858. for (i = 0; i < 12; i++) {
  51859. var face = PMREMGenerator._sgCubeEdgeList[i][0];
  51860. var edge = PMREMGenerator._sgCubeEdgeList[i][1];
  51861. var neighborFace = PMREMGenerator._sgCubeNgh[face][edge][0];
  51862. var neighborEdge = PMREMGenerator._sgCubeNgh[face][edge][1];
  51863. var edgeStartIndex = 0; // a_CubeMap[face].m_ImgData;
  51864. var neighborEdgeStartIndex = 0; // a_CubeMap[neighborFace].m_ImgData;
  51865. var edgeWalk = 0;
  51866. var neighborEdgeWalk = 0;
  51867. //Determine walking pointers based on edge type
  51868. // e.g. CP_EDGE_LEFT, CP_EDGE_RIGHT, CP_EDGE_TOP, CP_EDGE_BOTTOM
  51869. switch (edge) {
  51870. case PMREMGenerator.CP_EDGE_LEFT:
  51871. // no change to faceEdgeStartPtr
  51872. edgeWalk = this.numChannels * cubeMapSize;
  51873. break;
  51874. case PMREMGenerator.CP_EDGE_RIGHT:
  51875. edgeStartIndex += (cubeMapSize - 1) * this.numChannels;
  51876. edgeWalk = this.numChannels * cubeMapSize;
  51877. break;
  51878. case PMREMGenerator.CP_EDGE_TOP:
  51879. // no change to faceEdgeStartPtr
  51880. edgeWalk = this.numChannels;
  51881. break;
  51882. case PMREMGenerator.CP_EDGE_BOTTOM:
  51883. edgeStartIndex += (cubeMapSize) * (cubeMapSize - 1) * this.numChannels;
  51884. edgeWalk = this.numChannels;
  51885. break;
  51886. }
  51887. //For certain types of edge abutments, the neighbor edge walk needs to
  51888. // be flipped: the cases are
  51889. // if a left edge mates with a left or bottom edge on the neighbor
  51890. // if a top edge mates with a top or right edge on the neighbor
  51891. // if a right edge mates with a right or top edge on the neighbor
  51892. // if a bottom edge mates with a bottom or left edge on the neighbor
  51893. //Seeing as the edges are enumerated as follows
  51894. // left =0
  51895. // right =1
  51896. // top =2
  51897. // bottom =3
  51898. //
  51899. //If the edge enums are the same, or the sum of the enums == 3,
  51900. // the neighbor edge walk needs to be flipped
  51901. if ((edge == neighborEdge) || ((edge + neighborEdge) == 3)) {
  51902. switch (neighborEdge) {
  51903. case PMREMGenerator.CP_EDGE_LEFT:
  51904. neighborEdgeStartIndex += (cubeMapSize - 1) * (cubeMapSize) * this.numChannels;
  51905. neighborEdgeWalk = -(this.numChannels * cubeMapSize);
  51906. break;
  51907. case PMREMGenerator.CP_EDGE_RIGHT:
  51908. neighborEdgeStartIndex += ((cubeMapSize - 1) * (cubeMapSize) + (cubeMapSize - 1)) * this.numChannels;
  51909. neighborEdgeWalk = -(this.numChannels * cubeMapSize);
  51910. break;
  51911. case PMREMGenerator.CP_EDGE_TOP:
  51912. neighborEdgeStartIndex += (cubeMapSize - 1) * this.numChannels;
  51913. neighborEdgeWalk = -this.numChannels;
  51914. break;
  51915. case PMREMGenerator.CP_EDGE_BOTTOM:
  51916. neighborEdgeStartIndex += ((cubeMapSize - 1) * (cubeMapSize) + (cubeMapSize - 1)) * this.numChannels;
  51917. neighborEdgeWalk = -this.numChannels;
  51918. break;
  51919. }
  51920. }
  51921. else {
  51922. //swapped direction neighbor edge walk
  51923. switch (neighborEdge) {
  51924. case PMREMGenerator.CP_EDGE_LEFT:
  51925. //no change to neighborEdgeStartPtr for this case since it points
  51926. // to the upper left corner already
  51927. neighborEdgeWalk = this.numChannels * cubeMapSize;
  51928. break;
  51929. case PMREMGenerator.CP_EDGE_RIGHT:
  51930. neighborEdgeStartIndex += (cubeMapSize - 1) * this.numChannels;
  51931. neighborEdgeWalk = this.numChannels * cubeMapSize;
  51932. break;
  51933. case PMREMGenerator.CP_EDGE_TOP:
  51934. //no change to neighborEdgeStartPtr for this case since it points
  51935. // to the upper left corner already
  51936. neighborEdgeWalk = this.numChannels;
  51937. break;
  51938. case PMREMGenerator.CP_EDGE_BOTTOM:
  51939. neighborEdgeStartIndex += (cubeMapSize) * (cubeMapSize - 1) * this.numChannels;
  51940. neighborEdgeWalk = this.numChannels;
  51941. break;
  51942. }
  51943. }
  51944. //Perform edge walk, to average across the 12 edges and smoothly propagate change to
  51945. //nearby neighborhood
  51946. //step ahead one texel on edge
  51947. edgeStartIndex += edgeWalk;
  51948. neighborEdgeStartIndex += neighborEdgeWalk;
  51949. // note that this loop does not process the corner texels, since they have already been
  51950. // averaged across faces across earlier
  51951. for (j = 1; j < (cubeMapSize - 1); j++) {
  51952. //for each set of taps along edge, average them
  51953. // and rewrite the results into the edges
  51954. for (k = 0; k < this.numChannels; k++) {
  51955. var edgeTap = cubeMap[face][edgeStartIndex + k];
  51956. var neighborEdgeTap = cubeMap[neighborFace][neighborEdgeStartIndex + k];
  51957. //compute average of tap intensity values
  51958. var avgTap = 0.5 * (edgeTap + neighborEdgeTap);
  51959. //propagate average of taps to edge taps
  51960. cubeMap[face][edgeStartIndex + k] = avgTap;
  51961. cubeMap[neighborFace][neighborEdgeStartIndex + k] = avgTap;
  51962. }
  51963. edgeStartIndex += edgeWalk;
  51964. neighborEdgeStartIndex += neighborEdgeWalk;
  51965. }
  51966. }
  51967. };
  51968. return PMREMGenerator;
  51969. }());
  51970. PMREMGenerator.CP_MAX_MIPLEVELS = 16;
  51971. PMREMGenerator.CP_UDIR = 0;
  51972. PMREMGenerator.CP_VDIR = 1;
  51973. PMREMGenerator.CP_FACEAXIS = 2;
  51974. //used to index cube faces
  51975. PMREMGenerator.CP_FACE_X_POS = 0;
  51976. PMREMGenerator.CP_FACE_X_NEG = 1;
  51977. PMREMGenerator.CP_FACE_Y_POS = 2;
  51978. PMREMGenerator.CP_FACE_Y_NEG = 3;
  51979. PMREMGenerator.CP_FACE_Z_POS = 4;
  51980. PMREMGenerator.CP_FACE_Z_NEG = 5;
  51981. //used to index image edges
  51982. // NOTE.. the actual number corresponding to the edge is important
  51983. // do not change these, or the code will break
  51984. //
  51985. // CP_EDGE_LEFT is u = 0
  51986. // CP_EDGE_RIGHT is u = width-1
  51987. // CP_EDGE_TOP is v = 0
  51988. // CP_EDGE_BOTTOM is v = height-1
  51989. PMREMGenerator.CP_EDGE_LEFT = 0;
  51990. PMREMGenerator.CP_EDGE_RIGHT = 1;
  51991. PMREMGenerator.CP_EDGE_TOP = 2;
  51992. PMREMGenerator.CP_EDGE_BOTTOM = 3;
  51993. //corners of CUBE map (P or N specifys if it corresponds to the
  51994. // positive or negative direction each of X, Y, and Z
  51995. PMREMGenerator.CP_CORNER_NNN = 0;
  51996. PMREMGenerator.CP_CORNER_NNP = 1;
  51997. PMREMGenerator.CP_CORNER_NPN = 2;
  51998. PMREMGenerator.CP_CORNER_NPP = 3;
  51999. PMREMGenerator.CP_CORNER_PNN = 4;
  52000. PMREMGenerator.CP_CORNER_PNP = 5;
  52001. PMREMGenerator.CP_CORNER_PPN = 6;
  52002. PMREMGenerator.CP_CORNER_PPP = 7;
  52003. PMREMGenerator._vectorTemp = new BABYLON.Vector4(0, 0, 0, 0);
  52004. //3x2 matrices that map cube map indexing vectors in 3d
  52005. // (after face selection and divide through by the
  52006. // _ABSOLUTE VALUE_ of the max coord)
  52007. // into NVC space
  52008. //Note this currently assumes the D3D cube face ordering and orientation
  52009. PMREMGenerator._sgFace2DMapping = [
  52010. //XPOS face
  52011. [[0, 0, -1],
  52012. [0, -1, 0],
  52013. [1, 0, 0]],
  52014. //XNEG face
  52015. [[0, 0, 1],
  52016. [0, -1, 0],
  52017. [-1, 0, 0]],
  52018. //YPOS face
  52019. [[1, 0, 0],
  52020. [0, 0, 1],
  52021. [0, 1, 0]],
  52022. //YNEG face
  52023. [[1, 0, 0],
  52024. [0, 0, -1],
  52025. [0, -1, 0]],
  52026. //ZPOS face
  52027. [[1, 0, 0],
  52028. [0, -1, 0],
  52029. [0, 0, 1]],
  52030. //ZNEG face
  52031. [[-1, 0, 0],
  52032. [0, -1, 0],
  52033. [0, 0, -1]],
  52034. ];
  52035. //------------------------------------------------------------------------------
  52036. // D3D cube map face specification
  52037. // mapping from 3D x,y,z cube map lookup coordinates
  52038. // to 2D within face u,v coordinates
  52039. //
  52040. // --------------------> U direction
  52041. // | (within-face texture space)
  52042. // | _____
  52043. // | | |
  52044. // | | +Y |
  52045. // | _____|_____|_____ _____
  52046. // | | | | | |
  52047. // | | -X | +Z | +X | -Z |
  52048. // | |_____|_____|_____|_____|
  52049. // | | |
  52050. // | | -Y |
  52051. // | |_____|
  52052. // |
  52053. // v V direction
  52054. // (within-face texture space)
  52055. //------------------------------------------------------------------------------
  52056. //Information about neighbors and how texture coorrdinates change across faces
  52057. // in ORDER of left, right, top, bottom (e.g. edges corresponding to u=0,
  52058. // u=1, v=0, v=1 in the 2D coordinate system of the particular face.
  52059. //Note this currently assumes the D3D cube face ordering and orientation
  52060. PMREMGenerator._sgCubeNgh = [
  52061. //XPOS face
  52062. [[PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_RIGHT],
  52063. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_LEFT],
  52064. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_RIGHT],
  52065. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_RIGHT]],
  52066. //XNEG face
  52067. [[PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_RIGHT],
  52068. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_LEFT],
  52069. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_LEFT],
  52070. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_LEFT]],
  52071. //YPOS face
  52072. [[PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_TOP],
  52073. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_TOP],
  52074. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_TOP],
  52075. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_TOP]],
  52076. //YNEG face
  52077. [[PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_BOTTOM],
  52078. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  52079. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  52080. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_BOTTOM]],
  52081. //ZPOS face
  52082. [[PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_RIGHT],
  52083. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_LEFT],
  52084. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  52085. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_TOP]],
  52086. //ZNEG face
  52087. [[PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_RIGHT],
  52088. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_LEFT],
  52089. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_TOP],
  52090. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_BOTTOM]]
  52091. ];
  52092. //The 12 edges of the cubemap, (entries are used to index into the neighbor table)
  52093. // this table is used to average over the edges.
  52094. PMREMGenerator._sgCubeEdgeList = [
  52095. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_LEFT],
  52096. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_RIGHT],
  52097. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_TOP],
  52098. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  52099. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_LEFT],
  52100. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_RIGHT],
  52101. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_TOP],
  52102. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_BOTTOM],
  52103. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_TOP],
  52104. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  52105. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_TOP],
  52106. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_BOTTOM]
  52107. ];
  52108. //Information about which of the 8 cube corners are correspond to the
  52109. // the 4 corners in each cube face
  52110. // the order is upper left, upper right, lower left, lower right
  52111. PMREMGenerator._sgCubeCornerList = [
  52112. [PMREMGenerator.CP_CORNER_PPP, PMREMGenerator.CP_CORNER_PPN, PMREMGenerator.CP_CORNER_PNP, PMREMGenerator.CP_CORNER_PNN],
  52113. [PMREMGenerator.CP_CORNER_NPN, PMREMGenerator.CP_CORNER_NPP, PMREMGenerator.CP_CORNER_NNN, PMREMGenerator.CP_CORNER_NNP],
  52114. [PMREMGenerator.CP_CORNER_NPN, PMREMGenerator.CP_CORNER_PPN, PMREMGenerator.CP_CORNER_NPP, PMREMGenerator.CP_CORNER_PPP],
  52115. [PMREMGenerator.CP_CORNER_NNP, PMREMGenerator.CP_CORNER_PNP, PMREMGenerator.CP_CORNER_NNN, PMREMGenerator.CP_CORNER_PNN],
  52116. [PMREMGenerator.CP_CORNER_NPP, PMREMGenerator.CP_CORNER_PPP, PMREMGenerator.CP_CORNER_NNP, PMREMGenerator.CP_CORNER_PNP],
  52117. [PMREMGenerator.CP_CORNER_PPN, PMREMGenerator.CP_CORNER_NPN, PMREMGenerator.CP_CORNER_PNN, PMREMGenerator.CP_CORNER_NNN] // ZNEG face
  52118. ];
  52119. Internals.PMREMGenerator = PMREMGenerator;
  52120. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  52121. })(BABYLON || (BABYLON = {}));
  52122. //# sourceMappingURL=babylon.tools.pmremGenerator.js.map
  52123. var BABYLON;
  52124. (function (BABYLON) {
  52125. /**
  52126. * This represents a texture coming from an HDR input.
  52127. *
  52128. * The only supported format is currently panorama picture stored in RGBE format.
  52129. * Example of such files can be found on HDRLib: http://hdrlib.com/
  52130. */
  52131. var HDRCubeTexture = (function (_super) {
  52132. __extends(HDRCubeTexture, _super);
  52133. /**
  52134. * Instantiates an HDRTexture from the following parameters.
  52135. *
  52136. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  52137. * @param scene The scene the texture will be used in
  52138. * @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.
  52139. * @param noMipmap Forces to not generate the mipmap if true
  52140. * @param generateHarmonics Specifies wether you want to extract the polynomial harmonics during the generation process
  52141. * @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)
  52142. * @param usePMREMGenerator Specifies wether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time.
  52143. */
  52144. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator) {
  52145. if (noMipmap === void 0) { noMipmap = false; }
  52146. if (generateHarmonics === void 0) { generateHarmonics = true; }
  52147. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  52148. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  52149. var _this = _super.call(this, scene) || this;
  52150. _this._useInGammaSpace = false;
  52151. _this._generateHarmonics = true;
  52152. _this._isBABYLONPreprocessed = false;
  52153. /**
  52154. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  52155. */
  52156. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  52157. /**
  52158. * The spherical polynomial data extracted from the texture.
  52159. */
  52160. _this.sphericalPolynomial = null;
  52161. /**
  52162. * Specifies wether the texture has been generated through the PMREMGenerator tool.
  52163. * This is usefull at run time to apply the good shader.
  52164. */
  52165. _this.isPMREM = false;
  52166. if (!url) {
  52167. return _this;
  52168. }
  52169. _this.name = url;
  52170. _this.url = url;
  52171. _this.hasAlpha = false;
  52172. _this.isCube = true;
  52173. _this._textureMatrix = BABYLON.Matrix.Identity();
  52174. if (size) {
  52175. _this._isBABYLONPreprocessed = false;
  52176. _this._noMipmap = noMipmap;
  52177. _this._size = size;
  52178. _this._useInGammaSpace = useInGammaSpace;
  52179. _this._usePMREMGenerator = usePMREMGenerator &&
  52180. scene.getEngine().getCaps().textureLOD &&
  52181. _this.getScene().getEngine().getCaps().textureFloat &&
  52182. !_this._useInGammaSpace;
  52183. }
  52184. else {
  52185. _this._isBABYLONPreprocessed = true;
  52186. _this._noMipmap = false;
  52187. _this._useInGammaSpace = false;
  52188. _this._usePMREMGenerator = scene.getEngine().getCaps().textureLOD &&
  52189. _this.getScene().getEngine().getCaps().textureFloat &&
  52190. !_this._useInGammaSpace;
  52191. }
  52192. _this.isPMREM = _this._usePMREMGenerator;
  52193. _this._texture = _this._getFromCache(url, _this._noMipmap);
  52194. if (!_this._texture) {
  52195. if (!scene.useDelayedTextureLoading) {
  52196. _this.loadTexture();
  52197. }
  52198. else {
  52199. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  52200. }
  52201. }
  52202. return _this;
  52203. }
  52204. /**
  52205. * Occurs when the file is a preprocessed .babylon.hdr file.
  52206. */
  52207. HDRCubeTexture.prototype.loadBabylonTexture = function () {
  52208. var _this = this;
  52209. var mipLevels = 0;
  52210. var floatArrayView = null;
  52211. var mipmapGenerator = (!this._useInGammaSpace && this.getScene().getEngine().getCaps().textureFloat) ? function (data) {
  52212. var mips = [];
  52213. var startIndex = 30;
  52214. for (var level = 0; level < mipLevels; level++) {
  52215. mips.push([]);
  52216. // Fill each pixel of the mip level.
  52217. var faceSize = Math.pow(_this._size >> level, 2) * 3;
  52218. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  52219. var faceData = floatArrayView.subarray(startIndex, startIndex + faceSize);
  52220. mips[level].push(faceData);
  52221. startIndex += faceSize;
  52222. }
  52223. }
  52224. return mips;
  52225. } : null;
  52226. var callback = function (buffer) {
  52227. // Create Native Array Views
  52228. var intArrayView = new Int32Array(buffer);
  52229. floatArrayView = new Float32Array(buffer);
  52230. // Fill header.
  52231. var version = intArrayView[0]; // Version 1. (MAy be use in case of format changes for backward compaibility)
  52232. _this._size = intArrayView[1]; // CubeMap max mip face size.
  52233. // Update Texture Information.
  52234. _this.getScene().getEngine().updateTextureSize(_this._texture, _this._size, _this._size);
  52235. // Fill polynomial information.
  52236. _this.sphericalPolynomial = new BABYLON.SphericalPolynomial();
  52237. _this.sphericalPolynomial.x.copyFromFloats(floatArrayView[2], floatArrayView[3], floatArrayView[4]);
  52238. _this.sphericalPolynomial.y.copyFromFloats(floatArrayView[5], floatArrayView[6], floatArrayView[7]);
  52239. _this.sphericalPolynomial.z.copyFromFloats(floatArrayView[8], floatArrayView[9], floatArrayView[10]);
  52240. _this.sphericalPolynomial.xx.copyFromFloats(floatArrayView[11], floatArrayView[12], floatArrayView[13]);
  52241. _this.sphericalPolynomial.yy.copyFromFloats(floatArrayView[14], floatArrayView[15], floatArrayView[16]);
  52242. _this.sphericalPolynomial.zz.copyFromFloats(floatArrayView[17], floatArrayView[18], floatArrayView[19]);
  52243. _this.sphericalPolynomial.xy.copyFromFloats(floatArrayView[20], floatArrayView[21], floatArrayView[22]);
  52244. _this.sphericalPolynomial.yz.copyFromFloats(floatArrayView[23], floatArrayView[24], floatArrayView[25]);
  52245. _this.sphericalPolynomial.zx.copyFromFloats(floatArrayView[26], floatArrayView[27], floatArrayView[28]);
  52246. // Fill pixel data.
  52247. mipLevels = intArrayView[29]; // Number of mip levels.
  52248. var startIndex = 30;
  52249. var data = [];
  52250. var faceSize = Math.pow(_this._size, 2) * 3;
  52251. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  52252. data.push(floatArrayView.subarray(startIndex, startIndex + faceSize));
  52253. startIndex += faceSize;
  52254. }
  52255. var results = [];
  52256. var byteArray = null;
  52257. // Push each faces.
  52258. for (var k = 0; k < 6; k++) {
  52259. var dataFace = null;
  52260. // If special cases.
  52261. if (!mipmapGenerator) {
  52262. var j = ([0, 2, 4, 1, 3, 5])[k]; // Transforms +X+Y+Z... to +X-X+Y-Y... if no mipmapgenerator...
  52263. dataFace = data[j];
  52264. if (!_this.getScene().getEngine().getCaps().textureFloat) {
  52265. // 3 channels of 1 bytes per pixel in bytes.
  52266. var byteBuffer = new ArrayBuffer(faceSize);
  52267. byteArray = new Uint8Array(byteBuffer);
  52268. }
  52269. for (var i = 0; i < _this._size * _this._size; i++) {
  52270. // Put in gamma space if requested.
  52271. if (_this._useInGammaSpace) {
  52272. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  52273. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  52274. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  52275. }
  52276. // Convert to int texture for fallback.
  52277. if (byteArray) {
  52278. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  52279. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  52280. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  52281. // May use luminance instead if the result is not accurate.
  52282. var max = Math.max(Math.max(r, g), b);
  52283. if (max > 255) {
  52284. var scale = 255 / max;
  52285. r *= scale;
  52286. g *= scale;
  52287. b *= scale;
  52288. }
  52289. byteArray[(i * 3) + 0] = r;
  52290. byteArray[(i * 3) + 1] = g;
  52291. byteArray[(i * 3) + 2] = b;
  52292. }
  52293. }
  52294. }
  52295. else {
  52296. dataFace = data[k];
  52297. }
  52298. // Fill the array accordingly.
  52299. if (byteArray) {
  52300. results.push(byteArray);
  52301. }
  52302. else {
  52303. results.push(dataFace);
  52304. }
  52305. }
  52306. return results;
  52307. };
  52308. 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);
  52309. };
  52310. /**
  52311. * Occurs when the file is raw .hdr file.
  52312. */
  52313. HDRCubeTexture.prototype.loadHDRTexture = function () {
  52314. var _this = this;
  52315. var callback = function (buffer) {
  52316. // Extract the raw linear data.
  52317. var data = BABYLON.Internals.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  52318. // Generate harmonics if needed.
  52319. if (_this._generateHarmonics) {
  52320. _this.sphericalPolynomial = BABYLON.Internals.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  52321. }
  52322. var results = [];
  52323. var byteArray = null;
  52324. // Push each faces.
  52325. for (var j = 0; j < 6; j++) {
  52326. // Create uintarray fallback.
  52327. if (!_this.getScene().getEngine().getCaps().textureFloat) {
  52328. // 3 channels of 1 bytes per pixel in bytes.
  52329. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  52330. byteArray = new Uint8Array(byteBuffer);
  52331. }
  52332. var dataFace = data[HDRCubeTexture._facesMapping[j]];
  52333. // If special cases.
  52334. if (_this._useInGammaSpace || byteArray) {
  52335. for (var i = 0; i < _this._size * _this._size; i++) {
  52336. // Put in gamma space if requested.
  52337. if (_this._useInGammaSpace) {
  52338. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  52339. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  52340. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  52341. }
  52342. // Convert to int texture for fallback.
  52343. if (byteArray) {
  52344. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  52345. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  52346. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  52347. // May use luminance instead if the result is not accurate.
  52348. var max = Math.max(Math.max(r, g), b);
  52349. if (max > 255) {
  52350. var scale = 255 / max;
  52351. r *= scale;
  52352. g *= scale;
  52353. b *= scale;
  52354. }
  52355. byteArray[(i * 3) + 0] = r;
  52356. byteArray[(i * 3) + 1] = g;
  52357. byteArray[(i * 3) + 2] = b;
  52358. }
  52359. }
  52360. }
  52361. if (byteArray) {
  52362. results.push(byteArray);
  52363. }
  52364. else {
  52365. results.push(dataFace);
  52366. }
  52367. }
  52368. return results;
  52369. };
  52370. var mipmapGenerator = null;
  52371. if (!this._noMipmap &&
  52372. this._usePMREMGenerator) {
  52373. mipmapGenerator = function (data) {
  52374. // Custom setup of the generator matching with the PBR shader values.
  52375. var generator = new BABYLON.Internals.PMREMGenerator(data, _this._size, _this._size, 0, 3, _this.getScene().getEngine().getCaps().textureFloat, 2048, 0.25, false, true);
  52376. return generator.filterCubeMap();
  52377. };
  52378. }
  52379. 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);
  52380. };
  52381. /**
  52382. * Starts the loading process of the texture.
  52383. */
  52384. HDRCubeTexture.prototype.loadTexture = function () {
  52385. if (this._isBABYLONPreprocessed) {
  52386. this.loadBabylonTexture();
  52387. }
  52388. else {
  52389. this.loadHDRTexture();
  52390. }
  52391. };
  52392. HDRCubeTexture.prototype.clone = function () {
  52393. var size = this._isBABYLONPreprocessed ? null : this._size;
  52394. var newTexture = new HDRCubeTexture(this.url, this.getScene(), size, this._noMipmap, this._generateHarmonics, this._useInGammaSpace, this._usePMREMGenerator);
  52395. // Base texture
  52396. newTexture.level = this.level;
  52397. newTexture.wrapU = this.wrapU;
  52398. newTexture.wrapV = this.wrapV;
  52399. newTexture.coordinatesIndex = this.coordinatesIndex;
  52400. newTexture.coordinatesMode = this.coordinatesMode;
  52401. return newTexture;
  52402. };
  52403. // Methods
  52404. HDRCubeTexture.prototype.delayLoad = function () {
  52405. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  52406. return;
  52407. }
  52408. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  52409. this._texture = this._getFromCache(this.url, this._noMipmap);
  52410. if (!this._texture) {
  52411. this.loadTexture();
  52412. }
  52413. };
  52414. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  52415. return this._textureMatrix;
  52416. };
  52417. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  52418. var texture = null;
  52419. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  52420. var size = parsedTexture.isBABYLONPreprocessed ? null : parsedTexture.size;
  52421. texture = new BABYLON.HDRCubeTexture(rootUrl + parsedTexture.name, scene, size, parsedTexture.noMipmap, parsedTexture.generateHarmonics, parsedTexture.useInGammaSpace, parsedTexture.usePMREMGenerator);
  52422. texture.name = parsedTexture.name;
  52423. texture.hasAlpha = parsedTexture.hasAlpha;
  52424. texture.level = parsedTexture.level;
  52425. texture.coordinatesMode = parsedTexture.coordinatesMode;
  52426. }
  52427. return texture;
  52428. };
  52429. HDRCubeTexture.prototype.serialize = function () {
  52430. if (!this.name) {
  52431. return null;
  52432. }
  52433. var serializationObject = {};
  52434. serializationObject.name = this.name;
  52435. serializationObject.hasAlpha = this.hasAlpha;
  52436. serializationObject.isCube = true;
  52437. serializationObject.level = this.level;
  52438. serializationObject.size = this._size;
  52439. serializationObject.coordinatesMode = this.coordinatesMode;
  52440. serializationObject.useInGammaSpace = this._useInGammaSpace;
  52441. serializationObject.generateHarmonics = this._generateHarmonics;
  52442. serializationObject.usePMREMGenerator = this._usePMREMGenerator;
  52443. serializationObject.isBABYLONPreprocessed = this._isBABYLONPreprocessed;
  52444. serializationObject.customType = "BABYLON.HDRCubeTexture";
  52445. serializationObject.noMipmap = this._noMipmap;
  52446. return serializationObject;
  52447. };
  52448. /**
  52449. * Saves as a file the data contained in the texture in a binary format.
  52450. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  52451. * as the spherical used in the lighting.
  52452. * @param url The HDR file url.
  52453. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  52454. * @param onError Method called if any error happens during download.
  52455. * @return The packed binary data.
  52456. */
  52457. HDRCubeTexture.generateBabylonHDROnDisk = function (url, size, onError) {
  52458. if (onError === void 0) { onError = null; }
  52459. var callback = function (buffer) {
  52460. var data = new Blob([buffer], { type: 'application/octet-stream' });
  52461. // Returns a URL you can use as a href.
  52462. var objUrl = window.URL.createObjectURL(data);
  52463. // Simulates a link to it and click to dowload.
  52464. var a = document.createElement("a");
  52465. document.body.appendChild(a);
  52466. a.style.display = "none";
  52467. a.href = objUrl;
  52468. a.download = "envmap.babylon.hdr";
  52469. a.click();
  52470. };
  52471. HDRCubeTexture.generateBabylonHDR(url, size, callback, onError);
  52472. };
  52473. /**
  52474. * Serializes the data contained in the texture in a binary format.
  52475. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  52476. * as the spherical used in the lighting.
  52477. * @param url The HDR file url.
  52478. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  52479. * @param onError Method called if any error happens during download.
  52480. * @return The packed binary data.
  52481. */
  52482. HDRCubeTexture.generateBabylonHDR = function (url, size, callback, onError) {
  52483. if (onError === void 0) { onError = null; }
  52484. // Needs the url tho create the texture.
  52485. if (!url) {
  52486. return null;
  52487. }
  52488. // Check Power of two size.
  52489. if (!BABYLON.Tools.IsExponentOfTwo(size)) {
  52490. return null;
  52491. }
  52492. var getDataCallback = function (dataBuffer) {
  52493. // Extract the raw linear data.
  52494. var cubeData = BABYLON.Internals.HDRTools.GetCubeMapTextureData(dataBuffer, size);
  52495. // Generate harmonics if needed.
  52496. var sphericalPolynomial = BABYLON.Internals.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(cubeData);
  52497. // Generate seamless faces
  52498. var mipGeneratorArray = [];
  52499. // Data are known to be in +X +Y +Z -X -Y -Z
  52500. // mipmmapGenerator data is expected to be order in +X -X +Y -Y +Z -Z
  52501. mipGeneratorArray.push(cubeData.right); // +X
  52502. mipGeneratorArray.push(cubeData.left); // -X
  52503. mipGeneratorArray.push(cubeData.up); // +Y
  52504. mipGeneratorArray.push(cubeData.down); // -Y
  52505. mipGeneratorArray.push(cubeData.front); // +Z
  52506. mipGeneratorArray.push(cubeData.back); // -Z
  52507. // Custom setup of the generator matching with the PBR shader values.
  52508. var generator = new BABYLON.Internals.PMREMGenerator(mipGeneratorArray, size, size, 0, 3, true, 2048, 0.25, false, true);
  52509. var mippedData = generator.filterCubeMap();
  52510. // Compute required byte length.
  52511. var byteLength = 1 * 4; // Raw Data Version int32.
  52512. byteLength += 4; // CubeMap max mip face size int32.
  52513. byteLength += (9 * 3 * 4); // Spherical polynomial byte length 9 Vector 3 of floats.
  52514. // Add data size.
  52515. byteLength += 4; // Number of mip levels int32.
  52516. for (var level = 0; level < mippedData.length; level++) {
  52517. var mipSize = size >> level;
  52518. byteLength += (6 * mipSize * mipSize * 3 * 4); // 6 faces of size squared rgb float pixels.
  52519. }
  52520. // Prepare binary structure.
  52521. var buffer = new ArrayBuffer(byteLength);
  52522. var intArrayView = new Int32Array(buffer);
  52523. var floatArrayView = new Float32Array(buffer);
  52524. // Fill header.
  52525. intArrayView[0] = 1; // Version 1.
  52526. intArrayView[1] = size; // CubeMap max mip face size.
  52527. // Fill polynomial information.
  52528. sphericalPolynomial.x.toArray(floatArrayView, 2);
  52529. sphericalPolynomial.y.toArray(floatArrayView, 5);
  52530. sphericalPolynomial.z.toArray(floatArrayView, 8);
  52531. sphericalPolynomial.xx.toArray(floatArrayView, 11);
  52532. sphericalPolynomial.yy.toArray(floatArrayView, 14);
  52533. sphericalPolynomial.zz.toArray(floatArrayView, 17);
  52534. sphericalPolynomial.xy.toArray(floatArrayView, 20);
  52535. sphericalPolynomial.yz.toArray(floatArrayView, 23);
  52536. sphericalPolynomial.zx.toArray(floatArrayView, 26);
  52537. // Fill pixel data.
  52538. intArrayView[29] = mippedData.length; // Number of mip levels.
  52539. var startIndex = 30;
  52540. for (var level = 0; level < mippedData.length; level++) {
  52541. // Fill each pixel of the mip level.
  52542. var faceSize = Math.pow(size >> level, 2) * 3;
  52543. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  52544. floatArrayView.set(mippedData[level][faceIndex], startIndex);
  52545. startIndex += faceSize;
  52546. }
  52547. }
  52548. // Callback.
  52549. callback(buffer);
  52550. };
  52551. // Download and process.
  52552. BABYLON.Tools.LoadFile(url, function (data) {
  52553. getDataCallback(data);
  52554. }, null, null, true, onError);
  52555. };
  52556. return HDRCubeTexture;
  52557. }(BABYLON.BaseTexture));
  52558. HDRCubeTexture._facesMapping = [
  52559. "right",
  52560. "up",
  52561. "front",
  52562. "left",
  52563. "down",
  52564. "back"
  52565. ];
  52566. BABYLON.HDRCubeTexture = HDRCubeTexture;
  52567. })(BABYLON || (BABYLON = {}));
  52568. //# sourceMappingURL=babylon.hdrCubeTexture.js.map
  52569. var BABYLON;
  52570. (function (BABYLON) {
  52571. var Debug;
  52572. (function (Debug) {
  52573. /**
  52574. * Demo available here: http://www.babylonjs-playground.com/#1BZJVJ#8
  52575. */
  52576. var SkeletonViewer = (function () {
  52577. function SkeletonViewer(skeleton, mesh, scene, autoUpdateBonesMatrices, renderingGroupId) {
  52578. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  52579. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  52580. this.skeleton = skeleton;
  52581. this.mesh = mesh;
  52582. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  52583. this.renderingGroupId = renderingGroupId;
  52584. this.color = BABYLON.Color3.White();
  52585. this._debugLines = [];
  52586. this._isEnabled = false;
  52587. this._scene = scene;
  52588. this.update();
  52589. this._renderFunction = this.update.bind(this);
  52590. }
  52591. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  52592. get: function () {
  52593. return this._isEnabled;
  52594. },
  52595. set: function (value) {
  52596. if (this._isEnabled === value) {
  52597. return;
  52598. }
  52599. this._isEnabled = value;
  52600. if (value) {
  52601. this._scene.registerBeforeRender(this._renderFunction);
  52602. }
  52603. else {
  52604. this._scene.unregisterBeforeRender(this._renderFunction);
  52605. }
  52606. },
  52607. enumerable: true,
  52608. configurable: true
  52609. });
  52610. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  52611. if (x === void 0) { x = 0; }
  52612. if (y === void 0) { y = 0; }
  52613. if (z === void 0) { z = 0; }
  52614. var tmat = BABYLON.Tmp.Matrix[0];
  52615. var parentBone = bone.getParent();
  52616. tmat.copyFrom(bone.getLocalMatrix());
  52617. if (x !== 0 || y !== 0 || z !== 0) {
  52618. var tmat2 = BABYLON.Tmp.Matrix[1];
  52619. BABYLON.Matrix.IdentityToRef(tmat2);
  52620. tmat2.m[12] = x;
  52621. tmat2.m[13] = y;
  52622. tmat2.m[14] = z;
  52623. tmat2.multiplyToRef(tmat, tmat);
  52624. }
  52625. if (parentBone) {
  52626. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  52627. }
  52628. tmat.multiplyToRef(meshMat, tmat);
  52629. position.x = tmat.m[12];
  52630. position.y = tmat.m[13];
  52631. position.z = tmat.m[14];
  52632. };
  52633. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  52634. var len = bones.length;
  52635. for (var i = 0; i < len; i++) {
  52636. var bone = bones[i];
  52637. var points = this._debugLines[i];
  52638. if (!points) {
  52639. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  52640. this._debugLines[i] = points;
  52641. }
  52642. this._getBonePosition(points[0], bone, meshMat);
  52643. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  52644. }
  52645. };
  52646. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  52647. var len = bones.length;
  52648. var boneNum = 0;
  52649. for (var i = len - 1; i >= 0; i--) {
  52650. var childBone = bones[i];
  52651. var parentBone = childBone.getParent();
  52652. if (!parentBone) {
  52653. continue;
  52654. }
  52655. var points = this._debugLines[boneNum];
  52656. if (!points) {
  52657. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  52658. this._debugLines[boneNum] = points;
  52659. }
  52660. childBone.getAbsolutePositionToRef(this.mesh, points[0]);
  52661. parentBone.getAbsolutePositionToRef(this.mesh, points[1]);
  52662. boneNum++;
  52663. }
  52664. };
  52665. SkeletonViewer.prototype.update = function () {
  52666. if (this.autoUpdateBonesMatrices) {
  52667. this.skeleton.computeAbsoluteTransforms();
  52668. }
  52669. if (this.skeleton.bones[0].length === undefined) {
  52670. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  52671. }
  52672. else {
  52673. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  52674. }
  52675. if (!this._debugMesh) {
  52676. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem(null, { lines: this._debugLines, updatable: true }, this._scene);
  52677. this._debugMesh.renderingGroupId = this.renderingGroupId;
  52678. }
  52679. else {
  52680. BABYLON.MeshBuilder.CreateLineSystem(null, { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  52681. }
  52682. this._debugMesh.color = this.color;
  52683. };
  52684. SkeletonViewer.prototype.dispose = function () {
  52685. if (this._debugMesh) {
  52686. this.isEnabled = false;
  52687. this._debugMesh.dispose();
  52688. this._debugMesh = null;
  52689. }
  52690. };
  52691. return SkeletonViewer;
  52692. }());
  52693. Debug.SkeletonViewer = SkeletonViewer;
  52694. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  52695. })(BABYLON || (BABYLON = {}));
  52696. //# sourceMappingURL=babylon.skeletonViewer.js.map
  52697. var BABYLON;
  52698. (function (BABYLON) {
  52699. var Debug;
  52700. (function (Debug) {
  52701. var AxesViewer = (function () {
  52702. function AxesViewer(scene, scaleLines) {
  52703. if (scaleLines === void 0) { scaleLines = 1; }
  52704. this._xline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  52705. this._yline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  52706. this._zline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  52707. this.scaleLines = 1;
  52708. this.scaleLines = scaleLines;
  52709. this._xmesh = BABYLON.Mesh.CreateLines("xline", this._xline, scene, true);
  52710. this._ymesh = BABYLON.Mesh.CreateLines("yline", this._yline, scene, true);
  52711. this._zmesh = BABYLON.Mesh.CreateLines("zline", this._zline, scene, true);
  52712. this._xmesh.renderingGroupId = 2;
  52713. this._ymesh.renderingGroupId = 2;
  52714. this._zmesh.renderingGroupId = 2;
  52715. this._xmesh.material.checkReadyOnlyOnce = true;
  52716. this._xmesh.color = new BABYLON.Color3(1, 0, 0);
  52717. this._ymesh.material.checkReadyOnlyOnce = true;
  52718. this._ymesh.color = new BABYLON.Color3(0, 1, 0);
  52719. this._zmesh.material.checkReadyOnlyOnce = true;
  52720. this._zmesh.color = new BABYLON.Color3(0, 0, 1);
  52721. this.scene = scene;
  52722. }
  52723. AxesViewer.prototype.update = function (position, xaxis, yaxis, zaxis) {
  52724. var scaleLines = this.scaleLines;
  52725. var point1 = this._xline[0];
  52726. var point2 = this._xline[1];
  52727. point1.x = position.x;
  52728. point1.y = position.y;
  52729. point1.z = position.z;
  52730. point2.x = point1.x + xaxis.x * scaleLines;
  52731. point2.y = point1.y + xaxis.y * scaleLines;
  52732. point2.z = point1.z + xaxis.z * scaleLines;
  52733. BABYLON.Mesh.CreateLines(null, this._xline, null, null, this._xmesh);
  52734. point1 = this._yline[0];
  52735. point2 = this._yline[1];
  52736. point1.x = position.x;
  52737. point1.y = position.y;
  52738. point1.z = position.z;
  52739. point2.x = point1.x + yaxis.x * scaleLines;
  52740. point2.y = point1.y + yaxis.y * scaleLines;
  52741. point2.z = point1.z + yaxis.z * scaleLines;
  52742. BABYLON.Mesh.CreateLines(null, this._yline, null, null, this._ymesh);
  52743. point1 = this._zline[0];
  52744. point2 = this._zline[1];
  52745. point1.x = position.x;
  52746. point1.y = position.y;
  52747. point1.z = position.z;
  52748. point2.x = point1.x + zaxis.x * scaleLines;
  52749. point2.y = point1.y + zaxis.y * scaleLines;
  52750. point2.z = point1.z + zaxis.z * scaleLines;
  52751. BABYLON.Mesh.CreateLines(null, this._zline, null, null, this._zmesh);
  52752. };
  52753. AxesViewer.prototype.dispose = function () {
  52754. if (this._xmesh) {
  52755. this._xmesh.dispose();
  52756. this._ymesh.dispose();
  52757. this._zmesh.dispose();
  52758. this._xmesh = null;
  52759. this._ymesh = null;
  52760. this._zmesh = null;
  52761. this._xline = null;
  52762. this._yline = null;
  52763. this._zline = null;
  52764. this.scene = null;
  52765. }
  52766. };
  52767. return AxesViewer;
  52768. }());
  52769. Debug.AxesViewer = AxesViewer;
  52770. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  52771. })(BABYLON || (BABYLON = {}));
  52772. //# sourceMappingURL=babylon.axesViewer.js.map
  52773. var BABYLON;
  52774. (function (BABYLON) {
  52775. var Debug;
  52776. (function (Debug) {
  52777. var BoneAxesViewer = (function (_super) {
  52778. __extends(BoneAxesViewer, _super);
  52779. function BoneAxesViewer(scene, bone, mesh, scaleLines) {
  52780. if (scaleLines === void 0) { scaleLines = 1; }
  52781. var _this = _super.call(this, scene, scaleLines) || this;
  52782. _this.pos = BABYLON.Vector3.Zero();
  52783. _this.xaxis = BABYLON.Vector3.Zero();
  52784. _this.yaxis = BABYLON.Vector3.Zero();
  52785. _this.zaxis = BABYLON.Vector3.Zero();
  52786. _this.mesh = mesh;
  52787. _this.bone = bone;
  52788. return _this;
  52789. }
  52790. BoneAxesViewer.prototype.update = function () {
  52791. var bone = this.bone;
  52792. bone.getAbsolutePositionToRef(this.mesh, this.pos);
  52793. bone.getDirectionToRef(BABYLON.Axis.X, this.mesh, this.xaxis);
  52794. bone.getDirectionToRef(BABYLON.Axis.Y, this.mesh, this.yaxis);
  52795. bone.getDirectionToRef(BABYLON.Axis.Z, this.mesh, this.zaxis);
  52796. _super.prototype.update.call(this, this.pos, this.xaxis, this.yaxis, this.zaxis);
  52797. };
  52798. BoneAxesViewer.prototype.dispose = function () {
  52799. if (this.pos) {
  52800. this.pos = null;
  52801. this.xaxis = null;
  52802. this.yaxis = null;
  52803. this.zaxis = null;
  52804. this.mesh = null;
  52805. this.bone = null;
  52806. _super.prototype.dispose.call(this);
  52807. }
  52808. };
  52809. return BoneAxesViewer;
  52810. }(Debug.AxesViewer));
  52811. Debug.BoneAxesViewer = BoneAxesViewer;
  52812. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  52813. })(BABYLON || (BABYLON = {}));
  52814. //# sourceMappingURL=babylon.boneAxesViewer.js.map
  52815. var BABYLON;
  52816. (function (BABYLON) {
  52817. /**
  52818. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  52819. * It can help converting any input color in a desired output one. This can then be used to create effects
  52820. * from sepia, black and white to sixties or futuristic rendering...
  52821. *
  52822. * The only supported format is currently 3dl.
  52823. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
  52824. */
  52825. var ColorGradingTexture = (function (_super) {
  52826. __extends(ColorGradingTexture, _super);
  52827. /**
  52828. * Instantiates a ColorGradingTexture from the following parameters.
  52829. *
  52830. * @param url The location of the color gradind data (currently only supporting 3dl)
  52831. * @param scene The scene the texture will be used in
  52832. */
  52833. function ColorGradingTexture(url, scene) {
  52834. var _this = _super.call(this, scene) || this;
  52835. if (!url) {
  52836. return _this;
  52837. }
  52838. _this._textureMatrix = BABYLON.Matrix.Identity();
  52839. _this.name = url;
  52840. _this.url = url;
  52841. _this.hasAlpha = false;
  52842. _this.isCube = false;
  52843. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  52844. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  52845. _this.anisotropicFilteringLevel = 1;
  52846. _this._texture = _this._getFromCache(url, true);
  52847. if (!_this._texture) {
  52848. if (!scene.useDelayedTextureLoading) {
  52849. _this.loadTexture();
  52850. }
  52851. else {
  52852. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  52853. }
  52854. }
  52855. return _this;
  52856. }
  52857. /**
  52858. * Returns the texture matrix used in most of the material.
  52859. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  52860. */
  52861. ColorGradingTexture.prototype.getTextureMatrix = function () {
  52862. return this._textureMatrix;
  52863. };
  52864. /**
  52865. * Occurs when the file being loaded is a .3dl LUT file.
  52866. */
  52867. ColorGradingTexture.prototype.load3dlTexture = function () {
  52868. var _this = this;
  52869. var mipLevels = 0;
  52870. var floatArrayView = null;
  52871. var texture = this.getScene().getEngine().createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  52872. this._texture = texture;
  52873. var callback = function (text) {
  52874. var data;
  52875. var tempData;
  52876. var line;
  52877. var lines = text.split('\n');
  52878. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  52879. var maxColor = 0;
  52880. for (var i = 0; i < lines.length; i++) {
  52881. line = lines[i];
  52882. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  52883. continue;
  52884. if (line.indexOf('#') === 0)
  52885. continue;
  52886. var words = line.split(" ");
  52887. if (size === 0) {
  52888. // Number of space + one
  52889. size = words.length;
  52890. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  52891. tempData = new Float32Array(size * size * size * 4);
  52892. continue;
  52893. }
  52894. if (size != 0) {
  52895. var r = Math.max(parseInt(words[0]), 0);
  52896. var g = Math.max(parseInt(words[1]), 0);
  52897. var b = Math.max(parseInt(words[2]), 0);
  52898. maxColor = Math.max(r, maxColor);
  52899. maxColor = Math.max(g, maxColor);
  52900. maxColor = Math.max(b, maxColor);
  52901. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  52902. tempData[pixelStorageIndex + 0] = r;
  52903. tempData[pixelStorageIndex + 1] = g;
  52904. tempData[pixelStorageIndex + 2] = b;
  52905. tempData[pixelStorageIndex + 3] = 0;
  52906. pixelIndexSlice++;
  52907. if (pixelIndexSlice % size == 0) {
  52908. pixelIndexH++;
  52909. pixelIndexSlice = 0;
  52910. if (pixelIndexH % size == 0) {
  52911. pixelIndexW++;
  52912. pixelIndexH = 0;
  52913. }
  52914. }
  52915. }
  52916. }
  52917. for (var i = 0; i < tempData.length; i++) {
  52918. var value = tempData[i];
  52919. data[i] = (value / maxColor * 255);
  52920. }
  52921. _this.getScene().getEngine().updateTextureSize(texture, size * size, size);
  52922. _this.getScene().getEngine().updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  52923. };
  52924. BABYLON.Tools.LoadFile(this.url, callback);
  52925. return this._texture;
  52926. };
  52927. /**
  52928. * Starts the loading process of the texture.
  52929. */
  52930. ColorGradingTexture.prototype.loadTexture = function () {
  52931. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  52932. this.load3dlTexture();
  52933. }
  52934. };
  52935. /**
  52936. * Clones the color gradind texture.
  52937. */
  52938. ColorGradingTexture.prototype.clone = function () {
  52939. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  52940. // Base texture
  52941. newTexture.level = this.level;
  52942. return newTexture;
  52943. };
  52944. /**
  52945. * Called during delayed load for textures.
  52946. */
  52947. ColorGradingTexture.prototype.delayLoad = function () {
  52948. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  52949. return;
  52950. }
  52951. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  52952. this._texture = this._getFromCache(this.url, true);
  52953. if (!this._texture) {
  52954. this.loadTexture();
  52955. }
  52956. };
  52957. /**
  52958. * Binds the color grading to the shader.
  52959. * @param colorGrading The texture to bind
  52960. * @param effect The effect to bind to
  52961. */
  52962. ColorGradingTexture.Bind = function (colorGrading, effect) {
  52963. effect.setTexture("cameraColorGrading2DSampler", colorGrading);
  52964. var x = colorGrading.level; // Texture Level
  52965. var y = colorGrading.getSize().height; // Texture Size example with 8
  52966. var z = y - 1.0; // SizeMinusOne 8 - 1
  52967. var w = 1 / y; // Space of 1 slice 1 / 8
  52968. effect.setFloat4("vCameraColorGradingInfos", x, y, z, w);
  52969. var slicePixelSizeU = w / y; // Space of 1 pixel in U direction, e.g. 1/64
  52970. 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
  52971. 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
  52972. 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
  52973. var z2 = 0.5 * slicePixelSizeU; // Offset of lookup range in U to align sample position with texel centre, for example 0.5/64
  52974. var w2 = 0.5 * slicePixelSizeV; // Offset of lookup range in V to align sample position with texel centre, for example 0.5/8
  52975. effect.setFloat4("vCameraColorGradingScaleOffset", x2, y2, z2, w2);
  52976. };
  52977. /**
  52978. * Prepare the list of uniforms associated with the ColorGrading effects.
  52979. * @param uniformsList The list of uniforms used in the effect
  52980. * @param samplersList The list of samplers used in the effect
  52981. */
  52982. ColorGradingTexture.PrepareUniformsAndSamplers = function (uniformsList, samplersList) {
  52983. uniformsList.push("vCameraColorGradingInfos", "vCameraColorGradingScaleOffset");
  52984. samplersList.push("cameraColorGrading2DSampler");
  52985. };
  52986. /**
  52987. * Parses a color grading texture serialized by Babylon.
  52988. * @param parsedTexture The texture information being parsedTexture
  52989. * @param scene The scene to load the texture in
  52990. * @param rootUrl The root url of the data assets to load
  52991. * @return A color gradind texture
  52992. */
  52993. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  52994. var texture = null;
  52995. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  52996. texture = new BABYLON.ColorGradingTexture(parsedTexture.name, scene);
  52997. texture.name = parsedTexture.name;
  52998. texture.level = parsedTexture.level;
  52999. }
  53000. return texture;
  53001. };
  53002. /**
  53003. * Serializes the LUT texture to json format.
  53004. */
  53005. ColorGradingTexture.prototype.serialize = function () {
  53006. if (!this.name) {
  53007. return null;
  53008. }
  53009. var serializationObject = {};
  53010. serializationObject.name = this.name;
  53011. serializationObject.level = this.level;
  53012. serializationObject.customType = "BABYLON.ColorGradingTexture";
  53013. return serializationObject;
  53014. };
  53015. return ColorGradingTexture;
  53016. }(BABYLON.BaseTexture));
  53017. /**
  53018. * Empty line regex stored for GC.
  53019. */
  53020. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  53021. BABYLON.ColorGradingTexture = ColorGradingTexture;
  53022. })(BABYLON || (BABYLON = {}));
  53023. //# sourceMappingURL=babylon.colorGradingTexture.js.map
  53024. var BABYLON;
  53025. (function (BABYLON) {
  53026. /**
  53027. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  53028. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  53029. * 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;
  53030. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  53031. */
  53032. var ColorCurves = (function () {
  53033. function ColorCurves() {
  53034. this._dirty = true;
  53035. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  53036. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  53037. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  53038. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  53039. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  53040. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  53041. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  53042. this._globalHue = 30;
  53043. this._globalDensity = 0;
  53044. this._globalSaturation = 0;
  53045. this._globalExposure = 0;
  53046. this._highlightsHue = 30;
  53047. this._highlightsDensity = 0;
  53048. this._highlightsSaturation = 0;
  53049. this._highlightsExposure = 0;
  53050. this._midtonesHue = 30;
  53051. this._midtonesDensity = 0;
  53052. this._midtonesSaturation = 0;
  53053. this._midtonesExposure = 0;
  53054. this._shadowsHue = 30;
  53055. this._shadowsDensity = 0;
  53056. this._shadowsSaturation = 0;
  53057. this._shadowsExposure = 0;
  53058. }
  53059. Object.defineProperty(ColorCurves.prototype, "GlobalHue", {
  53060. /**
  53061. * Gets the global Hue value.
  53062. * 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).
  53063. */
  53064. get: function () {
  53065. return this._globalHue;
  53066. },
  53067. /**
  53068. * Sets the global Hue value.
  53069. * 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).
  53070. */
  53071. set: function (value) {
  53072. this._globalHue = value;
  53073. this._dirty = true;
  53074. },
  53075. enumerable: true,
  53076. configurable: true
  53077. });
  53078. Object.defineProperty(ColorCurves.prototype, "GlobalDensity", {
  53079. /**
  53080. * Gets the global Density value.
  53081. * 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.
  53082. * Values less than zero provide a filter of opposite hue.
  53083. */
  53084. get: function () {
  53085. return this._globalDensity;
  53086. },
  53087. /**
  53088. * Sets the global Density value.
  53089. * 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.
  53090. * Values less than zero provide a filter of opposite hue.
  53091. */
  53092. set: function (value) {
  53093. this._globalDensity = value;
  53094. this._dirty = true;
  53095. },
  53096. enumerable: true,
  53097. configurable: true
  53098. });
  53099. Object.defineProperty(ColorCurves.prototype, "GlobalSaturation", {
  53100. /**
  53101. * Gets the global Saturation value.
  53102. * 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.
  53103. */
  53104. get: function () {
  53105. return this._globalSaturation;
  53106. },
  53107. /**
  53108. * Sets the global Saturation value.
  53109. * 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.
  53110. */
  53111. set: function (value) {
  53112. this._globalSaturation = value;
  53113. this._dirty = true;
  53114. },
  53115. enumerable: true,
  53116. configurable: true
  53117. });
  53118. Object.defineProperty(ColorCurves.prototype, "HighlightsHue", {
  53119. /**
  53120. * Gets the highlights Hue value.
  53121. * 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).
  53122. */
  53123. get: function () {
  53124. return this._highlightsHue;
  53125. },
  53126. /**
  53127. * Sets the highlights Hue value.
  53128. * 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).
  53129. */
  53130. set: function (value) {
  53131. this._highlightsHue = value;
  53132. this._dirty = true;
  53133. },
  53134. enumerable: true,
  53135. configurable: true
  53136. });
  53137. Object.defineProperty(ColorCurves.prototype, "HighlightsDensity", {
  53138. /**
  53139. * Gets the highlights Density value.
  53140. * 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.
  53141. * Values less than zero provide a filter of opposite hue.
  53142. */
  53143. get: function () {
  53144. return this._highlightsDensity;
  53145. },
  53146. /**
  53147. * Sets the highlights Density value.
  53148. * 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.
  53149. * Values less than zero provide a filter of opposite hue.
  53150. */
  53151. set: function (value) {
  53152. this._highlightsDensity = value;
  53153. this._dirty = true;
  53154. },
  53155. enumerable: true,
  53156. configurable: true
  53157. });
  53158. Object.defineProperty(ColorCurves.prototype, "HighlightsSaturation", {
  53159. /**
  53160. * Gets the highlights Saturation value.
  53161. * 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.
  53162. */
  53163. get: function () {
  53164. return this._highlightsSaturation;
  53165. },
  53166. /**
  53167. * Sets the highlights Saturation value.
  53168. * 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.
  53169. */
  53170. set: function (value) {
  53171. this._highlightsSaturation = value;
  53172. this._dirty = true;
  53173. },
  53174. enumerable: true,
  53175. configurable: true
  53176. });
  53177. Object.defineProperty(ColorCurves.prototype, "HighlightsExposure", {
  53178. /**
  53179. * Gets the highlights Exposure value.
  53180. * 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.
  53181. */
  53182. get: function () {
  53183. return this._highlightsExposure;
  53184. },
  53185. /**
  53186. * Sets the highlights Exposure value.
  53187. * 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.
  53188. */
  53189. set: function (value) {
  53190. this._highlightsExposure = value;
  53191. this._dirty = true;
  53192. },
  53193. enumerable: true,
  53194. configurable: true
  53195. });
  53196. Object.defineProperty(ColorCurves.prototype, "MidtonesHue", {
  53197. /**
  53198. * Gets the midtones Hue value.
  53199. * 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).
  53200. */
  53201. get: function () {
  53202. return this._midtonesHue;
  53203. },
  53204. /**
  53205. * Sets the midtones Hue value.
  53206. * 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).
  53207. */
  53208. set: function (value) {
  53209. this._midtonesHue = value;
  53210. this._dirty = true;
  53211. },
  53212. enumerable: true,
  53213. configurable: true
  53214. });
  53215. Object.defineProperty(ColorCurves.prototype, "MidtonesDensity", {
  53216. /**
  53217. * Gets the midtones Density value.
  53218. * 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.
  53219. * Values less than zero provide a filter of opposite hue.
  53220. */
  53221. get: function () {
  53222. return this._midtonesDensity;
  53223. },
  53224. /**
  53225. * Sets the midtones Density value.
  53226. * 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.
  53227. * Values less than zero provide a filter of opposite hue.
  53228. */
  53229. set: function (value) {
  53230. this._midtonesDensity = value;
  53231. this._dirty = true;
  53232. },
  53233. enumerable: true,
  53234. configurable: true
  53235. });
  53236. Object.defineProperty(ColorCurves.prototype, "MidtonesSaturation", {
  53237. /**
  53238. * Gets the midtones Saturation value.
  53239. * 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.
  53240. */
  53241. get: function () {
  53242. return this._midtonesSaturation;
  53243. },
  53244. /**
  53245. * Sets the midtones Saturation value.
  53246. * 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.
  53247. */
  53248. set: function (value) {
  53249. this._midtonesSaturation = value;
  53250. this._dirty = true;
  53251. },
  53252. enumerable: true,
  53253. configurable: true
  53254. });
  53255. Object.defineProperty(ColorCurves.prototype, "MidtonesExposure", {
  53256. /**
  53257. * Gets the midtones Exposure value.
  53258. * 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.
  53259. */
  53260. get: function () {
  53261. return this._midtonesExposure;
  53262. },
  53263. /**
  53264. * Sets the midtones Exposure value.
  53265. * 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.
  53266. */
  53267. set: function (value) {
  53268. this._midtonesExposure = value;
  53269. this._dirty = true;
  53270. },
  53271. enumerable: true,
  53272. configurable: true
  53273. });
  53274. Object.defineProperty(ColorCurves.prototype, "ShadowsHue", {
  53275. /**
  53276. * Gets the shadows Hue value.
  53277. * 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).
  53278. */
  53279. get: function () {
  53280. return this._shadowsHue;
  53281. },
  53282. /**
  53283. * Sets the shadows Hue value.
  53284. * 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).
  53285. */
  53286. set: function (value) {
  53287. this._shadowsHue = value;
  53288. this._dirty = true;
  53289. },
  53290. enumerable: true,
  53291. configurable: true
  53292. });
  53293. Object.defineProperty(ColorCurves.prototype, "ShadowsDensity", {
  53294. /**
  53295. * Gets the shadows Density value.
  53296. * 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.
  53297. * Values less than zero provide a filter of opposite hue.
  53298. */
  53299. get: function () {
  53300. return this._shadowsDensity;
  53301. },
  53302. /**
  53303. * Sets the shadows Density value.
  53304. * 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.
  53305. * Values less than zero provide a filter of opposite hue.
  53306. */
  53307. set: function (value) {
  53308. this._shadowsDensity = value;
  53309. this._dirty = true;
  53310. },
  53311. enumerable: true,
  53312. configurable: true
  53313. });
  53314. Object.defineProperty(ColorCurves.prototype, "ShadowsSaturation", {
  53315. /**
  53316. * Gets the shadows Saturation value.
  53317. * 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.
  53318. */
  53319. get: function () {
  53320. return this._shadowsSaturation;
  53321. },
  53322. /**
  53323. * Sets the shadows Saturation value.
  53324. * 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.
  53325. */
  53326. set: function (value) {
  53327. this._shadowsSaturation = value;
  53328. this._dirty = true;
  53329. },
  53330. enumerable: true,
  53331. configurable: true
  53332. });
  53333. Object.defineProperty(ColorCurves.prototype, "ShadowsExposure", {
  53334. /**
  53335. * Gets the shadows Exposure value.
  53336. * 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.
  53337. */
  53338. get: function () {
  53339. return this._shadowsExposure;
  53340. },
  53341. /**
  53342. * Sets the shadows Exposure value.
  53343. * 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.
  53344. */
  53345. set: function (value) {
  53346. this._shadowsExposure = value;
  53347. this._dirty = true;
  53348. },
  53349. enumerable: true,
  53350. configurable: true
  53351. });
  53352. /**
  53353. * Binds the color curves to the shader.
  53354. * @param colorCurves The color curve to bind
  53355. * @param effect The effect to bind to
  53356. */
  53357. ColorCurves.Bind = function (colorCurves, effect) {
  53358. if (colorCurves._dirty) {
  53359. colorCurves._dirty = false;
  53360. // Fill in global info.
  53361. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  53362. // Compute highlights info.
  53363. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  53364. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  53365. // Compute midtones info.
  53366. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  53367. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  53368. // Compute shadows info.
  53369. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  53370. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  53371. // Compute deltas (neutral is midtones).
  53372. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  53373. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  53374. }
  53375. effect.setFloat4("vCameraColorCurvePositive", colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  53376. effect.setFloat4("vCameraColorCurveNeutral", colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  53377. effect.setFloat4("vCameraColorCurveNegative", colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  53378. };
  53379. /**
  53380. * Prepare the list of uniforms associated with the ColorCurves effects.
  53381. * @param uniformsList The list of uniforms used in the effect
  53382. */
  53383. ColorCurves.PrepareUniforms = function (uniformsList) {
  53384. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  53385. };
  53386. /**
  53387. * Returns color grading data based on a hue, density, saturation and exposure value.
  53388. * @param filterHue The hue of the color filter.
  53389. * @param filterDensity The density of the color filter.
  53390. * @param saturation The saturation.
  53391. * @param exposure The exposure.
  53392. * @param result The result data container.
  53393. */
  53394. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  53395. if (hue == null) {
  53396. return;
  53397. }
  53398. hue = ColorCurves.clamp(hue, 0, 360);
  53399. density = ColorCurves.clamp(density, -100, 100);
  53400. saturation = ColorCurves.clamp(saturation, -100, 100);
  53401. exposure = ColorCurves.clamp(exposure, -100, 100);
  53402. // Remap the slider/config filter density with non-linear mapping and also scale by half
  53403. // so that the maximum filter density is only 50% control. This provides fine control
  53404. // for small values and reasonable range.
  53405. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  53406. density *= 0.5;
  53407. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  53408. if (density < 0) {
  53409. density *= -1;
  53410. hue = (hue + 180) % 360;
  53411. }
  53412. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  53413. result.scaleToRef(2, result);
  53414. result.a = 1 + 0.01 * saturation;
  53415. };
  53416. /**
  53417. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  53418. * @param value The input slider value in range [-100,100].
  53419. * @returns Adjusted value.
  53420. */
  53421. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  53422. value /= 100;
  53423. var x = Math.abs(value);
  53424. x = Math.pow(x, 2);
  53425. if (value < 0) {
  53426. x *= -1;
  53427. }
  53428. x *= 100;
  53429. return x;
  53430. };
  53431. /**
  53432. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  53433. * @param hue The hue (H) input.
  53434. * @param saturation The saturation (S) input.
  53435. * @param brightness The brightness (B) input.
  53436. * @result An RGBA color represented as Vector4.
  53437. */
  53438. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  53439. var h = ColorCurves.clamp(hue, 0, 360);
  53440. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  53441. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  53442. if (s === 0) {
  53443. result.r = v;
  53444. result.g = v;
  53445. result.b = v;
  53446. }
  53447. else {
  53448. // sector 0 to 5
  53449. h /= 60;
  53450. var i = Math.floor(h);
  53451. // fractional part of h
  53452. var f = h - i;
  53453. var p = v * (1 - s);
  53454. var q = v * (1 - s * f);
  53455. var t = v * (1 - s * (1 - f));
  53456. switch (i) {
  53457. case 0:
  53458. result.r = v;
  53459. result.g = t;
  53460. result.b = p;
  53461. break;
  53462. case 1:
  53463. result.r = q;
  53464. result.g = v;
  53465. result.b = p;
  53466. break;
  53467. case 2:
  53468. result.r = p;
  53469. result.g = v;
  53470. result.b = t;
  53471. break;
  53472. case 3:
  53473. result.r = p;
  53474. result.g = q;
  53475. result.b = v;
  53476. break;
  53477. case 4:
  53478. result.r = t;
  53479. result.g = p;
  53480. result.b = v;
  53481. break;
  53482. default:
  53483. result.r = v;
  53484. result.g = p;
  53485. result.b = q;
  53486. break;
  53487. }
  53488. }
  53489. result.a = 1;
  53490. };
  53491. /**
  53492. * Returns a value clamped between min and max
  53493. * @param value The value to clamp
  53494. * @param min The minimum of value
  53495. * @param max The maximum of value
  53496. * @returns The clamped value.
  53497. */
  53498. ColorCurves.clamp = function (value, min, max) {
  53499. return Math.min(Math.max(value, min), max);
  53500. };
  53501. /**
  53502. * Clones the current color curve instance.
  53503. * @return The cloned curves
  53504. */
  53505. ColorCurves.prototype.clone = function () {
  53506. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  53507. };
  53508. /**
  53509. * Serializes the current color curve instance to a json representation.
  53510. * @return a JSON representation
  53511. */
  53512. ColorCurves.prototype.serialize = function () {
  53513. return BABYLON.SerializationHelper.Serialize(this);
  53514. };
  53515. /**
  53516. * Parses the color curve from a json representation.
  53517. * @param source the JSON source to parse
  53518. * @return The parsed curves
  53519. */
  53520. ColorCurves.Parse = function (source) {
  53521. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  53522. };
  53523. return ColorCurves;
  53524. }());
  53525. __decorate([
  53526. BABYLON.serialize()
  53527. ], ColorCurves.prototype, "_globalHue", void 0);
  53528. __decorate([
  53529. BABYLON.serialize()
  53530. ], ColorCurves.prototype, "_globalDensity", void 0);
  53531. __decorate([
  53532. BABYLON.serialize()
  53533. ], ColorCurves.prototype, "_globalSaturation", void 0);
  53534. __decorate([
  53535. BABYLON.serialize()
  53536. ], ColorCurves.prototype, "_globalExposure", void 0);
  53537. __decorate([
  53538. BABYLON.serialize()
  53539. ], ColorCurves.prototype, "_highlightsHue", void 0);
  53540. __decorate([
  53541. BABYLON.serialize()
  53542. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  53543. __decorate([
  53544. BABYLON.serialize()
  53545. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  53546. __decorate([
  53547. BABYLON.serialize()
  53548. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  53549. __decorate([
  53550. BABYLON.serialize()
  53551. ], ColorCurves.prototype, "_midtonesHue", void 0);
  53552. __decorate([
  53553. BABYLON.serialize()
  53554. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  53555. __decorate([
  53556. BABYLON.serialize()
  53557. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  53558. __decorate([
  53559. BABYLON.serialize()
  53560. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  53561. BABYLON.ColorCurves = ColorCurves;
  53562. })(BABYLON || (BABYLON = {}));
  53563. //# sourceMappingURL=babylon.colorCurves.js.map
  53564. var BABYLON;
  53565. (function (BABYLON) {
  53566. var PBRMaterialDefines = (function (_super) {
  53567. __extends(PBRMaterialDefines, _super);
  53568. function PBRMaterialDefines() {
  53569. var _this = _super.call(this) || this;
  53570. _this.ALBEDO = false;
  53571. _this.AMBIENT = false;
  53572. _this.OPACITY = false;
  53573. _this.OPACITYRGB = false;
  53574. _this.REFLECTION = false;
  53575. _this.EMISSIVE = false;
  53576. _this.REFLECTIVITY = false;
  53577. _this.BUMP = false;
  53578. _this.PARALLAX = false;
  53579. _this.PARALLAXOCCLUSION = false;
  53580. _this.SPECULAROVERALPHA = false;
  53581. _this.CLIPPLANE = false;
  53582. _this.ALPHATEST = false;
  53583. _this.ALPHAFROMALBEDO = false;
  53584. _this.POINTSIZE = false;
  53585. _this.FOG = false;
  53586. _this.SPECULARTERM = false;
  53587. _this.OPACITYFRESNEL = false;
  53588. _this.EMISSIVEFRESNEL = false;
  53589. _this.FRESNEL = false;
  53590. _this.NORMAL = false;
  53591. _this.UV1 = false;
  53592. _this.UV2 = false;
  53593. _this.VERTEXCOLOR = false;
  53594. _this.VERTEXALPHA = false;
  53595. _this.NUM_BONE_INFLUENCERS = 0;
  53596. _this.BonesPerMesh = 0;
  53597. _this.INSTANCES = false;
  53598. _this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  53599. _this.MICROSURFACEAUTOMATIC = false;
  53600. _this.EMISSIVEASILLUMINATION = false;
  53601. _this.LINKEMISSIVEWITHALBEDO = false;
  53602. _this.LIGHTMAP = false;
  53603. _this.USELIGHTMAPASSHADOWMAP = false;
  53604. _this.REFLECTIONMAP_3D = false;
  53605. _this.REFLECTIONMAP_SPHERICAL = false;
  53606. _this.REFLECTIONMAP_PLANAR = false;
  53607. _this.REFLECTIONMAP_CUBIC = false;
  53608. _this.REFLECTIONMAP_PROJECTION = false;
  53609. _this.REFLECTIONMAP_SKYBOX = false;
  53610. _this.REFLECTIONMAP_EXPLICIT = false;
  53611. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  53612. _this.INVERTCUBICMAP = false;
  53613. _this.LOGARITHMICDEPTH = false;
  53614. _this.CAMERATONEMAP = false;
  53615. _this.CAMERACONTRAST = false;
  53616. _this.CAMERACOLORGRADING = false;
  53617. _this.CAMERACOLORCURVES = false;
  53618. _this.OVERLOADEDVALUES = false;
  53619. _this.OVERLOADEDSHADOWVALUES = false;
  53620. _this.USESPHERICALFROMREFLECTIONMAP = false;
  53621. _this.REFRACTION = false;
  53622. _this.REFRACTIONMAP_3D = false;
  53623. _this.LINKREFRACTIONTOTRANSPARENCY = false;
  53624. _this.REFRACTIONMAPINLINEARSPACE = false;
  53625. _this.LODBASEDMICROSFURACE = false;
  53626. _this.USEPHYSICALLIGHTFALLOFF = false;
  53627. _this.RADIANCEOVERALPHA = false;
  53628. _this.USEPMREMREFLECTION = false;
  53629. _this.USEPMREMREFRACTION = false;
  53630. _this.OPENGLNORMALMAP = false;
  53631. _this.INVERTNORMALMAPX = false;
  53632. _this.INVERTNORMALMAPY = false;
  53633. _this.SHADOWFULLFLOAT = false;
  53634. _this.METALLICWORKFLOW = false;
  53635. _this.METALLICROUGHNESSMAP = false;
  53636. _this.METALLICROUGHNESSGSTOREINALPHA = false;
  53637. _this.METALLICROUGHNESSGSTOREINGREEN = false;
  53638. _this.rebuild();
  53639. return _this;
  53640. }
  53641. return PBRMaterialDefines;
  53642. }(BABYLON.MaterialDefines));
  53643. /**
  53644. * The Physically based material of BJS.
  53645. *
  53646. * This offers the main features of a standard PBR material.
  53647. * For more information, please refer to the documentation :
  53648. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  53649. */
  53650. var PBRMaterial = (function (_super) {
  53651. __extends(PBRMaterial, _super);
  53652. /**
  53653. * Instantiates a new PBRMaterial instance.
  53654. *
  53655. * @param name The material name
  53656. * @param scene The scene the material will be use in.
  53657. */
  53658. function PBRMaterial(name, scene) {
  53659. var _this = _super.call(this, name, scene) || this;
  53660. /**
  53661. * Intensity of the direct lights e.g. the four lights available in your scene.
  53662. * This impacts both the direct diffuse and specular highlights.
  53663. */
  53664. _this.directIntensity = 1.0;
  53665. /**
  53666. * Intensity of the emissive part of the material.
  53667. * This helps controlling the emissive effect without modifying the emissive color.
  53668. */
  53669. _this.emissiveIntensity = 1.0;
  53670. /**
  53671. * Intensity of the environment e.g. how much the environment will light the object
  53672. * either through harmonics for rough material or through the refelction for shiny ones.
  53673. */
  53674. _this.environmentIntensity = 1.0;
  53675. /**
  53676. * This is a special control allowing the reduction of the specular highlights coming from the
  53677. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  53678. */
  53679. _this.specularIntensity = 1.0;
  53680. _this._lightingInfos = new BABYLON.Vector4(_this.directIntensity, _this.emissiveIntensity, _this.environmentIntensity, _this.specularIntensity);
  53681. /**
  53682. * Debug Control allowing disabling the bump map on this material.
  53683. */
  53684. _this.disableBumpMap = false;
  53685. /**
  53686. * Debug Control helping enforcing or dropping the darkness of shadows.
  53687. * 1.0 means the shadows have their normal darkness, 0.0 means the shadows are not visible.
  53688. */
  53689. _this.overloadedShadowIntensity = 1.0;
  53690. /**
  53691. * Debug Control helping dropping the shading effect coming from the diffuse lighting.
  53692. * 1.0 means the shade have their normal impact, 0.0 means no shading at all.
  53693. */
  53694. _this.overloadedShadeIntensity = 1.0;
  53695. _this._overloadedShadowInfos = new BABYLON.Vector4(_this.overloadedShadowIntensity, _this.overloadedShadeIntensity, 0.0, 0.0);
  53696. /**
  53697. * The camera exposure used on this material.
  53698. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  53699. * This corresponds to a photographic exposure.
  53700. */
  53701. _this.cameraExposure = 1.0;
  53702. /**
  53703. * The camera contrast used on this material.
  53704. * This property is here and not in the camera to allow controlling contrast without full screen post process.
  53705. */
  53706. _this.cameraContrast = 1.0;
  53707. /**
  53708. * Color Grading 2D Lookup Texture.
  53709. * This allows special effects like sepia, black and white to sixties rendering style.
  53710. */
  53711. _this.cameraColorGradingTexture = null;
  53712. /**
  53713. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  53714. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  53715. * 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;
  53716. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  53717. */
  53718. _this.cameraColorCurves = null;
  53719. _this._cameraInfos = new BABYLON.Vector4(1.0, 1.0, 0.0, 0.0);
  53720. _this._microsurfaceTextureLods = new BABYLON.Vector2(0.0, 0.0);
  53721. /**
  53722. * Debug Control allowing to overload the ambient color.
  53723. * This as to be use with the overloadedAmbientIntensity parameter.
  53724. */
  53725. _this.overloadedAmbient = BABYLON.Color3.White();
  53726. /**
  53727. * Debug Control indicating how much the overloaded ambient color is used against the default one.
  53728. */
  53729. _this.overloadedAmbientIntensity = 0.0;
  53730. /**
  53731. * Debug Control allowing to overload the albedo color.
  53732. * This as to be use with the overloadedAlbedoIntensity parameter.
  53733. */
  53734. _this.overloadedAlbedo = BABYLON.Color3.White();
  53735. /**
  53736. * Debug Control indicating how much the overloaded albedo color is used against the default one.
  53737. */
  53738. _this.overloadedAlbedoIntensity = 0.0;
  53739. /**
  53740. * Debug Control allowing to overload the reflectivity color.
  53741. * This as to be use with the overloadedReflectivityIntensity parameter.
  53742. */
  53743. _this.overloadedReflectivity = new BABYLON.Color3(0.3, 0.3, 0.3);
  53744. /**
  53745. * Debug Control indicating how much the overloaded reflectivity color is used against the default one.
  53746. */
  53747. _this.overloadedReflectivityIntensity = 0.0;
  53748. /**
  53749. * Debug Control allowing to overload the emissive color.
  53750. * This as to be use with the overloadedEmissiveIntensity parameter.
  53751. */
  53752. _this.overloadedEmissive = BABYLON.Color3.White();
  53753. /**
  53754. * Debug Control indicating how much the overloaded emissive color is used against the default one.
  53755. */
  53756. _this.overloadedEmissiveIntensity = 0.0;
  53757. _this._overloadedIntensity = new BABYLON.Vector4(_this.overloadedAmbientIntensity, _this.overloadedAlbedoIntensity, _this.overloadedReflectivityIntensity, _this.overloadedEmissiveIntensity);
  53758. /**
  53759. * Debug Control allowing to overload the reflection color.
  53760. * This as to be use with the overloadedReflectionIntensity parameter.
  53761. */
  53762. _this.overloadedReflection = BABYLON.Color3.White();
  53763. /**
  53764. * Debug Control indicating how much the overloaded reflection color is used against the default one.
  53765. */
  53766. _this.overloadedReflectionIntensity = 0.0;
  53767. /**
  53768. * Debug Control allowing to overload the microsurface.
  53769. * This as to be use with the overloadedMicroSurfaceIntensity parameter.
  53770. */
  53771. _this.overloadedMicroSurface = 0.0;
  53772. /**
  53773. * Debug Control indicating how much the overloaded microsurface is used against the default one.
  53774. */
  53775. _this.overloadedMicroSurfaceIntensity = 0.0;
  53776. _this._overloadedMicroSurface = new BABYLON.Vector3(_this.overloadedMicroSurface, _this.overloadedMicroSurfaceIntensity, _this.overloadedReflectionIntensity);
  53777. /**
  53778. * AKA Occlusion Texture Intensity in other nomenclature.
  53779. */
  53780. _this.ambientTextureStrength = 1.0;
  53781. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  53782. /**
  53783. * AKA Diffuse Color in other nomenclature.
  53784. */
  53785. _this.albedoColor = new BABYLON.Color3(1, 1, 1);
  53786. /**
  53787. * AKA Specular Color in other nomenclature.
  53788. */
  53789. _this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  53790. _this.reflectionColor = new BABYLON.Color3(0.5, 0.5, 0.5);
  53791. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  53792. /**
  53793. * AKA Glossiness in other nomenclature.
  53794. */
  53795. _this.microSurface = 0.9;
  53796. /**
  53797. * source material index of refraction (IOR)' / 'destination material IOR.
  53798. */
  53799. _this.indexOfRefraction = 0.66;
  53800. /**
  53801. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  53802. */
  53803. _this.invertRefractionY = false;
  53804. /**
  53805. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  53806. * Materials half opaque for instance using refraction could benefit from this control.
  53807. */
  53808. _this.linkRefractionWithTransparency = false;
  53809. /**
  53810. * The emissive and albedo are linked to never be more than one (Energy conservation).
  53811. */
  53812. _this.linkEmissiveWithAlbedo = false;
  53813. _this.useLightmapAsShadowmap = false;
  53814. /**
  53815. * In this mode, the emissive informtaion will always be added to the lighting once.
  53816. * A light for instance can be thought as emissive.
  53817. */
  53818. _this.useEmissiveAsIllumination = false;
  53819. /**
  53820. * Secifies that the alpha is coming form the albedo channel alpha channel.
  53821. */
  53822. _this.useAlphaFromAlbedoTexture = false;
  53823. /**
  53824. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  53825. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  53826. */
  53827. _this.useSpecularOverAlpha = true;
  53828. /**
  53829. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  53830. */
  53831. _this.useMicroSurfaceFromReflectivityMapAlpha = false;
  53832. /**
  53833. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  53834. */
  53835. _this.useRoughnessFromMetallicTextureAlpha = true;
  53836. /**
  53837. * Specifies if the metallic texture contains the roughness information in its green channel.
  53838. */
  53839. _this.useRoughnessFromMetallicTextureGreen = false;
  53840. /**
  53841. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  53842. * The material will try to infer what glossiness each pixel should be.
  53843. */
  53844. _this.useAutoMicroSurfaceFromReflectivityMap = false;
  53845. /**
  53846. * Allows to work with scalar in linear mode. This is definitely a matter of preferences and tools used during
  53847. * the creation of the material.
  53848. */
  53849. _this.useScalarInLinearSpace = false;
  53850. /**
  53851. * BJS is using an harcoded light falloff based on a manually sets up range.
  53852. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  53853. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  53854. */
  53855. _this.usePhysicalLightFalloff = true;
  53856. /**
  53857. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  53858. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  53859. */
  53860. _this.useRadianceOverAlpha = true;
  53861. /**
  53862. * Allows using the bump map in parallax mode.
  53863. */
  53864. _this.useParallax = false;
  53865. /**
  53866. * Allows using the bump map in parallax occlusion mode.
  53867. */
  53868. _this.useParallaxOcclusion = false;
  53869. /**
  53870. * Controls the scale bias of the parallax mode.
  53871. */
  53872. _this.parallaxScaleBias = 0.05;
  53873. /**
  53874. * If sets to true, disables all the lights affecting the material.
  53875. */
  53876. _this.disableLighting = false;
  53877. /**
  53878. * Number of Simultaneous lights allowed on the material.
  53879. */
  53880. _this.maxSimultaneousLights = 4;
  53881. /**
  53882. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  53883. */
  53884. _this.invertNormalMapX = false;
  53885. /**
  53886. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  53887. */
  53888. _this.invertNormalMapY = false;
  53889. _this._renderTargets = new BABYLON.SmartArray(16);
  53890. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  53891. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  53892. _this._tempColor = new BABYLON.Color3();
  53893. _this._defines = new PBRMaterialDefines();
  53894. _this._cachedDefines = new PBRMaterialDefines();
  53895. _this._myScene = null;
  53896. _this._myShadowGenerator = null;
  53897. _this._cachedDefines.BonesPerMesh = -1;
  53898. _this.getRenderTargetTextures = function () {
  53899. _this._renderTargets.reset();
  53900. if (_this.reflectionTexture && _this.reflectionTexture.isRenderTarget) {
  53901. _this._renderTargets.push(_this.reflectionTexture);
  53902. }
  53903. if (_this.refractionTexture && _this.refractionTexture.isRenderTarget) {
  53904. _this._renderTargets.push(_this.refractionTexture);
  53905. }
  53906. return _this._renderTargets;
  53907. };
  53908. return _this;
  53909. }
  53910. PBRMaterial.prototype.getClassName = function () {
  53911. return "PBRMaterial";
  53912. };
  53913. Object.defineProperty(PBRMaterial.prototype, "useLogarithmicDepth", {
  53914. get: function () {
  53915. return this._useLogarithmicDepth;
  53916. },
  53917. set: function (value) {
  53918. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  53919. },
  53920. enumerable: true,
  53921. configurable: true
  53922. });
  53923. PBRMaterial.prototype.needAlphaBlending = function () {
  53924. if (this.linkRefractionWithTransparency) {
  53925. return false;
  53926. }
  53927. return (this.alpha < 1.0) || (this.opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture() || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled;
  53928. };
  53929. PBRMaterial.prototype.needAlphaTesting = function () {
  53930. if (this.linkRefractionWithTransparency) {
  53931. return false;
  53932. }
  53933. return this.albedoTexture != null && this.albedoTexture.hasAlpha;
  53934. };
  53935. PBRMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  53936. return this.albedoTexture != null && this.albedoTexture.hasAlpha && this.useAlphaFromAlbedoTexture;
  53937. };
  53938. PBRMaterial.prototype.getAlphaTestTexture = function () {
  53939. return this.albedoTexture;
  53940. };
  53941. PBRMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  53942. if (!mesh) {
  53943. return true;
  53944. }
  53945. if (this._defines.INSTANCES !== useInstances) {
  53946. return false;
  53947. }
  53948. if (mesh._materialDefines && mesh._materialDefines.isEqual(this._defines)) {
  53949. return true;
  53950. }
  53951. return false;
  53952. };
  53953. PBRMaterial.prototype.convertColorToLinearSpaceToRef = function (color, ref) {
  53954. PBRMaterial.convertColorToLinearSpaceToRef(color, ref, this.useScalarInLinearSpace);
  53955. };
  53956. PBRMaterial.convertColorToLinearSpaceToRef = function (color, ref, useScalarInLinear) {
  53957. if (!useScalarInLinear) {
  53958. color.toLinearSpaceToRef(ref);
  53959. }
  53960. else {
  53961. ref.r = color.r;
  53962. ref.g = color.g;
  53963. ref.b = color.b;
  53964. }
  53965. };
  53966. PBRMaterial.BindLights = function (scene, mesh, effect, defines, useScalarInLinearSpace, maxSimultaneousLights, usePhysicalLightFalloff) {
  53967. var lightIndex = 0;
  53968. var depthValuesAlreadySet = false;
  53969. for (var index = 0; index < scene.lights.length; index++) {
  53970. var light = scene.lights[index];
  53971. if (!light.isEnabled()) {
  53972. continue;
  53973. }
  53974. if (!light.canAffectMesh(mesh)) {
  53975. continue;
  53976. }
  53977. BABYLON.MaterialHelper.BindLightProperties(light, effect, lightIndex);
  53978. // GAMMA CORRECTION.
  53979. this.convertColorToLinearSpaceToRef(light.diffuse, PBRMaterial._scaledAlbedo, useScalarInLinearSpace);
  53980. PBRMaterial._scaledAlbedo.scaleToRef(light.intensity, PBRMaterial._scaledAlbedo);
  53981. effect.setColor4("vLightDiffuse" + lightIndex, PBRMaterial._scaledAlbedo, usePhysicalLightFalloff ? light.radius : light.range);
  53982. if (defines["SPECULARTERM"]) {
  53983. this.convertColorToLinearSpaceToRef(light.specular, PBRMaterial._scaledReflectivity, useScalarInLinearSpace);
  53984. PBRMaterial._scaledReflectivity.scaleToRef(light.intensity, PBRMaterial._scaledReflectivity);
  53985. effect.setColor3("vLightSpecular" + lightIndex, PBRMaterial._scaledReflectivity);
  53986. }
  53987. // Shadows
  53988. if (scene.shadowsEnabled) {
  53989. depthValuesAlreadySet = BABYLON.MaterialHelper.BindLightShadow(light, scene, mesh, lightIndex, effect, depthValuesAlreadySet);
  53990. }
  53991. lightIndex++;
  53992. if (lightIndex === maxSimultaneousLights)
  53993. break;
  53994. }
  53995. };
  53996. PBRMaterial.prototype.isReady = function (mesh, useInstances) {
  53997. if (this.isFrozen) {
  53998. if (this._wasPreviouslyReady) {
  53999. return true;
  54000. }
  54001. }
  54002. var scene = this.getScene();
  54003. var engine = scene.getEngine();
  54004. var needNormals = false;
  54005. var needUVs = false;
  54006. this._defines.reset();
  54007. if (scene.lightsEnabled && !this.disableLighting) {
  54008. needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, this._defines, this.maxSimultaneousLights) || needNormals;
  54009. }
  54010. if (!this.checkReadyOnEveryCall) {
  54011. if (this._renderId === scene.getRenderId()) {
  54012. if (this._checkCache(scene, mesh, useInstances)) {
  54013. return true;
  54014. }
  54015. }
  54016. }
  54017. if (scene.texturesEnabled) {
  54018. if (scene.getEngine().getCaps().textureLOD) {
  54019. this._defines.LODBASEDMICROSFURACE = true;
  54020. }
  54021. if (this.albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  54022. if (!this.albedoTexture.isReady()) {
  54023. return false;
  54024. }
  54025. else {
  54026. needUVs = true;
  54027. this._defines.ALBEDO = true;
  54028. }
  54029. }
  54030. if (this.ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  54031. if (!this.ambientTexture.isReady()) {
  54032. return false;
  54033. }
  54034. else {
  54035. needUVs = true;
  54036. this._defines.AMBIENT = true;
  54037. }
  54038. }
  54039. if (this.opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  54040. if (!this.opacityTexture.isReady()) {
  54041. return false;
  54042. }
  54043. else {
  54044. needUVs = true;
  54045. this._defines.OPACITY = true;
  54046. if (this.opacityTexture.getAlphaFromRGB) {
  54047. this._defines.OPACITYRGB = true;
  54048. }
  54049. }
  54050. }
  54051. if (this.reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  54052. if (!this.reflectionTexture.isReady()) {
  54053. return false;
  54054. }
  54055. else {
  54056. needNormals = true;
  54057. this._defines.REFLECTION = true;
  54058. if (this.reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  54059. this._defines.INVERTCUBICMAP = true;
  54060. }
  54061. this._defines.REFLECTIONMAP_3D = this.reflectionTexture.isCube;
  54062. switch (this.reflectionTexture.coordinatesMode) {
  54063. case BABYLON.Texture.CUBIC_MODE:
  54064. case BABYLON.Texture.INVCUBIC_MODE:
  54065. this._defines.REFLECTIONMAP_CUBIC = true;
  54066. break;
  54067. case BABYLON.Texture.EXPLICIT_MODE:
  54068. this._defines.REFLECTIONMAP_EXPLICIT = true;
  54069. break;
  54070. case BABYLON.Texture.PLANAR_MODE:
  54071. this._defines.REFLECTIONMAP_PLANAR = true;
  54072. break;
  54073. case BABYLON.Texture.PROJECTION_MODE:
  54074. this._defines.REFLECTIONMAP_PROJECTION = true;
  54075. break;
  54076. case BABYLON.Texture.SKYBOX_MODE:
  54077. this._defines.REFLECTIONMAP_SKYBOX = true;
  54078. break;
  54079. case BABYLON.Texture.SPHERICAL_MODE:
  54080. this._defines.REFLECTIONMAP_SPHERICAL = true;
  54081. break;
  54082. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  54083. this._defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  54084. break;
  54085. }
  54086. if (this.reflectionTexture instanceof BABYLON.HDRCubeTexture && this.reflectionTexture) {
  54087. this._defines.USESPHERICALFROMREFLECTIONMAP = true;
  54088. needNormals = true;
  54089. if (this.reflectionTexture.isPMREM) {
  54090. this._defines.USEPMREMREFLECTION = true;
  54091. }
  54092. }
  54093. }
  54094. }
  54095. if (this.lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  54096. if (!this.lightmapTexture.isReady()) {
  54097. return false;
  54098. }
  54099. else {
  54100. needUVs = true;
  54101. this._defines.LIGHTMAP = true;
  54102. this._defines.USELIGHTMAPASSHADOWMAP = this.useLightmapAsShadowmap;
  54103. }
  54104. }
  54105. if (this.emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  54106. if (!this.emissiveTexture.isReady()) {
  54107. return false;
  54108. }
  54109. else {
  54110. needUVs = true;
  54111. this._defines.EMISSIVE = true;
  54112. }
  54113. }
  54114. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  54115. if (this.metallicTexture) {
  54116. if (!this.metallicTexture.isReady()) {
  54117. return false;
  54118. }
  54119. else {
  54120. needUVs = true;
  54121. this._defines.METALLICWORKFLOW = true;
  54122. this._defines.METALLICROUGHNESSMAP = true;
  54123. this._defines.METALLICROUGHNESSGSTOREINALPHA = this.useRoughnessFromMetallicTextureAlpha;
  54124. this._defines.METALLICROUGHNESSGSTOREINGREEN = !this.useRoughnessFromMetallicTextureAlpha && this.useRoughnessFromMetallicTextureGreen;
  54125. }
  54126. }
  54127. else if (this.reflectivityTexture) {
  54128. if (!this.reflectivityTexture.isReady()) {
  54129. return false;
  54130. }
  54131. else {
  54132. needUVs = true;
  54133. this._defines.REFLECTIVITY = true;
  54134. this._defines.MICROSURFACEFROMREFLECTIVITYMAP = this.useMicroSurfaceFromReflectivityMapAlpha;
  54135. this._defines.MICROSURFACEAUTOMATIC = this.useAutoMicroSurfaceFromReflectivityMap;
  54136. }
  54137. }
  54138. }
  54139. if (scene.getEngine().getCaps().standardDerivatives && this.bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this.disableBumpMap) {
  54140. if (!this.bumpTexture.isReady()) {
  54141. return false;
  54142. }
  54143. else {
  54144. needUVs = true;
  54145. this._defines.BUMP = true;
  54146. if (this.useParallax && this.albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  54147. this._defines.PARALLAX = true;
  54148. if (this.useParallaxOcclusion) {
  54149. this._defines.PARALLAXOCCLUSION = true;
  54150. }
  54151. }
  54152. if (this.invertNormalMapX) {
  54153. this._defines.INVERTNORMALMAPX = true;
  54154. }
  54155. if (this.invertNormalMapY) {
  54156. this._defines.INVERTNORMALMAPY = true;
  54157. }
  54158. if (scene._mirroredCameraPosition) {
  54159. this._defines.INVERTNORMALMAPX = !this._defines.INVERTNORMALMAPX;
  54160. this._defines.INVERTNORMALMAPY = !this._defines.INVERTNORMALMAPY;
  54161. }
  54162. }
  54163. }
  54164. if (this.refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  54165. if (!this.refractionTexture.isReady()) {
  54166. return false;
  54167. }
  54168. else {
  54169. needUVs = true;
  54170. this._defines.REFRACTION = true;
  54171. this._defines.REFRACTIONMAP_3D = this.refractionTexture.isCube;
  54172. if (this.linkRefractionWithTransparency) {
  54173. this._defines.LINKREFRACTIONTOTRANSPARENCY = true;
  54174. }
  54175. if (this.refractionTexture instanceof BABYLON.HDRCubeTexture) {
  54176. this._defines.REFRACTIONMAPINLINEARSPACE = true;
  54177. if (this.refractionTexture.isPMREM) {
  54178. this._defines.USEPMREMREFRACTION = true;
  54179. }
  54180. }
  54181. }
  54182. }
  54183. if (this.cameraColorGradingTexture && BABYLON.StandardMaterial.ColorGradingTextureEnabled) {
  54184. if (!this.cameraColorGradingTexture.isReady()) {
  54185. return false;
  54186. }
  54187. else {
  54188. this._defines.CAMERACOLORGRADING = true;
  54189. }
  54190. }
  54191. }
  54192. // Effect
  54193. if (scene.clipPlane) {
  54194. this._defines.CLIPPLANE = true;
  54195. }
  54196. if (engine.getAlphaTesting()) {
  54197. this._defines.ALPHATEST = true;
  54198. }
  54199. if (this._shouldUseAlphaFromAlbedoTexture()) {
  54200. this._defines.ALPHAFROMALBEDO = true;
  54201. }
  54202. if (this.useEmissiveAsIllumination) {
  54203. this._defines.EMISSIVEASILLUMINATION = true;
  54204. }
  54205. if (this.linkEmissiveWithAlbedo) {
  54206. this._defines.LINKEMISSIVEWITHALBEDO = true;
  54207. }
  54208. if (this.useLogarithmicDepth) {
  54209. this._defines.LOGARITHMICDEPTH = true;
  54210. }
  54211. if (this.cameraContrast != 1) {
  54212. this._defines.CAMERACONTRAST = true;
  54213. }
  54214. if (this.cameraExposure != 1) {
  54215. this._defines.CAMERATONEMAP = true;
  54216. }
  54217. if (this.cameraColorCurves) {
  54218. this._defines.CAMERACOLORCURVES = true;
  54219. }
  54220. if (this.overloadedShadeIntensity != 1 ||
  54221. this.overloadedShadowIntensity != 1) {
  54222. this._defines.OVERLOADEDSHADOWVALUES = true;
  54223. }
  54224. if (this.overloadedMicroSurfaceIntensity > 0 ||
  54225. this.overloadedEmissiveIntensity > 0 ||
  54226. this.overloadedReflectivityIntensity > 0 ||
  54227. this.overloadedAlbedoIntensity > 0 ||
  54228. this.overloadedAmbientIntensity > 0 ||
  54229. this.overloadedReflectionIntensity > 0) {
  54230. this._defines.OVERLOADEDVALUES = true;
  54231. }
  54232. // Point size
  54233. if (this.pointsCloud || scene.forcePointsCloud) {
  54234. this._defines.POINTSIZE = true;
  54235. }
  54236. // Fog
  54237. if (scene.fogEnabled && mesh && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  54238. this._defines.FOG = true;
  54239. }
  54240. if (BABYLON.StandardMaterial.FresnelEnabled) {
  54241. // Fresnel
  54242. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled ||
  54243. this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  54244. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  54245. this._defines.OPACITYFRESNEL = true;
  54246. }
  54247. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  54248. this._defines.EMISSIVEFRESNEL = true;
  54249. }
  54250. needNormals = true;
  54251. this._defines.FRESNEL = true;
  54252. }
  54253. }
  54254. if (this._defines.SPECULARTERM && this.useSpecularOverAlpha) {
  54255. this._defines.SPECULAROVERALPHA = true;
  54256. }
  54257. if (this.usePhysicalLightFalloff) {
  54258. this._defines.USEPHYSICALLIGHTFALLOFF = true;
  54259. }
  54260. if (this.useRadianceOverAlpha) {
  54261. this._defines.RADIANCEOVERALPHA = true;
  54262. }
  54263. if ((this.metallic !== undefined && this.metallic !== null) || (this.roughness !== undefined && this.roughness !== null)) {
  54264. this._defines.METALLICWORKFLOW = true;
  54265. }
  54266. // Attribs
  54267. if (mesh) {
  54268. if (needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  54269. this._defines.NORMAL = true;
  54270. }
  54271. if (needUVs) {
  54272. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  54273. this._defines.UV1 = true;
  54274. }
  54275. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  54276. this._defines.UV2 = true;
  54277. }
  54278. }
  54279. if (mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  54280. this._defines.VERTEXCOLOR = true;
  54281. if (mesh.hasVertexAlpha) {
  54282. this._defines.VERTEXALPHA = true;
  54283. }
  54284. }
  54285. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  54286. this._defines.NUM_BONE_INFLUENCERS = mesh.numBoneInfluencers;
  54287. this._defines.BonesPerMesh = (mesh.skeleton.bones.length + 1);
  54288. }
  54289. // Instances
  54290. if (useInstances) {
  54291. this._defines.INSTANCES = true;
  54292. }
  54293. }
  54294. // Get correct effect
  54295. if (!this._defines.isEqual(this._cachedDefines)) {
  54296. this._defines.cloneTo(this._cachedDefines);
  54297. scene.resetCachedMaterial();
  54298. // Fallbacks
  54299. var fallbacks = new BABYLON.EffectFallbacks();
  54300. if (this._defines.REFLECTION) {
  54301. fallbacks.addFallback(0, "REFLECTION");
  54302. }
  54303. if (this._defines.REFRACTION) {
  54304. fallbacks.addFallback(0, "REFRACTION");
  54305. }
  54306. if (this._defines.REFLECTIVITY) {
  54307. fallbacks.addFallback(0, "REFLECTIVITY");
  54308. }
  54309. if (this._defines.BUMP) {
  54310. fallbacks.addFallback(0, "BUMP");
  54311. }
  54312. if (this._defines.PARALLAX) {
  54313. fallbacks.addFallback(1, "PARALLAX");
  54314. }
  54315. if (this._defines.PARALLAXOCCLUSION) {
  54316. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  54317. }
  54318. if (this._defines.SPECULAROVERALPHA) {
  54319. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  54320. }
  54321. if (this._defines.FOG) {
  54322. fallbacks.addFallback(1, "FOG");
  54323. }
  54324. if (this._defines.POINTSIZE) {
  54325. fallbacks.addFallback(0, "POINTSIZE");
  54326. }
  54327. if (this._defines.LOGARITHMICDEPTH) {
  54328. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  54329. }
  54330. BABYLON.MaterialHelper.HandleFallbacksForShadows(this._defines, fallbacks, this.maxSimultaneousLights);
  54331. if (this._defines.SPECULARTERM) {
  54332. fallbacks.addFallback(0, "SPECULARTERM");
  54333. }
  54334. if (this._defines.OPACITYFRESNEL) {
  54335. fallbacks.addFallback(1, "OPACITYFRESNEL");
  54336. }
  54337. if (this._defines.EMISSIVEFRESNEL) {
  54338. fallbacks.addFallback(2, "EMISSIVEFRESNEL");
  54339. }
  54340. if (this._defines.FRESNEL) {
  54341. fallbacks.addFallback(3, "FRESNEL");
  54342. }
  54343. if (this._defines.NUM_BONE_INFLUENCERS > 0) {
  54344. fallbacks.addCPUSkinningFallback(0, mesh);
  54345. }
  54346. //Attributes
  54347. var attribs = [BABYLON.VertexBuffer.PositionKind];
  54348. if (this._defines.NORMAL) {
  54349. attribs.push(BABYLON.VertexBuffer.NormalKind);
  54350. }
  54351. if (this._defines.UV1) {
  54352. attribs.push(BABYLON.VertexBuffer.UVKind);
  54353. }
  54354. if (this._defines.UV2) {
  54355. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  54356. }
  54357. if (this._defines.VERTEXCOLOR) {
  54358. attribs.push(BABYLON.VertexBuffer.ColorKind);
  54359. }
  54360. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, this._defines, fallbacks);
  54361. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, this._defines);
  54362. // Legacy browser patch
  54363. var join = this._defines.toString();
  54364. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  54365. "vFogInfos", "vFogColor", "pointSize",
  54366. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vReflectivityInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  54367. "mBones",
  54368. "vClipPlane", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  54369. "depthValues",
  54370. "opacityParts", "emissiveLeftColor", "emissiveRightColor",
  54371. "vLightingIntensity", "vOverloadedShadowIntensity", "vOverloadedIntensity", "vOverloadedAlbedo", "vOverloadedReflection", "vOverloadedReflectivity", "vOverloadedEmissive", "vOverloadedMicroSurface",
  54372. "logarithmicDepthConstant",
  54373. "vSphericalX", "vSphericalY", "vSphericalZ",
  54374. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  54375. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  54376. "vMicrosurfaceTextureLods",
  54377. "vCameraInfos"
  54378. ];
  54379. var samplers = ["albedoSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "reflectivitySampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  54380. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  54381. BABYLON.ColorGradingTexture.PrepareUniformsAndSamplers(uniforms, samplers);
  54382. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList(uniforms, samplers, this._defines, this.maxSimultaneousLights);
  54383. this._effect = scene.getEngine().createEffect("pbr", attribs, uniforms, samplers, join, fallbacks, this.onCompiled, this.onError, { maxSimultaneousLights: this.maxSimultaneousLights });
  54384. }
  54385. if (!this._effect.isReady()) {
  54386. return false;
  54387. }
  54388. this._renderId = scene.getRenderId();
  54389. this._wasPreviouslyReady = true;
  54390. if (mesh) {
  54391. if (!mesh._materialDefines) {
  54392. mesh._materialDefines = new PBRMaterialDefines();
  54393. }
  54394. this._defines.cloneTo(mesh._materialDefines);
  54395. }
  54396. return true;
  54397. };
  54398. PBRMaterial.prototype.unbind = function () {
  54399. if (this.reflectionTexture && this.reflectionTexture.isRenderTarget) {
  54400. this._effect.setTexture("reflection2DSampler", null);
  54401. }
  54402. if (this.refractionTexture && this.refractionTexture.isRenderTarget) {
  54403. this._effect.setTexture("refraction2DSampler", null);
  54404. }
  54405. _super.prototype.unbind.call(this);
  54406. };
  54407. PBRMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  54408. this._effect.setMatrix("world", world);
  54409. };
  54410. PBRMaterial.prototype.bind = function (world, mesh) {
  54411. this._myScene = this.getScene();
  54412. // Matrices
  54413. this.bindOnlyWorldMatrix(world);
  54414. // Bones
  54415. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  54416. if (this._myScene.getCachedMaterial() !== this) {
  54417. this._effect.setMatrix("viewProjection", this._myScene.getTransformMatrix());
  54418. if (BABYLON.StandardMaterial.FresnelEnabled) {
  54419. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  54420. this._effect.setColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  54421. }
  54422. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  54423. this._effect.setColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  54424. this._effect.setColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  54425. }
  54426. }
  54427. // Textures
  54428. if (this._myScene.texturesEnabled) {
  54429. if (this.albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  54430. this._effect.setTexture("albedoSampler", this.albedoTexture);
  54431. this._effect.setFloat2("vAlbedoInfos", this.albedoTexture.coordinatesIndex, this.albedoTexture.level);
  54432. this._effect.setMatrix("albedoMatrix", this.albedoTexture.getTextureMatrix());
  54433. }
  54434. if (this.ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  54435. this._effect.setTexture("ambientSampler", this.ambientTexture);
  54436. this._effect.setFloat3("vAmbientInfos", this.ambientTexture.coordinatesIndex, this.ambientTexture.level, this.ambientTextureStrength);
  54437. this._effect.setMatrix("ambientMatrix", this.ambientTexture.getTextureMatrix());
  54438. }
  54439. if (this.opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  54440. this._effect.setTexture("opacitySampler", this.opacityTexture);
  54441. this._effect.setFloat2("vOpacityInfos", this.opacityTexture.coordinatesIndex, this.opacityTexture.level);
  54442. this._effect.setMatrix("opacityMatrix", this.opacityTexture.getTextureMatrix());
  54443. }
  54444. if (this.reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  54445. this._microsurfaceTextureLods.x = Math.round(Math.log(this.reflectionTexture.getSize().width) * Math.LOG2E);
  54446. if (this.reflectionTexture.isCube) {
  54447. this._effect.setTexture("reflectionCubeSampler", this.reflectionTexture);
  54448. }
  54449. else {
  54450. this._effect.setTexture("reflection2DSampler", this.reflectionTexture);
  54451. }
  54452. this._effect.setMatrix("reflectionMatrix", this.reflectionTexture.getReflectionTextureMatrix());
  54453. this._effect.setFloat2("vReflectionInfos", this.reflectionTexture.level, 0);
  54454. if (this._defines.USESPHERICALFROMREFLECTIONMAP) {
  54455. this._effect.setFloat3("vSphericalX", this.reflectionTexture.sphericalPolynomial.x.x, this.reflectionTexture.sphericalPolynomial.x.y, this.reflectionTexture.sphericalPolynomial.x.z);
  54456. this._effect.setFloat3("vSphericalY", this.reflectionTexture.sphericalPolynomial.y.x, this.reflectionTexture.sphericalPolynomial.y.y, this.reflectionTexture.sphericalPolynomial.y.z);
  54457. this._effect.setFloat3("vSphericalZ", this.reflectionTexture.sphericalPolynomial.z.x, this.reflectionTexture.sphericalPolynomial.z.y, this.reflectionTexture.sphericalPolynomial.z.z);
  54458. this._effect.setFloat3("vSphericalXX", this.reflectionTexture.sphericalPolynomial.xx.x, this.reflectionTexture.sphericalPolynomial.xx.y, this.reflectionTexture.sphericalPolynomial.xx.z);
  54459. this._effect.setFloat3("vSphericalYY", this.reflectionTexture.sphericalPolynomial.yy.x, this.reflectionTexture.sphericalPolynomial.yy.y, this.reflectionTexture.sphericalPolynomial.yy.z);
  54460. this._effect.setFloat3("vSphericalZZ", this.reflectionTexture.sphericalPolynomial.zz.x, this.reflectionTexture.sphericalPolynomial.zz.y, this.reflectionTexture.sphericalPolynomial.zz.z);
  54461. this._effect.setFloat3("vSphericalXY", this.reflectionTexture.sphericalPolynomial.xy.x, this.reflectionTexture.sphericalPolynomial.xy.y, this.reflectionTexture.sphericalPolynomial.xy.z);
  54462. this._effect.setFloat3("vSphericalYZ", this.reflectionTexture.sphericalPolynomial.yz.x, this.reflectionTexture.sphericalPolynomial.yz.y, this.reflectionTexture.sphericalPolynomial.yz.z);
  54463. this._effect.setFloat3("vSphericalZX", this.reflectionTexture.sphericalPolynomial.zx.x, this.reflectionTexture.sphericalPolynomial.zx.y, this.reflectionTexture.sphericalPolynomial.zx.z);
  54464. }
  54465. }
  54466. if (this.emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  54467. this._effect.setTexture("emissiveSampler", this.emissiveTexture);
  54468. this._effect.setFloat2("vEmissiveInfos", this.emissiveTexture.coordinatesIndex, this.emissiveTexture.level);
  54469. this._effect.setMatrix("emissiveMatrix", this.emissiveTexture.getTextureMatrix());
  54470. }
  54471. if (this.lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  54472. this._effect.setTexture("lightmapSampler", this.lightmapTexture);
  54473. this._effect.setFloat2("vLightmapInfos", this.lightmapTexture.coordinatesIndex, this.lightmapTexture.level);
  54474. this._effect.setMatrix("lightmapMatrix", this.lightmapTexture.getTextureMatrix());
  54475. }
  54476. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  54477. if (this.metallicTexture) {
  54478. this._effect.setTexture("reflectivitySampler", this.metallicTexture);
  54479. this._effect.setFloat2("vReflectivityInfos", this.metallicTexture.coordinatesIndex, this.metallicTexture.level);
  54480. this._effect.setMatrix("reflectivityMatrix", this.metallicTexture.getTextureMatrix());
  54481. }
  54482. else if (this.reflectivityTexture) {
  54483. this._effect.setTexture("reflectivitySampler", this.reflectivityTexture);
  54484. this._effect.setFloat2("vReflectivityInfos", this.reflectivityTexture.coordinatesIndex, this.reflectivityTexture.level);
  54485. this._effect.setMatrix("reflectivityMatrix", this.reflectivityTexture.getTextureMatrix());
  54486. }
  54487. }
  54488. if (this.bumpTexture && this._myScene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this.disableBumpMap) {
  54489. this._effect.setTexture("bumpSampler", this.bumpTexture);
  54490. this._effect.setFloat3("vBumpInfos", this.bumpTexture.coordinatesIndex, 1.0 / this.bumpTexture.level, this.parallaxScaleBias);
  54491. this._effect.setMatrix("bumpMatrix", this.bumpTexture.getTextureMatrix());
  54492. }
  54493. if (this.refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  54494. this._microsurfaceTextureLods.y = Math.round(Math.log(this.refractionTexture.getSize().width) * Math.LOG2E);
  54495. var depth = 1.0;
  54496. if (this.refractionTexture.isCube) {
  54497. this._effect.setTexture("refractionCubeSampler", this.refractionTexture);
  54498. }
  54499. else {
  54500. this._effect.setTexture("refraction2DSampler", this.refractionTexture);
  54501. this._effect.setMatrix("refractionMatrix", this.refractionTexture.getReflectionTextureMatrix());
  54502. if (this.refractionTexture.depth) {
  54503. depth = this.refractionTexture.depth;
  54504. }
  54505. }
  54506. this._effect.setFloat4("vRefractionInfos", this.refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  54507. }
  54508. if ((this.reflectionTexture || this.refractionTexture)) {
  54509. this._effect.setFloat2("vMicrosurfaceTextureLods", this._microsurfaceTextureLods.x, this._microsurfaceTextureLods.y);
  54510. }
  54511. if (this.cameraColorGradingTexture && BABYLON.StandardMaterial.ColorGradingTextureEnabled) {
  54512. BABYLON.ColorGradingTexture.Bind(this.cameraColorGradingTexture, this._effect);
  54513. }
  54514. }
  54515. // Clip plane
  54516. BABYLON.MaterialHelper.BindClipPlane(this._effect, this._myScene);
  54517. // Point size
  54518. if (this.pointsCloud) {
  54519. this._effect.setFloat("pointSize", this.pointSize);
  54520. }
  54521. // Colors
  54522. this._myScene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  54523. if (this._defines.METALLICWORKFLOW) {
  54524. PBRMaterial._scaledReflectivity.r = this.metallic === undefined ? 1 : this.metallic;
  54525. PBRMaterial._scaledReflectivity.g = this.roughness === undefined ? 1 : this.roughness;
  54526. this._effect.setColor4("vReflectivityColor", PBRMaterial._scaledReflectivity, 0);
  54527. }
  54528. else {
  54529. // GAMMA CORRECTION.
  54530. this.convertColorToLinearSpaceToRef(this.reflectivityColor, PBRMaterial._scaledReflectivity);
  54531. this._effect.setColor4("vReflectivityColor", PBRMaterial._scaledReflectivity, this.microSurface);
  54532. }
  54533. this._effect.setVector3("vEyePosition", this._myScene._mirroredCameraPosition ? this._myScene._mirroredCameraPosition : this._myScene.activeCamera.position);
  54534. this._effect.setColor3("vAmbientColor", this._globalAmbientColor);
  54535. // GAMMA CORRECTION.
  54536. this.convertColorToLinearSpaceToRef(this.emissiveColor, PBRMaterial._scaledEmissive);
  54537. this._effect.setColor3("vEmissiveColor", PBRMaterial._scaledEmissive);
  54538. // GAMMA CORRECTION.
  54539. this.convertColorToLinearSpaceToRef(this.reflectionColor, PBRMaterial._scaledReflection);
  54540. this._effect.setColor3("vReflectionColor", PBRMaterial._scaledReflection);
  54541. }
  54542. if (this._myScene.getCachedMaterial() !== this || !this.isFrozen) {
  54543. // GAMMA CORRECTION.
  54544. this.convertColorToLinearSpaceToRef(this.albedoColor, PBRMaterial._scaledAlbedo);
  54545. this._effect.setColor4("vAlbedoColor", PBRMaterial._scaledAlbedo, this.alpha * mesh.visibility);
  54546. // Lights
  54547. if (this._myScene.lightsEnabled && !this.disableLighting) {
  54548. PBRMaterial.BindLights(this._myScene, mesh, this._effect, this._defines, this.useScalarInLinearSpace, this.maxSimultaneousLights, this.usePhysicalLightFalloff);
  54549. }
  54550. // View
  54551. if (this._myScene.fogEnabled && mesh.applyFog && this._myScene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this.reflectionTexture) {
  54552. this._effect.setMatrix("view", this._myScene.getViewMatrix());
  54553. }
  54554. // Fog
  54555. BABYLON.MaterialHelper.BindFogParameters(this._myScene, mesh, this._effect);
  54556. this._lightingInfos.x = this.directIntensity;
  54557. this._lightingInfos.y = this.emissiveIntensity;
  54558. this._lightingInfos.z = this.environmentIntensity;
  54559. this._lightingInfos.w = this.specularIntensity;
  54560. this._effect.setVector4("vLightingIntensity", this._lightingInfos);
  54561. this._overloadedShadowInfos.x = this.overloadedShadowIntensity;
  54562. this._overloadedShadowInfos.y = this.overloadedShadeIntensity;
  54563. this._effect.setVector4("vOverloadedShadowIntensity", this._overloadedShadowInfos);
  54564. this._cameraInfos.x = this.cameraExposure;
  54565. this._cameraInfos.y = this.cameraContrast;
  54566. this._effect.setVector4("vCameraInfos", this._cameraInfos);
  54567. if (this.cameraColorCurves) {
  54568. BABYLON.ColorCurves.Bind(this.cameraColorCurves, this._effect);
  54569. }
  54570. this._overloadedIntensity.x = this.overloadedAmbientIntensity;
  54571. this._overloadedIntensity.y = this.overloadedAlbedoIntensity;
  54572. this._overloadedIntensity.z = this.overloadedReflectivityIntensity;
  54573. this._overloadedIntensity.w = this.overloadedEmissiveIntensity;
  54574. this._effect.setVector4("vOverloadedIntensity", this._overloadedIntensity);
  54575. this._effect.setColor3("vOverloadedAmbient", this.overloadedAmbient);
  54576. this.convertColorToLinearSpaceToRef(this.overloadedAlbedo, this._tempColor);
  54577. this._effect.setColor3("vOverloadedAlbedo", this._tempColor);
  54578. this.convertColorToLinearSpaceToRef(this.overloadedReflectivity, this._tempColor);
  54579. this._effect.setColor3("vOverloadedReflectivity", this._tempColor);
  54580. this.convertColorToLinearSpaceToRef(this.overloadedEmissive, this._tempColor);
  54581. this._effect.setColor3("vOverloadedEmissive", this._tempColor);
  54582. this.convertColorToLinearSpaceToRef(this.overloadedReflection, this._tempColor);
  54583. this._effect.setColor3("vOverloadedReflection", this._tempColor);
  54584. this._overloadedMicroSurface.x = this.overloadedMicroSurface;
  54585. this._overloadedMicroSurface.y = this.overloadedMicroSurfaceIntensity;
  54586. this._overloadedMicroSurface.z = this.overloadedReflectionIntensity;
  54587. this._effect.setVector3("vOverloadedMicroSurface", this._overloadedMicroSurface);
  54588. // Log. depth
  54589. BABYLON.MaterialHelper.BindLogDepth(this._defines, this._effect, this._myScene);
  54590. }
  54591. _super.prototype.bind.call(this, world, mesh);
  54592. this._myScene = null;
  54593. };
  54594. PBRMaterial.prototype.getAnimatables = function () {
  54595. var results = [];
  54596. if (this.albedoTexture && this.albedoTexture.animations && this.albedoTexture.animations.length > 0) {
  54597. results.push(this.albedoTexture);
  54598. }
  54599. if (this.ambientTexture && this.ambientTexture.animations && this.ambientTexture.animations.length > 0) {
  54600. results.push(this.ambientTexture);
  54601. }
  54602. if (this.opacityTexture && this.opacityTexture.animations && this.opacityTexture.animations.length > 0) {
  54603. results.push(this.opacityTexture);
  54604. }
  54605. if (this.reflectionTexture && this.reflectionTexture.animations && this.reflectionTexture.animations.length > 0) {
  54606. results.push(this.reflectionTexture);
  54607. }
  54608. if (this.emissiveTexture && this.emissiveTexture.animations && this.emissiveTexture.animations.length > 0) {
  54609. results.push(this.emissiveTexture);
  54610. }
  54611. if (this.metallicTexture && this.metallicTexture.animations && this.metallicTexture.animations.length > 0) {
  54612. results.push(this.metallicTexture);
  54613. }
  54614. else if (this.reflectivityTexture && this.reflectivityTexture.animations && this.reflectivityTexture.animations.length > 0) {
  54615. results.push(this.reflectivityTexture);
  54616. }
  54617. if (this.bumpTexture && this.bumpTexture.animations && this.bumpTexture.animations.length > 0) {
  54618. results.push(this.bumpTexture);
  54619. }
  54620. if (this.lightmapTexture && this.lightmapTexture.animations && this.lightmapTexture.animations.length > 0) {
  54621. results.push(this.lightmapTexture);
  54622. }
  54623. if (this.refractionTexture && this.refractionTexture.animations && this.refractionTexture.animations.length > 0) {
  54624. results.push(this.refractionTexture);
  54625. }
  54626. if (this.cameraColorGradingTexture && this.cameraColorGradingTexture.animations && this.cameraColorGradingTexture.animations.length > 0) {
  54627. results.push(this.cameraColorGradingTexture);
  54628. }
  54629. return results;
  54630. };
  54631. PBRMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  54632. if (forceDisposeTextures) {
  54633. if (this.albedoTexture) {
  54634. this.albedoTexture.dispose();
  54635. }
  54636. if (this.ambientTexture) {
  54637. this.ambientTexture.dispose();
  54638. }
  54639. if (this.opacityTexture) {
  54640. this.opacityTexture.dispose();
  54641. }
  54642. if (this.reflectionTexture) {
  54643. this.reflectionTexture.dispose();
  54644. }
  54645. if (this.emissiveTexture) {
  54646. this.emissiveTexture.dispose();
  54647. }
  54648. if (this.metallicTexture) {
  54649. this.metallicTexture.dispose();
  54650. }
  54651. if (this.reflectivityTexture) {
  54652. this.reflectivityTexture.dispose();
  54653. }
  54654. if (this.bumpTexture) {
  54655. this.bumpTexture.dispose();
  54656. }
  54657. if (this.lightmapTexture) {
  54658. this.lightmapTexture.dispose();
  54659. }
  54660. if (this.refractionTexture) {
  54661. this.refractionTexture.dispose();
  54662. }
  54663. if (this.cameraColorGradingTexture) {
  54664. this.cameraColorGradingTexture.dispose();
  54665. }
  54666. }
  54667. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  54668. };
  54669. PBRMaterial.prototype.clone = function (name) {
  54670. var _this = this;
  54671. return BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  54672. };
  54673. PBRMaterial.prototype.serialize = function () {
  54674. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  54675. serializationObject.customType = "BABYLON.PBRMaterial";
  54676. return serializationObject;
  54677. };
  54678. // Statics
  54679. PBRMaterial.Parse = function (source, scene, rootUrl) {
  54680. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  54681. };
  54682. return PBRMaterial;
  54683. }(BABYLON.Material));
  54684. PBRMaterial._scaledAlbedo = new BABYLON.Color3();
  54685. PBRMaterial._scaledReflectivity = new BABYLON.Color3();
  54686. PBRMaterial._scaledEmissive = new BABYLON.Color3();
  54687. PBRMaterial._scaledReflection = new BABYLON.Color3();
  54688. __decorate([
  54689. BABYLON.serialize()
  54690. ], PBRMaterial.prototype, "directIntensity", void 0);
  54691. __decorate([
  54692. BABYLON.serialize()
  54693. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  54694. __decorate([
  54695. BABYLON.serialize()
  54696. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  54697. __decorate([
  54698. BABYLON.serialize()
  54699. ], PBRMaterial.prototype, "specularIntensity", void 0);
  54700. __decorate([
  54701. BABYLON.serialize()
  54702. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  54703. __decorate([
  54704. BABYLON.serialize()
  54705. ], PBRMaterial.prototype, "overloadedShadowIntensity", void 0);
  54706. __decorate([
  54707. BABYLON.serialize()
  54708. ], PBRMaterial.prototype, "overloadedShadeIntensity", void 0);
  54709. __decorate([
  54710. BABYLON.serialize()
  54711. ], PBRMaterial.prototype, "cameraExposure", void 0);
  54712. __decorate([
  54713. BABYLON.serialize()
  54714. ], PBRMaterial.prototype, "cameraContrast", void 0);
  54715. __decorate([
  54716. BABYLON.serializeAsTexture()
  54717. ], PBRMaterial.prototype, "cameraColorGradingTexture", void 0);
  54718. __decorate([
  54719. BABYLON.serializeAsColorCurves()
  54720. ], PBRMaterial.prototype, "cameraColorCurves", void 0);
  54721. __decorate([
  54722. BABYLON.serializeAsColor3()
  54723. ], PBRMaterial.prototype, "overloadedAmbient", void 0);
  54724. __decorate([
  54725. BABYLON.serialize()
  54726. ], PBRMaterial.prototype, "overloadedAmbientIntensity", void 0);
  54727. __decorate([
  54728. BABYLON.serializeAsColor3()
  54729. ], PBRMaterial.prototype, "overloadedAlbedo", void 0);
  54730. __decorate([
  54731. BABYLON.serialize()
  54732. ], PBRMaterial.prototype, "overloadedAlbedoIntensity", void 0);
  54733. __decorate([
  54734. BABYLON.serializeAsColor3()
  54735. ], PBRMaterial.prototype, "overloadedReflectivity", void 0);
  54736. __decorate([
  54737. BABYLON.serialize()
  54738. ], PBRMaterial.prototype, "overloadedReflectivityIntensity", void 0);
  54739. __decorate([
  54740. BABYLON.serializeAsColor3()
  54741. ], PBRMaterial.prototype, "overloadedEmissive", void 0);
  54742. __decorate([
  54743. BABYLON.serialize()
  54744. ], PBRMaterial.prototype, "overloadedEmissiveIntensity", void 0);
  54745. __decorate([
  54746. BABYLON.serializeAsColor3()
  54747. ], PBRMaterial.prototype, "overloadedReflection", void 0);
  54748. __decorate([
  54749. BABYLON.serialize()
  54750. ], PBRMaterial.prototype, "overloadedReflectionIntensity", void 0);
  54751. __decorate([
  54752. BABYLON.serialize()
  54753. ], PBRMaterial.prototype, "overloadedMicroSurface", void 0);
  54754. __decorate([
  54755. BABYLON.serialize()
  54756. ], PBRMaterial.prototype, "overloadedMicroSurfaceIntensity", void 0);
  54757. __decorate([
  54758. BABYLON.serializeAsTexture()
  54759. ], PBRMaterial.prototype, "albedoTexture", void 0);
  54760. __decorate([
  54761. BABYLON.serializeAsTexture()
  54762. ], PBRMaterial.prototype, "ambientTexture", void 0);
  54763. __decorate([
  54764. BABYLON.serialize()
  54765. ], PBRMaterial.prototype, "ambientTextureStrength", void 0);
  54766. __decorate([
  54767. BABYLON.serializeAsTexture()
  54768. ], PBRMaterial.prototype, "opacityTexture", void 0);
  54769. __decorate([
  54770. BABYLON.serializeAsTexture()
  54771. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  54772. __decorate([
  54773. BABYLON.serializeAsTexture()
  54774. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  54775. __decorate([
  54776. BABYLON.serializeAsTexture()
  54777. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  54778. __decorate([
  54779. BABYLON.serializeAsTexture()
  54780. ], PBRMaterial.prototype, "metallicTexture", void 0);
  54781. __decorate([
  54782. BABYLON.serialize()
  54783. ], PBRMaterial.prototype, "metallic", void 0);
  54784. __decorate([
  54785. BABYLON.serialize()
  54786. ], PBRMaterial.prototype, "roughness", void 0);
  54787. __decorate([
  54788. BABYLON.serializeAsTexture()
  54789. ], PBRMaterial.prototype, "bumpTexture", void 0);
  54790. __decorate([
  54791. BABYLON.serializeAsTexture()
  54792. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  54793. __decorate([
  54794. BABYLON.serializeAsTexture()
  54795. ], PBRMaterial.prototype, "refractionTexture", void 0);
  54796. __decorate([
  54797. BABYLON.serializeAsColor3("ambient")
  54798. ], PBRMaterial.prototype, "ambientColor", void 0);
  54799. __decorate([
  54800. BABYLON.serializeAsColor3("albedo")
  54801. ], PBRMaterial.prototype, "albedoColor", void 0);
  54802. __decorate([
  54803. BABYLON.serializeAsColor3("reflectivity")
  54804. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  54805. __decorate([
  54806. BABYLON.serializeAsColor3("reflection")
  54807. ], PBRMaterial.prototype, "reflectionColor", void 0);
  54808. __decorate([
  54809. BABYLON.serializeAsColor3("emissive")
  54810. ], PBRMaterial.prototype, "emissiveColor", void 0);
  54811. __decorate([
  54812. BABYLON.serialize()
  54813. ], PBRMaterial.prototype, "microSurface", void 0);
  54814. __decorate([
  54815. BABYLON.serialize()
  54816. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  54817. __decorate([
  54818. BABYLON.serialize()
  54819. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  54820. __decorate([
  54821. BABYLON.serializeAsFresnelParameters()
  54822. ], PBRMaterial.prototype, "opacityFresnelParameters", void 0);
  54823. __decorate([
  54824. BABYLON.serializeAsFresnelParameters()
  54825. ], PBRMaterial.prototype, "emissiveFresnelParameters", void 0);
  54826. __decorate([
  54827. BABYLON.serialize()
  54828. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  54829. __decorate([
  54830. BABYLON.serialize()
  54831. ], PBRMaterial.prototype, "linkEmissiveWithAlbedo", void 0);
  54832. __decorate([
  54833. BABYLON.serialize()
  54834. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  54835. __decorate([
  54836. BABYLON.serialize()
  54837. ], PBRMaterial.prototype, "useEmissiveAsIllumination", void 0);
  54838. __decorate([
  54839. BABYLON.serialize()
  54840. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  54841. __decorate([
  54842. BABYLON.serialize()
  54843. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  54844. __decorate([
  54845. BABYLON.serialize()
  54846. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  54847. __decorate([
  54848. BABYLON.serialize()
  54849. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureAlpha", void 0);
  54850. __decorate([
  54851. BABYLON.serialize()
  54852. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureGreen", void 0);
  54853. __decorate([
  54854. BABYLON.serialize()
  54855. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  54856. __decorate([
  54857. BABYLON.serialize()
  54858. ], PBRMaterial.prototype, "useScalarInLinearSpace", void 0);
  54859. __decorate([
  54860. BABYLON.serialize()
  54861. ], PBRMaterial.prototype, "usePhysicalLightFalloff", void 0);
  54862. __decorate([
  54863. BABYLON.serialize()
  54864. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  54865. __decorate([
  54866. BABYLON.serialize()
  54867. ], PBRMaterial.prototype, "useParallax", void 0);
  54868. __decorate([
  54869. BABYLON.serialize()
  54870. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  54871. __decorate([
  54872. BABYLON.serialize()
  54873. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  54874. __decorate([
  54875. BABYLON.serialize()
  54876. ], PBRMaterial.prototype, "disableLighting", void 0);
  54877. __decorate([
  54878. BABYLON.serialize()
  54879. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  54880. __decorate([
  54881. BABYLON.serialize()
  54882. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  54883. __decorate([
  54884. BABYLON.serialize()
  54885. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  54886. __decorate([
  54887. BABYLON.serialize()
  54888. ], PBRMaterial.prototype, "useLogarithmicDepth", null);
  54889. BABYLON.PBRMaterial = PBRMaterial;
  54890. })(BABYLON || (BABYLON = {}));
  54891. //# sourceMappingURL=babylon.pbrMaterial.js.map
  54892. var BABYLON;
  54893. (function (BABYLON) {
  54894. var DebugLayer = (function () {
  54895. function DebugLayer(scene) {
  54896. this._scene = scene;
  54897. }
  54898. /** Creates the inspector window. */
  54899. DebugLayer.prototype._createInspector = function (popup) {
  54900. if (!this._inspector) {
  54901. this._inspector = new INSPECTOR.Inspector(this._scene, popup);
  54902. } // else nothing to do,; instance is already existing
  54903. };
  54904. DebugLayer.prototype.isVisible = function () {
  54905. return false;
  54906. };
  54907. DebugLayer.prototype.hide = function () {
  54908. if (this._inspector) {
  54909. this._inspector.dispose();
  54910. this._inspector = null;
  54911. }
  54912. };
  54913. DebugLayer.prototype.show = function (popup) {
  54914. if (typeof INSPECTOR == 'undefined') {
  54915. // Load inspector and add it to the DOM
  54916. BABYLON.Tools.LoadScript(DebugLayer.InspectorURL, this._createInspector.bind(this, popup));
  54917. }
  54918. else {
  54919. // Otherwise creates the inspector
  54920. this._createInspector(popup);
  54921. }
  54922. };
  54923. return DebugLayer;
  54924. }());
  54925. DebugLayer.InspectorURL = 'http://www.babylonjs.com/babylon.inspector.bundle.js';
  54926. BABYLON.DebugLayer = DebugLayer;
  54927. })(BABYLON || (BABYLON = {}));
  54928. //# sourceMappingURL=babylon.debugLayer.js.map
  54929. var BABYLON;
  54930. (function (BABYLON) {
  54931. var StandardRenderingPipeline = (function (_super) {
  54932. __extends(StandardRenderingPipeline, _super);
  54933. /**
  54934. * @constructor
  54935. * @param {string} name - The rendering pipeline name
  54936. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  54937. * @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)
  54938. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  54939. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  54940. */
  54941. function StandardRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  54942. if (originalPostProcess === void 0) { originalPostProcess = null; }
  54943. var _this = _super.call(this, scene.getEngine(), name) || this;
  54944. _this.downSampleX4PostProcess = null;
  54945. _this.brightPassPostProcess = null;
  54946. _this.gaussianBlurHPostProcesses = [];
  54947. _this.gaussianBlurVPostProcesses = [];
  54948. _this.textureAdderPostProcess = null;
  54949. _this.textureAdderFinalPostProcess = null;
  54950. _this.lensFlarePostProcess = null;
  54951. _this.lensFlareComposePostProcess = null;
  54952. _this.depthOfFieldPostProcess = null;
  54953. // Values
  54954. _this.brightThreshold = 1.0;
  54955. _this.blurWidth = 2.0;
  54956. _this.gaussianCoefficient = 0.25;
  54957. _this.gaussianMean = 1.0;
  54958. _this.gaussianStandardDeviation = 1.0;
  54959. _this.exposure = 1.0;
  54960. _this.lensTexture = null;
  54961. _this.lensColorTexture = null;
  54962. _this.lensFlareStrength = 20.0;
  54963. _this.lensFlareGhostDispersal = 1.4;
  54964. _this.lensFlareHaloWidth = 0.7;
  54965. _this.lensFlareDistortionStrength = 16.0;
  54966. _this.lensStarTexture = null;
  54967. _this.lensFlareDirtTexture = null;
  54968. _this.depthOfFieldDistance = 10.0;
  54969. // IAnimatable
  54970. _this.animations = [];
  54971. _this._depthRenderer = null;
  54972. // Getters and setters
  54973. _this._depthOfFieldEnabled = true;
  54974. _this._lensFlareEnabled = true;
  54975. // Initialize
  54976. _this._scene = scene;
  54977. // Create pass post-processe
  54978. if (!originalPostProcess) {
  54979. _this.originalPostProcess = new BABYLON.PostProcess("HDRPass", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), true, "#define PASS_POST_PROCESS", BABYLON.Engine.TEXTURETYPE_FLOAT);
  54980. }
  54981. else {
  54982. _this.originalPostProcess = originalPostProcess;
  54983. }
  54984. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this.originalPostProcess; }, true));
  54985. // Create down sample X4 post-process
  54986. _this._createDownSampleX4PostProcess(scene, ratio / 2);
  54987. // Create bright pass post-process
  54988. _this._createBrightPassPostProcess(scene, ratio / 2);
  54989. // Create gaussian blur post-processes (down sampling blurs)
  54990. _this._createGaussianBlurPostProcesses(scene, ratio / 2, 0);
  54991. _this._createGaussianBlurPostProcesses(scene, ratio / 4, 1);
  54992. _this._createGaussianBlurPostProcesses(scene, ratio / 8, 2);
  54993. _this._createGaussianBlurPostProcesses(scene, ratio / 16, 3);
  54994. // Create texture adder post-process
  54995. _this._createTextureAdderPostProcess(scene, ratio);
  54996. // Create depth-of-field source post-process
  54997. _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);
  54998. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfFieldSource", function () { return _this.textureAdderFinalPostProcess; }, true));
  54999. // Create lens flare post-process
  55000. _this._createLensFlarePostProcess(scene, ratio);
  55001. // Create gaussian blur used by depth-of-field
  55002. _this._createGaussianBlurPostProcesses(scene, ratio / 2, 5);
  55003. // Create depth-of-field post-process
  55004. _this._createDepthOfFieldPostProcess(scene, ratio);
  55005. // Finish
  55006. scene.postProcessRenderPipelineManager.addPipeline(_this);
  55007. if (cameras !== null) {
  55008. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  55009. }
  55010. // Deactivate
  55011. _this.LensFlareEnabled = false;
  55012. _this.DepthOfFieldEnabled = false;
  55013. return _this;
  55014. }
  55015. Object.defineProperty(StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", {
  55016. get: function () {
  55017. return this._depthOfFieldEnabled;
  55018. },
  55019. set: function (enabled) {
  55020. var blurIndex = this.gaussianBlurHPostProcesses.length - 1;
  55021. if (enabled && !this._depthOfFieldEnabled) {
  55022. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRGaussianBlurH" + blurIndex, this._scene.cameras);
  55023. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRGaussianBlurV" + blurIndex, this._scene.cameras);
  55024. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRDepthOfField", this._scene.cameras);
  55025. this._depthRenderer = this._scene.enableDepthRenderer();
  55026. }
  55027. else if (!enabled && this._depthOfFieldEnabled) {
  55028. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRGaussianBlurH" + blurIndex, this._scene.cameras);
  55029. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRGaussianBlurV" + blurIndex, this._scene.cameras);
  55030. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRDepthOfField", this._scene.cameras);
  55031. }
  55032. this._depthOfFieldEnabled = enabled;
  55033. },
  55034. enumerable: true,
  55035. configurable: true
  55036. });
  55037. Object.defineProperty(StandardRenderingPipeline.prototype, "LensFlareEnabled", {
  55038. get: function () {
  55039. return this._lensFlareEnabled;
  55040. },
  55041. set: function (enabled) {
  55042. var blurIndex = this.gaussianBlurHPostProcesses.length - 2;
  55043. if (enabled && !this._lensFlareEnabled) {
  55044. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRLensFlare", this._scene.cameras);
  55045. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRLensFlareShift", this._scene.cameras);
  55046. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRGaussianBlurH" + blurIndex, this._scene.cameras);
  55047. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRGaussianBlurV" + blurIndex, this._scene.cameras);
  55048. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRLensFlareCompose", this._scene.cameras);
  55049. }
  55050. else if (!enabled && this._lensFlareEnabled) {
  55051. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRLensFlare", this._scene.cameras);
  55052. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRLensFlareShift", this._scene.cameras);
  55053. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRGaussianBlurH" + blurIndex, this._scene.cameras);
  55054. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRGaussianBlurV" + blurIndex, this._scene.cameras);
  55055. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRLensFlareCompose", this._scene.cameras);
  55056. }
  55057. this._lensFlareEnabled = enabled;
  55058. },
  55059. enumerable: true,
  55060. configurable: true
  55061. });
  55062. // Down Sample X4 Post-Processs
  55063. StandardRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  55064. var _this = this;
  55065. var downSampleX4Offsets = new Array(32);
  55066. 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);
  55067. this.downSampleX4PostProcess.onApply = function (effect) {
  55068. var id = 0;
  55069. for (var i = -2; i < 2; i++) {
  55070. for (var j = -2; j < 2; j++) {
  55071. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / _this.downSampleX4PostProcess.width);
  55072. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / _this.downSampleX4PostProcess.height);
  55073. id += 2;
  55074. }
  55075. }
  55076. effect.setArray2("dsOffsets", downSampleX4Offsets);
  55077. };
  55078. // Add to pipeline
  55079. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this.downSampleX4PostProcess; }, true));
  55080. };
  55081. // Brightpass Post-Process
  55082. StandardRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  55083. var _this = this;
  55084. var brightOffsets = new Array(8);
  55085. 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);
  55086. this.brightPassPostProcess.onApply = function (effect) {
  55087. var sU = (1.0 / _this.brightPassPostProcess.width);
  55088. var sV = (1.0 / _this.brightPassPostProcess.height);
  55089. brightOffsets[0] = -0.5 * sU;
  55090. brightOffsets[1] = 0.5 * sV;
  55091. brightOffsets[2] = 0.5 * sU;
  55092. brightOffsets[3] = 0.5 * sV;
  55093. brightOffsets[4] = -0.5 * sU;
  55094. brightOffsets[5] = -0.5 * sV;
  55095. brightOffsets[6] = 0.5 * sU;
  55096. brightOffsets[7] = -0.5 * sV;
  55097. effect.setArray2("dsOffsets", brightOffsets);
  55098. effect.setFloat("brightThreshold", _this.brightThreshold);
  55099. };
  55100. // Add to pipeline
  55101. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this.brightPassPostProcess; }, true));
  55102. };
  55103. // Create gaussian blur H&V post-processes
  55104. StandardRenderingPipeline.prototype._createGaussianBlurPostProcesses = function (scene, ratio, indice) {
  55105. var _this = this;
  55106. var blurOffsets = new Array(9);
  55107. var blurWeights = new Array(9);
  55108. var uniforms = ["blurOffsets", "blurWeights", "blurWidth"];
  55109. var callback = function (height) {
  55110. return function (effect) {
  55111. // Weights
  55112. var x = 0.0;
  55113. for (var i = 0; i < 9; i++) {
  55114. x = (i - 4.0) / 4.0;
  55115. blurWeights[i] =
  55116. _this.gaussianCoefficient
  55117. * (1.0 / Math.sqrt(2.0 * Math.PI * _this.gaussianStandardDeviation))
  55118. * Math.exp((-((x - _this.gaussianMean) * (x - _this.gaussianMean))) / (2.0 * _this.gaussianStandardDeviation * _this.gaussianStandardDeviation));
  55119. }
  55120. var lastOutputDimensions = {
  55121. width: scene.getEngine().getRenderWidth(),
  55122. height: scene.getEngine().getRenderHeight()
  55123. };
  55124. for (var i = 0; i < 9; i++) {
  55125. var value = (i - 4.0) * (1.0 / (height === true ? lastOutputDimensions.height : lastOutputDimensions.width));
  55126. blurOffsets[i] = value;
  55127. }
  55128. effect.setArray("blurOffsets", blurOffsets);
  55129. effect.setArray("blurWeights", blurWeights);
  55130. effect.setFloat("blurWidth", _this.blurWidth);
  55131. };
  55132. };
  55133. // Create horizontal gaussian blur post-processes
  55134. 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);
  55135. gaussianBlurHPostProcess.onApply = callback(false);
  55136. // Create vertical gaussian blur post-process
  55137. 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);
  55138. gaussianBlurVPostProcess.onApply = callback(true);
  55139. // Add to pipeline
  55140. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurH" + indice, function () { return gaussianBlurHPostProcess; }, true));
  55141. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurV" + indice, function () { return gaussianBlurVPostProcess; }, true));
  55142. // Finish
  55143. this.gaussianBlurHPostProcesses.push(gaussianBlurHPostProcess);
  55144. this.gaussianBlurVPostProcesses.push(gaussianBlurVPostProcess);
  55145. };
  55146. // Create texture adder post-process
  55147. StandardRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  55148. var _this = this;
  55149. var lastGaussianBlurPostProcess = this.gaussianBlurVPostProcesses[3];
  55150. 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);
  55151. this.textureAdderPostProcess.onApply = function (effect) {
  55152. effect.setTextureFromPostProcess("otherSampler", _this.originalPostProcess);
  55153. effect.setTexture("lensSampler", _this.lensTexture);
  55154. effect.setFloat("exposure", _this.exposure);
  55155. };
  55156. // Add to pipeline
  55157. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this.textureAdderPostProcess; }, true));
  55158. };
  55159. // Create lens flare post-process
  55160. StandardRenderingPipeline.prototype._createLensFlarePostProcess = function (scene, ratio) {
  55161. var _this = this;
  55162. 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);
  55163. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlare", function () { return _this.lensFlarePostProcess; }, false));
  55164. this._createGaussianBlurPostProcesses(scene, ratio / 4, 4);
  55165. 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);
  55166. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlareCompose", function () { return _this.lensFlareComposePostProcess; }, false));
  55167. var resolution = new BABYLON.Vector2(0, 0);
  55168. // Lens flare
  55169. this.lensFlarePostProcess.onApply = function (effect) {
  55170. effect.setTextureFromPostProcess("textureSampler", _this.gaussianBlurHPostProcesses[0]);
  55171. effect.setTexture("lensColorSampler", _this.lensColorTexture);
  55172. effect.setFloat("strength", _this.lensFlareStrength);
  55173. effect.setFloat("ghostDispersal", _this.lensFlareGhostDispersal);
  55174. effect.setFloat("haloWidth", _this.lensFlareHaloWidth);
  55175. // Shift
  55176. resolution.x = _this.lensFlarePostProcess.width;
  55177. resolution.y = _this.lensFlarePostProcess.height;
  55178. effect.setVector2("resolution", resolution);
  55179. effect.setFloat("distortionStrength", _this.lensFlareDistortionStrength);
  55180. };
  55181. // Compose
  55182. 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);
  55183. 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);
  55184. this.lensFlareComposePostProcess.onApply = function (effect) {
  55185. effect.setTextureFromPostProcess("otherSampler", _this.textureAdderFinalPostProcess);
  55186. effect.setTexture("lensDirtSampler", _this.lensFlareDirtTexture);
  55187. effect.setTexture("lensStarSampler", _this.lensStarTexture);
  55188. // Lens start rotation matrix
  55189. var camerax = _this._scene.activeCamera.getViewMatrix().getRow(0);
  55190. var cameraz = _this._scene.activeCamera.getViewMatrix().getRow(2);
  55191. 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));
  55192. camRot *= 4.0;
  55193. 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);
  55194. var lensStarMatrix = scaleBias2.multiply(starRotation).multiply(scaleBias1);
  55195. effect.setMatrix("lensStarMatrix", lensStarMatrix);
  55196. };
  55197. };
  55198. // Create depth-of-field post-process
  55199. StandardRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (scene, ratio) {
  55200. var _this = this;
  55201. 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);
  55202. this.depthOfFieldPostProcess.onApply = function (effect) {
  55203. effect.setTextureFromPostProcess("otherSampler", _this.textureAdderFinalPostProcess);
  55204. effect.setTexture("depthSampler", _this._depthRenderer.getDepthMap());
  55205. effect.setFloat("distance", _this.depthOfFieldDistance);
  55206. };
  55207. // Add to pipeline
  55208. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfField", function () { return _this.depthOfFieldPostProcess; }, true));
  55209. };
  55210. // Dispose
  55211. StandardRenderingPipeline.prototype.dispose = function () {
  55212. for (var i = 0; i < this._scene.cameras.length; i++) {
  55213. var camera = this._scene.cameras[i];
  55214. this.originalPostProcess.dispose(camera);
  55215. this.downSampleX4PostProcess.dispose(camera);
  55216. this.brightPassPostProcess.dispose(camera);
  55217. this.textureAdderPostProcess.dispose(camera);
  55218. for (var j = 0; j < this.gaussianBlurHPostProcesses.length; j++) {
  55219. this.gaussianBlurHPostProcesses[j].dispose(camera);
  55220. }
  55221. for (var j = 0; j < this.gaussianBlurVPostProcesses.length; j++) {
  55222. this.gaussianBlurVPostProcesses[j].dispose(camera);
  55223. }
  55224. this.textureAdderFinalPostProcess.dispose(camera);
  55225. this.lensFlarePostProcess.dispose(camera);
  55226. this.lensFlareComposePostProcess.dispose(camera);
  55227. this.depthOfFieldPostProcess.dispose(camera);
  55228. }
  55229. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  55230. _super.prototype.dispose.call(this);
  55231. };
  55232. return StandardRenderingPipeline;
  55233. }(BABYLON.PostProcessRenderPipeline));
  55234. BABYLON.StandardRenderingPipeline = StandardRenderingPipeline;
  55235. })(BABYLON || (BABYLON = {}));
  55236. //# sourceMappingURL=babylon.standardRenderingPipeline.js.map
  55237. 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}"};
  55238. 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"};
  55239. 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 Int32Array(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,1,0,h+e/2,s/2+a,0,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={}));";
  55240. if (((typeof window != "undefined" && window.module) || (typeof module != "undefined")) && typeof module.exports != "undefined") {
  55241. module.exports = BABYLON;
  55242. };