babylon.max.js 3.0 MB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739287402874128742287432874428745287462874728748287492875028751287522875328754287552875628757287582875928760287612876228763287642876528766287672876828769287702877128772287732877428775287762877728778287792878028781287822878328784287852878628787287882878928790287912879228793287942879528796287972879828799288002880128802288032880428805288062880728808288092881028811288122881328814288152881628817288182881928820288212882228823288242882528826288272882828829288302883128832288332883428835288362883728838288392884028841288422884328844288452884628847288482884928850288512885228853288542885528856288572885828859288602886128862288632886428865288662886728868288692887028871288722887328874288752887628877288782887928880288812888228883288842888528886288872888828889288902889128892288932889428895288962889728898288992890028901289022890328904289052890628907289082890928910289112891228913289142891528916289172891828919289202892128922289232892428925289262892728928289292893028931289322893328934289352893628937289382893928940289412894228943289442894528946289472894828949289502895128952289532895428955289562895728958289592896028961289622896328964289652896628967289682896928970289712897228973289742897528976289772897828979289802898128982289832898428985289862898728988289892899028991289922899328994289952899628997289982899929000290012900229003290042900529006290072900829009290102901129012290132901429015290162901729018290192902029021290222902329024290252902629027290282902929030290312903229033290342903529036290372903829039290402904129042290432904429045290462904729048290492905029051290522905329054290552905629057290582905929060290612906229063290642906529066290672906829069290702907129072290732907429075290762907729078290792908029081290822908329084290852908629087290882908929090290912909229093290942909529096290972909829099291002910129102291032910429105291062910729108291092911029111291122911329114291152911629117291182911929120291212912229123291242912529126291272912829129291302913129132291332913429135291362913729138291392914029141291422914329144291452914629147291482914929150291512915229153291542915529156291572915829159291602916129162291632916429165291662916729168291692917029171291722917329174291752917629177291782917929180291812918229183291842918529186291872918829189291902919129192291932919429195291962919729198291992920029201292022920329204292052920629207292082920929210292112921229213292142921529216292172921829219292202922129222292232922429225292262922729228292292923029231292322923329234292352923629237292382923929240292412924229243292442924529246292472924829249292502925129252292532925429255292562925729258292592926029261292622926329264292652926629267292682926929270292712927229273292742927529276292772927829279292802928129282292832928429285292862928729288292892929029291292922929329294292952929629297292982929929300293012930229303293042930529306293072930829309293102931129312293132931429315293162931729318293192932029321293222932329324293252932629327293282932929330293312933229333293342933529336293372933829339293402934129342293432934429345293462934729348293492935029351293522935329354293552935629357293582935929360293612936229363293642936529366293672936829369293702937129372293732937429375293762937729378293792938029381293822938329384293852938629387293882938929390293912939229393293942939529396293972939829399294002940129402294032940429405294062940729408294092941029411294122941329414294152941629417294182941929420294212942229423294242942529426294272942829429294302943129432294332943429435294362943729438294392944029441294422944329444294452944629447294482944929450294512945229453294542945529456294572945829459294602946129462294632946429465294662946729468294692947029471294722947329474294752947629477294782947929480294812948229483294842948529486294872948829489294902949129492294932949429495294962949729498294992950029501295022950329504295052950629507295082950929510295112951229513295142951529516295172951829519295202952129522295232952429525295262952729528295292953029531295322953329534295352953629537295382953929540295412954229543295442954529546295472954829549295502955129552295532955429555295562955729558295592956029561295622956329564295652956629567295682956929570295712957229573295742957529576295772957829579295802958129582295832958429585295862958729588295892959029591295922959329594295952959629597295982959929600296012960229603296042960529606296072960829609296102961129612296132961429615296162961729618296192962029621296222962329624296252962629627296282962929630296312963229633296342963529636296372963829639296402964129642296432964429645296462964729648296492965029651296522965329654296552965629657296582965929660296612966229663296642966529666296672966829669296702967129672296732967429675296762967729678296792968029681296822968329684296852968629687296882968929690296912969229693296942969529696296972969829699297002970129702297032970429705297062970729708297092971029711297122971329714297152971629717297182971929720297212972229723297242972529726297272972829729297302973129732297332973429735297362973729738297392974029741297422974329744297452974629747297482974929750297512975229753297542975529756297572975829759297602976129762297632976429765297662976729768297692977029771297722977329774297752977629777297782977929780297812978229783297842978529786297872978829789297902979129792297932979429795297962979729798297992980029801298022980329804298052980629807298082980929810298112981229813298142981529816298172981829819298202982129822298232982429825298262982729828298292983029831298322983329834298352983629837298382983929840298412984229843298442984529846298472984829849298502985129852298532985429855298562985729858298592986029861298622986329864298652986629867298682986929870298712987229873298742987529876298772987829879298802988129882298832988429885298862988729888298892989029891298922989329894298952989629897298982989929900299012990229903299042990529906299072990829909299102991129912299132991429915299162991729918299192992029921299222992329924299252992629927299282992929930299312993229933299342993529936299372993829939299402994129942299432994429945299462994729948299492995029951299522995329954299552995629957299582995929960299612996229963299642996529966299672996829969299702997129972299732997429975299762997729978299792998029981299822998329984299852998629987299882998929990299912999229993299942999529996299972999829999300003000130002300033000430005300063000730008300093001030011300123001330014300153001630017300183001930020300213002230023300243002530026300273002830029300303003130032300333003430035300363003730038300393004030041300423004330044300453004630047300483004930050300513005230053300543005530056300573005830059300603006130062300633006430065300663006730068300693007030071300723007330074300753007630077300783007930080300813008230083300843008530086300873008830089300903009130092300933009430095300963009730098300993010030101301023010330104301053010630107301083010930110301113011230113301143011530116301173011830119301203012130122301233012430125301263012730128301293013030131301323013330134301353013630137301383013930140301413014230143301443014530146301473014830149301503015130152301533015430155301563015730158301593016030161301623016330164301653016630167301683016930170301713017230173301743017530176301773017830179301803018130182301833018430185301863018730188301893019030191301923019330194301953019630197301983019930200302013020230203302043020530206302073020830209302103021130212302133021430215302163021730218302193022030221302223022330224302253022630227302283022930230302313023230233302343023530236302373023830239302403024130242302433024430245302463024730248302493025030251302523025330254302553025630257302583025930260302613026230263302643026530266302673026830269302703027130272302733027430275302763027730278302793028030281302823028330284302853028630287302883028930290302913029230293302943029530296302973029830299303003030130302303033030430305303063030730308303093031030311303123031330314303153031630317303183031930320303213032230323303243032530326303273032830329303303033130332303333033430335303363033730338303393034030341303423034330344303453034630347303483034930350303513035230353303543035530356303573035830359303603036130362303633036430365303663036730368303693037030371303723037330374303753037630377303783037930380303813038230383303843038530386303873038830389303903039130392303933039430395303963039730398303993040030401304023040330404304053040630407304083040930410304113041230413304143041530416304173041830419304203042130422304233042430425304263042730428304293043030431304323043330434304353043630437304383043930440304413044230443304443044530446304473044830449304503045130452304533045430455304563045730458304593046030461304623046330464304653046630467304683046930470304713047230473304743047530476304773047830479304803048130482304833048430485304863048730488304893049030491304923049330494304953049630497304983049930500305013050230503305043050530506305073050830509305103051130512305133051430515305163051730518305193052030521305223052330524305253052630527305283052930530305313053230533305343053530536305373053830539305403054130542305433054430545305463054730548305493055030551305523055330554305553055630557305583055930560305613056230563305643056530566305673056830569305703057130572305733057430575305763057730578305793058030581305823058330584305853058630587305883058930590305913059230593305943059530596305973059830599306003060130602306033060430605306063060730608306093061030611306123061330614306153061630617306183061930620306213062230623306243062530626306273062830629306303063130632306333063430635306363063730638306393064030641306423064330644306453064630647306483064930650306513065230653306543065530656306573065830659306603066130662306633066430665306663066730668306693067030671306723067330674306753067630677306783067930680306813068230683306843068530686306873068830689306903069130692306933069430695306963069730698306993070030701307023070330704307053070630707307083070930710307113071230713307143071530716307173071830719307203072130722307233072430725307263072730728307293073030731307323073330734307353073630737307383073930740307413074230743307443074530746307473074830749307503075130752307533075430755307563075730758307593076030761307623076330764307653076630767307683076930770307713077230773307743077530776307773077830779307803078130782307833078430785307863078730788307893079030791307923079330794307953079630797307983079930800308013080230803308043080530806308073080830809308103081130812308133081430815308163081730818308193082030821308223082330824308253082630827308283082930830308313083230833308343083530836308373083830839308403084130842308433084430845308463084730848308493085030851308523085330854308553085630857308583085930860308613086230863308643086530866308673086830869308703087130872308733087430875308763087730878308793088030881308823088330884308853088630887308883088930890308913089230893308943089530896308973089830899309003090130902309033090430905309063090730908309093091030911309123091330914309153091630917309183091930920309213092230923309243092530926309273092830929309303093130932309333093430935309363093730938309393094030941309423094330944309453094630947309483094930950309513095230953309543095530956309573095830959309603096130962309633096430965309663096730968309693097030971309723097330974309753097630977309783097930980309813098230983309843098530986309873098830989309903099130992309933099430995309963099730998309993100031001310023100331004310053100631007310083100931010310113101231013310143101531016310173101831019310203102131022310233102431025310263102731028310293103031031310323103331034310353103631037310383103931040310413104231043310443104531046310473104831049310503105131052310533105431055310563105731058310593106031061310623106331064310653106631067310683106931070310713107231073310743107531076310773107831079310803108131082310833108431085310863108731088310893109031091310923109331094310953109631097310983109931100311013110231103311043110531106311073110831109311103111131112311133111431115311163111731118311193112031121311223112331124311253112631127311283112931130311313113231133311343113531136311373113831139311403114131142311433114431145311463114731148311493115031151311523115331154311553115631157311583115931160311613116231163311643116531166311673116831169311703117131172311733117431175311763117731178311793118031181311823118331184311853118631187311883118931190311913119231193311943119531196311973119831199312003120131202312033120431205312063120731208312093121031211312123121331214312153121631217312183121931220312213122231223312243122531226312273122831229312303123131232312333123431235312363123731238312393124031241312423124331244312453124631247312483124931250312513125231253312543125531256312573125831259312603126131262312633126431265312663126731268312693127031271312723127331274312753127631277312783127931280312813128231283312843128531286312873128831289312903129131292312933129431295312963129731298312993130031301313023130331304313053130631307313083130931310313113131231313313143131531316313173131831319313203132131322313233132431325313263132731328313293133031331313323133331334313353133631337313383133931340313413134231343313443134531346313473134831349313503135131352313533135431355313563135731358313593136031361313623136331364313653136631367313683136931370313713137231373313743137531376313773137831379313803138131382313833138431385313863138731388313893139031391313923139331394313953139631397313983139931400314013140231403314043140531406314073140831409314103141131412314133141431415314163141731418314193142031421314223142331424314253142631427314283142931430314313143231433314343143531436314373143831439314403144131442314433144431445314463144731448314493145031451314523145331454314553145631457314583145931460314613146231463314643146531466314673146831469314703147131472314733147431475314763147731478314793148031481314823148331484314853148631487314883148931490314913149231493314943149531496314973149831499315003150131502315033150431505315063150731508315093151031511315123151331514315153151631517315183151931520315213152231523315243152531526315273152831529315303153131532315333153431535315363153731538315393154031541315423154331544315453154631547315483154931550315513155231553315543155531556315573155831559315603156131562315633156431565315663156731568315693157031571315723157331574315753157631577315783157931580315813158231583315843158531586315873158831589315903159131592315933159431595315963159731598315993160031601316023160331604316053160631607316083160931610316113161231613316143161531616316173161831619316203162131622316233162431625316263162731628316293163031631316323163331634316353163631637316383163931640316413164231643316443164531646316473164831649316503165131652316533165431655316563165731658316593166031661316623166331664316653166631667316683166931670316713167231673316743167531676316773167831679316803168131682316833168431685316863168731688316893169031691316923169331694316953169631697316983169931700317013170231703317043170531706317073170831709317103171131712317133171431715317163171731718317193172031721317223172331724317253172631727317283172931730317313173231733317343173531736317373173831739317403174131742317433174431745317463174731748317493175031751317523175331754317553175631757317583175931760317613176231763317643176531766317673176831769317703177131772317733177431775317763177731778317793178031781317823178331784317853178631787317883178931790317913179231793317943179531796317973179831799318003180131802318033180431805318063180731808318093181031811318123181331814318153181631817318183181931820318213182231823318243182531826318273182831829318303183131832318333183431835318363183731838318393184031841318423184331844318453184631847318483184931850318513185231853318543185531856318573185831859318603186131862318633186431865318663186731868318693187031871318723187331874318753187631877318783187931880318813188231883318843188531886318873188831889318903189131892318933189431895318963189731898318993190031901319023190331904319053190631907319083190931910319113191231913319143191531916319173191831919319203192131922319233192431925319263192731928319293193031931319323193331934319353193631937319383193931940319413194231943319443194531946319473194831949319503195131952319533195431955319563195731958319593196031961319623196331964319653196631967319683196931970319713197231973319743197531976319773197831979319803198131982319833198431985319863198731988319893199031991319923199331994319953199631997319983199932000320013200232003320043200532006320073200832009320103201132012320133201432015320163201732018320193202032021320223202332024320253202632027320283202932030320313203232033320343203532036320373203832039320403204132042320433204432045320463204732048320493205032051320523205332054320553205632057320583205932060320613206232063320643206532066320673206832069320703207132072320733207432075320763207732078320793208032081320823208332084320853208632087320883208932090320913209232093320943209532096320973209832099321003210132102321033210432105321063210732108321093211032111321123211332114321153211632117321183211932120321213212232123321243212532126321273212832129321303213132132321333213432135321363213732138321393214032141321423214332144321453214632147321483214932150321513215232153321543215532156321573215832159321603216132162321633216432165321663216732168321693217032171321723217332174321753217632177321783217932180321813218232183321843218532186321873218832189321903219132192321933219432195321963219732198321993220032201322023220332204322053220632207322083220932210322113221232213322143221532216322173221832219322203222132222322233222432225322263222732228322293223032231322323223332234322353223632237322383223932240322413224232243322443224532246322473224832249322503225132252322533225432255322563225732258322593226032261322623226332264322653226632267322683226932270322713227232273322743227532276322773227832279322803228132282322833228432285322863228732288322893229032291322923229332294322953229632297322983229932300323013230232303323043230532306323073230832309323103231132312323133231432315323163231732318323193232032321323223232332324323253232632327323283232932330323313233232333323343233532336323373233832339323403234132342323433234432345323463234732348323493235032351323523235332354323553235632357323583235932360323613236232363323643236532366323673236832369323703237132372323733237432375323763237732378323793238032381323823238332384323853238632387323883238932390323913239232393323943239532396323973239832399324003240132402324033240432405324063240732408324093241032411324123241332414324153241632417324183241932420324213242232423324243242532426324273242832429324303243132432324333243432435324363243732438324393244032441324423244332444324453244632447324483244932450324513245232453324543245532456324573245832459324603246132462324633246432465324663246732468324693247032471324723247332474324753247632477324783247932480324813248232483324843248532486324873248832489324903249132492324933249432495324963249732498324993250032501325023250332504325053250632507325083250932510325113251232513325143251532516325173251832519325203252132522325233252432525325263252732528325293253032531325323253332534325353253632537325383253932540325413254232543325443254532546325473254832549325503255132552325533255432555325563255732558325593256032561325623256332564325653256632567325683256932570325713257232573325743257532576325773257832579325803258132582325833258432585325863258732588325893259032591325923259332594325953259632597325983259932600326013260232603326043260532606326073260832609326103261132612326133261432615326163261732618326193262032621326223262332624326253262632627326283262932630326313263232633326343263532636326373263832639326403264132642326433264432645326463264732648326493265032651326523265332654326553265632657326583265932660326613266232663326643266532666326673266832669326703267132672326733267432675326763267732678326793268032681326823268332684326853268632687326883268932690326913269232693326943269532696326973269832699327003270132702327033270432705327063270732708327093271032711327123271332714327153271632717327183271932720327213272232723327243272532726327273272832729327303273132732327333273432735327363273732738327393274032741327423274332744327453274632747327483274932750327513275232753327543275532756327573275832759327603276132762327633276432765327663276732768327693277032771327723277332774327753277632777327783277932780327813278232783327843278532786327873278832789327903279132792327933279432795327963279732798327993280032801328023280332804328053280632807328083280932810328113281232813328143281532816328173281832819328203282132822328233282432825328263282732828328293283032831328323283332834328353283632837328383283932840328413284232843328443284532846328473284832849328503285132852328533285432855328563285732858328593286032861328623286332864328653286632867328683286932870328713287232873328743287532876328773287832879328803288132882328833288432885328863288732888328893289032891328923289332894328953289632897328983289932900329013290232903329043290532906329073290832909329103291132912329133291432915329163291732918329193292032921329223292332924329253292632927329283292932930329313293232933329343293532936329373293832939329403294132942329433294432945329463294732948329493295032951329523295332954329553295632957329583295932960329613296232963329643296532966329673296832969329703297132972329733297432975329763297732978329793298032981329823298332984329853298632987329883298932990329913299232993329943299532996329973299832999330003300133002330033300433005330063300733008330093301033011330123301333014330153301633017330183301933020330213302233023330243302533026330273302833029330303303133032330333303433035330363303733038330393304033041330423304333044330453304633047330483304933050330513305233053330543305533056330573305833059330603306133062330633306433065330663306733068330693307033071330723307333074330753307633077330783307933080330813308233083330843308533086330873308833089330903309133092330933309433095330963309733098330993310033101331023310333104331053310633107331083310933110331113311233113331143311533116331173311833119331203312133122331233312433125331263312733128331293313033131331323313333134331353313633137331383313933140331413314233143331443314533146331473314833149331503315133152331533315433155331563315733158331593316033161331623316333164331653316633167331683316933170331713317233173331743317533176331773317833179331803318133182331833318433185331863318733188331893319033191331923319333194331953319633197331983319933200332013320233203332043320533206332073320833209332103321133212332133321433215332163321733218332193322033221332223322333224332253322633227332283322933230332313323233233332343323533236332373323833239332403324133242332433324433245332463324733248332493325033251332523325333254332553325633257332583325933260332613326233263332643326533266332673326833269332703327133272332733327433275332763327733278332793328033281332823328333284332853328633287332883328933290332913329233293332943329533296332973329833299333003330133302333033330433305333063330733308333093331033311333123331333314333153331633317333183331933320333213332233323333243332533326333273332833329333303333133332333333333433335333363333733338333393334033341333423334333344333453334633347333483334933350333513335233353333543335533356333573335833359333603336133362333633336433365333663336733368333693337033371333723337333374333753337633377333783337933380333813338233383333843338533386333873338833389333903339133392333933339433395333963339733398333993340033401334023340333404334053340633407334083340933410334113341233413334143341533416334173341833419334203342133422334233342433425334263342733428334293343033431334323343333434334353343633437334383343933440334413344233443334443344533446334473344833449334503345133452334533345433455334563345733458334593346033461334623346333464334653346633467334683346933470334713347233473334743347533476334773347833479334803348133482334833348433485334863348733488334893349033491334923349333494334953349633497334983349933500335013350233503335043350533506335073350833509335103351133512335133351433515335163351733518335193352033521335223352333524335253352633527335283352933530335313353233533335343353533536335373353833539335403354133542335433354433545335463354733548335493355033551335523355333554335553355633557335583355933560335613356233563335643356533566335673356833569335703357133572335733357433575335763357733578335793358033581335823358333584335853358633587335883358933590335913359233593335943359533596335973359833599336003360133602336033360433605336063360733608336093361033611336123361333614336153361633617336183361933620336213362233623336243362533626336273362833629336303363133632336333363433635336363363733638336393364033641336423364333644336453364633647336483364933650336513365233653336543365533656336573365833659336603366133662336633366433665336663366733668336693367033671336723367333674336753367633677336783367933680336813368233683336843368533686336873368833689336903369133692336933369433695336963369733698336993370033701337023370333704337053370633707337083370933710337113371233713337143371533716337173371833719337203372133722337233372433725337263372733728337293373033731337323373333734337353373633737337383373933740337413374233743337443374533746337473374833749337503375133752337533375433755337563375733758337593376033761337623376333764337653376633767337683376933770337713377233773337743377533776337773377833779337803378133782337833378433785337863378733788337893379033791337923379333794337953379633797337983379933800338013380233803338043380533806338073380833809338103381133812338133381433815338163381733818338193382033821338223382333824338253382633827338283382933830338313383233833338343383533836338373383833839338403384133842338433384433845338463384733848338493385033851338523385333854338553385633857338583385933860338613386233863338643386533866338673386833869338703387133872338733387433875338763387733878338793388033881338823388333884338853388633887338883388933890338913389233893338943389533896338973389833899339003390133902339033390433905339063390733908339093391033911339123391333914339153391633917339183391933920339213392233923339243392533926339273392833929339303393133932339333393433935339363393733938339393394033941339423394333944339453394633947339483394933950339513395233953339543395533956339573395833959339603396133962339633396433965339663396733968339693397033971339723397333974339753397633977339783397933980339813398233983339843398533986339873398833989339903399133992339933399433995339963399733998339993400034001340023400334004340053400634007340083400934010340113401234013340143401534016340173401834019340203402134022340233402434025340263402734028340293403034031340323403334034340353403634037340383403934040340413404234043340443404534046340473404834049340503405134052340533405434055340563405734058340593406034061340623406334064340653406634067340683406934070340713407234073340743407534076340773407834079340803408134082340833408434085340863408734088340893409034091340923409334094340953409634097340983409934100341013410234103341043410534106341073410834109341103411134112341133411434115341163411734118341193412034121341223412334124341253412634127341283412934130341313413234133341343413534136341373413834139341403414134142341433414434145341463414734148341493415034151341523415334154341553415634157341583415934160341613416234163341643416534166341673416834169341703417134172341733417434175341763417734178341793418034181341823418334184341853418634187341883418934190341913419234193341943419534196341973419834199342003420134202342033420434205342063420734208342093421034211342123421334214342153421634217342183421934220342213422234223342243422534226342273422834229342303423134232342333423434235342363423734238342393424034241342423424334244342453424634247342483424934250342513425234253342543425534256342573425834259342603426134262342633426434265342663426734268342693427034271342723427334274342753427634277342783427934280342813428234283342843428534286342873428834289342903429134292342933429434295342963429734298342993430034301343023430334304343053430634307343083430934310343113431234313343143431534316343173431834319343203432134322343233432434325343263432734328343293433034331343323433334334343353433634337343383433934340343413434234343343443434534346343473434834349343503435134352343533435434355343563435734358343593436034361343623436334364343653436634367343683436934370343713437234373343743437534376343773437834379343803438134382343833438434385343863438734388343893439034391343923439334394343953439634397343983439934400344013440234403344043440534406344073440834409344103441134412344133441434415344163441734418344193442034421344223442334424344253442634427344283442934430344313443234433344343443534436344373443834439344403444134442344433444434445344463444734448344493445034451344523445334454344553445634457344583445934460344613446234463344643446534466344673446834469344703447134472344733447434475344763447734478344793448034481344823448334484344853448634487344883448934490344913449234493344943449534496344973449834499345003450134502345033450434505345063450734508345093451034511345123451334514345153451634517345183451934520345213452234523345243452534526345273452834529345303453134532345333453434535345363453734538345393454034541345423454334544345453454634547345483454934550345513455234553345543455534556345573455834559345603456134562345633456434565345663456734568345693457034571345723457334574345753457634577345783457934580345813458234583345843458534586345873458834589345903459134592345933459434595345963459734598345993460034601346023460334604346053460634607346083460934610346113461234613346143461534616346173461834619346203462134622346233462434625346263462734628346293463034631346323463334634346353463634637346383463934640346413464234643346443464534646346473464834649346503465134652346533465434655346563465734658346593466034661346623466334664346653466634667346683466934670346713467234673346743467534676346773467834679346803468134682346833468434685346863468734688346893469034691346923469334694346953469634697346983469934700347013470234703347043470534706347073470834709347103471134712347133471434715347163471734718347193472034721347223472334724347253472634727347283472934730347313473234733347343473534736347373473834739347403474134742347433474434745347463474734748347493475034751347523475334754347553475634757347583475934760347613476234763347643476534766347673476834769347703477134772347733477434775347763477734778347793478034781347823478334784347853478634787347883478934790347913479234793347943479534796347973479834799348003480134802348033480434805348063480734808348093481034811348123481334814348153481634817348183481934820348213482234823348243482534826348273482834829348303483134832348333483434835348363483734838348393484034841348423484334844348453484634847348483484934850348513485234853348543485534856348573485834859348603486134862348633486434865348663486734868348693487034871348723487334874348753487634877348783487934880348813488234883348843488534886348873488834889348903489134892348933489434895348963489734898348993490034901349023490334904349053490634907349083490934910349113491234913349143491534916349173491834919349203492134922349233492434925349263492734928349293493034931349323493334934349353493634937349383493934940349413494234943349443494534946349473494834949349503495134952349533495434955349563495734958349593496034961349623496334964349653496634967349683496934970349713497234973349743497534976349773497834979349803498134982349833498434985349863498734988349893499034991349923499334994349953499634997349983499935000350013500235003350043500535006350073500835009350103501135012350133501435015350163501735018350193502035021350223502335024350253502635027350283502935030350313503235033350343503535036350373503835039350403504135042350433504435045350463504735048350493505035051350523505335054350553505635057350583505935060350613506235063350643506535066350673506835069350703507135072350733507435075350763507735078350793508035081350823508335084350853508635087350883508935090350913509235093350943509535096350973509835099351003510135102351033510435105351063510735108351093511035111351123511335114351153511635117351183511935120351213512235123351243512535126351273512835129351303513135132351333513435135351363513735138351393514035141351423514335144351453514635147351483514935150351513515235153351543515535156351573515835159351603516135162351633516435165351663516735168351693517035171351723517335174351753517635177351783517935180351813518235183351843518535186351873518835189351903519135192351933519435195351963519735198351993520035201352023520335204352053520635207352083520935210352113521235213352143521535216352173521835219352203522135222352233522435225352263522735228352293523035231352323523335234352353523635237352383523935240352413524235243352443524535246352473524835249352503525135252352533525435255352563525735258352593526035261352623526335264352653526635267352683526935270352713527235273352743527535276352773527835279352803528135282352833528435285352863528735288352893529035291352923529335294352953529635297352983529935300353013530235303353043530535306353073530835309353103531135312353133531435315353163531735318353193532035321353223532335324353253532635327353283532935330353313533235333353343533535336353373533835339353403534135342353433534435345353463534735348353493535035351353523535335354353553535635357353583535935360353613536235363353643536535366353673536835369353703537135372353733537435375353763537735378353793538035381353823538335384353853538635387353883538935390353913539235393353943539535396353973539835399354003540135402354033540435405354063540735408354093541035411354123541335414354153541635417354183541935420354213542235423354243542535426354273542835429354303543135432354333543435435354363543735438354393544035441354423544335444354453544635447354483544935450354513545235453354543545535456354573545835459354603546135462354633546435465354663546735468354693547035471354723547335474354753547635477354783547935480354813548235483354843548535486354873548835489354903549135492354933549435495354963549735498354993550035501355023550335504355053550635507355083550935510355113551235513355143551535516355173551835519355203552135522355233552435525355263552735528355293553035531355323553335534355353553635537355383553935540355413554235543355443554535546355473554835549355503555135552355533555435555355563555735558355593556035561355623556335564355653556635567355683556935570355713557235573355743557535576355773557835579355803558135582355833558435585355863558735588355893559035591355923559335594355953559635597355983559935600356013560235603356043560535606356073560835609356103561135612356133561435615356163561735618356193562035621356223562335624356253562635627356283562935630356313563235633356343563535636356373563835639356403564135642356433564435645356463564735648356493565035651356523565335654356553565635657356583565935660356613566235663356643566535666356673566835669356703567135672356733567435675356763567735678356793568035681356823568335684356853568635687356883568935690356913569235693356943569535696356973569835699357003570135702357033570435705357063570735708357093571035711357123571335714357153571635717357183571935720357213572235723357243572535726357273572835729357303573135732357333573435735357363573735738357393574035741357423574335744357453574635747357483574935750357513575235753357543575535756357573575835759357603576135762357633576435765357663576735768357693577035771357723577335774357753577635777357783577935780357813578235783357843578535786357873578835789357903579135792357933579435795357963579735798357993580035801358023580335804358053580635807358083580935810358113581235813358143581535816358173581835819358203582135822358233582435825358263582735828358293583035831358323583335834358353583635837358383583935840358413584235843358443584535846358473584835849358503585135852358533585435855358563585735858358593586035861358623586335864358653586635867358683586935870358713587235873358743587535876358773587835879358803588135882358833588435885358863588735888358893589035891358923589335894358953589635897358983589935900359013590235903359043590535906359073590835909359103591135912359133591435915359163591735918359193592035921359223592335924359253592635927359283592935930359313593235933359343593535936359373593835939359403594135942359433594435945359463594735948359493595035951359523595335954359553595635957359583595935960359613596235963359643596535966359673596835969359703597135972359733597435975359763597735978359793598035981359823598335984359853598635987359883598935990359913599235993359943599535996359973599835999360003600136002360033600436005360063600736008360093601036011360123601336014360153601636017360183601936020360213602236023360243602536026360273602836029360303603136032360333603436035360363603736038360393604036041360423604336044360453604636047360483604936050360513605236053360543605536056360573605836059360603606136062360633606436065360663606736068360693607036071360723607336074360753607636077360783607936080360813608236083360843608536086360873608836089360903609136092360933609436095360963609736098360993610036101361023610336104361053610636107361083610936110361113611236113361143611536116361173611836119361203612136122361233612436125361263612736128361293613036131361323613336134361353613636137361383613936140361413614236143361443614536146361473614836149361503615136152361533615436155361563615736158361593616036161361623616336164361653616636167361683616936170361713617236173361743617536176361773617836179361803618136182361833618436185361863618736188361893619036191361923619336194361953619636197361983619936200362013620236203362043620536206362073620836209362103621136212362133621436215362163621736218362193622036221362223622336224362253622636227362283622936230362313623236233362343623536236362373623836239362403624136242362433624436245362463624736248362493625036251362523625336254362553625636257362583625936260362613626236263362643626536266362673626836269362703627136272362733627436275362763627736278362793628036281362823628336284362853628636287362883628936290362913629236293362943629536296362973629836299363003630136302363033630436305363063630736308363093631036311363123631336314363153631636317363183631936320363213632236323363243632536326363273632836329363303633136332363333633436335363363633736338363393634036341363423634336344363453634636347363483634936350363513635236353363543635536356363573635836359363603636136362363633636436365363663636736368363693637036371363723637336374363753637636377363783637936380363813638236383363843638536386363873638836389363903639136392363933639436395363963639736398363993640036401364023640336404364053640636407364083640936410364113641236413364143641536416364173641836419364203642136422364233642436425364263642736428364293643036431364323643336434364353643636437364383643936440364413644236443364443644536446364473644836449364503645136452364533645436455364563645736458364593646036461364623646336464364653646636467364683646936470364713647236473364743647536476364773647836479364803648136482364833648436485364863648736488364893649036491364923649336494364953649636497364983649936500365013650236503365043650536506365073650836509365103651136512365133651436515365163651736518365193652036521365223652336524365253652636527365283652936530365313653236533365343653536536365373653836539365403654136542365433654436545365463654736548365493655036551365523655336554365553655636557365583655936560365613656236563365643656536566365673656836569365703657136572365733657436575365763657736578365793658036581365823658336584365853658636587365883658936590365913659236593365943659536596365973659836599366003660136602366033660436605366063660736608366093661036611366123661336614366153661636617366183661936620366213662236623366243662536626366273662836629366303663136632366333663436635366363663736638366393664036641366423664336644366453664636647366483664936650366513665236653366543665536656366573665836659366603666136662366633666436665366663666736668366693667036671366723667336674366753667636677366783667936680366813668236683366843668536686366873668836689366903669136692366933669436695366963669736698366993670036701367023670336704367053670636707367083670936710367113671236713367143671536716367173671836719367203672136722367233672436725367263672736728367293673036731367323673336734367353673636737367383673936740367413674236743367443674536746367473674836749367503675136752367533675436755367563675736758367593676036761367623676336764367653676636767367683676936770367713677236773367743677536776367773677836779367803678136782367833678436785367863678736788367893679036791367923679336794367953679636797367983679936800368013680236803368043680536806368073680836809368103681136812368133681436815368163681736818368193682036821368223682336824368253682636827368283682936830368313683236833368343683536836368373683836839368403684136842368433684436845368463684736848368493685036851368523685336854368553685636857368583685936860368613686236863368643686536866368673686836869368703687136872368733687436875368763687736878368793688036881368823688336884368853688636887368883688936890368913689236893368943689536896368973689836899369003690136902369033690436905369063690736908369093691036911369123691336914369153691636917369183691936920369213692236923369243692536926369273692836929369303693136932369333693436935369363693736938369393694036941369423694336944369453694636947369483694936950369513695236953369543695536956369573695836959369603696136962369633696436965369663696736968369693697036971369723697336974369753697636977369783697936980369813698236983369843698536986369873698836989369903699136992369933699436995369963699736998369993700037001370023700337004370053700637007370083700937010370113701237013370143701537016370173701837019370203702137022370233702437025370263702737028370293703037031370323703337034370353703637037370383703937040370413704237043370443704537046370473704837049370503705137052370533705437055370563705737058370593706037061370623706337064370653706637067370683706937070370713707237073370743707537076370773707837079370803708137082370833708437085370863708737088370893709037091370923709337094370953709637097370983709937100371013710237103371043710537106371073710837109371103711137112371133711437115371163711737118371193712037121371223712337124371253712637127371283712937130371313713237133371343713537136371373713837139371403714137142371433714437145371463714737148371493715037151371523715337154371553715637157371583715937160371613716237163371643716537166371673716837169371703717137172371733717437175371763717737178371793718037181371823718337184371853718637187371883718937190371913719237193371943719537196371973719837199372003720137202372033720437205372063720737208372093721037211372123721337214372153721637217372183721937220372213722237223372243722537226372273722837229372303723137232372333723437235372363723737238372393724037241372423724337244372453724637247372483724937250372513725237253372543725537256372573725837259372603726137262372633726437265372663726737268372693727037271372723727337274372753727637277372783727937280372813728237283372843728537286372873728837289372903729137292372933729437295372963729737298372993730037301373023730337304373053730637307373083730937310373113731237313373143731537316373173731837319373203732137322373233732437325373263732737328373293733037331373323733337334373353733637337373383733937340373413734237343373443734537346373473734837349373503735137352373533735437355373563735737358373593736037361373623736337364373653736637367373683736937370373713737237373373743737537376373773737837379373803738137382373833738437385373863738737388373893739037391373923739337394373953739637397373983739937400374013740237403374043740537406374073740837409374103741137412374133741437415374163741737418374193742037421374223742337424374253742637427374283742937430374313743237433374343743537436374373743837439374403744137442374433744437445374463744737448374493745037451374523745337454374553745637457374583745937460374613746237463374643746537466374673746837469374703747137472374733747437475374763747737478374793748037481374823748337484374853748637487374883748937490374913749237493374943749537496374973749837499375003750137502375033750437505375063750737508375093751037511375123751337514375153751637517375183751937520375213752237523375243752537526375273752837529375303753137532375333753437535375363753737538375393754037541375423754337544375453754637547375483754937550375513755237553375543755537556375573755837559375603756137562375633756437565375663756737568375693757037571375723757337574375753757637577375783757937580375813758237583375843758537586375873758837589375903759137592375933759437595375963759737598375993760037601376023760337604376053760637607376083760937610376113761237613376143761537616376173761837619376203762137622376233762437625376263762737628376293763037631376323763337634376353763637637376383763937640376413764237643376443764537646376473764837649376503765137652376533765437655376563765737658376593766037661376623766337664376653766637667376683766937670376713767237673376743767537676376773767837679376803768137682376833768437685376863768737688376893769037691376923769337694376953769637697376983769937700377013770237703377043770537706377073770837709377103771137712377133771437715377163771737718377193772037721377223772337724377253772637727377283772937730377313773237733377343773537736377373773837739377403774137742377433774437745377463774737748377493775037751377523775337754377553775637757377583775937760377613776237763377643776537766377673776837769377703777137772377733777437775377763777737778377793778037781377823778337784377853778637787377883778937790377913779237793377943779537796377973779837799378003780137802378033780437805378063780737808378093781037811378123781337814378153781637817378183781937820378213782237823378243782537826378273782837829378303783137832378333783437835378363783737838378393784037841378423784337844378453784637847378483784937850378513785237853378543785537856378573785837859378603786137862378633786437865378663786737868378693787037871378723787337874378753787637877378783787937880378813788237883378843788537886378873788837889378903789137892378933789437895378963789737898378993790037901379023790337904379053790637907379083790937910379113791237913379143791537916379173791837919379203792137922379233792437925379263792737928379293793037931379323793337934379353793637937379383793937940379413794237943379443794537946379473794837949379503795137952379533795437955379563795737958379593796037961379623796337964379653796637967379683796937970379713797237973379743797537976379773797837979379803798137982379833798437985379863798737988379893799037991379923799337994379953799637997379983799938000380013800238003380043800538006380073800838009380103801138012380133801438015380163801738018380193802038021380223802338024380253802638027380283802938030380313803238033380343803538036380373803838039380403804138042380433804438045380463804738048380493805038051380523805338054380553805638057380583805938060380613806238063380643806538066380673806838069380703807138072380733807438075380763807738078380793808038081380823808338084380853808638087380883808938090380913809238093380943809538096380973809838099381003810138102381033810438105381063810738108381093811038111381123811338114381153811638117381183811938120381213812238123381243812538126381273812838129381303813138132381333813438135381363813738138381393814038141381423814338144381453814638147381483814938150381513815238153381543815538156381573815838159381603816138162381633816438165381663816738168381693817038171381723817338174381753817638177381783817938180381813818238183381843818538186381873818838189381903819138192381933819438195381963819738198381993820038201382023820338204382053820638207382083820938210382113821238213382143821538216382173821838219382203822138222382233822438225382263822738228382293823038231382323823338234382353823638237382383823938240382413824238243382443824538246382473824838249382503825138252382533825438255382563825738258382593826038261382623826338264382653826638267382683826938270382713827238273382743827538276382773827838279382803828138282382833828438285382863828738288382893829038291382923829338294382953829638297382983829938300383013830238303383043830538306383073830838309383103831138312383133831438315383163831738318383193832038321383223832338324383253832638327383283832938330383313833238333383343833538336383373833838339383403834138342383433834438345383463834738348383493835038351383523835338354383553835638357383583835938360383613836238363383643836538366383673836838369383703837138372383733837438375383763837738378383793838038381383823838338384383853838638387383883838938390383913839238393383943839538396383973839838399384003840138402384033840438405384063840738408384093841038411384123841338414384153841638417384183841938420384213842238423384243842538426384273842838429384303843138432384333843438435384363843738438384393844038441384423844338444384453844638447384483844938450384513845238453384543845538456384573845838459384603846138462384633846438465384663846738468384693847038471384723847338474384753847638477384783847938480384813848238483384843848538486384873848838489384903849138492384933849438495384963849738498384993850038501385023850338504385053850638507385083850938510385113851238513385143851538516385173851838519385203852138522385233852438525385263852738528385293853038531385323853338534385353853638537385383853938540385413854238543385443854538546385473854838549385503855138552385533855438555385563855738558385593856038561385623856338564385653856638567385683856938570385713857238573385743857538576385773857838579385803858138582385833858438585385863858738588385893859038591385923859338594385953859638597385983859938600386013860238603386043860538606386073860838609386103861138612386133861438615386163861738618386193862038621386223862338624386253862638627386283862938630386313863238633386343863538636386373863838639386403864138642386433864438645386463864738648386493865038651386523865338654386553865638657386583865938660386613866238663386643866538666386673866838669386703867138672386733867438675386763867738678386793868038681386823868338684386853868638687386883868938690386913869238693386943869538696386973869838699387003870138702387033870438705387063870738708387093871038711387123871338714387153871638717387183871938720387213872238723387243872538726387273872838729387303873138732387333873438735387363873738738387393874038741387423874338744387453874638747387483874938750387513875238753387543875538756387573875838759387603876138762387633876438765387663876738768387693877038771387723877338774387753877638777387783877938780387813878238783387843878538786387873878838789387903879138792387933879438795387963879738798387993880038801388023880338804388053880638807388083880938810388113881238813388143881538816388173881838819388203882138822388233882438825388263882738828388293883038831388323883338834388353883638837388383883938840388413884238843388443884538846388473884838849388503885138852388533885438855388563885738858388593886038861388623886338864388653886638867388683886938870388713887238873388743887538876388773887838879388803888138882388833888438885388863888738888388893889038891388923889338894388953889638897388983889938900389013890238903389043890538906389073890838909389103891138912389133891438915389163891738918389193892038921389223892338924389253892638927389283892938930389313893238933389343893538936389373893838939389403894138942389433894438945389463894738948389493895038951389523895338954389553895638957389583895938960389613896238963389643896538966389673896838969389703897138972389733897438975389763897738978389793898038981389823898338984389853898638987389883898938990389913899238993389943899538996389973899838999390003900139002390033900439005390063900739008390093901039011390123901339014390153901639017390183901939020390213902239023390243902539026390273902839029390303903139032390333903439035390363903739038390393904039041390423904339044390453904639047390483904939050390513905239053390543905539056390573905839059390603906139062390633906439065390663906739068390693907039071390723907339074390753907639077390783907939080390813908239083390843908539086390873908839089390903909139092390933909439095390963909739098390993910039101391023910339104391053910639107391083910939110391113911239113391143911539116391173911839119391203912139122391233912439125391263912739128391293913039131391323913339134391353913639137391383913939140391413914239143391443914539146391473914839149391503915139152391533915439155391563915739158391593916039161391623916339164391653916639167391683916939170391713917239173391743917539176391773917839179391803918139182391833918439185391863918739188391893919039191391923919339194391953919639197391983919939200392013920239203392043920539206392073920839209392103921139212392133921439215392163921739218392193922039221392223922339224392253922639227392283922939230392313923239233392343923539236392373923839239392403924139242392433924439245392463924739248392493925039251392523925339254392553925639257392583925939260392613926239263392643926539266392673926839269392703927139272392733927439275392763927739278392793928039281392823928339284392853928639287392883928939290392913929239293392943929539296392973929839299393003930139302393033930439305393063930739308393093931039311393123931339314393153931639317393183931939320393213932239323393243932539326393273932839329393303933139332393333933439335393363933739338393393934039341393423934339344393453934639347393483934939350393513935239353393543935539356393573935839359393603936139362393633936439365393663936739368393693937039371393723937339374393753937639377393783937939380393813938239383393843938539386393873938839389393903939139392393933939439395393963939739398393993940039401394023940339404394053940639407394083940939410394113941239413394143941539416394173941839419394203942139422394233942439425394263942739428394293943039431394323943339434394353943639437394383943939440394413944239443394443944539446394473944839449394503945139452394533945439455394563945739458394593946039461394623946339464394653946639467394683946939470394713947239473394743947539476394773947839479394803948139482394833948439485394863948739488394893949039491394923949339494394953949639497394983949939500395013950239503395043950539506395073950839509395103951139512395133951439515395163951739518395193952039521395223952339524395253952639527395283952939530395313953239533395343953539536395373953839539395403954139542395433954439545395463954739548395493955039551395523955339554395553955639557395583955939560395613956239563395643956539566395673956839569395703957139572395733957439575395763957739578395793958039581395823958339584395853958639587395883958939590395913959239593395943959539596395973959839599396003960139602396033960439605396063960739608396093961039611396123961339614396153961639617396183961939620396213962239623396243962539626396273962839629396303963139632396333963439635396363963739638396393964039641396423964339644396453964639647396483964939650396513965239653396543965539656396573965839659396603966139662396633966439665396663966739668396693967039671396723967339674396753967639677396783967939680396813968239683396843968539686396873968839689396903969139692396933969439695396963969739698396993970039701397023970339704397053970639707397083970939710397113971239713397143971539716397173971839719397203972139722397233972439725397263972739728397293973039731397323973339734397353973639737397383973939740397413974239743397443974539746397473974839749397503975139752397533975439755397563975739758397593976039761397623976339764397653976639767397683976939770397713977239773397743977539776397773977839779397803978139782397833978439785397863978739788397893979039791397923979339794397953979639797397983979939800398013980239803398043980539806398073980839809398103981139812398133981439815398163981739818398193982039821398223982339824398253982639827398283982939830398313983239833398343983539836398373983839839398403984139842398433984439845398463984739848398493985039851398523985339854398553985639857398583985939860398613986239863398643986539866398673986839869398703987139872398733987439875398763987739878398793988039881398823988339884398853988639887398883988939890398913989239893398943989539896398973989839899399003990139902399033990439905399063990739908399093991039911399123991339914399153991639917399183991939920399213992239923399243992539926399273992839929399303993139932399333993439935399363993739938399393994039941399423994339944399453994639947399483994939950399513995239953399543995539956399573995839959399603996139962399633996439965399663996739968399693997039971399723997339974399753997639977399783997939980399813998239983399843998539986399873998839989399903999139992399933999439995399963999739998399994000040001400024000340004400054000640007400084000940010400114001240013400144001540016400174001840019400204002140022400234002440025400264002740028400294003040031400324003340034400354003640037400384003940040400414004240043400444004540046400474004840049400504005140052400534005440055400564005740058400594006040061400624006340064400654006640067400684006940070400714007240073400744007540076400774007840079400804008140082400834008440085400864008740088400894009040091400924009340094400954009640097400984009940100401014010240103401044010540106401074010840109401104011140112401134011440115401164011740118401194012040121401224012340124401254012640127401284012940130401314013240133401344013540136401374013840139401404014140142401434014440145401464014740148401494015040151401524015340154401554015640157401584015940160401614016240163401644016540166401674016840169401704017140172401734017440175401764017740178401794018040181401824018340184401854018640187401884018940190401914019240193401944019540196401974019840199402004020140202402034020440205402064020740208402094021040211402124021340214402154021640217402184021940220402214022240223402244022540226402274022840229402304023140232402334023440235402364023740238402394024040241402424024340244402454024640247402484024940250402514025240253402544025540256402574025840259402604026140262402634026440265402664026740268402694027040271402724027340274402754027640277402784027940280402814028240283402844028540286402874028840289402904029140292402934029440295402964029740298402994030040301403024030340304403054030640307403084030940310403114031240313403144031540316403174031840319403204032140322403234032440325403264032740328403294033040331403324033340334403354033640337403384033940340403414034240343403444034540346403474034840349403504035140352403534035440355403564035740358403594036040361403624036340364403654036640367403684036940370403714037240373403744037540376403774037840379403804038140382403834038440385403864038740388403894039040391403924039340394403954039640397403984039940400404014040240403404044040540406404074040840409404104041140412404134041440415404164041740418404194042040421404224042340424404254042640427404284042940430404314043240433404344043540436404374043840439404404044140442404434044440445404464044740448404494045040451404524045340454404554045640457404584045940460404614046240463404644046540466404674046840469404704047140472404734047440475404764047740478404794048040481404824048340484404854048640487404884048940490404914049240493404944049540496404974049840499405004050140502405034050440505405064050740508405094051040511405124051340514405154051640517405184051940520405214052240523405244052540526405274052840529405304053140532405334053440535405364053740538405394054040541405424054340544405454054640547405484054940550405514055240553405544055540556405574055840559405604056140562405634056440565405664056740568405694057040571405724057340574405754057640577405784057940580405814058240583405844058540586405874058840589405904059140592405934059440595405964059740598405994060040601406024060340604406054060640607406084060940610406114061240613406144061540616406174061840619406204062140622406234062440625406264062740628406294063040631406324063340634406354063640637406384063940640406414064240643406444064540646406474064840649406504065140652406534065440655406564065740658406594066040661406624066340664406654066640667406684066940670406714067240673406744067540676406774067840679406804068140682406834068440685406864068740688406894069040691406924069340694406954069640697406984069940700407014070240703407044070540706407074070840709407104071140712407134071440715407164071740718407194072040721407224072340724407254072640727407284072940730407314073240733407344073540736407374073840739407404074140742407434074440745407464074740748407494075040751407524075340754407554075640757407584075940760407614076240763407644076540766407674076840769407704077140772407734077440775407764077740778407794078040781407824078340784407854078640787407884078940790407914079240793407944079540796407974079840799408004080140802408034080440805408064080740808408094081040811408124081340814408154081640817408184081940820408214082240823408244082540826408274082840829408304083140832408334083440835408364083740838408394084040841408424084340844408454084640847408484084940850408514085240853408544085540856408574085840859408604086140862408634086440865408664086740868408694087040871408724087340874408754087640877408784087940880408814088240883408844088540886408874088840889408904089140892408934089440895408964089740898408994090040901409024090340904409054090640907409084090940910409114091240913409144091540916409174091840919409204092140922409234092440925409264092740928409294093040931409324093340934409354093640937409384093940940409414094240943409444094540946409474094840949409504095140952409534095440955409564095740958409594096040961409624096340964409654096640967409684096940970409714097240973409744097540976409774097840979409804098140982409834098440985409864098740988409894099040991409924099340994409954099640997409984099941000410014100241003410044100541006410074100841009410104101141012410134101441015410164101741018410194102041021410224102341024410254102641027410284102941030410314103241033410344103541036410374103841039410404104141042410434104441045410464104741048410494105041051410524105341054410554105641057410584105941060410614106241063410644106541066410674106841069410704107141072410734107441075410764107741078410794108041081410824108341084410854108641087410884108941090410914109241093410944109541096410974109841099411004110141102411034110441105411064110741108411094111041111411124111341114411154111641117411184111941120411214112241123411244112541126411274112841129411304113141132411334113441135411364113741138411394114041141411424114341144411454114641147411484114941150411514115241153411544115541156411574115841159411604116141162411634116441165411664116741168411694117041171411724117341174411754117641177411784117941180411814118241183411844118541186411874118841189411904119141192411934119441195411964119741198411994120041201412024120341204412054120641207412084120941210412114121241213412144121541216412174121841219412204122141222412234122441225412264122741228412294123041231412324123341234412354123641237412384123941240412414124241243412444124541246412474124841249412504125141252412534125441255412564125741258412594126041261412624126341264412654126641267412684126941270412714127241273412744127541276412774127841279412804128141282412834128441285412864128741288412894129041291412924129341294412954129641297412984129941300413014130241303413044130541306413074130841309413104131141312413134131441315413164131741318413194132041321413224132341324413254132641327413284132941330413314133241333413344133541336413374133841339413404134141342413434134441345413464134741348413494135041351413524135341354413554135641357413584135941360413614136241363413644136541366413674136841369413704137141372413734137441375413764137741378413794138041381413824138341384413854138641387413884138941390413914139241393413944139541396413974139841399414004140141402414034140441405414064140741408414094141041411414124141341414414154141641417414184141941420414214142241423414244142541426414274142841429414304143141432414334143441435414364143741438414394144041441414424144341444414454144641447414484144941450414514145241453414544145541456414574145841459414604146141462414634146441465414664146741468414694147041471414724147341474414754147641477414784147941480414814148241483414844148541486414874148841489414904149141492414934149441495414964149741498414994150041501415024150341504415054150641507415084150941510415114151241513415144151541516415174151841519415204152141522415234152441525415264152741528415294153041531415324153341534415354153641537415384153941540415414154241543415444154541546415474154841549415504155141552415534155441555415564155741558415594156041561415624156341564415654156641567415684156941570415714157241573415744157541576415774157841579415804158141582415834158441585415864158741588415894159041591415924159341594415954159641597415984159941600416014160241603416044160541606416074160841609416104161141612416134161441615416164161741618416194162041621416224162341624416254162641627416284162941630416314163241633416344163541636416374163841639416404164141642416434164441645416464164741648416494165041651416524165341654416554165641657416584165941660416614166241663416644166541666416674166841669416704167141672416734167441675416764167741678416794168041681416824168341684416854168641687416884168941690416914169241693416944169541696416974169841699417004170141702417034170441705417064170741708417094171041711417124171341714417154171641717417184171941720417214172241723417244172541726417274172841729417304173141732417334173441735417364173741738417394174041741417424174341744417454174641747417484174941750417514175241753417544175541756417574175841759417604176141762417634176441765417664176741768417694177041771417724177341774417754177641777417784177941780417814178241783417844178541786417874178841789417904179141792417934179441795417964179741798417994180041801418024180341804418054180641807418084180941810418114181241813418144181541816418174181841819418204182141822418234182441825418264182741828418294183041831418324183341834418354183641837418384183941840418414184241843418444184541846418474184841849418504185141852418534185441855418564185741858418594186041861418624186341864418654186641867418684186941870418714187241873418744187541876418774187841879418804188141882418834188441885418864188741888418894189041891418924189341894418954189641897418984189941900419014190241903419044190541906419074190841909419104191141912419134191441915419164191741918419194192041921419224192341924419254192641927419284192941930419314193241933419344193541936419374193841939419404194141942419434194441945419464194741948419494195041951419524195341954419554195641957419584195941960419614196241963419644196541966419674196841969419704197141972419734197441975419764197741978419794198041981419824198341984419854198641987419884198941990419914199241993419944199541996419974199841999420004200142002420034200442005420064200742008420094201042011420124201342014420154201642017420184201942020420214202242023420244202542026420274202842029420304203142032420334203442035420364203742038420394204042041420424204342044420454204642047420484204942050420514205242053420544205542056420574205842059420604206142062420634206442065420664206742068420694207042071420724207342074420754207642077420784207942080420814208242083420844208542086420874208842089420904209142092420934209442095420964209742098420994210042101421024210342104421054210642107421084210942110421114211242113421144211542116421174211842119421204212142122421234212442125421264212742128421294213042131421324213342134421354213642137421384213942140421414214242143421444214542146421474214842149421504215142152421534215442155421564215742158421594216042161421624216342164421654216642167421684216942170421714217242173421744217542176421774217842179421804218142182421834218442185421864218742188421894219042191421924219342194421954219642197421984219942200422014220242203422044220542206422074220842209422104221142212422134221442215422164221742218422194222042221422224222342224422254222642227422284222942230422314223242233422344223542236422374223842239422404224142242422434224442245422464224742248422494225042251422524225342254422554225642257422584225942260422614226242263422644226542266422674226842269422704227142272422734227442275422764227742278422794228042281422824228342284422854228642287422884228942290422914229242293422944229542296422974229842299423004230142302423034230442305423064230742308423094231042311423124231342314423154231642317423184231942320423214232242323423244232542326423274232842329423304233142332423334233442335423364233742338423394234042341423424234342344423454234642347423484234942350423514235242353423544235542356423574235842359423604236142362423634236442365423664236742368423694237042371423724237342374423754237642377423784237942380423814238242383423844238542386423874238842389423904239142392423934239442395423964239742398423994240042401424024240342404424054240642407424084240942410424114241242413424144241542416424174241842419424204242142422424234242442425424264242742428424294243042431424324243342434424354243642437424384243942440424414244242443424444244542446424474244842449424504245142452424534245442455424564245742458424594246042461424624246342464424654246642467424684246942470424714247242473424744247542476424774247842479424804248142482424834248442485424864248742488424894249042491424924249342494424954249642497424984249942500425014250242503425044250542506425074250842509425104251142512425134251442515425164251742518425194252042521425224252342524425254252642527425284252942530425314253242533425344253542536425374253842539425404254142542425434254442545425464254742548425494255042551425524255342554425554255642557425584255942560425614256242563425644256542566425674256842569425704257142572425734257442575425764257742578425794258042581425824258342584425854258642587425884258942590425914259242593425944259542596425974259842599426004260142602426034260442605426064260742608426094261042611426124261342614426154261642617426184261942620426214262242623426244262542626426274262842629426304263142632426334263442635426364263742638426394264042641426424264342644426454264642647426484264942650426514265242653426544265542656426574265842659426604266142662426634266442665426664266742668426694267042671426724267342674426754267642677426784267942680426814268242683426844268542686426874268842689426904269142692426934269442695426964269742698426994270042701427024270342704427054270642707427084270942710427114271242713427144271542716427174271842719427204272142722427234272442725427264272742728427294273042731427324273342734427354273642737427384273942740427414274242743427444274542746427474274842749427504275142752427534275442755427564275742758427594276042761427624276342764427654276642767427684276942770427714277242773427744277542776427774277842779427804278142782427834278442785427864278742788427894279042791427924279342794427954279642797427984279942800428014280242803428044280542806428074280842809428104281142812428134281442815428164281742818428194282042821428224282342824428254282642827428284282942830428314283242833428344283542836428374283842839428404284142842428434284442845428464284742848428494285042851428524285342854428554285642857428584285942860428614286242863428644286542866428674286842869428704287142872428734287442875428764287742878428794288042881428824288342884428854288642887428884288942890428914289242893428944289542896428974289842899429004290142902429034290442905429064290742908429094291042911429124291342914429154291642917429184291942920429214292242923429244292542926429274292842929429304293142932429334293442935429364293742938429394294042941429424294342944429454294642947429484294942950429514295242953429544295542956429574295842959429604296142962429634296442965429664296742968429694297042971429724297342974429754297642977429784297942980429814298242983429844298542986429874298842989429904299142992429934299442995429964299742998429994300043001430024300343004430054300643007430084300943010430114301243013430144301543016430174301843019430204302143022430234302443025430264302743028430294303043031430324303343034430354303643037430384303943040430414304243043430444304543046430474304843049430504305143052430534305443055430564305743058430594306043061430624306343064430654306643067430684306943070430714307243073430744307543076430774307843079430804308143082430834308443085430864308743088430894309043091430924309343094430954309643097430984309943100431014310243103431044310543106431074310843109431104311143112431134311443115431164311743118431194312043121431224312343124431254312643127431284312943130431314313243133431344313543136431374313843139431404314143142431434314443145431464314743148431494315043151431524315343154431554315643157431584315943160431614316243163431644316543166431674316843169431704317143172431734317443175431764317743178431794318043181431824318343184431854318643187431884318943190431914319243193431944319543196431974319843199432004320143202432034320443205432064320743208432094321043211432124321343214432154321643217432184321943220432214322243223432244322543226432274322843229432304323143232432334323443235432364323743238432394324043241432424324343244432454324643247432484324943250432514325243253432544325543256432574325843259432604326143262432634326443265432664326743268432694327043271432724327343274432754327643277432784327943280432814328243283432844328543286432874328843289432904329143292432934329443295432964329743298432994330043301433024330343304433054330643307433084330943310433114331243313433144331543316433174331843319433204332143322433234332443325433264332743328433294333043331433324333343334433354333643337433384333943340433414334243343433444334543346433474334843349433504335143352433534335443355433564335743358433594336043361433624336343364433654336643367433684336943370433714337243373433744337543376433774337843379433804338143382433834338443385433864338743388433894339043391433924339343394433954339643397433984339943400434014340243403434044340543406434074340843409434104341143412434134341443415434164341743418434194342043421434224342343424434254342643427434284342943430434314343243433434344343543436434374343843439434404344143442434434344443445434464344743448434494345043451434524345343454434554345643457434584345943460434614346243463434644346543466434674346843469434704347143472434734347443475434764347743478434794348043481434824348343484434854348643487434884348943490434914349243493434944349543496434974349843499435004350143502435034350443505435064350743508435094351043511435124351343514435154351643517435184351943520435214352243523435244352543526435274352843529435304353143532435334353443535435364353743538435394354043541435424354343544435454354643547435484354943550435514355243553435544355543556435574355843559435604356143562435634356443565435664356743568435694357043571435724357343574435754357643577435784357943580435814358243583435844358543586435874358843589435904359143592435934359443595435964359743598435994360043601436024360343604436054360643607436084360943610436114361243613436144361543616436174361843619436204362143622436234362443625436264362743628436294363043631436324363343634436354363643637436384363943640436414364243643436444364543646436474364843649436504365143652436534365443655436564365743658436594366043661436624366343664436654366643667436684366943670436714367243673436744367543676436774367843679436804368143682436834368443685436864368743688436894369043691436924369343694436954369643697436984369943700437014370243703437044370543706437074370843709437104371143712437134371443715437164371743718437194372043721437224372343724437254372643727437284372943730437314373243733437344373543736437374373843739437404374143742437434374443745437464374743748437494375043751437524375343754437554375643757437584375943760437614376243763437644376543766437674376843769437704377143772437734377443775437764377743778437794378043781437824378343784437854378643787437884378943790437914379243793437944379543796437974379843799438004380143802438034380443805438064380743808438094381043811438124381343814438154381643817438184381943820438214382243823438244382543826438274382843829438304383143832438334383443835438364383743838438394384043841438424384343844438454384643847438484384943850438514385243853438544385543856438574385843859438604386143862438634386443865438664386743868438694387043871438724387343874438754387643877438784387943880438814388243883438844388543886438874388843889438904389143892438934389443895438964389743898438994390043901439024390343904439054390643907439084390943910439114391243913439144391543916439174391843919439204392143922439234392443925439264392743928439294393043931439324393343934439354393643937439384393943940439414394243943439444394543946439474394843949439504395143952439534395443955439564395743958439594396043961439624396343964439654396643967439684396943970439714397243973439744397543976439774397843979439804398143982439834398443985439864398743988439894399043991439924399343994439954399643997439984399944000440014400244003440044400544006440074400844009440104401144012440134401444015440164401744018440194402044021440224402344024440254402644027440284402944030440314403244033440344403544036440374403844039440404404144042440434404444045440464404744048440494405044051440524405344054440554405644057440584405944060440614406244063440644406544066440674406844069440704407144072440734407444075440764407744078440794408044081440824408344084440854408644087440884408944090440914409244093440944409544096440974409844099441004410144102441034410444105441064410744108441094411044111441124411344114441154411644117441184411944120441214412244123441244412544126441274412844129441304413144132441334413444135441364413744138441394414044141441424414344144441454414644147441484414944150441514415244153441544415544156441574415844159441604416144162441634416444165441664416744168441694417044171441724417344174441754417644177441784417944180441814418244183441844418544186441874418844189441904419144192441934419444195441964419744198441994420044201442024420344204442054420644207442084420944210442114421244213442144421544216442174421844219442204422144222442234422444225442264422744228442294423044231442324423344234442354423644237442384423944240442414424244243442444424544246442474424844249442504425144252442534425444255442564425744258442594426044261442624426344264442654426644267442684426944270442714427244273442744427544276442774427844279442804428144282442834428444285442864428744288442894429044291442924429344294442954429644297442984429944300443014430244303443044430544306443074430844309443104431144312443134431444315443164431744318443194432044321443224432344324443254432644327443284432944330443314433244333443344433544336443374433844339443404434144342443434434444345443464434744348443494435044351443524435344354443554435644357443584435944360443614436244363443644436544366443674436844369443704437144372443734437444375443764437744378443794438044381443824438344384443854438644387443884438944390443914439244393443944439544396443974439844399444004440144402444034440444405444064440744408444094441044411444124441344414444154441644417444184441944420444214442244423444244442544426444274442844429444304443144432444334443444435444364443744438444394444044441444424444344444444454444644447444484444944450444514445244453444544445544456444574445844459444604446144462444634446444465444664446744468444694447044471444724447344474444754447644477444784447944480444814448244483444844448544486444874448844489444904449144492444934449444495444964449744498444994450044501445024450344504445054450644507445084450944510445114451244513445144451544516445174451844519445204452144522445234452444525445264452744528445294453044531445324453344534445354453644537445384453944540445414454244543445444454544546445474454844549445504455144552445534455444555445564455744558445594456044561445624456344564445654456644567445684456944570445714457244573445744457544576445774457844579445804458144582445834458444585445864458744588445894459044591445924459344594445954459644597445984459944600446014460244603446044460544606446074460844609446104461144612446134461444615446164461744618446194462044621446224462344624446254462644627446284462944630446314463244633446344463544636446374463844639446404464144642446434464444645446464464744648446494465044651446524465344654446554465644657446584465944660446614466244663446644466544666446674466844669446704467144672446734467444675446764467744678446794468044681446824468344684446854468644687446884468944690446914469244693446944469544696446974469844699447004470144702447034470444705447064470744708447094471044711447124471344714447154471644717447184471944720447214472244723447244472544726447274472844729447304473144732447334473444735447364473744738447394474044741447424474344744447454474644747447484474944750447514475244753447544475544756447574475844759447604476144762447634476444765447664476744768447694477044771447724477344774447754477644777447784477944780447814478244783447844478544786447874478844789447904479144792447934479444795447964479744798447994480044801448024480344804448054480644807448084480944810448114481244813448144481544816448174481844819448204482144822448234482444825448264482744828448294483044831448324483344834448354483644837448384483944840448414484244843448444484544846448474484844849448504485144852448534485444855448564485744858448594486044861448624486344864448654486644867448684486944870448714487244873448744487544876448774487844879448804488144882448834488444885448864488744888448894489044891448924489344894448954489644897448984489944900449014490244903449044490544906449074490844909449104491144912449134491444915449164491744918449194492044921449224492344924449254492644927449284492944930449314493244933449344493544936449374493844939449404494144942449434494444945449464494744948449494495044951449524495344954449554495644957449584495944960449614496244963449644496544966449674496844969449704497144972449734497444975449764497744978449794498044981449824498344984449854498644987449884498944990449914499244993449944499544996449974499844999450004500145002450034500445005450064500745008450094501045011450124501345014450154501645017450184501945020450214502245023450244502545026450274502845029450304503145032450334503445035450364503745038450394504045041450424504345044450454504645047450484504945050450514505245053450544505545056450574505845059450604506145062450634506445065450664506745068450694507045071450724507345074450754507645077450784507945080450814508245083450844508545086450874508845089450904509145092450934509445095450964509745098450994510045101451024510345104451054510645107451084510945110451114511245113451144511545116451174511845119451204512145122451234512445125451264512745128451294513045131451324513345134451354513645137451384513945140451414514245143451444514545146451474514845149451504515145152451534515445155451564515745158451594516045161451624516345164451654516645167451684516945170451714517245173451744517545176451774517845179451804518145182451834518445185451864518745188451894519045191451924519345194451954519645197451984519945200452014520245203452044520545206452074520845209452104521145212452134521445215452164521745218452194522045221452224522345224452254522645227452284522945230452314523245233452344523545236452374523845239452404524145242452434524445245452464524745248452494525045251452524525345254452554525645257452584525945260452614526245263452644526545266452674526845269452704527145272452734527445275452764527745278452794528045281452824528345284452854528645287452884528945290452914529245293452944529545296452974529845299453004530145302453034530445305453064530745308453094531045311453124531345314453154531645317453184531945320453214532245323453244532545326453274532845329453304533145332453334533445335453364533745338453394534045341453424534345344453454534645347453484534945350453514535245353453544535545356453574535845359453604536145362453634536445365453664536745368453694537045371453724537345374453754537645377453784537945380453814538245383453844538545386453874538845389453904539145392453934539445395453964539745398453994540045401454024540345404454054540645407454084540945410454114541245413454144541545416454174541845419454204542145422454234542445425454264542745428454294543045431454324543345434454354543645437454384543945440454414544245443454444544545446454474544845449454504545145452454534545445455454564545745458454594546045461454624546345464454654546645467454684546945470454714547245473454744547545476454774547845479454804548145482454834548445485454864548745488454894549045491454924549345494454954549645497454984549945500455014550245503455044550545506455074550845509455104551145512455134551445515455164551745518455194552045521455224552345524455254552645527455284552945530455314553245533455344553545536455374553845539455404554145542455434554445545455464554745548455494555045551455524555345554455554555645557455584555945560455614556245563455644556545566455674556845569455704557145572455734557445575455764557745578455794558045581455824558345584455854558645587455884558945590455914559245593455944559545596455974559845599456004560145602456034560445605456064560745608456094561045611456124561345614456154561645617456184561945620456214562245623456244562545626456274562845629456304563145632456334563445635456364563745638456394564045641456424564345644456454564645647456484564945650456514565245653456544565545656456574565845659456604566145662456634566445665456664566745668456694567045671456724567345674456754567645677456784567945680456814568245683456844568545686456874568845689456904569145692456934569445695456964569745698456994570045701457024570345704457054570645707457084570945710457114571245713457144571545716457174571845719457204572145722457234572445725457264572745728457294573045731457324573345734457354573645737457384573945740457414574245743457444574545746457474574845749457504575145752457534575445755457564575745758457594576045761457624576345764457654576645767457684576945770457714577245773457744577545776457774577845779457804578145782457834578445785457864578745788457894579045791457924579345794457954579645797457984579945800458014580245803458044580545806458074580845809458104581145812458134581445815458164581745818458194582045821458224582345824458254582645827458284582945830458314583245833458344583545836458374583845839458404584145842458434584445845458464584745848458494585045851458524585345854458554585645857458584585945860458614586245863458644586545866458674586845869458704587145872458734587445875458764587745878458794588045881458824588345884458854588645887458884588945890458914589245893458944589545896458974589845899459004590145902459034590445905459064590745908459094591045911459124591345914459154591645917459184591945920459214592245923459244592545926459274592845929459304593145932459334593445935459364593745938459394594045941459424594345944459454594645947459484594945950459514595245953459544595545956459574595845959459604596145962459634596445965459664596745968459694597045971459724597345974459754597645977459784597945980459814598245983459844598545986459874598845989459904599145992459934599445995459964599745998459994600046001460024600346004460054600646007460084600946010460114601246013460144601546016460174601846019460204602146022460234602446025460264602746028460294603046031460324603346034460354603646037460384603946040460414604246043460444604546046460474604846049460504605146052460534605446055460564605746058460594606046061460624606346064460654606646067460684606946070460714607246073460744607546076460774607846079460804608146082460834608446085460864608746088460894609046091460924609346094460954609646097460984609946100461014610246103461044610546106461074610846109461104611146112461134611446115461164611746118461194612046121461224612346124461254612646127461284612946130461314613246133461344613546136461374613846139461404614146142461434614446145461464614746148461494615046151461524615346154461554615646157461584615946160461614616246163461644616546166461674616846169461704617146172461734617446175461764617746178461794618046181461824618346184461854618646187461884618946190461914619246193461944619546196461974619846199462004620146202462034620446205462064620746208462094621046211462124621346214462154621646217462184621946220462214622246223462244622546226462274622846229462304623146232462334623446235462364623746238462394624046241462424624346244462454624646247462484624946250462514625246253462544625546256462574625846259462604626146262462634626446265462664626746268462694627046271462724627346274462754627646277462784627946280462814628246283462844628546286462874628846289462904629146292462934629446295462964629746298462994630046301463024630346304463054630646307463084630946310463114631246313463144631546316463174631846319463204632146322463234632446325463264632746328463294633046331463324633346334463354633646337463384633946340463414634246343463444634546346463474634846349463504635146352463534635446355463564635746358463594636046361463624636346364463654636646367463684636946370463714637246373463744637546376463774637846379463804638146382463834638446385463864638746388463894639046391463924639346394463954639646397463984639946400464014640246403464044640546406464074640846409464104641146412464134641446415464164641746418464194642046421464224642346424464254642646427464284642946430464314643246433464344643546436464374643846439464404644146442464434644446445464464644746448464494645046451464524645346454464554645646457464584645946460464614646246463464644646546466464674646846469464704647146472464734647446475464764647746478464794648046481464824648346484464854648646487464884648946490464914649246493464944649546496464974649846499465004650146502465034650446505465064650746508465094651046511465124651346514465154651646517465184651946520465214652246523465244652546526465274652846529465304653146532465334653446535465364653746538465394654046541465424654346544465454654646547465484654946550465514655246553465544655546556465574655846559465604656146562465634656446565465664656746568465694657046571465724657346574465754657646577465784657946580465814658246583465844658546586465874658846589465904659146592465934659446595465964659746598465994660046601466024660346604466054660646607466084660946610466114661246613466144661546616466174661846619466204662146622466234662446625466264662746628466294663046631466324663346634466354663646637466384663946640466414664246643466444664546646466474664846649466504665146652466534665446655466564665746658466594666046661466624666346664466654666646667466684666946670466714667246673466744667546676466774667846679466804668146682466834668446685466864668746688466894669046691466924669346694466954669646697466984669946700467014670246703467044670546706467074670846709467104671146712467134671446715467164671746718467194672046721467224672346724467254672646727467284672946730467314673246733467344673546736467374673846739467404674146742467434674446745467464674746748467494675046751467524675346754467554675646757467584675946760467614676246763467644676546766467674676846769467704677146772467734677446775467764677746778467794678046781467824678346784467854678646787467884678946790467914679246793467944679546796467974679846799468004680146802468034680446805468064680746808468094681046811468124681346814468154681646817468184681946820468214682246823468244682546826468274682846829468304683146832468334683446835468364683746838468394684046841468424684346844468454684646847468484684946850468514685246853468544685546856468574685846859468604686146862468634686446865468664686746868468694687046871468724687346874468754687646877468784687946880468814688246883468844688546886468874688846889468904689146892468934689446895468964689746898468994690046901469024690346904469054690646907469084690946910469114691246913469144691546916469174691846919469204692146922469234692446925469264692746928469294693046931469324693346934469354693646937469384693946940469414694246943469444694546946469474694846949469504695146952469534695446955469564695746958469594696046961469624696346964469654696646967469684696946970469714697246973469744697546976469774697846979469804698146982469834698446985469864698746988469894699046991469924699346994469954699646997469984699947000470014700247003470044700547006470074700847009470104701147012470134701447015470164701747018470194702047021470224702347024470254702647027470284702947030470314703247033470344703547036470374703847039470404704147042470434704447045470464704747048470494705047051470524705347054470554705647057470584705947060470614706247063470644706547066470674706847069470704707147072470734707447075470764707747078470794708047081470824708347084470854708647087470884708947090470914709247093470944709547096470974709847099471004710147102471034710447105471064710747108471094711047111471124711347114471154711647117471184711947120471214712247123471244712547126471274712847129471304713147132471334713447135471364713747138471394714047141471424714347144471454714647147471484714947150471514715247153471544715547156471574715847159471604716147162471634716447165471664716747168471694717047171471724717347174471754717647177471784717947180471814718247183471844718547186471874718847189471904719147192471934719447195471964719747198471994720047201472024720347204472054720647207472084720947210472114721247213472144721547216472174721847219472204722147222472234722447225472264722747228472294723047231472324723347234472354723647237472384723947240472414724247243472444724547246472474724847249472504725147252472534725447255472564725747258472594726047261472624726347264472654726647267472684726947270472714727247273472744727547276472774727847279472804728147282472834728447285472864728747288472894729047291472924729347294472954729647297472984729947300473014730247303473044730547306473074730847309473104731147312473134731447315473164731747318473194732047321473224732347324473254732647327473284732947330473314733247333473344733547336473374733847339473404734147342473434734447345473464734747348473494735047351473524735347354473554735647357473584735947360473614736247363473644736547366473674736847369473704737147372473734737447375473764737747378473794738047381473824738347384473854738647387473884738947390473914739247393473944739547396473974739847399474004740147402474034740447405474064740747408474094741047411474124741347414474154741647417474184741947420474214742247423474244742547426474274742847429474304743147432474334743447435474364743747438474394744047441474424744347444474454744647447474484744947450474514745247453474544745547456474574745847459474604746147462474634746447465474664746747468474694747047471474724747347474474754747647477474784747947480474814748247483474844748547486474874748847489474904749147492474934749447495474964749747498474994750047501475024750347504475054750647507475084750947510475114751247513475144751547516475174751847519475204752147522475234752447525475264752747528475294753047531475324753347534475354753647537475384753947540475414754247543475444754547546475474754847549475504755147552475534755447555475564755747558475594756047561475624756347564475654756647567475684756947570475714757247573475744757547576475774757847579475804758147582475834758447585475864758747588475894759047591475924759347594475954759647597475984759947600476014760247603476044760547606476074760847609476104761147612476134761447615476164761747618476194762047621476224762347624476254762647627476284762947630476314763247633476344763547636476374763847639476404764147642476434764447645476464764747648476494765047651476524765347654476554765647657476584765947660476614766247663476644766547666476674766847669476704767147672476734767447675476764767747678476794768047681476824768347684476854768647687476884768947690476914769247693476944769547696476974769847699477004770147702477034770447705477064770747708477094771047711477124771347714477154771647717477184771947720477214772247723477244772547726477274772847729477304773147732477334773447735477364773747738477394774047741477424774347744477454774647747477484774947750477514775247753477544775547756477574775847759477604776147762477634776447765477664776747768477694777047771477724777347774477754777647777477784777947780477814778247783477844778547786477874778847789477904779147792477934779447795477964779747798477994780047801478024780347804478054780647807478084780947810478114781247813478144781547816478174781847819478204782147822478234782447825478264782747828478294783047831478324783347834478354783647837478384783947840478414784247843478444784547846478474784847849478504785147852478534785447855478564785747858478594786047861478624786347864478654786647867478684786947870478714787247873478744787547876478774787847879478804788147882478834788447885478864788747888478894789047891478924789347894478954789647897478984789947900479014790247903479044790547906479074790847909479104791147912479134791447915479164791747918479194792047921479224792347924479254792647927479284792947930479314793247933479344793547936479374793847939479404794147942479434794447945479464794747948479494795047951479524795347954479554795647957479584795947960479614796247963479644796547966479674796847969479704797147972479734797447975479764797747978479794798047981479824798347984479854798647987479884798947990479914799247993479944799547996479974799847999480004800148002480034800448005480064800748008480094801048011480124801348014480154801648017480184801948020480214802248023480244802548026480274802848029480304803148032480334803448035480364803748038480394804048041480424804348044480454804648047480484804948050480514805248053480544805548056480574805848059480604806148062480634806448065480664806748068480694807048071480724807348074480754807648077480784807948080480814808248083480844808548086480874808848089480904809148092480934809448095480964809748098480994810048101481024810348104481054810648107481084810948110481114811248113481144811548116481174811848119481204812148122481234812448125481264812748128481294813048131481324813348134481354813648137481384813948140481414814248143481444814548146481474814848149481504815148152481534815448155481564815748158481594816048161481624816348164481654816648167481684816948170481714817248173481744817548176481774817848179481804818148182481834818448185481864818748188481894819048191481924819348194481954819648197481984819948200482014820248203482044820548206482074820848209482104821148212482134821448215482164821748218482194822048221482224822348224482254822648227482284822948230482314823248233482344823548236482374823848239482404824148242482434824448245482464824748248482494825048251482524825348254482554825648257482584825948260482614826248263482644826548266482674826848269482704827148272482734827448275482764827748278482794828048281482824828348284482854828648287482884828948290482914829248293482944829548296482974829848299483004830148302483034830448305483064830748308483094831048311483124831348314483154831648317483184831948320483214832248323483244832548326483274832848329483304833148332483334833448335483364833748338483394834048341483424834348344483454834648347483484834948350483514835248353483544835548356483574835848359483604836148362483634836448365483664836748368483694837048371483724837348374483754837648377483784837948380483814838248383483844838548386483874838848389483904839148392483934839448395483964839748398483994840048401484024840348404484054840648407484084840948410484114841248413484144841548416484174841848419484204842148422484234842448425484264842748428484294843048431484324843348434484354843648437484384843948440484414844248443484444844548446484474844848449484504845148452484534845448455484564845748458484594846048461484624846348464484654846648467484684846948470484714847248473484744847548476484774847848479484804848148482484834848448485484864848748488484894849048491484924849348494484954849648497484984849948500485014850248503485044850548506485074850848509485104851148512485134851448515485164851748518485194852048521485224852348524485254852648527485284852948530485314853248533485344853548536485374853848539485404854148542485434854448545485464854748548485494855048551485524855348554485554855648557485584855948560485614856248563485644856548566485674856848569485704857148572485734857448575485764857748578485794858048581485824858348584485854858648587485884858948590485914859248593485944859548596485974859848599486004860148602486034860448605486064860748608486094861048611486124861348614486154861648617486184861948620486214862248623486244862548626486274862848629486304863148632486334863448635486364863748638486394864048641486424864348644486454864648647486484864948650486514865248653486544865548656486574865848659486604866148662486634866448665486664866748668486694867048671486724867348674486754867648677486784867948680486814868248683486844868548686486874868848689486904869148692486934869448695486964869748698486994870048701487024870348704487054870648707487084870948710487114871248713487144871548716487174871848719487204872148722487234872448725487264872748728487294873048731487324873348734487354873648737487384873948740487414874248743487444874548746487474874848749487504875148752487534875448755487564875748758487594876048761487624876348764487654876648767487684876948770487714877248773487744877548776487774877848779487804878148782487834878448785487864878748788487894879048791487924879348794487954879648797487984879948800488014880248803488044880548806488074880848809488104881148812488134881448815488164881748818488194882048821488224882348824488254882648827488284882948830488314883248833488344883548836488374883848839488404884148842488434884448845488464884748848488494885048851488524885348854488554885648857488584885948860488614886248863488644886548866488674886848869488704887148872488734887448875488764887748878488794888048881488824888348884488854888648887488884888948890488914889248893488944889548896488974889848899489004890148902489034890448905489064890748908489094891048911489124891348914489154891648917489184891948920489214892248923489244892548926489274892848929489304893148932489334893448935489364893748938489394894048941489424894348944489454894648947489484894948950489514895248953489544895548956489574895848959489604896148962489634896448965489664896748968489694897048971489724897348974489754897648977489784897948980489814898248983489844898548986489874898848989489904899148992489934899448995489964899748998489994900049001490024900349004490054900649007490084900949010490114901249013490144901549016490174901849019490204902149022490234902449025490264902749028490294903049031490324903349034490354903649037490384903949040490414904249043490444904549046490474904849049490504905149052490534905449055490564905749058490594906049061490624906349064490654906649067490684906949070490714907249073490744907549076490774907849079490804908149082490834908449085490864908749088490894909049091490924909349094490954909649097490984909949100491014910249103491044910549106491074910849109491104911149112491134911449115491164911749118491194912049121491224912349124491254912649127491284912949130491314913249133491344913549136491374913849139491404914149142491434914449145491464914749148491494915049151491524915349154491554915649157491584915949160491614916249163491644916549166491674916849169491704917149172491734917449175491764917749178491794918049181491824918349184491854918649187491884918949190491914919249193491944919549196491974919849199492004920149202492034920449205492064920749208492094921049211492124921349214492154921649217492184921949220492214922249223492244922549226492274922849229492304923149232492334923449235492364923749238492394924049241492424924349244492454924649247492484924949250492514925249253492544925549256492574925849259492604926149262492634926449265492664926749268492694927049271492724927349274492754927649277492784927949280492814928249283492844928549286492874928849289492904929149292492934929449295492964929749298492994930049301493024930349304493054930649307493084930949310493114931249313493144931549316493174931849319493204932149322493234932449325493264932749328493294933049331493324933349334493354933649337493384933949340493414934249343493444934549346493474934849349493504935149352493534935449355493564935749358493594936049361493624936349364493654936649367493684936949370493714937249373493744937549376493774937849379493804938149382493834938449385493864938749388493894939049391493924939349394493954939649397493984939949400494014940249403494044940549406494074940849409494104941149412494134941449415494164941749418494194942049421494224942349424494254942649427494284942949430494314943249433494344943549436494374943849439494404944149442494434944449445494464944749448494494945049451494524945349454494554945649457494584945949460494614946249463494644946549466494674946849469494704947149472494734947449475494764947749478494794948049481494824948349484494854948649487494884948949490494914949249493494944949549496494974949849499495004950149502495034950449505495064950749508495094951049511495124951349514495154951649517495184951949520495214952249523495244952549526495274952849529495304953149532495334953449535495364953749538495394954049541495424954349544495454954649547495484954949550495514955249553495544955549556495574955849559495604956149562495634956449565495664956749568495694957049571495724957349574495754957649577495784957949580495814958249583495844958549586495874958849589495904959149592495934959449595495964959749598495994960049601496024960349604496054960649607496084960949610496114961249613496144961549616496174961849619496204962149622496234962449625496264962749628496294963049631496324963349634496354963649637496384963949640496414964249643496444964549646496474964849649496504965149652496534965449655496564965749658496594966049661496624966349664496654966649667496684966949670496714967249673496744967549676496774967849679496804968149682496834968449685496864968749688496894969049691496924969349694496954969649697496984969949700497014970249703497044970549706497074970849709497104971149712497134971449715497164971749718497194972049721497224972349724497254972649727497284972949730497314973249733497344973549736497374973849739497404974149742497434974449745497464974749748497494975049751497524975349754497554975649757497584975949760497614976249763497644976549766497674976849769497704977149772497734977449775497764977749778497794978049781497824978349784497854978649787497884978949790497914979249793497944979549796497974979849799498004980149802498034980449805498064980749808498094981049811498124981349814498154981649817498184981949820498214982249823498244982549826498274982849829498304983149832498334983449835498364983749838498394984049841498424984349844498454984649847498484984949850498514985249853498544985549856498574985849859498604986149862498634986449865498664986749868498694987049871498724987349874498754987649877498784987949880498814988249883498844988549886498874988849889498904989149892498934989449895498964989749898498994990049901499024990349904499054990649907499084990949910499114991249913499144991549916499174991849919499204992149922499234992449925499264992749928499294993049931499324993349934499354993649937499384993949940499414994249943499444994549946499474994849949499504995149952499534995449955499564995749958499594996049961499624996349964499654996649967499684996949970499714997249973499744997549976499774997849979499804998149982499834998449985499864998749988499894999049991499924999349994499954999649997499984999950000500015000250003500045000550006500075000850009500105001150012500135001450015500165001750018500195002050021500225002350024500255002650027500285002950030500315003250033500345003550036500375003850039500405004150042500435004450045500465004750048500495005050051500525005350054500555005650057500585005950060500615006250063500645006550066500675006850069500705007150072500735007450075500765007750078500795008050081500825008350084500855008650087500885008950090500915009250093500945009550096500975009850099501005010150102501035010450105501065010750108501095011050111501125011350114501155011650117501185011950120501215012250123501245012550126501275012850129501305013150132501335013450135501365013750138501395014050141501425014350144501455014650147501485014950150501515015250153501545015550156501575015850159501605016150162501635016450165501665016750168501695017050171501725017350174501755017650177501785017950180501815018250183501845018550186501875018850189501905019150192501935019450195501965019750198501995020050201502025020350204502055020650207502085020950210502115021250213502145021550216502175021850219502205022150222502235022450225502265022750228502295023050231502325023350234502355023650237502385023950240502415024250243502445024550246502475024850249502505025150252502535025450255502565025750258502595026050261502625026350264502655026650267502685026950270502715027250273502745027550276502775027850279502805028150282502835028450285502865028750288502895029050291502925029350294502955029650297502985029950300503015030250303503045030550306503075030850309503105031150312503135031450315503165031750318503195032050321503225032350324503255032650327503285032950330503315033250333503345033550336503375033850339503405034150342503435034450345503465034750348503495035050351503525035350354503555035650357503585035950360503615036250363503645036550366503675036850369503705037150372503735037450375503765037750378503795038050381503825038350384503855038650387503885038950390503915039250393503945039550396503975039850399504005040150402504035040450405504065040750408504095041050411504125041350414504155041650417504185041950420504215042250423504245042550426504275042850429504305043150432504335043450435504365043750438504395044050441504425044350444504455044650447504485044950450504515045250453504545045550456504575045850459504605046150462504635046450465504665046750468504695047050471504725047350474504755047650477504785047950480504815048250483504845048550486504875048850489504905049150492504935049450495504965049750498504995050050501505025050350504505055050650507505085050950510505115051250513505145051550516505175051850519505205052150522505235052450525505265052750528505295053050531505325053350534505355053650537505385053950540505415054250543505445054550546505475054850549505505055150552505535055450555505565055750558505595056050561505625056350564505655056650567505685056950570505715057250573505745057550576505775057850579505805058150582505835058450585505865058750588505895059050591505925059350594505955059650597505985059950600506015060250603506045060550606506075060850609506105061150612506135061450615506165061750618506195062050621506225062350624506255062650627506285062950630506315063250633506345063550636506375063850639506405064150642506435064450645506465064750648506495065050651506525065350654506555065650657506585065950660506615066250663506645066550666506675066850669506705067150672506735067450675506765067750678506795068050681506825068350684506855068650687506885068950690506915069250693506945069550696506975069850699507005070150702507035070450705507065070750708507095071050711507125071350714507155071650717507185071950720507215072250723507245072550726507275072850729507305073150732507335073450735507365073750738507395074050741507425074350744507455074650747507485074950750507515075250753507545075550756507575075850759507605076150762507635076450765507665076750768507695077050771507725077350774507755077650777507785077950780507815078250783507845078550786507875078850789507905079150792507935079450795507965079750798507995080050801508025080350804508055080650807508085080950810508115081250813508145081550816508175081850819508205082150822508235082450825508265082750828508295083050831508325083350834508355083650837508385083950840508415084250843508445084550846508475084850849508505085150852508535085450855508565085750858508595086050861508625086350864508655086650867508685086950870508715087250873508745087550876508775087850879508805088150882508835088450885508865088750888508895089050891508925089350894508955089650897508985089950900509015090250903509045090550906509075090850909509105091150912509135091450915509165091750918509195092050921509225092350924509255092650927509285092950930509315093250933509345093550936509375093850939509405094150942509435094450945509465094750948509495095050951509525095350954509555095650957509585095950960509615096250963509645096550966509675096850969509705097150972509735097450975509765097750978509795098050981509825098350984509855098650987509885098950990509915099250993509945099550996509975099850999510005100151002510035100451005510065100751008510095101051011510125101351014510155101651017510185101951020510215102251023510245102551026510275102851029510305103151032510335103451035510365103751038510395104051041510425104351044510455104651047510485104951050510515105251053510545105551056510575105851059510605106151062510635106451065510665106751068510695107051071510725107351074510755107651077510785107951080510815108251083510845108551086510875108851089510905109151092510935109451095510965109751098510995110051101511025110351104511055110651107511085110951110511115111251113511145111551116511175111851119511205112151122511235112451125511265112751128511295113051131511325113351134511355113651137511385113951140511415114251143511445114551146511475114851149511505115151152511535115451155511565115751158511595116051161511625116351164511655116651167511685116951170511715117251173511745117551176511775117851179511805118151182511835118451185511865118751188511895119051191511925119351194511955119651197511985119951200512015120251203512045120551206512075120851209512105121151212512135121451215512165121751218512195122051221512225122351224512255122651227512285122951230512315123251233512345123551236512375123851239512405124151242512435124451245512465124751248512495125051251512525125351254512555125651257512585125951260512615126251263512645126551266512675126851269512705127151272512735127451275512765127751278512795128051281512825128351284512855128651287512885128951290512915129251293512945129551296512975129851299513005130151302513035130451305513065130751308513095131051311513125131351314513155131651317513185131951320513215132251323513245132551326513275132851329513305133151332513335133451335513365133751338513395134051341513425134351344513455134651347513485134951350513515135251353513545135551356513575135851359513605136151362513635136451365513665136751368513695137051371513725137351374513755137651377513785137951380513815138251383513845138551386513875138851389513905139151392513935139451395513965139751398513995140051401514025140351404514055140651407514085140951410514115141251413514145141551416514175141851419514205142151422514235142451425514265142751428514295143051431514325143351434514355143651437514385143951440514415144251443514445144551446514475144851449514505145151452514535145451455514565145751458514595146051461514625146351464514655146651467514685146951470514715147251473514745147551476514775147851479514805148151482514835148451485514865148751488514895149051491514925149351494514955149651497514985149951500515015150251503515045150551506515075150851509515105151151512515135151451515515165151751518515195152051521515225152351524515255152651527515285152951530515315153251533515345153551536515375153851539515405154151542515435154451545515465154751548515495155051551515525155351554515555155651557515585155951560515615156251563515645156551566515675156851569515705157151572515735157451575515765157751578515795158051581515825158351584515855158651587515885158951590515915159251593515945159551596515975159851599516005160151602516035160451605516065160751608516095161051611516125161351614516155161651617516185161951620516215162251623516245162551626516275162851629516305163151632516335163451635516365163751638516395164051641516425164351644516455164651647516485164951650516515165251653516545165551656516575165851659516605166151662516635166451665516665166751668516695167051671516725167351674516755167651677516785167951680516815168251683516845168551686516875168851689516905169151692516935169451695516965169751698516995170051701517025170351704517055170651707517085170951710517115171251713517145171551716517175171851719517205172151722517235172451725517265172751728517295173051731517325173351734517355173651737517385173951740517415174251743517445174551746517475174851749517505175151752517535175451755517565175751758517595176051761517625176351764517655176651767517685176951770517715177251773517745177551776517775177851779517805178151782517835178451785517865178751788517895179051791517925179351794517955179651797517985179951800518015180251803518045180551806518075180851809518105181151812518135181451815518165181751818518195182051821518225182351824518255182651827518285182951830518315183251833518345183551836518375183851839518405184151842518435184451845518465184751848518495185051851518525185351854518555185651857518585185951860518615186251863518645186551866518675186851869518705187151872518735187451875518765187751878518795188051881518825188351884518855188651887518885188951890518915189251893518945189551896518975189851899519005190151902519035190451905519065190751908519095191051911519125191351914519155191651917519185191951920519215192251923519245192551926519275192851929519305193151932519335193451935519365193751938519395194051941519425194351944519455194651947519485194951950519515195251953519545195551956519575195851959519605196151962519635196451965519665196751968519695197051971519725197351974519755197651977519785197951980519815198251983519845198551986519875198851989519905199151992519935199451995519965199751998519995200052001520025200352004520055200652007520085200952010520115201252013520145201552016520175201852019520205202152022520235202452025520265202752028520295203052031520325203352034520355203652037520385203952040520415204252043520445204552046520475204852049520505205152052520535205452055520565205752058520595206052061520625206352064520655206652067520685206952070520715207252073520745207552076520775207852079520805208152082520835208452085520865208752088520895209052091520925209352094520955209652097520985209952100521015210252103521045210552106521075210852109521105211152112521135211452115521165211752118521195212052121521225212352124521255212652127521285212952130521315213252133521345213552136521375213852139521405214152142521435214452145521465214752148521495215052151521525215352154521555215652157521585215952160521615216252163521645216552166521675216852169521705217152172521735217452175521765217752178521795218052181521825218352184521855218652187521885218952190521915219252193521945219552196521975219852199522005220152202522035220452205522065220752208522095221052211522125221352214522155221652217522185221952220522215222252223522245222552226522275222852229522305223152232522335223452235522365223752238522395224052241522425224352244522455224652247522485224952250522515225252253522545225552256522575225852259522605226152262522635226452265522665226752268522695227052271522725227352274522755227652277522785227952280522815228252283522845228552286522875228852289522905229152292522935229452295522965229752298522995230052301523025230352304523055230652307523085230952310523115231252313523145231552316523175231852319523205232152322523235232452325523265232752328523295233052331523325233352334523355233652337523385233952340523415234252343523445234552346523475234852349523505235152352523535235452355523565235752358523595236052361523625236352364523655236652367523685236952370523715237252373523745237552376523775237852379523805238152382523835238452385523865238752388523895239052391523925239352394523955239652397523985239952400524015240252403524045240552406524075240852409524105241152412524135241452415524165241752418524195242052421524225242352424524255242652427524285242952430524315243252433524345243552436524375243852439524405244152442524435244452445524465244752448524495245052451524525245352454524555245652457524585245952460524615246252463524645246552466524675246852469524705247152472524735247452475524765247752478524795248052481524825248352484524855248652487524885248952490524915249252493524945249552496524975249852499525005250152502525035250452505525065250752508525095251052511525125251352514525155251652517525185251952520525215252252523525245252552526525275252852529525305253152532525335253452535525365253752538525395254052541525425254352544525455254652547525485254952550525515255252553525545255552556525575255852559525605256152562525635256452565525665256752568525695257052571525725257352574525755257652577525785257952580525815258252583525845258552586525875258852589525905259152592525935259452595525965259752598525995260052601526025260352604526055260652607526085260952610526115261252613526145261552616526175261852619526205262152622526235262452625526265262752628526295263052631526325263352634526355263652637526385263952640526415264252643526445264552646526475264852649526505265152652526535265452655526565265752658526595266052661526625266352664526655266652667526685266952670526715267252673526745267552676526775267852679526805268152682526835268452685526865268752688526895269052691526925269352694526955269652697526985269952700527015270252703527045270552706527075270852709527105271152712527135271452715527165271752718527195272052721527225272352724527255272652727527285272952730527315273252733527345273552736527375273852739527405274152742527435274452745527465274752748527495275052751527525275352754527555275652757527585275952760527615276252763527645276552766527675276852769527705277152772527735277452775527765277752778527795278052781527825278352784527855278652787527885278952790527915279252793527945279552796527975279852799528005280152802528035280452805528065280752808528095281052811528125281352814528155281652817528185281952820528215282252823528245282552826528275282852829528305283152832528335283452835528365283752838528395284052841528425284352844528455284652847528485284952850528515285252853528545285552856528575285852859528605286152862528635286452865528665286752868528695287052871528725287352874528755287652877528785287952880528815288252883528845288552886528875288852889528905289152892528935289452895528965289752898528995290052901529025290352904529055290652907529085290952910529115291252913529145291552916529175291852919529205292152922529235292452925529265292752928529295293052931529325293352934529355293652937529385293952940529415294252943529445294552946529475294852949529505295152952529535295452955529565295752958529595296052961529625296352964529655296652967529685296952970529715297252973529745297552976529775297852979529805298152982529835298452985529865298752988529895299052991529925299352994529955299652997529985299953000530015300253003530045300553006530075300853009530105301153012530135301453015530165301753018530195302053021530225302353024530255302653027530285302953030530315303253033530345303553036530375303853039530405304153042530435304453045530465304753048530495305053051530525305353054530555305653057530585305953060530615306253063530645306553066530675306853069530705307153072530735307453075530765307753078530795308053081530825308353084530855308653087530885308953090530915309253093530945309553096530975309853099531005310153102531035310453105531065310753108531095311053111531125311353114531155311653117531185311953120531215312253123531245312553126531275312853129531305313153132531335313453135531365313753138531395314053141531425314353144531455314653147531485314953150531515315253153531545315553156531575315853159531605316153162531635316453165531665316753168531695317053171531725317353174531755317653177531785317953180531815318253183531845318553186531875318853189531905319153192531935319453195531965319753198531995320053201532025320353204532055320653207532085320953210532115321253213532145321553216532175321853219532205322153222532235322453225532265322753228532295323053231532325323353234532355323653237532385323953240532415324253243532445324553246532475324853249532505325153252532535325453255532565325753258532595326053261532625326353264532655326653267532685326953270532715327253273532745327553276532775327853279532805328153282532835328453285532865328753288532895329053291532925329353294532955329653297532985329953300533015330253303533045330553306533075330853309533105331153312533135331453315533165331753318533195332053321533225332353324533255332653327533285332953330533315333253333533345333553336533375333853339533405334153342533435334453345533465334753348533495335053351533525335353354533555335653357533585335953360533615336253363533645336553366533675336853369533705337153372533735337453375533765337753378533795338053381533825338353384533855338653387533885338953390533915339253393533945339553396533975339853399534005340153402534035340453405534065340753408534095341053411534125341353414534155341653417534185341953420534215342253423534245342553426534275342853429534305343153432534335343453435534365343753438534395344053441534425344353444534455344653447534485344953450534515345253453534545345553456534575345853459534605346153462534635346453465534665346753468534695347053471534725347353474534755347653477534785347953480534815348253483534845348553486534875348853489534905349153492534935349453495534965349753498534995350053501535025350353504535055350653507535085350953510535115351253513535145351553516535175351853519535205352153522535235352453525535265352753528535295353053531535325353353534535355353653537535385353953540535415354253543535445354553546535475354853549535505355153552535535355453555535565355753558535595356053561535625356353564535655356653567535685356953570535715357253573535745357553576535775357853579535805358153582535835358453585535865358753588535895359053591535925359353594535955359653597535985359953600536015360253603536045360553606536075360853609536105361153612536135361453615536165361753618536195362053621536225362353624536255362653627536285362953630536315363253633536345363553636536375363853639536405364153642536435364453645536465364753648536495365053651536525365353654536555365653657536585365953660536615366253663536645366553666536675366853669536705367153672536735367453675536765367753678536795368053681536825368353684536855368653687536885368953690536915369253693536945369553696536975369853699537005370153702537035370453705537065370753708537095371053711537125371353714537155371653717537185371953720537215372253723537245372553726537275372853729537305373153732537335373453735537365373753738537395374053741537425374353744537455374653747537485374953750537515375253753537545375553756537575375853759537605376153762537635376453765537665376753768537695377053771537725377353774537755377653777537785377953780537815378253783537845378553786537875378853789537905379153792537935379453795537965379753798537995380053801538025380353804538055380653807538085380953810538115381253813538145381553816538175381853819538205382153822538235382453825538265382753828538295383053831538325383353834538355383653837538385383953840538415384253843538445384553846538475384853849538505385153852538535385453855538565385753858538595386053861538625386353864538655386653867538685386953870538715387253873538745387553876538775387853879538805388153882538835388453885538865388753888538895389053891538925389353894538955389653897538985389953900539015390253903539045390553906539075390853909539105391153912539135391453915539165391753918539195392053921539225392353924539255392653927539285392953930539315393253933539345393553936539375393853939539405394153942539435394453945539465394753948539495395053951539525395353954539555395653957539585395953960539615396253963539645396553966539675396853969539705397153972539735397453975539765397753978539795398053981539825398353984539855398653987539885398953990539915399253993539945399553996539975399853999540005400154002540035400454005540065400754008540095401054011540125401354014540155401654017540185401954020540215402254023540245402554026540275402854029540305403154032540335403454035540365403754038540395404054041540425404354044540455404654047540485404954050540515405254053540545405554056540575405854059540605406154062540635406454065540665406754068540695407054071540725407354074540755407654077540785407954080540815408254083540845408554086540875408854089540905409154092540935409454095540965409754098540995410054101541025410354104541055410654107541085410954110541115411254113541145411554116541175411854119541205412154122541235412454125541265412754128541295413054131541325413354134541355413654137541385413954140541415414254143541445414554146541475414854149541505415154152541535415454155541565415754158541595416054161541625416354164541655416654167541685416954170541715417254173541745417554176541775417854179541805418154182541835418454185541865418754188541895419054191541925419354194541955419654197541985419954200542015420254203542045420554206542075420854209542105421154212542135421454215542165421754218542195422054221542225422354224542255422654227542285422954230542315423254233542345423554236542375423854239542405424154242542435424454245542465424754248542495425054251542525425354254542555425654257542585425954260542615426254263542645426554266542675426854269542705427154272542735427454275542765427754278542795428054281542825428354284542855428654287542885428954290542915429254293542945429554296542975429854299543005430154302543035430454305543065430754308543095431054311543125431354314543155431654317543185431954320543215432254323543245432554326543275432854329543305433154332543335433454335543365433754338543395434054341543425434354344543455434654347543485434954350543515435254353543545435554356543575435854359543605436154362543635436454365543665436754368543695437054371543725437354374543755437654377543785437954380543815438254383543845438554386543875438854389543905439154392543935439454395543965439754398543995440054401544025440354404544055440654407544085440954410544115441254413544145441554416544175441854419544205442154422544235442454425544265442754428544295443054431544325443354434544355443654437544385443954440544415444254443544445444554446544475444854449544505445154452544535445454455544565445754458544595446054461544625446354464544655446654467544685446954470544715447254473544745447554476544775447854479544805448154482544835448454485544865448754488544895449054491544925449354494544955449654497544985449954500545015450254503545045450554506545075450854509545105451154512545135451454515545165451754518545195452054521545225452354524545255452654527545285452954530545315453254533545345453554536545375453854539545405454154542545435454454545545465454754548545495455054551545525455354554545555455654557545585455954560545615456254563545645456554566545675456854569545705457154572545735457454575545765457754578545795458054581545825458354584545855458654587545885458954590545915459254593545945459554596545975459854599546005460154602546035460454605546065460754608546095461054611546125461354614546155461654617546185461954620546215462254623546245462554626546275462854629546305463154632546335463454635546365463754638546395464054641546425464354644546455464654647546485464954650546515465254653546545465554656546575465854659546605466154662546635466454665546665466754668546695467054671546725467354674546755467654677546785467954680546815468254683546845468554686546875468854689546905469154692546935469454695546965469754698546995470054701547025470354704547055470654707547085470954710547115471254713547145471554716547175471854719547205472154722547235472454725547265472754728547295473054731547325473354734547355473654737547385473954740547415474254743547445474554746547475474854749547505475154752547535475454755547565475754758547595476054761547625476354764547655476654767547685476954770547715477254773547745477554776547775477854779547805478154782547835478454785547865478754788547895479054791547925479354794547955479654797547985479954800548015480254803548045480554806548075480854809548105481154812548135481454815548165481754818548195482054821548225482354824548255482654827548285482954830548315483254833548345483554836548375483854839548405484154842548435484454845548465484754848548495485054851548525485354854548555485654857548585485954860548615486254863548645486554866548675486854869548705487154872548735487454875548765487754878548795488054881548825488354884548855488654887548885488954890548915489254893548945489554896548975489854899549005490154902549035490454905549065490754908549095491054911549125491354914549155491654917549185491954920549215492254923549245492554926549275492854929549305493154932549335493454935549365493754938549395494054941549425494354944549455494654947549485494954950549515495254953549545495554956549575495854959549605496154962549635496454965549665496754968549695497054971549725497354974549755497654977549785497954980549815498254983549845498554986549875498854989549905499154992549935499454995549965499754998549995500055001550025500355004550055500655007550085500955010550115501255013550145501555016550175501855019550205502155022550235502455025550265502755028550295503055031550325503355034550355503655037550385503955040550415504255043550445504555046550475504855049550505505155052550535505455055550565505755058550595506055061550625506355064550655506655067550685506955070550715507255073550745507555076550775507855079550805508155082550835508455085550865508755088550895509055091550925509355094550955509655097550985509955100551015510255103551045510555106551075510855109551105511155112551135511455115551165511755118551195512055121551225512355124551255512655127551285512955130551315513255133551345513555136551375513855139551405514155142551435514455145551465514755148551495515055151551525515355154551555515655157551585515955160551615516255163551645516555166551675516855169551705517155172551735517455175551765517755178551795518055181551825518355184551855518655187551885518955190551915519255193551945519555196551975519855199552005520155202552035520455205552065520755208552095521055211552125521355214552155521655217552185521955220552215522255223552245522555226552275522855229552305523155232552335523455235552365523755238552395524055241552425524355244552455524655247552485524955250552515525255253552545525555256552575525855259552605526155262552635526455265552665526755268552695527055271552725527355274552755527655277552785527955280552815528255283552845528555286552875528855289552905529155292552935529455295552965529755298552995530055301553025530355304553055530655307553085530955310553115531255313553145531555316553175531855319553205532155322553235532455325553265532755328553295533055331553325533355334553355533655337553385533955340553415534255343553445534555346553475534855349553505535155352553535535455355553565535755358553595536055361553625536355364553655536655367553685536955370553715537255373553745537555376553775537855379553805538155382553835538455385553865538755388553895539055391553925539355394553955539655397553985539955400554015540255403554045540555406554075540855409554105541155412554135541455415554165541755418554195542055421554225542355424554255542655427554285542955430554315543255433554345543555436554375543855439554405544155442554435544455445554465544755448554495545055451554525545355454554555545655457554585545955460554615546255463554645546555466554675546855469554705547155472554735547455475554765547755478554795548055481554825548355484554855548655487554885548955490554915549255493554945549555496554975549855499555005550155502555035550455505555065550755508555095551055511555125551355514555155551655517555185551955520555215552255523555245552555526555275552855529555305553155532555335553455535555365553755538555395554055541555425554355544555455554655547555485554955550555515555255553555545555555556555575555855559555605556155562555635556455565555665556755568555695557055571555725557355574555755557655577555785557955580555815558255583555845558555586555875558855589555905559155592555935559455595555965559755598555995560055601556025560355604556055560655607556085560955610556115561255613556145561555616556175561855619556205562155622556235562455625556265562755628556295563055631556325563355634556355563655637556385563955640556415564255643556445564555646556475564855649556505565155652556535565455655556565565755658556595566055661556625566355664556655566655667556685566955670556715567255673556745567555676556775567855679556805568155682556835568455685556865568755688556895569055691556925569355694556955569655697556985569955700557015570255703557045570555706557075570855709557105571155712557135571455715557165571755718557195572055721557225572355724557255572655727557285572955730557315573255733557345573555736557375573855739557405574155742557435574455745557465574755748557495575055751557525575355754557555575655757557585575955760557615576255763557645576555766557675576855769557705577155772557735577455775557765577755778557795578055781557825578355784557855578655787557885578955790557915579255793557945579555796557975579855799558005580155802558035580455805558065580755808558095581055811558125581355814558155581655817558185581955820558215582255823558245582555826558275582855829558305583155832558335583455835558365583755838558395584055841558425584355844558455584655847558485584955850558515585255853558545585555856558575585855859558605586155862558635586455865558665586755868558695587055871558725587355874558755587655877558785587955880558815588255883558845588555886558875588855889558905589155892558935589455895558965589755898558995590055901559025590355904559055590655907559085590955910559115591255913559145591555916559175591855919559205592155922559235592455925559265592755928559295593055931559325593355934559355593655937559385593955940559415594255943559445594555946559475594855949559505595155952559535595455955559565595755958559595596055961559625596355964559655596655967559685596955970559715597255973559745597555976559775597855979559805598155982559835598455985559865598755988559895599055991559925599355994559955599655997559985599956000560015600256003560045600556006560075600856009560105601156012560135601456015560165601756018560195602056021560225602356024560255602656027560285602956030560315603256033560345603556036560375603856039560405604156042560435604456045560465604756048560495605056051560525605356054560555605656057560585605956060560615606256063560645606556066560675606856069560705607156072560735607456075560765607756078560795608056081560825608356084560855608656087560885608956090560915609256093560945609556096560975609856099561005610156102561035610456105561065610756108561095611056111561125611356114561155611656117561185611956120561215612256123561245612556126561275612856129561305613156132561335613456135561365613756138561395614056141561425614356144561455614656147561485614956150561515615256153561545615556156561575615856159561605616156162561635616456165561665616756168561695617056171561725617356174561755617656177561785617956180561815618256183561845618556186561875618856189561905619156192561935619456195561965619756198561995620056201562025620356204562055620656207562085620956210562115621256213562145621556216562175621856219562205622156222562235622456225562265622756228562295623056231562325623356234562355623656237562385623956240562415624256243562445624556246562475624856249562505625156252562535625456255562565625756258562595626056261562625626356264562655626656267562685626956270562715627256273562745627556276562775627856279562805628156282562835628456285562865628756288562895629056291562925629356294562955629656297562985629956300563015630256303563045630556306563075630856309563105631156312563135631456315563165631756318563195632056321563225632356324563255632656327563285632956330563315633256333563345633556336563375633856339563405634156342563435634456345563465634756348563495635056351563525635356354563555635656357563585635956360563615636256363563645636556366563675636856369563705637156372563735637456375563765637756378563795638056381563825638356384563855638656387563885638956390563915639256393563945639556396563975639856399564005640156402564035640456405564065640756408564095641056411564125641356414564155641656417564185641956420564215642256423564245642556426564275642856429564305643156432564335643456435564365643756438564395644056441564425644356444564455644656447564485644956450564515645256453564545645556456564575645856459564605646156462564635646456465564665646756468564695647056471564725647356474564755647656477564785647956480564815648256483564845648556486564875648856489564905649156492564935649456495564965649756498564995650056501565025650356504565055650656507565085650956510565115651256513565145651556516565175651856519565205652156522565235652456525565265652756528565295653056531565325653356534565355653656537565385653956540565415654256543565445654556546565475654856549565505655156552565535655456555565565655756558565595656056561565625656356564565655656656567565685656956570565715657256573565745657556576565775657856579565805658156582565835658456585565865658756588565895659056591565925659356594565955659656597565985659956600566015660256603566045660556606566075660856609566105661156612566135661456615566165661756618566195662056621566225662356624566255662656627566285662956630566315663256633566345663556636566375663856639566405664156642566435664456645566465664756648566495665056651566525665356654566555665656657566585665956660566615666256663566645666556666566675666856669566705667156672566735667456675566765667756678566795668056681566825668356684566855668656687566885668956690566915669256693566945669556696566975669856699567005670156702567035670456705567065670756708567095671056711567125671356714567155671656717567185671956720567215672256723567245672556726567275672856729567305673156732567335673456735567365673756738567395674056741567425674356744567455674656747567485674956750567515675256753567545675556756567575675856759567605676156762567635676456765567665676756768567695677056771567725677356774567755677656777567785677956780567815678256783567845678556786567875678856789567905679156792567935679456795567965679756798567995680056801568025680356804568055680656807568085680956810568115681256813568145681556816568175681856819568205682156822568235682456825568265682756828568295683056831568325683356834568355683656837568385683956840568415684256843568445684556846568475684856849568505685156852568535685456855568565685756858568595686056861568625686356864568655686656867568685686956870568715687256873568745687556876568775687856879568805688156882568835688456885568865688756888568895689056891568925689356894568955689656897568985689956900569015690256903569045690556906569075690856909569105691156912569135691456915569165691756918569195692056921569225692356924569255692656927569285692956930569315693256933569345693556936569375693856939569405694156942569435694456945569465694756948569495695056951569525695356954569555695656957569585695956960569615696256963569645696556966569675696856969569705697156972569735697456975569765697756978569795698056981569825698356984569855698656987569885698956990569915699256993569945699556996569975699856999570005700157002570035700457005570065700757008570095701057011570125701357014570155701657017570185701957020570215702257023570245702557026570275702857029570305703157032570335703457035570365703757038570395704057041570425704357044570455704657047570485704957050570515705257053570545705557056570575705857059570605706157062570635706457065570665706757068570695707057071570725707357074570755707657077570785707957080570815708257083570845708557086570875708857089570905709157092570935709457095570965709757098570995710057101571025710357104571055710657107571085710957110571115711257113571145711557116571175711857119571205712157122571235712457125571265712757128571295713057131571325713357134571355713657137571385713957140571415714257143571445714557146571475714857149571505715157152571535715457155571565715757158571595716057161571625716357164571655716657167571685716957170571715717257173571745717557176571775717857179571805718157182571835718457185571865718757188571895719057191571925719357194571955719657197571985719957200572015720257203572045720557206572075720857209572105721157212572135721457215572165721757218572195722057221572225722357224572255722657227572285722957230572315723257233572345723557236572375723857239572405724157242572435724457245572465724757248572495725057251572525725357254572555725657257572585725957260572615726257263572645726557266572675726857269572705727157272572735727457275572765727757278572795728057281572825728357284572855728657287572885728957290572915729257293572945729557296572975729857299573005730157302573035730457305573065730757308573095731057311573125731357314573155731657317573185731957320573215732257323573245732557326573275732857329573305733157332573335733457335573365733757338573395734057341573425734357344573455734657347573485734957350573515735257353573545735557356573575735857359573605736157362573635736457365573665736757368573695737057371573725737357374573755737657377573785737957380573815738257383573845738557386573875738857389573905739157392573935739457395573965739757398573995740057401574025740357404574055740657407574085740957410574115741257413574145741557416574175741857419574205742157422574235742457425574265742757428574295743057431574325743357434574355743657437574385743957440574415744257443574445744557446574475744857449574505745157452574535745457455574565745757458574595746057461574625746357464574655746657467574685746957470574715747257473574745747557476574775747857479574805748157482574835748457485574865748757488574895749057491574925749357494574955749657497574985749957500575015750257503575045750557506575075750857509575105751157512575135751457515575165751757518575195752057521575225752357524575255752657527575285752957530575315753257533575345753557536575375753857539575405754157542575435754457545575465754757548575495755057551575525755357554575555755657557575585755957560575615756257563575645756557566575675756857569575705757157572575735757457575575765757757578575795758057581575825758357584575855758657587575885758957590575915759257593575945759557596575975759857599576005760157602576035760457605576065760757608576095761057611576125761357614576155761657617576185761957620576215762257623576245762557626576275762857629576305763157632576335763457635576365763757638576395764057641576425764357644576455764657647576485764957650576515765257653576545765557656576575765857659576605766157662576635766457665576665766757668576695767057671576725767357674576755767657677576785767957680576815768257683576845768557686576875768857689576905769157692576935769457695576965769757698576995770057701577025770357704577055770657707577085770957710577115771257713577145771557716577175771857719577205772157722577235772457725577265772757728577295773057731577325773357734577355773657737577385773957740577415774257743577445774557746577475774857749577505775157752577535775457755577565775757758577595776057761577625776357764577655776657767577685776957770577715777257773577745777557776577775777857779577805778157782577835778457785577865778757788577895779057791577925779357794577955779657797577985779957800578015780257803578045780557806578075780857809578105781157812578135781457815578165781757818578195782057821578225782357824578255782657827578285782957830578315783257833578345783557836578375783857839578405784157842578435784457845578465784757848578495785057851578525785357854578555785657857578585785957860578615786257863578645786557866578675786857869578705787157872578735787457875578765787757878578795788057881578825788357884578855788657887578885788957890578915789257893578945789557896578975789857899579005790157902579035790457905579065790757908579095791057911579125791357914579155791657917579185791957920579215792257923579245792557926579275792857929579305793157932579335793457935579365793757938579395794057941579425794357944579455794657947579485794957950579515795257953579545795557956579575795857959579605796157962579635796457965579665796757968579695797057971579725797357974579755797657977579785797957980579815798257983579845798557986579875798857989579905799157992579935799457995579965799757998579995800058001580025800358004580055800658007580085800958010580115801258013580145801558016580175801858019580205802158022580235802458025580265802758028580295803058031580325803358034580355803658037580385803958040580415804258043580445804558046580475804858049580505805158052580535805458055580565805758058580595806058061580625806358064580655806658067580685806958070580715807258073580745807558076580775807858079580805808158082580835808458085580865808758088580895809058091580925809358094580955809658097580985809958100581015810258103581045810558106581075810858109581105811158112581135811458115581165811758118581195812058121581225812358124581255812658127581285812958130581315813258133581345813558136581375813858139581405814158142581435814458145581465814758148581495815058151581525815358154581555815658157581585815958160581615816258163581645816558166581675816858169581705817158172581735817458175581765817758178581795818058181581825818358184581855818658187581885818958190581915819258193581945819558196581975819858199582005820158202582035820458205582065820758208582095821058211582125821358214582155821658217582185821958220582215822258223582245822558226582275822858229582305823158232582335823458235582365823758238582395824058241582425824358244582455824658247582485824958250582515825258253582545825558256582575825858259582605826158262582635826458265582665826758268582695827058271582725827358274582755827658277582785827958280582815828258283582845828558286582875828858289582905829158292582935829458295582965829758298582995830058301583025830358304583055830658307583085830958310583115831258313583145831558316583175831858319583205832158322583235832458325583265832758328583295833058331583325833358334583355833658337583385833958340583415834258343583445834558346583475834858349583505835158352583535835458355583565835758358583595836058361583625836358364583655836658367583685836958370583715837258373583745837558376583775837858379583805838158382583835838458385583865838758388583895839058391583925839358394583955839658397583985839958400584015840258403584045840558406584075840858409584105841158412584135841458415584165841758418584195842058421584225842358424584255842658427584285842958430584315843258433584345843558436584375843858439584405844158442584435844458445584465844758448584495845058451584525845358454584555845658457584585845958460584615846258463584645846558466584675846858469584705847158472584735847458475584765847758478584795848058481584825848358484584855848658487584885848958490584915849258493584945849558496584975849858499585005850158502585035850458505585065850758508585095851058511585125851358514585155851658517585185851958520585215852258523585245852558526585275852858529585305853158532585335853458535585365853758538585395854058541585425854358544585455854658547585485854958550585515855258553585545855558556585575855858559585605856158562585635856458565585665856758568585695857058571585725857358574585755857658577585785857958580585815858258583585845858558586585875858858589585905859158592585935859458595585965859758598585995860058601586025860358604586055860658607586085860958610586115861258613586145861558616586175861858619586205862158622586235862458625586265862758628586295863058631586325863358634586355863658637586385863958640586415864258643586445864558646586475864858649586505865158652586535865458655586565865758658586595866058661586625866358664586655866658667586685866958670586715867258673586745867558676586775867858679586805868158682586835868458685586865868758688586895869058691586925869358694586955869658697586985869958700587015870258703587045870558706587075870858709587105871158712587135871458715587165871758718587195872058721587225872358724587255872658727587285872958730587315873258733587345873558736587375873858739587405874158742587435874458745587465874758748587495875058751587525875358754587555875658757587585875958760587615876258763587645876558766587675876858769587705877158772587735877458775587765877758778587795878058781587825878358784587855878658787587885878958790587915879258793587945879558796587975879858799588005880158802588035880458805588065880758808588095881058811588125881358814588155881658817588185881958820588215882258823588245882558826588275882858829588305883158832588335883458835588365883758838588395884058841588425884358844588455884658847588485884958850588515885258853588545885558856588575885858859588605886158862588635886458865588665886758868588695887058871588725887358874588755887658877588785887958880588815888258883588845888558886588875888858889588905889158892588935889458895588965889758898588995890058901589025890358904589055890658907589085890958910589115891258913589145891558916589175891858919589205892158922589235892458925589265892758928589295893058931589325893358934589355893658937589385893958940589415894258943589445894558946589475894858949589505895158952589535895458955589565895758958589595896058961589625896358964589655896658967589685896958970589715897258973589745897558976589775897858979589805898158982589835898458985589865898758988589895899058991589925899358994589955899658997589985899959000590015900259003590045900559006590075900859009590105901159012590135901459015590165901759018590195902059021590225902359024590255902659027590285902959030590315903259033590345903559036590375903859039590405904159042590435904459045590465904759048590495905059051590525905359054590555905659057590585905959060590615906259063590645906559066590675906859069590705907159072590735907459075590765907759078590795908059081590825908359084590855908659087590885908959090590915909259093590945909559096590975909859099591005910159102591035910459105591065910759108591095911059111591125911359114591155911659117591185911959120591215912259123591245912559126591275912859129591305913159132591335913459135591365913759138591395914059141591425914359144591455914659147591485914959150591515915259153591545915559156591575915859159591605916159162591635916459165591665916759168591695917059171591725917359174591755917659177591785917959180591815918259183591845918559186591875918859189591905919159192591935919459195591965919759198591995920059201592025920359204592055920659207592085920959210592115921259213592145921559216592175921859219592205922159222592235922459225592265922759228592295923059231592325923359234592355923659237592385923959240592415924259243592445924559246592475924859249592505925159252592535925459255592565925759258592595926059261592625926359264592655926659267592685926959270592715927259273592745927559276592775927859279592805928159282592835928459285592865928759288592895929059291592925929359294592955929659297592985929959300593015930259303593045930559306593075930859309593105931159312593135931459315593165931759318593195932059321593225932359324593255932659327593285932959330593315933259333593345933559336593375933859339593405934159342593435934459345593465934759348593495935059351593525935359354593555935659357593585935959360593615936259363593645936559366593675936859369593705937159372593735937459375593765937759378593795938059381593825938359384593855938659387593885938959390593915939259393593945939559396593975939859399594005940159402594035940459405594065940759408594095941059411594125941359414594155941659417594185941959420594215942259423594245942559426594275942859429594305943159432594335943459435594365943759438594395944059441594425944359444594455944659447594485944959450594515945259453594545945559456594575945859459594605946159462594635946459465594665946759468594695947059471594725947359474594755947659477594785947959480594815948259483594845948559486594875948859489594905949159492594935949459495594965949759498594995950059501595025950359504595055950659507595085950959510595115951259513595145951559516595175951859519595205952159522595235952459525595265952759528595295953059531595325953359534595355953659537595385953959540595415954259543595445954559546595475954859549595505955159552595535955459555595565955759558595595956059561595625956359564595655956659567595685956959570595715957259573595745957559576595775957859579595805958159582595835958459585595865958759588595895959059591595925959359594595955959659597595985959959600596015960259603596045960559606596075960859609596105961159612596135961459615596165961759618596195962059621596225962359624596255962659627596285962959630596315963259633596345963559636596375963859639596405964159642596435964459645596465964759648596495965059651596525965359654596555965659657596585965959660596615966259663596645966559666596675966859669596705967159672596735967459675596765967759678596795968059681596825968359684596855968659687596885968959690596915969259693596945969559696596975969859699597005970159702597035970459705597065970759708597095971059711597125971359714597155971659717597185971959720597215972259723597245972559726597275972859729597305973159732597335973459735597365973759738597395974059741597425974359744597455974659747597485974959750597515975259753597545975559756597575975859759597605976159762597635976459765597665976759768597695977059771597725977359774597755977659777597785977959780597815978259783597845978559786597875978859789597905979159792597935979459795597965979759798597995980059801598025980359804598055980659807598085980959810598115981259813598145981559816598175981859819598205982159822598235982459825598265982759828598295983059831598325983359834598355983659837598385983959840598415984259843598445984559846598475984859849598505985159852598535985459855598565985759858598595986059861598625986359864598655986659867598685986959870598715987259873598745987559876598775987859879598805988159882598835988459885598865988759888598895989059891598925989359894598955989659897598985989959900599015990259903599045990559906599075990859909599105991159912599135991459915599165991759918599195992059921599225992359924599255992659927599285992959930599315993259933599345993559936599375993859939599405994159942599435994459945599465994759948599495995059951599525995359954599555995659957599585995959960599615996259963599645996559966599675996859969599705997159972599735997459975599765997759978599795998059981599825998359984599855998659987599885998959990599915999259993599945999559996599975999859999600006000160002600036000460005600066000760008600096001060011600126001360014600156001660017600186001960020600216002260023600246002560026600276002860029600306003160032600336003460035600366003760038600396004060041600426004360044600456004660047600486004960050600516005260053600546005560056600576005860059600606006160062600636006460065600666006760068600696007060071600726007360074600756007660077600786007960080600816008260083600846008560086600876008860089600906009160092600936009460095600966009760098600996010060101601026010360104601056010660107601086010960110601116011260113601146011560116601176011860119601206012160122601236012460125601266012760128601296013060131601326013360134601356013660137601386013960140601416014260143601446014560146601476014860149601506015160152601536015460155601566015760158601596016060161601626016360164601656016660167601686016960170601716017260173601746017560176601776017860179601806018160182601836018460185601866018760188601896019060191601926019360194601956019660197601986019960200602016020260203602046020560206602076020860209602106021160212602136021460215602166021760218602196022060221602226022360224602256022660227602286022960230602316023260233602346023560236602376023860239602406024160242602436024460245602466024760248602496025060251602526025360254602556025660257602586025960260602616026260263602646026560266602676026860269602706027160272602736027460275602766027760278602796028060281602826028360284602856028660287602886028960290602916029260293602946029560296602976029860299603006030160302603036030460305603066030760308603096031060311603126031360314603156031660317603186031960320603216032260323603246032560326603276032860329603306033160332603336033460335603366033760338603396034060341603426034360344603456034660347603486034960350603516035260353603546035560356603576035860359603606036160362603636036460365603666036760368603696037060371603726037360374603756037660377603786037960380603816038260383603846038560386603876038860389603906039160392603936039460395603966039760398603996040060401604026040360404604056040660407604086040960410604116041260413604146041560416604176041860419604206042160422604236042460425604266042760428604296043060431604326043360434604356043660437604386043960440604416044260443604446044560446604476044860449604506045160452604536045460455604566045760458604596046060461604626046360464604656046660467604686046960470604716047260473
  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. /**
  22. * Boolean : true if the absolute difference between a and b is lower than epsilon (default = 1.401298E-45)
  23. */
  24. MathTools.WithinEpsilon = function (a, b, epsilon) {
  25. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  26. var num = a - b;
  27. return -epsilon <= num && num <= epsilon;
  28. };
  29. /**
  30. * Returns a string : the upper case translation of the number i to hexadecimal.
  31. */
  32. MathTools.ToHex = function (i) {
  33. var str = i.toString(16);
  34. if (i <= 15) {
  35. return ("0" + str).toUpperCase();
  36. }
  37. return str.toUpperCase();
  38. };
  39. /**
  40. * Returns -1 if value is negative and +1 is value is positive.
  41. * Returns the value itself if it's equal to zero.
  42. */
  43. MathTools.Sign = function (value) {
  44. value = +value; // convert to a number
  45. if (value === 0 || isNaN(value))
  46. return value;
  47. return value > 0 ? 1 : -1;
  48. };
  49. /**
  50. * Returns the value itself if it's between min and max.
  51. * Returns min if the value is lower than min.
  52. * Returns max if the value is greater than max.
  53. */
  54. MathTools.Clamp = function (value, min, max) {
  55. if (min === void 0) { min = 0; }
  56. if (max === void 0) { max = 1; }
  57. return Math.min(max, Math.max(min, value));
  58. };
  59. return MathTools;
  60. }());
  61. BABYLON.MathTools = MathTools;
  62. var Color3 = (function () {
  63. /**
  64. * Creates a new Color3 object from red, green, blue values, all between 0 and 1.
  65. */
  66. function Color3(r, g, b) {
  67. if (r === void 0) { r = 0; }
  68. if (g === void 0) { g = 0; }
  69. if (b === void 0) { b = 0; }
  70. this.r = r;
  71. this.g = g;
  72. this.b = b;
  73. }
  74. /**
  75. * Returns a string with the Color3 current values.
  76. */
  77. Color3.prototype.toString = function () {
  78. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  79. };
  80. /**
  81. * Returns the string "Color3".
  82. */
  83. Color3.prototype.getClassName = function () {
  84. return "Color3";
  85. };
  86. /**
  87. * Returns the Color3 hash code.
  88. */
  89. Color3.prototype.getHashCode = function () {
  90. var hash = this.r || 0;
  91. hash = (hash * 397) ^ (this.g || 0);
  92. hash = (hash * 397) ^ (this.b || 0);
  93. return hash;
  94. };
  95. // Operators
  96. /**
  97. * Stores in the passed array from the passed starting index the red, green, blue values as successive elements.
  98. * Returns the Color3.
  99. */
  100. Color3.prototype.toArray = function (array, index) {
  101. if (index === undefined) {
  102. index = 0;
  103. }
  104. array[index] = this.r;
  105. array[index + 1] = this.g;
  106. array[index + 2] = this.b;
  107. return this;
  108. };
  109. /**
  110. * Returns a new Color4 object from the current Color3 and the passed alpha.
  111. */
  112. Color3.prototype.toColor4 = function (alpha) {
  113. if (alpha === void 0) { alpha = 1; }
  114. return new Color4(this.r, this.g, this.b, alpha);
  115. };
  116. /**
  117. * Returns a new array populated with 3 numeric elements : red, green and blue values.
  118. */
  119. Color3.prototype.asArray = function () {
  120. var result = [];
  121. this.toArray(result, 0);
  122. return result;
  123. };
  124. /**
  125. * Returns the luminance value (float).
  126. */
  127. Color3.prototype.toLuminance = function () {
  128. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  129. };
  130. /**
  131. * Multiply each Color3 rgb values by the passed Color3 rgb values in a new Color3 object.
  132. * Returns this new object.
  133. */
  134. Color3.prototype.multiply = function (otherColor) {
  135. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  136. };
  137. /**
  138. * Multiply the rgb values of the Color3 and the passed Color3 and stores the result in the object "result".
  139. * Returns the current Color3.
  140. */
  141. Color3.prototype.multiplyToRef = function (otherColor, result) {
  142. result.r = this.r * otherColor.r;
  143. result.g = this.g * otherColor.g;
  144. result.b = this.b * otherColor.b;
  145. return this;
  146. };
  147. /**
  148. * Boolean : True if the rgb values are equal to the passed ones.
  149. */
  150. Color3.prototype.equals = function (otherColor) {
  151. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  152. };
  153. /**
  154. * Boolean : True if the rgb values are equal to the passed ones.
  155. */
  156. Color3.prototype.equalsFloats = function (r, g, b) {
  157. return this.r === r && this.g === g && this.b === b;
  158. };
  159. /**
  160. * Multiplies in place each rgb value by scale.
  161. * Returns the updated Color3.
  162. */
  163. Color3.prototype.scale = function (scale) {
  164. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  165. };
  166. /**
  167. * Multiplies the rgb values by scale and stores the result into "result".
  168. * Returns the unmodified current Color3.
  169. */
  170. Color3.prototype.scaleToRef = function (scale, result) {
  171. result.r = this.r * scale;
  172. result.g = this.g * scale;
  173. result.b = this.b * scale;
  174. return this;
  175. };
  176. /**
  177. * Returns a new Color3 set with the added values of the current Color3 and of the passed one.
  178. */
  179. Color3.prototype.add = function (otherColor) {
  180. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  181. };
  182. /**
  183. * Stores the result of the addition of the current Color3 and passed one rgb values into "result".
  184. * Returns the unmodified current Color3.
  185. */
  186. Color3.prototype.addToRef = function (otherColor, result) {
  187. result.r = this.r + otherColor.r;
  188. result.g = this.g + otherColor.g;
  189. result.b = this.b + otherColor.b;
  190. return this;
  191. };
  192. /**
  193. * Returns a new Color3 set with the subtracted values of the passed one from the current Color3 .
  194. */
  195. Color3.prototype.subtract = function (otherColor) {
  196. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  197. };
  198. /**
  199. * Stores the result of the subtraction of passed one from the current Color3 rgb values into "result".
  200. * Returns the unmodified current Color3.
  201. */
  202. Color3.prototype.subtractToRef = function (otherColor, result) {
  203. result.r = this.r - otherColor.r;
  204. result.g = this.g - otherColor.g;
  205. result.b = this.b - otherColor.b;
  206. return this;
  207. };
  208. /**
  209. * Returns a new Color3 copied the current one.
  210. */
  211. Color3.prototype.clone = function () {
  212. return new Color3(this.r, this.g, this.b);
  213. };
  214. /**
  215. * Copies the rgb values from the source in the current Color3.
  216. * Returns the updated Color3.
  217. */
  218. Color3.prototype.copyFrom = function (source) {
  219. this.r = source.r;
  220. this.g = source.g;
  221. this.b = source.b;
  222. return this;
  223. };
  224. /**
  225. * Updates the Color3 rgb values from the passed floats.
  226. * Returns the Color3.
  227. */
  228. Color3.prototype.copyFromFloats = function (r, g, b) {
  229. this.r = r;
  230. this.g = g;
  231. this.b = b;
  232. return this;
  233. };
  234. /**
  235. * Updates the Color3 rgb values from the passed floats.
  236. * Returns the Color3.
  237. */
  238. Color3.prototype.set = function (r, g, b) {
  239. return this.copyFromFloats(r, g, b);
  240. };
  241. /**
  242. * Returns the Color3 hexadecimal code as a string.
  243. */
  244. Color3.prototype.toHexString = function () {
  245. var intR = (this.r * 255) | 0;
  246. var intG = (this.g * 255) | 0;
  247. var intB = (this.b * 255) | 0;
  248. return "#" + MathTools.ToHex(intR) + MathTools.ToHex(intG) + MathTools.ToHex(intB);
  249. };
  250. /**
  251. * Returns a new Color3 converted to linear space.
  252. */
  253. Color3.prototype.toLinearSpace = function () {
  254. var convertedColor = new Color3();
  255. this.toLinearSpaceToRef(convertedColor);
  256. return convertedColor;
  257. };
  258. /**
  259. * Converts the Color3 values to linear space and stores the result in "convertedColor".
  260. * Returns the unmodified Color3.
  261. */
  262. Color3.prototype.toLinearSpaceToRef = function (convertedColor) {
  263. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  264. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  265. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  266. return this;
  267. };
  268. /**
  269. * Returns a new Color3 converted to gamma space.
  270. */
  271. Color3.prototype.toGammaSpace = function () {
  272. var convertedColor = new Color3();
  273. this.toGammaSpaceToRef(convertedColor);
  274. return convertedColor;
  275. };
  276. /**
  277. * Converts the Color3 values to gamma space and stores the result in "convertedColor".
  278. * Returns the unmodified Color3.
  279. */
  280. Color3.prototype.toGammaSpaceToRef = function (convertedColor) {
  281. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  282. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  283. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  284. return this;
  285. };
  286. // Statics
  287. /**
  288. * Creates a new Color3 from the string containing valid hexadecimal values.
  289. */
  290. Color3.FromHexString = function (hex) {
  291. if (hex.substring(0, 1) !== "#" || hex.length !== 7) {
  292. //Tools.Warn("Color3.FromHexString must be called with a string like #FFFFFF");
  293. return new Color3(0, 0, 0);
  294. }
  295. var r = parseInt(hex.substring(1, 3), 16);
  296. var g = parseInt(hex.substring(3, 5), 16);
  297. var b = parseInt(hex.substring(5, 7), 16);
  298. return Color3.FromInts(r, g, b);
  299. };
  300. /**
  301. * Creates a new Vector3 from the startind index of the passed array.
  302. */
  303. Color3.FromArray = function (array, offset) {
  304. if (offset === void 0) { offset = 0; }
  305. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  306. };
  307. /**
  308. * Creates a new Color3 from integer values ( < 256).
  309. */
  310. Color3.FromInts = function (r, g, b) {
  311. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  312. };
  313. /**
  314. * Creates a new Color3 with values linearly interpolated of "amount" between the start Color3 and the end Color3.
  315. */
  316. Color3.Lerp = function (start, end, amount) {
  317. var r = start.r + ((end.r - start.r) * amount);
  318. var g = start.g + ((end.g - start.g) * amount);
  319. var b = start.b + ((end.b - start.b) * amount);
  320. return new Color3(r, g, b);
  321. };
  322. Color3.Red = function () { return new Color3(1, 0, 0); };
  323. Color3.Green = function () { return new Color3(0, 1, 0); };
  324. Color3.Blue = function () { return new Color3(0, 0, 1); };
  325. Color3.Black = function () { return new Color3(0, 0, 0); };
  326. Color3.White = function () { return new Color3(1, 1, 1); };
  327. Color3.Purple = function () { return new Color3(0.5, 0, 0.5); };
  328. Color3.Magenta = function () { return new Color3(1, 0, 1); };
  329. Color3.Yellow = function () { return new Color3(1, 1, 0); };
  330. Color3.Gray = function () { return new Color3(0.5, 0.5, 0.5); };
  331. Color3.Random = function () { return new Color3(Math.random(), Math.random(), Math.random()); };
  332. return Color3;
  333. }());
  334. BABYLON.Color3 = Color3;
  335. var Color4 = (function () {
  336. /**
  337. * Creates a new Color4 object from the passed float values ( < 1) : red, green, blue, alpha.
  338. */
  339. function Color4(r, g, b, a) {
  340. this.r = r;
  341. this.g = g;
  342. this.b = b;
  343. this.a = a;
  344. }
  345. // Operators
  346. /**
  347. * Adds in place the passed Color4 values to the current Color4.
  348. * Returns the updated Color4.
  349. */
  350. Color4.prototype.addInPlace = function (right) {
  351. this.r += right.r;
  352. this.g += right.g;
  353. this.b += right.b;
  354. this.a += right.a;
  355. return this;
  356. };
  357. /**
  358. * Returns a new array populated with 4 numeric elements : red, green, blue, alpha values.
  359. */
  360. Color4.prototype.asArray = function () {
  361. var result = [];
  362. this.toArray(result, 0);
  363. return result;
  364. };
  365. /**
  366. * Stores from the starting index in the passed array the Color4 successive values.
  367. * Returns the Color4.
  368. */
  369. Color4.prototype.toArray = function (array, index) {
  370. if (index === undefined) {
  371. index = 0;
  372. }
  373. array[index] = this.r;
  374. array[index + 1] = this.g;
  375. array[index + 2] = this.b;
  376. array[index + 3] = this.a;
  377. return this;
  378. };
  379. /**
  380. * Returns a new Color4 set with the added values of the current Color4 and of the passed one.
  381. */
  382. Color4.prototype.add = function (right) {
  383. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  384. };
  385. /**
  386. * Returns a new Color4 set with the subtracted values of the passed one from the current Color4.
  387. */
  388. Color4.prototype.subtract = function (right) {
  389. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  390. };
  391. /**
  392. * Subtracts the passed ones from the current Color4 values and stores the results in "result".
  393. * Returns the Color4.
  394. */
  395. Color4.prototype.subtractToRef = function (right, result) {
  396. result.r = this.r - right.r;
  397. result.g = this.g - right.g;
  398. result.b = this.b - right.b;
  399. result.a = this.a - right.a;
  400. return this;
  401. };
  402. /**
  403. * Creates a new Color4 with the current Color4 values multiplied by scale.
  404. */
  405. Color4.prototype.scale = function (scale) {
  406. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  407. };
  408. /**
  409. * Multiplies the current Color4 values by scale and stores the result in "result".
  410. * Returns the Color4.
  411. */
  412. Color4.prototype.scaleToRef = function (scale, result) {
  413. result.r = this.r * scale;
  414. result.g = this.g * scale;
  415. result.b = this.b * scale;
  416. result.a = this.a * scale;
  417. return this;
  418. };
  419. /**
  420. * Multipy an RGBA Color4 value by another and return a new Color4 object
  421. * @param color The Color4 (RGBA) value to multiply by
  422. * @returns A new Color4.
  423. */
  424. Color4.prototype.multiply = function (color) {
  425. return new Color4(this.r * color.r, this.g * color.g, this.b * color.b, this.a * color.a);
  426. };
  427. /**
  428. * Multipy an RGBA Color4 value by another and push the result in a reference value
  429. * @param color The Color4 (RGBA) value to multiply by
  430. * @param result The Color4 (RGBA) to fill the result in
  431. * @returns the result Color4.
  432. */
  433. Color4.prototype.multiplyToRef = function (color, result) {
  434. result.r = this.r * color.r;
  435. result.g = this.g * color.g;
  436. result.b = this.b * color.b;
  437. result.a = this.a * color.a;
  438. return result;
  439. };
  440. /**
  441. * Returns a string with the Color4 values.
  442. */
  443. Color4.prototype.toString = function () {
  444. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  445. };
  446. /**
  447. * Returns the string "Color4"
  448. */
  449. Color4.prototype.getClassName = function () {
  450. return "Color4";
  451. };
  452. /**
  453. * Return the Color4 hash code as a number.
  454. */
  455. Color4.prototype.getHashCode = function () {
  456. var hash = this.r || 0;
  457. hash = (hash * 397) ^ (this.g || 0);
  458. hash = (hash * 397) ^ (this.b || 0);
  459. hash = (hash * 397) ^ (this.a || 0);
  460. return hash;
  461. };
  462. /**
  463. * Creates a new Color4 copied from the current one.
  464. */
  465. Color4.prototype.clone = function () {
  466. return new Color4(this.r, this.g, this.b, this.a);
  467. };
  468. /**
  469. * Copies the passed Color4 values into the current one.
  470. * Returns the updated Color4.
  471. */
  472. Color4.prototype.copyFrom = function (source) {
  473. this.r = source.r;
  474. this.g = source.g;
  475. this.b = source.b;
  476. this.a = source.a;
  477. return this;
  478. };
  479. /**
  480. * Copies the passed float values into the current one.
  481. * Returns the updated Color4.
  482. */
  483. Color4.prototype.copyFromFloats = function (r, g, b, a) {
  484. this.r = r;
  485. this.g = g;
  486. this.b = b;
  487. this.a = a;
  488. return this;
  489. };
  490. /**
  491. * Copies the passed float values into the current one.
  492. * Returns the updated Color4.
  493. */
  494. Color4.prototype.set = function (r, g, b, a) {
  495. return this.copyFromFloats(r, g, b, a);
  496. };
  497. /**
  498. * Returns a string containing the hexadecimal Color4 code.
  499. */
  500. Color4.prototype.toHexString = function () {
  501. var intR = (this.r * 255) | 0;
  502. var intG = (this.g * 255) | 0;
  503. var intB = (this.b * 255) | 0;
  504. var intA = (this.a * 255) | 0;
  505. return "#" + MathTools.ToHex(intR) + MathTools.ToHex(intG) + MathTools.ToHex(intB) + MathTools.ToHex(intA);
  506. };
  507. // Statics
  508. /**
  509. * Creates a new Color4 from the valid hexadecimal value contained in the passed string.
  510. */
  511. Color4.FromHexString = function (hex) {
  512. if (hex.substring(0, 1) !== "#" || hex.length !== 9) {
  513. //Tools.Warn("Color4.FromHexString must be called with a string like #FFFFFFFF");
  514. return new Color4(0.0, 0.0, 0.0, 0.0);
  515. }
  516. var r = parseInt(hex.substring(1, 3), 16);
  517. var g = parseInt(hex.substring(3, 5), 16);
  518. var b = parseInt(hex.substring(5, 7), 16);
  519. var a = parseInt(hex.substring(7, 9), 16);
  520. return Color4.FromInts(r, g, b, a);
  521. };
  522. /**
  523. * Creates a new Color4 object set with the linearly interpolated values of "amount" between the left Color4 and the right Color4.
  524. */
  525. Color4.Lerp = function (left, right, amount) {
  526. var result = new Color4(0.0, 0.0, 0.0, 0.0);
  527. Color4.LerpToRef(left, right, amount, result);
  528. return result;
  529. };
  530. /**
  531. * Set the passed "result" with the linearly interpolated values of "amount" between the left Color4 and the right Color4.
  532. */
  533. Color4.LerpToRef = function (left, right, amount, result) {
  534. result.r = left.r + (right.r - left.r) * amount;
  535. result.g = left.g + (right.g - left.g) * amount;
  536. result.b = left.b + (right.b - left.b) * amount;
  537. result.a = left.a + (right.a - left.a) * amount;
  538. };
  539. /**
  540. * Creates a new Color4 from the starting index element of the passed array.
  541. */
  542. Color4.FromArray = function (array, offset) {
  543. if (offset === void 0) { offset = 0; }
  544. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  545. };
  546. /**
  547. * Creates a new Color4 from the passed integers ( < 256 ).
  548. */
  549. Color4.FromInts = function (r, g, b, a) {
  550. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  551. };
  552. Color4.CheckColors4 = function (colors, count) {
  553. // Check if color3 was used
  554. if (colors.length === count * 3) {
  555. var colors4 = [];
  556. for (var index = 0; index < colors.length; index += 3) {
  557. var newIndex = (index / 3) * 4;
  558. colors4[newIndex] = colors[index];
  559. colors4[newIndex + 1] = colors[index + 1];
  560. colors4[newIndex + 2] = colors[index + 2];
  561. colors4[newIndex + 3] = 1.0;
  562. }
  563. return colors4;
  564. }
  565. return colors;
  566. };
  567. return Color4;
  568. }());
  569. BABYLON.Color4 = Color4;
  570. var Vector2 = (function () {
  571. /**
  572. * Creates a new Vector2 from the passed x and y coordinates.
  573. */
  574. function Vector2(x, y) {
  575. this.x = x;
  576. this.y = y;
  577. }
  578. /**
  579. * Returns a string with the Vector2 coordinates.
  580. */
  581. Vector2.prototype.toString = function () {
  582. return "{X: " + this.x + " Y:" + this.y + "}";
  583. };
  584. /**
  585. * Returns the string "Vector2"
  586. */
  587. Vector2.prototype.getClassName = function () {
  588. return "Vector2";
  589. };
  590. /**
  591. * Returns the Vector2 hash code as a number.
  592. */
  593. Vector2.prototype.getHashCode = function () {
  594. var hash = this.x || 0;
  595. hash = (hash * 397) ^ (this.y || 0);
  596. return hash;
  597. };
  598. // Operators
  599. /**
  600. * Sets the Vector2 coordinates in the passed array or Float32Array from the passed index.
  601. * Returns the Vector2.
  602. */
  603. Vector2.prototype.toArray = function (array, index) {
  604. if (index === void 0) { index = 0; }
  605. array[index] = this.x;
  606. array[index + 1] = this.y;
  607. return this;
  608. };
  609. /**
  610. * Returns a new array with 2 elements : the Vector2 coordinates.
  611. */
  612. Vector2.prototype.asArray = function () {
  613. var result = [];
  614. this.toArray(result, 0);
  615. return result;
  616. };
  617. /**
  618. * Sets the Vector2 coordinates with the passed Vector2 coordinates.
  619. * Returns the updated Vector2.
  620. */
  621. Vector2.prototype.copyFrom = function (source) {
  622. this.x = source.x;
  623. this.y = source.y;
  624. return this;
  625. };
  626. /**
  627. * Sets the Vector2 coordinates with the passed floats.
  628. * Returns the updated Vector2.
  629. */
  630. Vector2.prototype.copyFromFloats = function (x, y) {
  631. this.x = x;
  632. this.y = y;
  633. return this;
  634. };
  635. /**
  636. * Sets the Vector2 coordinates with the passed floats.
  637. * Returns the updated Vector2.
  638. */
  639. Vector2.prototype.set = function (x, y) {
  640. return this.copyFromFloats(x, y);
  641. };
  642. /**
  643. * Returns a new Vector2 set with the addition of the current Vector2 and the passed one coordinates.
  644. */
  645. Vector2.prototype.add = function (otherVector) {
  646. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  647. };
  648. /**
  649. * Sets the "result" coordinates with the addition of the current Vector2 and the passed one coordinates.
  650. * Returns the Vector2.
  651. */
  652. Vector2.prototype.addToRef = function (otherVector, result) {
  653. result.x = this.x + otherVector.x;
  654. result.y = this.y + otherVector.y;
  655. return this;
  656. };
  657. /**
  658. * Set the Vector2 coordinates by adding the passed Vector2 coordinates.
  659. * Returns the updated Vector2.
  660. */
  661. Vector2.prototype.addInPlace = function (otherVector) {
  662. this.x += otherVector.x;
  663. this.y += otherVector.y;
  664. return this;
  665. };
  666. /**
  667. * Returns a new Vector2 by adding the current Vector2 coordinates to the passed Vector3 x, y coordinates.
  668. */
  669. Vector2.prototype.addVector3 = function (otherVector) {
  670. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  671. };
  672. /**
  673. * Returns a new Vector2 set with the subtracted coordinates of the passed one from the current Vector2.
  674. */
  675. Vector2.prototype.subtract = function (otherVector) {
  676. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  677. };
  678. /**
  679. * Sets the "result" coordinates with the subtraction of the passed one from the current Vector2 coordinates.
  680. * Returns the Vector2.
  681. */
  682. Vector2.prototype.subtractToRef = function (otherVector, result) {
  683. result.x = this.x - otherVector.x;
  684. result.y = this.y - otherVector.y;
  685. return this;
  686. };
  687. /**
  688. * Sets the current Vector2 coordinates by subtracting from it the passed one coordinates.
  689. * Returns the updated Vector2.
  690. */
  691. Vector2.prototype.subtractInPlace = function (otherVector) {
  692. this.x -= otherVector.x;
  693. this.y -= otherVector.y;
  694. return this;
  695. };
  696. /**
  697. * Multiplies in place the current Vector2 coordinates by the passed ones.
  698. * Returns the updated Vector2.
  699. */
  700. Vector2.prototype.multiplyInPlace = function (otherVector) {
  701. this.x *= otherVector.x;
  702. this.y *= otherVector.y;
  703. return this;
  704. };
  705. /**
  706. * Returns a new Vector2 set with the multiplication of the current Vector2 and the passed one coordinates.
  707. */
  708. Vector2.prototype.multiply = function (otherVector) {
  709. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  710. };
  711. /**
  712. * Sets "result" coordinates with the multiplication of the current Vector2 and the passed one coordinates.
  713. * Returns the Vector2.
  714. */
  715. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  716. result.x = this.x * otherVector.x;
  717. result.y = this.y * otherVector.y;
  718. return this;
  719. };
  720. /**
  721. * Returns a new Vector2 set with the Vector2 coordinates multiplied by the passed floats.
  722. */
  723. Vector2.prototype.multiplyByFloats = function (x, y) {
  724. return new Vector2(this.x * x, this.y * y);
  725. };
  726. /**
  727. * Returns a new Vector2 set with the Vector2 coordinates divided by the passed one coordinates.
  728. */
  729. Vector2.prototype.divide = function (otherVector) {
  730. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  731. };
  732. /**
  733. * Sets the "result" coordinates with the Vector2 divided by the passed one coordinates.
  734. * Returns the Vector2.
  735. */
  736. Vector2.prototype.divideToRef = function (otherVector, result) {
  737. result.x = this.x / otherVector.x;
  738. result.y = this.y / otherVector.y;
  739. return this;
  740. };
  741. /**
  742. * Returns a new Vector2 with current Vector2 negated coordinates.
  743. */
  744. Vector2.prototype.negate = function () {
  745. return new Vector2(-this.x, -this.y);
  746. };
  747. /**
  748. * Multiply the Vector2 coordinates by scale.
  749. * Returns the updated Vector2.
  750. */
  751. Vector2.prototype.scaleInPlace = function (scale) {
  752. this.x *= scale;
  753. this.y *= scale;
  754. return this;
  755. };
  756. /**
  757. * Returns a new Vector2 scaled by "scale" from the current Vector2.
  758. */
  759. Vector2.prototype.scale = function (scale) {
  760. return new Vector2(this.x * scale, this.y * scale);
  761. };
  762. /**
  763. * Boolean : True if the passed vector coordinates strictly equal the current Vector2 ones.
  764. */
  765. Vector2.prototype.equals = function (otherVector) {
  766. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  767. };
  768. /**
  769. * Boolean : True if the passed vector coordinates are close to the current ones by a distance of epsilon.
  770. */
  771. Vector2.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  772. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  773. return otherVector && MathTools.WithinEpsilon(this.x, otherVector.x, epsilon) && MathTools.WithinEpsilon(this.y, otherVector.y, epsilon);
  774. };
  775. // Properties
  776. /**
  777. * Returns the vector length (float).
  778. */
  779. Vector2.prototype.length = function () {
  780. return Math.sqrt(this.x * this.x + this.y * this.y);
  781. };
  782. /**
  783. * Returns the vector squared length (float);
  784. */
  785. Vector2.prototype.lengthSquared = function () {
  786. return (this.x * this.x + this.y * this.y);
  787. };
  788. // Methods
  789. /**
  790. * Normalize the vector.
  791. * Returns the updated Vector2.
  792. */
  793. Vector2.prototype.normalize = function () {
  794. var len = this.length();
  795. if (len === 0)
  796. return this;
  797. var num = 1.0 / len;
  798. this.x *= num;
  799. this.y *= num;
  800. return this;
  801. };
  802. /**
  803. * Returns a new Vector2 copied from the Vector2.
  804. */
  805. Vector2.prototype.clone = function () {
  806. return new Vector2(this.x, this.y);
  807. };
  808. // Statics
  809. /**
  810. * Returns a new Vector2(0, 0)
  811. */
  812. Vector2.Zero = function () {
  813. return new Vector2(0, 0);
  814. };
  815. /**
  816. * Returns a new Vector2 set from the passed index element of the passed array or Float32Array.
  817. */
  818. Vector2.FromArray = function (array, offset) {
  819. if (offset === void 0) { offset = 0; }
  820. return new Vector2(array[offset], array[offset + 1]);
  821. };
  822. /**
  823. * Sets "result" from the passed index element of the passed array or Float32Array.
  824. * Returns the Vector2.
  825. */
  826. Vector2.FromArrayToRef = function (array, offset, result) {
  827. result.x = array[offset];
  828. result.y = array[offset + 1];
  829. };
  830. /**
  831. * Retuns a new Vector2 located for "amount" (float) on the CatmullRom spline defined by the passed four Vector2.
  832. */
  833. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  834. var squared = amount * amount;
  835. var cubed = amount * squared;
  836. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  837. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  838. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  839. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  840. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  841. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  842. return new Vector2(x, y);
  843. };
  844. /**
  845. * Returns a new Vector2 set with same the coordinates than "value" ones if the vector "value" is in the square defined by "min" and "max".
  846. * If a coordinate of "value" is lower than "min" coordinates, the returned Vector2 is given this "min" coordinate.
  847. * If a coordinate of "value" is greater than "max" coordinates, the returned Vector2 is given this "max" coordinate.
  848. */
  849. Vector2.Clamp = function (value, min, max) {
  850. var x = value.x;
  851. x = (x > max.x) ? max.x : x;
  852. x = (x < min.x) ? min.x : x;
  853. var y = value.y;
  854. y = (y > max.y) ? max.y : y;
  855. y = (y < min.y) ? min.y : y;
  856. return new Vector2(x, y);
  857. };
  858. /**
  859. * Returns a new Vecto2 located for "amount" (float) on the Hermite spline defined by the vectors "value1", "value3", "tangent1", "tangent2".
  860. */
  861. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  862. var squared = amount * amount;
  863. var cubed = amount * squared;
  864. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  865. var part2 = (-2.0 * cubed) + (3.0 * squared);
  866. var part3 = (cubed - (2.0 * squared)) + amount;
  867. var part4 = cubed - squared;
  868. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  869. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  870. return new Vector2(x, y);
  871. };
  872. /**
  873. * Returns a new Vector2 located for "amount" (float) on the linear interpolation between the vector "start" adn the vector "end".
  874. */
  875. Vector2.Lerp = function (start, end, amount) {
  876. var x = start.x + ((end.x - start.x) * amount);
  877. var y = start.y + ((end.y - start.y) * amount);
  878. return new Vector2(x, y);
  879. };
  880. /**
  881. * Returns the dot product (float) of the vector "left" and the vector "right".
  882. */
  883. Vector2.Dot = function (left, right) {
  884. return left.x * right.x + left.y * right.y;
  885. };
  886. /**
  887. * Returns a new Vector2 equal to the normalized passed vector.
  888. */
  889. Vector2.Normalize = function (vector) {
  890. var newVector = vector.clone();
  891. newVector.normalize();
  892. return newVector;
  893. };
  894. /**
  895. * Returns a new Vecto2 set with the minimal coordinate values from the "left" and "right" vectors.
  896. */
  897. Vector2.Minimize = function (left, right) {
  898. var x = (left.x < right.x) ? left.x : right.x;
  899. var y = (left.y < right.y) ? left.y : right.y;
  900. return new Vector2(x, y);
  901. };
  902. /**
  903. * Returns a new Vecto2 set with the maximal coordinate values from the "left" and "right" vectors.
  904. */
  905. Vector2.Maximize = function (left, right) {
  906. var x = (left.x > right.x) ? left.x : right.x;
  907. var y = (left.y > right.y) ? left.y : right.y;
  908. return new Vector2(x, y);
  909. };
  910. /**
  911. * Returns a new Vecto2 set with the transformed coordinates of the passed vector by the passed transformation matrix.
  912. */
  913. Vector2.Transform = function (vector, transformation) {
  914. var r = Vector2.Zero();
  915. Vector2.TransformToRef(vector, transformation, r);
  916. return r;
  917. };
  918. /**
  919. * Transforms the passed vector coordinates by the passed transformation matrix and stores the result in the vector "result" coordinates.
  920. */
  921. Vector2.TransformToRef = function (vector, transformation, result) {
  922. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + transformation.m[12];
  923. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + transformation.m[13];
  924. result.x = x;
  925. result.y = y;
  926. };
  927. /**
  928. * Boolean : True if the point "p" is in the triangle defined by the vertors "p0", "p1", "p2"
  929. */
  930. Vector2.PointInTriangle = function (p, p0, p1, p2) {
  931. var a = 1 / 2 * (-p1.y * p2.x + p0.y * (-p1.x + p2.x) + p0.x * (p1.y - p2.y) + p1.x * p2.y);
  932. var sign = a < 0 ? -1 : 1;
  933. var s = (p0.y * p2.x - p0.x * p2.y + (p2.y - p0.y) * p.x + (p0.x - p2.x) * p.y) * sign;
  934. var t = (p0.x * p1.y - p0.y * p1.x + (p0.y - p1.y) * p.x + (p1.x - p0.x) * p.y) * sign;
  935. return s > 0 && t > 0 && (s + t) < 2 * a * sign;
  936. };
  937. /**
  938. * Returns the distance (float) between the vectors "value1" and "value2".
  939. */
  940. Vector2.Distance = function (value1, value2) {
  941. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  942. };
  943. /**
  944. * Returns the squared distance (float) between the vectors "value1" and "value2".
  945. */
  946. Vector2.DistanceSquared = function (value1, value2) {
  947. var x = value1.x - value2.x;
  948. var y = value1.y - value2.y;
  949. return (x * x) + (y * y);
  950. };
  951. /**
  952. * Returns a new Vecto2 located at the center of the vectors "value1" and "value2".
  953. */
  954. Vector2.Center = function (value1, value2) {
  955. var center = value1.add(value2);
  956. center.scaleInPlace(0.5);
  957. return center;
  958. };
  959. /**
  960. * Returns the shortest distance (float) between the point "p" and the segment defined by the two points "segA" and "segB".
  961. */
  962. Vector2.DistanceOfPointFromSegment = function (p, segA, segB) {
  963. var l2 = Vector2.DistanceSquared(segA, segB);
  964. if (l2 === 0.0) {
  965. return Vector2.Distance(p, segA);
  966. }
  967. var v = segB.subtract(segA);
  968. var t = Math.max(0, Math.min(1, Vector2.Dot(p.subtract(segA), v) / l2));
  969. var proj = segA.add(v.multiplyByFloats(t, t));
  970. return Vector2.Distance(p, proj);
  971. };
  972. return Vector2;
  973. }());
  974. BABYLON.Vector2 = Vector2;
  975. var Vector3 = (function () {
  976. /**
  977. * Creates a new Vector3 object from the passed x, y, z (floats) coordinates.
  978. * A Vector3 is the main object used in 3D geometry.
  979. * It can represent etiher the coordinates of a point the space, either a direction.
  980. */
  981. function Vector3(x, y, z) {
  982. this.x = x;
  983. this.y = y;
  984. this.z = z;
  985. }
  986. /**
  987. * Returns a string with the Vector3 coordinates.
  988. */
  989. Vector3.prototype.toString = function () {
  990. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  991. };
  992. /**
  993. * Returns the string "Vector3"
  994. */
  995. Vector3.prototype.getClassName = function () {
  996. return "Vector3";
  997. };
  998. /**
  999. * Returns the Vector hash code.
  1000. */
  1001. Vector3.prototype.getHashCode = function () {
  1002. var hash = this.x || 0;
  1003. hash = (hash * 397) ^ (this.y || 0);
  1004. hash = (hash * 397) ^ (this.z || 0);
  1005. return hash;
  1006. };
  1007. // Operators
  1008. /**
  1009. * Returns a new array with three elements : the coordinates the Vector3.
  1010. */
  1011. Vector3.prototype.asArray = function () {
  1012. var result = [];
  1013. this.toArray(result, 0);
  1014. return result;
  1015. };
  1016. /**
  1017. * Populates the passed array or Float32Array from the passed index with the successive coordinates of the Vector3.
  1018. * Returns the Vector3.
  1019. */
  1020. Vector3.prototype.toArray = function (array, index) {
  1021. if (index === void 0) { index = 0; }
  1022. array[index] = this.x;
  1023. array[index + 1] = this.y;
  1024. array[index + 2] = this.z;
  1025. return this;
  1026. };
  1027. /**
  1028. * Returns a new Quaternion object, computed from the Vector3 coordinates.
  1029. */
  1030. Vector3.prototype.toQuaternion = function () {
  1031. var result = new Quaternion(0.0, 0.0, 0.0, 1.0);
  1032. var cosxPlusz = Math.cos((this.x + this.z) * 0.5);
  1033. var sinxPlusz = Math.sin((this.x + this.z) * 0.5);
  1034. var coszMinusx = Math.cos((this.z - this.x) * 0.5);
  1035. var sinzMinusx = Math.sin((this.z - this.x) * 0.5);
  1036. var cosy = Math.cos(this.y * 0.5);
  1037. var siny = Math.sin(this.y * 0.5);
  1038. result.x = coszMinusx * siny;
  1039. result.y = -sinzMinusx * siny;
  1040. result.z = sinxPlusz * cosy;
  1041. result.w = cosxPlusz * cosy;
  1042. return result;
  1043. };
  1044. /**
  1045. * Adds the passed vector to the current Vector3.
  1046. * Returns the updated Vector3.
  1047. */
  1048. Vector3.prototype.addInPlace = function (otherVector) {
  1049. this.x += otherVector.x;
  1050. this.y += otherVector.y;
  1051. this.z += otherVector.z;
  1052. return this;
  1053. };
  1054. /**
  1055. * Returns a new Vector3, result of the addition the current Vector3 and the passed vector.
  1056. */
  1057. Vector3.prototype.add = function (otherVector) {
  1058. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  1059. };
  1060. /**
  1061. * Adds the current Vector3 to the passed one and stores the result in the vector "result".
  1062. * Returns the current Vector3.
  1063. */
  1064. Vector3.prototype.addToRef = function (otherVector, result) {
  1065. result.x = this.x + otherVector.x;
  1066. result.y = this.y + otherVector.y;
  1067. result.z = this.z + otherVector.z;
  1068. return this;
  1069. };
  1070. /**
  1071. * Subtract the passed vector from the current Vector3.
  1072. * Returns the updated Vector3.
  1073. */
  1074. Vector3.prototype.subtractInPlace = function (otherVector) {
  1075. this.x -= otherVector.x;
  1076. this.y -= otherVector.y;
  1077. this.z -= otherVector.z;
  1078. return this;
  1079. };
  1080. /**
  1081. * Returns a new Vector3, result of the subtraction of the passed vector from the current Vector3.
  1082. */
  1083. Vector3.prototype.subtract = function (otherVector) {
  1084. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  1085. };
  1086. /**
  1087. * Subtracts the passed vector from the current Vector3 and stores the result in the vector "result".
  1088. * Returns the current Vector3.
  1089. */
  1090. Vector3.prototype.subtractToRef = function (otherVector, result) {
  1091. result.x = this.x - otherVector.x;
  1092. result.y = this.y - otherVector.y;
  1093. result.z = this.z - otherVector.z;
  1094. return this;
  1095. };
  1096. /**
  1097. * Returns a new Vector3 set with the subtraction of the passed floats from the current Vector3 coordinates.
  1098. */
  1099. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  1100. return new Vector3(this.x - x, this.y - y, this.z - z);
  1101. };
  1102. /**
  1103. * Subtracts the passed floats from the current Vector3 coordinates and set the passed vector "result" with this result.
  1104. * Returns the current Vector3.
  1105. */
  1106. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  1107. result.x = this.x - x;
  1108. result.y = this.y - y;
  1109. result.z = this.z - z;
  1110. return this;
  1111. };
  1112. /**
  1113. * Returns a new Vector3 set with the current Vector3 negated coordinates.
  1114. */
  1115. Vector3.prototype.negate = function () {
  1116. return new Vector3(-this.x, -this.y, -this.z);
  1117. };
  1118. /**
  1119. * Multiplies the Vector3 coordinates by the float "scale".
  1120. * Returns the updated Vector3.
  1121. */
  1122. Vector3.prototype.scaleInPlace = function (scale) {
  1123. this.x *= scale;
  1124. this.y *= scale;
  1125. this.z *= scale;
  1126. return this;
  1127. };
  1128. /**
  1129. * Returns a new Vector3 set with the current Vector3 coordinates multiplied by the float "scale".
  1130. */
  1131. Vector3.prototype.scale = function (scale) {
  1132. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  1133. };
  1134. /**
  1135. * Multiplies the current Vector3 coordinates by the float "scale" and stores the result in the passed vector "result" coordinates.
  1136. * Returns the current Vector3.
  1137. */
  1138. Vector3.prototype.scaleToRef = function (scale, result) {
  1139. result.x = this.x * scale;
  1140. result.y = this.y * scale;
  1141. result.z = this.z * scale;
  1142. return this;
  1143. };
  1144. /**
  1145. * Boolean : True if the current Vector3 and the passed vector coordinates are strictly equal.
  1146. */
  1147. Vector3.prototype.equals = function (otherVector) {
  1148. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  1149. };
  1150. /**
  1151. * Boolean : True if the current Vector3 and the passed vector coordinates are distant less than epsilon.
  1152. */
  1153. Vector3.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  1154. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  1155. return otherVector && MathTools.WithinEpsilon(this.x, otherVector.x, epsilon) && MathTools.WithinEpsilon(this.y, otherVector.y, epsilon) && MathTools.WithinEpsilon(this.z, otherVector.z, epsilon);
  1156. };
  1157. /**
  1158. * Boolean : True if the current Vector3 coordinate equal the passed floats.
  1159. */
  1160. Vector3.prototype.equalsToFloats = function (x, y, z) {
  1161. return this.x === x && this.y === y && this.z === z;
  1162. };
  1163. /**
  1164. * Muliplies the current Vector3 coordinates by the passed ones.
  1165. * Returns the updated Vector3.
  1166. */
  1167. Vector3.prototype.multiplyInPlace = function (otherVector) {
  1168. this.x *= otherVector.x;
  1169. this.y *= otherVector.y;
  1170. this.z *= otherVector.z;
  1171. return this;
  1172. };
  1173. /**
  1174. * Returns a new Vector3, result of the multiplication of the current Vector3 by the passed vector.
  1175. */
  1176. Vector3.prototype.multiply = function (otherVector) {
  1177. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  1178. };
  1179. /**
  1180. * Multiplies the current Vector3 by the passed one and stores the result in the passed vector "result".
  1181. * Returns the current Vector3.
  1182. */
  1183. Vector3.prototype.multiplyToRef = 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. return this;
  1188. };
  1189. /**
  1190. * Returns a new Vector3 set witth the result of the mulliplication of the current Vector3 coordinates by the passed floats.
  1191. */
  1192. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  1193. return new Vector3(this.x * x, this.y * y, this.z * z);
  1194. };
  1195. /**
  1196. * Returns a new Vector3 set witth the result of the division of the current Vector3 coordinates by the passed ones.
  1197. */
  1198. Vector3.prototype.divide = function (otherVector) {
  1199. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  1200. };
  1201. /**
  1202. * Divides the current Vector3 coordinates by the passed ones and stores the result in the passed vector "result".
  1203. * Returns the current Vector3.
  1204. */
  1205. Vector3.prototype.divideToRef = function (otherVector, result) {
  1206. result.x = this.x / otherVector.x;
  1207. result.y = this.y / otherVector.y;
  1208. result.z = this.z / otherVector.z;
  1209. return this;
  1210. };
  1211. /**
  1212. * Updates the current Vector3 with the minimal coordinate values between its and the passed vector ones.
  1213. * Returns the updated Vector3.
  1214. */
  1215. Vector3.prototype.MinimizeInPlace = function (other) {
  1216. if (other.x < this.x)
  1217. this.x = other.x;
  1218. if (other.y < this.y)
  1219. this.y = other.y;
  1220. if (other.z < this.z)
  1221. this.z = other.z;
  1222. return this;
  1223. };
  1224. /**
  1225. * Updates the current Vector3 with the maximal coordinate values between its and the passed vector ones.
  1226. * Returns the updated Vector3.
  1227. */
  1228. Vector3.prototype.MaximizeInPlace = function (other) {
  1229. if (other.x > this.x)
  1230. this.x = other.x;
  1231. if (other.y > this.y)
  1232. this.y = other.y;
  1233. if (other.z > this.z)
  1234. this.z = other.z;
  1235. return this;
  1236. };
  1237. // Properties
  1238. /**
  1239. * Returns the length of the Vector3 (float).
  1240. */
  1241. Vector3.prototype.length = function () {
  1242. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  1243. };
  1244. /**
  1245. * Returns the squared length of the Vector3 (float).
  1246. */
  1247. Vector3.prototype.lengthSquared = function () {
  1248. return (this.x * this.x + this.y * this.y + this.z * this.z);
  1249. };
  1250. // Methods
  1251. /**
  1252. * Normalize the current Vector3.
  1253. * Returns the updated Vector3.
  1254. */
  1255. Vector3.prototype.normalize = function () {
  1256. var len = this.length();
  1257. if (len === 0 || len === 1.0)
  1258. return this;
  1259. var num = 1.0 / len;
  1260. this.x *= num;
  1261. this.y *= num;
  1262. this.z *= num;
  1263. return this;
  1264. };
  1265. /**
  1266. * Returns a new Vector3 copied from the current Vector3.
  1267. */
  1268. Vector3.prototype.clone = function () {
  1269. return new Vector3(this.x, this.y, this.z);
  1270. };
  1271. /**
  1272. * Copies the passed vector coordinates to the current Vector3 ones.
  1273. * Returns the updated Vector3.
  1274. */
  1275. Vector3.prototype.copyFrom = function (source) {
  1276. this.x = source.x;
  1277. this.y = source.y;
  1278. this.z = source.z;
  1279. return this;
  1280. };
  1281. /**
  1282. * Copies the passed floats to the current Vector3 coordinates.
  1283. * Returns the updated Vector3.
  1284. */
  1285. Vector3.prototype.copyFromFloats = function (x, y, z) {
  1286. this.x = x;
  1287. this.y = y;
  1288. this.z = z;
  1289. return this;
  1290. };
  1291. /**
  1292. * Copies the passed floats to the current Vector3 coordinates.
  1293. * Returns the updated Vector3.
  1294. */
  1295. Vector3.prototype.set = function (x, y, z) {
  1296. return this.copyFromFloats(x, y, z);
  1297. };
  1298. // Statics
  1299. /**
  1300. *
  1301. */
  1302. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  1303. var d0 = Vector3.Dot(vector0, axis) - size;
  1304. var d1 = Vector3.Dot(vector1, axis) - size;
  1305. var s = d0 / (d0 - d1);
  1306. return s;
  1307. };
  1308. /**
  1309. * Returns a new Vector3 set from the index "offset" of the passed array or Float32Array.
  1310. */
  1311. Vector3.FromArray = function (array, offset) {
  1312. if (!offset) {
  1313. offset = 0;
  1314. }
  1315. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  1316. };
  1317. /**
  1318. * Returns a new Vector3 set from the index "offset" of the passed Float32Array.
  1319. */
  1320. Vector3.FromFloatArray = function (array, offset) {
  1321. if (!offset) {
  1322. offset = 0;
  1323. }
  1324. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  1325. };
  1326. /**
  1327. * Sets the passed vector "result" with the element values from the index "offset" of the passed array or Float32Array.
  1328. */
  1329. Vector3.FromArrayToRef = function (array, offset, result) {
  1330. result.x = array[offset];
  1331. result.y = array[offset + 1];
  1332. result.z = array[offset + 2];
  1333. };
  1334. /**
  1335. * Sets the passed vector "result" with the element values from the index "offset" of the passed Float32Array.
  1336. */
  1337. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  1338. result.x = array[offset];
  1339. result.y = array[offset + 1];
  1340. result.z = array[offset + 2];
  1341. };
  1342. /**
  1343. * Sets the passed vector "result" with the passed floats.
  1344. */
  1345. Vector3.FromFloatsToRef = function (x, y, z, result) {
  1346. result.x = x;
  1347. result.y = y;
  1348. result.z = z;
  1349. };
  1350. /**
  1351. * Returns a new Vector3 set to (0.0, 0.0, 0.0).
  1352. */
  1353. Vector3.Zero = function () {
  1354. return new Vector3(0.0, 0.0, 0.0);
  1355. };
  1356. /**
  1357. * Returns a new Vector3 set to (0.0, 1.0, 0.0)
  1358. */
  1359. Vector3.Up = function () {
  1360. return new Vector3(0.0, 1.0, 0.0);
  1361. };
  1362. /**
  1363. * Returns a new Vector3 set to (0.0, 0.0, 1.0)
  1364. */
  1365. Vector3.Forward = function () {
  1366. return new Vector3(0.0, 0.0, 1.0);
  1367. };
  1368. /**
  1369. * Returns a new Vector3 set to (1.0, 0.0, 0.0)
  1370. */
  1371. Vector3.Right = function () {
  1372. return new Vector3(1.0, 0.0, 0.0);
  1373. };
  1374. /**
  1375. * Returns a new Vector3 set to (-1.0, 0.0, 0.0)
  1376. */
  1377. Vector3.Left = function () {
  1378. return new Vector3(-1.0, 0.0, 0.0);
  1379. };
  1380. /**
  1381. * Returns a new Vector3 set with the result of the transformation by the passed matrix of the passed vector.
  1382. * This method computes tranformed coordinates only, not transformed direction vectors.
  1383. */
  1384. Vector3.TransformCoordinates = function (vector, transformation) {
  1385. var result = Vector3.Zero();
  1386. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  1387. return result;
  1388. };
  1389. /**
  1390. * Sets the passed vector "result" coordinates with the result of the transformation by the passed matrix of the passed vector.
  1391. * This method computes tranformed coordinates only, not transformed direction vectors.
  1392. */
  1393. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  1394. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  1395. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  1396. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  1397. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  1398. result.x = x / w;
  1399. result.y = y / w;
  1400. result.z = z / w;
  1401. };
  1402. /**
  1403. * Sets the passed vector "result" coordinates with the result of the transformation by the passed matrix of the passed floats (x, y, z).
  1404. * This method computes tranformed coordinates only, not transformed direction vectors.
  1405. */
  1406. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  1407. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  1408. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  1409. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  1410. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  1411. result.x = rx / rw;
  1412. result.y = ry / rw;
  1413. result.z = rz / rw;
  1414. };
  1415. /**
  1416. * Returns a new Vector3 set with the result of the normal transformation by the passed matrix of the passed vector.
  1417. * This methods computes transformed normalized direction vectors only.
  1418. */
  1419. Vector3.TransformNormal = function (vector, transformation) {
  1420. var result = Vector3.Zero();
  1421. Vector3.TransformNormalToRef(vector, transformation, result);
  1422. return result;
  1423. };
  1424. /**
  1425. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed vector.
  1426. * This methods computes transformed normalized direction vectors only.
  1427. */
  1428. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  1429. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  1430. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  1431. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  1432. result.x = x;
  1433. result.y = y;
  1434. result.z = z;
  1435. };
  1436. /**
  1437. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed floats (x, y, z).
  1438. * This methods computes transformed normalized direction vectors only.
  1439. */
  1440. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  1441. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  1442. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  1443. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  1444. };
  1445. /**
  1446. * Returns a new Vector3 located for "amount" on the CatmullRom interpolation spline defined by the vectors "value1", "value2", "value3", "value4".
  1447. */
  1448. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  1449. var squared = amount * amount;
  1450. var cubed = amount * squared;
  1451. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  1452. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  1453. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  1454. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  1455. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  1456. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  1457. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  1458. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  1459. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  1460. return new Vector3(x, y, z);
  1461. };
  1462. /**
  1463. * Returns a new Vector3 set with the coordinates of "value", if the vector "value" is in the cube defined by the vectors "min" and "max".
  1464. * If a coordinate value of "value" is lower than one of the "min" coordinate, then this "value" coordinate is set with the "min" one.
  1465. * If a coordinate value of "value" is greater than one of the "max" coordinate, then this "value" coordinate is set with the "max" one.
  1466. */
  1467. Vector3.Clamp = function (value, min, max) {
  1468. var x = value.x;
  1469. x = (x > max.x) ? max.x : x;
  1470. x = (x < min.x) ? min.x : x;
  1471. var y = value.y;
  1472. y = (y > max.y) ? max.y : y;
  1473. y = (y < min.y) ? min.y : y;
  1474. var z = value.z;
  1475. z = (z > max.z) ? max.z : z;
  1476. z = (z < min.z) ? min.z : z;
  1477. return new Vector3(x, y, z);
  1478. };
  1479. /**
  1480. * Returns a new Vector3 located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2".
  1481. */
  1482. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  1483. var squared = amount * amount;
  1484. var cubed = amount * squared;
  1485. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  1486. var part2 = (-2.0 * cubed) + (3.0 * squared);
  1487. var part3 = (cubed - (2.0 * squared)) + amount;
  1488. var part4 = cubed - squared;
  1489. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  1490. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  1491. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  1492. return new Vector3(x, y, z);
  1493. };
  1494. /**
  1495. * Returns a new Vector3 located for "amount" (float) on the linear interpolation between the vectors "start" and "end".
  1496. */
  1497. Vector3.Lerp = function (start, end, amount) {
  1498. var result = new Vector3(0, 0, 0);
  1499. Vector3.LerpToRef(start, end, amount, result);
  1500. return result;
  1501. };
  1502. /**
  1503. * Sets the passed vector "result" with the result of the linear interpolation from the vector "start" for "amount" to the vector "end".
  1504. */
  1505. Vector3.LerpToRef = function (start, end, amount, result) {
  1506. result.x = start.x + ((end.x - start.x) * amount);
  1507. result.y = start.y + ((end.y - start.y) * amount);
  1508. result.z = start.z + ((end.z - start.z) * amount);
  1509. };
  1510. /**
  1511. * Returns the dot product (float) between the vectors "left" and "right".
  1512. */
  1513. Vector3.Dot = function (left, right) {
  1514. return (left.x * right.x + left.y * right.y + left.z * right.z);
  1515. };
  1516. /**
  1517. * Returns a new Vector3 as the cross product of the vectors "left" and "right".
  1518. * The cross product is then orthogonal to both "left" and "right".
  1519. */
  1520. Vector3.Cross = function (left, right) {
  1521. var result = Vector3.Zero();
  1522. Vector3.CrossToRef(left, right, result);
  1523. return result;
  1524. };
  1525. /**
  1526. * Sets the passed vector "result" with the cross product of "left" and "right".
  1527. * The cross product is then orthogonal to both "left" and "right".
  1528. */
  1529. Vector3.CrossToRef = function (left, right, result) {
  1530. MathTmp.Vector3[0].x = left.y * right.z - left.z * right.y;
  1531. MathTmp.Vector3[0].y = left.z * right.x - left.x * right.z;
  1532. MathTmp.Vector3[0].z = left.x * right.y - left.y * right.x;
  1533. result.copyFrom(MathTmp.Vector3[0]);
  1534. };
  1535. /**
  1536. * Returns a new Vector3 as the normalization of the passed vector.
  1537. */
  1538. Vector3.Normalize = function (vector) {
  1539. var result = Vector3.Zero();
  1540. Vector3.NormalizeToRef(vector, result);
  1541. return result;
  1542. };
  1543. /**
  1544. * Sets the passed vector "result" with the normalization of the passed first vector.
  1545. */
  1546. Vector3.NormalizeToRef = function (vector, result) {
  1547. result.copyFrom(vector);
  1548. result.normalize();
  1549. };
  1550. Vector3.Project = function (vector, world, transform, viewport) {
  1551. var cw = viewport.width;
  1552. var ch = viewport.height;
  1553. var cx = viewport.x;
  1554. var cy = viewport.y;
  1555. var viewportMatrix = Vector3._viewportMatrixCache ? Vector3._viewportMatrixCache : (Vector3._viewportMatrixCache = new Matrix());
  1556. Matrix.FromValuesToRef(cw / 2.0, 0, 0, 0, 0, -ch / 2.0, 0, 0, 0, 0, 0.5, 0, cx + cw / 2.0, ch / 2.0 + cy, 0.5, 1, viewportMatrix);
  1557. var matrix = Vector3._matrixCache ? Vector3._matrixCache : (Vector3._matrixCache = new Matrix());
  1558. world.multiplyToRef(transform, matrix);
  1559. matrix.multiplyToRef(viewportMatrix, matrix);
  1560. return Vector3.TransformCoordinates(vector, matrix);
  1561. };
  1562. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  1563. var matrix = Vector3._matrixCache ? Vector3._matrixCache : (Vector3._matrixCache = new Matrix());
  1564. world.multiplyToRef(transform, matrix);
  1565. matrix.invert();
  1566. source.x = source.x / viewportWidth * 2 - 1;
  1567. source.y = -(source.y / viewportHeight * 2 - 1);
  1568. var vector = Vector3.TransformCoordinates(source, matrix);
  1569. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  1570. if (MathTools.WithinEpsilon(num, 1.0)) {
  1571. vector = vector.scale(1.0 / num);
  1572. }
  1573. return vector;
  1574. };
  1575. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  1576. var matrix = Vector3._matrixCache ? Vector3._matrixCache : (Vector3._matrixCache = new Matrix());
  1577. world.multiplyToRef(view, matrix);
  1578. matrix.multiplyToRef(projection, matrix);
  1579. matrix.invert();
  1580. var screenSource = new Vector3(source.x / viewportWidth * 2 - 1, -(source.y / viewportHeight * 2 - 1), 2 * source.z - 1.0);
  1581. var vector = Vector3.TransformCoordinates(screenSource, matrix);
  1582. var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15];
  1583. if (MathTools.WithinEpsilon(num, 1.0)) {
  1584. vector = vector.scale(1.0 / num);
  1585. }
  1586. return vector;
  1587. };
  1588. Vector3.Minimize = function (left, right) {
  1589. var min = left.clone();
  1590. min.MinimizeInPlace(right);
  1591. return min;
  1592. };
  1593. Vector3.Maximize = function (left, right) {
  1594. var max = left.clone();
  1595. max.MaximizeInPlace(right);
  1596. return max;
  1597. };
  1598. /**
  1599. * Returns the distance (float) between the vectors "value1" and "value2".
  1600. */
  1601. Vector3.Distance = function (value1, value2) {
  1602. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  1603. };
  1604. /**
  1605. * Returns the squared distance (float) between the vectors "value1" and "value2".
  1606. */
  1607. Vector3.DistanceSquared = function (value1, value2) {
  1608. var x = value1.x - value2.x;
  1609. var y = value1.y - value2.y;
  1610. var z = value1.z - value2.z;
  1611. return (x * x) + (y * y) + (z * z);
  1612. };
  1613. /**
  1614. * Returns a new Vector3 located at the center between "value1" and "value2".
  1615. */
  1616. Vector3.Center = function (value1, value2) {
  1617. var center = value1.add(value2);
  1618. center.scaleInPlace(0.5);
  1619. return center;
  1620. };
  1621. /**
  1622. * Given three orthogonal normalized left-handed oriented Vector3 axis in space (target system),
  1623. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  1624. * to something in order to rotate it from its local system to the given target system.
  1625. * Note : axis1, axis2 and axis3 are normalized during this operation.
  1626. * Returns a new Vector3.
  1627. */
  1628. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  1629. var rotation = Vector3.Zero();
  1630. Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
  1631. return rotation;
  1632. };
  1633. /**
  1634. * The same than RotationFromAxis but updates the passed ref Vector3 parameter instead of returning a new Vector3.
  1635. */
  1636. Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
  1637. var quat = MathTmp.Quaternion[0];
  1638. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  1639. quat.toEulerAnglesToRef(ref);
  1640. };
  1641. return Vector3;
  1642. }());
  1643. BABYLON.Vector3 = Vector3;
  1644. //Vector4 class created for EulerAngle class conversion to Quaternion
  1645. var Vector4 = (function () {
  1646. /**
  1647. * Creates a Vector4 object from the passed floats.
  1648. */
  1649. function Vector4(x, y, z, w) {
  1650. this.x = x;
  1651. this.y = y;
  1652. this.z = z;
  1653. this.w = w;
  1654. }
  1655. /**
  1656. * Returns the string with the Vector4 coordinates.
  1657. */
  1658. Vector4.prototype.toString = function () {
  1659. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  1660. };
  1661. /**
  1662. * Returns the string "Vector4".
  1663. */
  1664. Vector4.prototype.getClassName = function () {
  1665. return "Vector4";
  1666. };
  1667. /**
  1668. * Returns the Vector4 hash code.
  1669. */
  1670. Vector4.prototype.getHashCode = function () {
  1671. var hash = this.x || 0;
  1672. hash = (hash * 397) ^ (this.y || 0);
  1673. hash = (hash * 397) ^ (this.z || 0);
  1674. hash = (hash * 397) ^ (this.w || 0);
  1675. return hash;
  1676. };
  1677. // Operators
  1678. /**
  1679. * Returns a new array populated with 4 elements : the Vector4 coordinates.
  1680. */
  1681. Vector4.prototype.asArray = function () {
  1682. var result = [];
  1683. this.toArray(result, 0);
  1684. return result;
  1685. };
  1686. /**
  1687. * Populates the passed array from the passed index with the Vector4 coordinates.
  1688. * Returns the Vector4.
  1689. */
  1690. Vector4.prototype.toArray = function (array, index) {
  1691. if (index === undefined) {
  1692. index = 0;
  1693. }
  1694. array[index] = this.x;
  1695. array[index + 1] = this.y;
  1696. array[index + 2] = this.z;
  1697. array[index + 3] = this.w;
  1698. return this;
  1699. };
  1700. /**
  1701. * Adds the passed vector to the current Vector4.
  1702. * Returns the updated Vector4.
  1703. */
  1704. Vector4.prototype.addInPlace = function (otherVector) {
  1705. this.x += otherVector.x;
  1706. this.y += otherVector.y;
  1707. this.z += otherVector.z;
  1708. this.w += otherVector.w;
  1709. return this;
  1710. };
  1711. /**
  1712. * Returns a new Vector4 as the result of the addition of the current Vector4 and the passed one.
  1713. */
  1714. Vector4.prototype.add = function (otherVector) {
  1715. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  1716. };
  1717. /**
  1718. * Updates the passed vector "result" with the result of the addition of the current Vector4 and the passed one.
  1719. * Returns the current Vector4.
  1720. */
  1721. Vector4.prototype.addToRef = function (otherVector, result) {
  1722. result.x = this.x + otherVector.x;
  1723. result.y = this.y + otherVector.y;
  1724. result.z = this.z + otherVector.z;
  1725. result.w = this.w + otherVector.w;
  1726. return this;
  1727. };
  1728. /**
  1729. * Subtract in place the passed vector from the current Vector4.
  1730. * Returns the updated Vector4.
  1731. */
  1732. Vector4.prototype.subtractInPlace = function (otherVector) {
  1733. this.x -= otherVector.x;
  1734. this.y -= otherVector.y;
  1735. this.z -= otherVector.z;
  1736. this.w -= otherVector.w;
  1737. return this;
  1738. };
  1739. /**
  1740. * Returns a new Vector4 with the result of the subtraction of the passed vector from the current Vector4.
  1741. */
  1742. Vector4.prototype.subtract = function (otherVector) {
  1743. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  1744. };
  1745. /**
  1746. * Sets the passed vector "result" with the result of the subtraction of the passed vector from the current Vector4.
  1747. * Returns the current Vector4.
  1748. */
  1749. Vector4.prototype.subtractToRef = function (otherVector, result) {
  1750. result.x = this.x - otherVector.x;
  1751. result.y = this.y - otherVector.y;
  1752. result.z = this.z - otherVector.z;
  1753. result.w = this.w - otherVector.w;
  1754. return this;
  1755. };
  1756. /**
  1757. * Returns a new Vector4 set with the result of the subtraction of the passed floats from the current Vector4 coordinates.
  1758. */
  1759. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  1760. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  1761. };
  1762. /**
  1763. * Sets the passed vector "result" set with the result of the subtraction of the passed floats from the current Vector4 coordinates.
  1764. * Returns the current Vector4.
  1765. */
  1766. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  1767. result.x = this.x - x;
  1768. result.y = this.y - y;
  1769. result.z = this.z - z;
  1770. result.w = this.w - w;
  1771. return this;
  1772. };
  1773. /**
  1774. * Returns a new Vector4 set with the current Vector4 negated coordinates.
  1775. */
  1776. Vector4.prototype.negate = function () {
  1777. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  1778. };
  1779. /**
  1780. * Multiplies the current Vector4 coordinates by scale (float).
  1781. * Returns the updated Vector4.
  1782. */
  1783. Vector4.prototype.scaleInPlace = function (scale) {
  1784. this.x *= scale;
  1785. this.y *= scale;
  1786. this.z *= scale;
  1787. this.w *= scale;
  1788. return this;
  1789. };
  1790. /**
  1791. * Returns a new Vector4 set with the current Vector4 coordinates multiplied by scale (float).
  1792. */
  1793. Vector4.prototype.scale = function (scale) {
  1794. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  1795. };
  1796. /**
  1797. * Sets the passed vector "result" with the current Vector4 coordinates multiplied by scale (float).
  1798. * Returns the current Vector4.
  1799. */
  1800. Vector4.prototype.scaleToRef = function (scale, result) {
  1801. result.x = this.x * scale;
  1802. result.y = this.y * scale;
  1803. result.z = this.z * scale;
  1804. result.w = this.w * scale;
  1805. return this;
  1806. };
  1807. /**
  1808. * Boolean : True if the current Vector4 coordinates are stricly equal to the passed ones.
  1809. */
  1810. Vector4.prototype.equals = function (otherVector) {
  1811. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  1812. };
  1813. /**
  1814. * Boolean : True if the current Vector4 coordinates are each beneath the distance "epsilon" from the passed vector ones.
  1815. */
  1816. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  1817. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  1818. return otherVector
  1819. && MathTools.WithinEpsilon(this.x, otherVector.x, epsilon)
  1820. && MathTools.WithinEpsilon(this.y, otherVector.y, epsilon)
  1821. && MathTools.WithinEpsilon(this.z, otherVector.z, epsilon)
  1822. && MathTools.WithinEpsilon(this.w, otherVector.w, epsilon);
  1823. };
  1824. /**
  1825. * Boolean : True if the passed floats are strictly equal to the current Vector4 coordinates.
  1826. */
  1827. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  1828. return this.x === x && this.y === y && this.z === z && this.w === w;
  1829. };
  1830. /**
  1831. * Multiplies in place the current Vector4 by the passed one.
  1832. * Returns the updated Vector4.
  1833. */
  1834. Vector4.prototype.multiplyInPlace = function (otherVector) {
  1835. this.x *= otherVector.x;
  1836. this.y *= otherVector.y;
  1837. this.z *= otherVector.z;
  1838. this.w *= otherVector.w;
  1839. return this;
  1840. };
  1841. /**
  1842. * Returns a new Vector4 set with the multiplication result of the current Vector4 and the passed one.
  1843. */
  1844. Vector4.prototype.multiply = function (otherVector) {
  1845. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  1846. };
  1847. /**
  1848. * Updates the passed vector "result" with the multiplication result of the current Vector4 and the passed one.
  1849. * Returns the current Vector4.
  1850. */
  1851. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  1852. result.x = this.x * otherVector.x;
  1853. result.y = this.y * otherVector.y;
  1854. result.z = this.z * otherVector.z;
  1855. result.w = this.w * otherVector.w;
  1856. return this;
  1857. };
  1858. /**
  1859. * Returns a new Vector4 set with the multiplication result of the passed floats and the current Vector4 coordinates.
  1860. */
  1861. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  1862. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  1863. };
  1864. /**
  1865. * Returns a new Vector4 set with the division result of the current Vector4 by the passed one.
  1866. */
  1867. Vector4.prototype.divide = function (otherVector) {
  1868. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  1869. };
  1870. /**
  1871. * Updates the passed vector "result" with the division result of the current Vector4 by the passed one.
  1872. * Returns the current Vector4.
  1873. */
  1874. Vector4.prototype.divideToRef = function (otherVector, result) {
  1875. result.x = this.x / otherVector.x;
  1876. result.y = this.y / otherVector.y;
  1877. result.z = this.z / otherVector.z;
  1878. result.w = this.w / otherVector.w;
  1879. return this;
  1880. };
  1881. /**
  1882. * Updates the Vector4 coordinates with the minimum values between its own and the passed vector ones.
  1883. */
  1884. Vector4.prototype.MinimizeInPlace = function (other) {
  1885. if (other.x < this.x)
  1886. this.x = other.x;
  1887. if (other.y < this.y)
  1888. this.y = other.y;
  1889. if (other.z < this.z)
  1890. this.z = other.z;
  1891. if (other.w < this.w)
  1892. this.w = other.w;
  1893. return this;
  1894. };
  1895. /**
  1896. * Updates the Vector4 coordinates with the maximum values between its own and the passed vector ones.
  1897. */
  1898. Vector4.prototype.MaximizeInPlace = function (other) {
  1899. if (other.x > this.x)
  1900. this.x = other.x;
  1901. if (other.y > this.y)
  1902. this.y = other.y;
  1903. if (other.z > this.z)
  1904. this.z = other.z;
  1905. if (other.w > this.w)
  1906. this.w = other.w;
  1907. return this;
  1908. };
  1909. // Properties
  1910. /**
  1911. * Returns the Vector4 length (float).
  1912. */
  1913. Vector4.prototype.length = function () {
  1914. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  1915. };
  1916. /**
  1917. * Returns the Vector4 squared length (float).
  1918. */
  1919. Vector4.prototype.lengthSquared = function () {
  1920. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  1921. };
  1922. // Methods
  1923. /**
  1924. * Normalizes in place the Vector4.
  1925. * Returns the updated Vector4.
  1926. */
  1927. Vector4.prototype.normalize = function () {
  1928. var len = this.length();
  1929. if (len === 0)
  1930. return this;
  1931. var num = 1.0 / len;
  1932. this.x *= num;
  1933. this.y *= num;
  1934. this.z *= num;
  1935. this.w *= num;
  1936. return this;
  1937. };
  1938. /**
  1939. * Returns a new Vector3 from the Vector4 (x, y, z) coordinates.
  1940. */
  1941. Vector4.prototype.toVector3 = function () {
  1942. return new Vector3(this.x, this.y, this.z);
  1943. };
  1944. /**
  1945. * Returns a new Vector4 copied from the current one.
  1946. */
  1947. Vector4.prototype.clone = function () {
  1948. return new Vector4(this.x, this.y, this.z, this.w);
  1949. };
  1950. /**
  1951. * Updates the current Vector4 with the passed one coordinates.
  1952. * Returns the updated Vector4.
  1953. */
  1954. Vector4.prototype.copyFrom = function (source) {
  1955. this.x = source.x;
  1956. this.y = source.y;
  1957. this.z = source.z;
  1958. this.w = source.w;
  1959. return this;
  1960. };
  1961. /**
  1962. * Updates the current Vector4 coordinates with the passed floats.
  1963. * Returns the updated Vector4.
  1964. */
  1965. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  1966. this.x = x;
  1967. this.y = y;
  1968. this.z = z;
  1969. this.w = w;
  1970. return this;
  1971. };
  1972. /**
  1973. * Updates the current Vector4 coordinates with the passed floats.
  1974. * Returns the updated Vector4.
  1975. */
  1976. Vector4.prototype.set = function (x, y, z, w) {
  1977. return this.copyFromFloats(x, y, z, w);
  1978. };
  1979. // Statics
  1980. /**
  1981. * Returns a new Vector4 set from the starting index of the passed array.
  1982. */
  1983. Vector4.FromArray = function (array, offset) {
  1984. if (!offset) {
  1985. offset = 0;
  1986. }
  1987. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  1988. };
  1989. /**
  1990. * Updates the passed vector "result" from the starting index of the passed array.
  1991. */
  1992. Vector4.FromArrayToRef = function (array, offset, result) {
  1993. result.x = array[offset];
  1994. result.y = array[offset + 1];
  1995. result.z = array[offset + 2];
  1996. result.w = array[offset + 3];
  1997. };
  1998. /**
  1999. * Updates the passed vector "result" from the starting index of the passed Float32Array.
  2000. */
  2001. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  2002. result.x = array[offset];
  2003. result.y = array[offset + 1];
  2004. result.z = array[offset + 2];
  2005. result.w = array[offset + 3];
  2006. };
  2007. /**
  2008. * Updates the passed vector "result" coordinates from the passed floats.
  2009. */
  2010. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  2011. result.x = x;
  2012. result.y = y;
  2013. result.z = z;
  2014. result.w = w;
  2015. };
  2016. /**
  2017. * Returns a new Vector4 set to (0.0, 0.0, 0.0, 0.0)
  2018. */
  2019. Vector4.Zero = function () {
  2020. return new Vector4(0.0, 0.0, 0.0, 0.0);
  2021. };
  2022. /**
  2023. * Returns a new normalized Vector4 from the passed one.
  2024. */
  2025. Vector4.Normalize = function (vector) {
  2026. var result = Vector4.Zero();
  2027. Vector4.NormalizeToRef(vector, result);
  2028. return result;
  2029. };
  2030. /**
  2031. * Updates the passed vector "result" from the normalization of the passed one.
  2032. */
  2033. Vector4.NormalizeToRef = function (vector, result) {
  2034. result.copyFrom(vector);
  2035. result.normalize();
  2036. };
  2037. Vector4.Minimize = function (left, right) {
  2038. var min = left.clone();
  2039. min.MinimizeInPlace(right);
  2040. return min;
  2041. };
  2042. Vector4.Maximize = function (left, right) {
  2043. var max = left.clone();
  2044. max.MaximizeInPlace(right);
  2045. return max;
  2046. };
  2047. /**
  2048. * Returns the distance (float) between the vectors "value1" and "value2".
  2049. */
  2050. Vector4.Distance = function (value1, value2) {
  2051. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  2052. };
  2053. /**
  2054. * Returns the squared distance (float) between the vectors "value1" and "value2".
  2055. */
  2056. Vector4.DistanceSquared = function (value1, value2) {
  2057. var x = value1.x - value2.x;
  2058. var y = value1.y - value2.y;
  2059. var z = value1.z - value2.z;
  2060. var w = value1.w - value2.w;
  2061. return (x * x) + (y * y) + (z * z) + (w * w);
  2062. };
  2063. /**
  2064. * Returns a new Vector4 located at the center between the vectors "value1" and "value2".
  2065. */
  2066. Vector4.Center = function (value1, value2) {
  2067. var center = value1.add(value2);
  2068. center.scaleInPlace(0.5);
  2069. return center;
  2070. };
  2071. /**
  2072. * Returns a new Vector4 set with the result of the normal transformation by the passed matrix of the passed vector.
  2073. * This methods computes transformed normalized direction vectors only.
  2074. */
  2075. Vector4.TransformNormal = function (vector, transformation) {
  2076. var result = Vector4.Zero();
  2077. Vector4.TransformNormalToRef(vector, transformation, result);
  2078. return result;
  2079. };
  2080. /**
  2081. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed vector.
  2082. * This methods computes transformed normalized direction vectors only.
  2083. */
  2084. Vector4.TransformNormalToRef = function (vector, transformation, result) {
  2085. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  2086. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  2087. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  2088. result.x = x;
  2089. result.y = y;
  2090. result.z = z;
  2091. result.w = vector.w;
  2092. };
  2093. /**
  2094. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed floats (x, y, z, w).
  2095. * This methods computes transformed normalized direction vectors only.
  2096. */
  2097. Vector4.TransformNormalFromFloatsToRef = function (x, y, z, w, transformation, result) {
  2098. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  2099. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  2100. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  2101. result.w = w;
  2102. };
  2103. return Vector4;
  2104. }());
  2105. BABYLON.Vector4 = Vector4;
  2106. var Size = (function () {
  2107. /**
  2108. * Creates a Size object from the passed width and height (floats).
  2109. */
  2110. function Size(width, height) {
  2111. this.width = width;
  2112. this.height = height;
  2113. }
  2114. // Returns a string with the Size width and height.
  2115. Size.prototype.toString = function () {
  2116. return "{W: " + this.width + ", H: " + this.height + "}";
  2117. };
  2118. /**
  2119. * Returns the string "Size"
  2120. */
  2121. Size.prototype.getClassName = function () {
  2122. return "Size";
  2123. };
  2124. /**
  2125. * Returns the Size hash code.
  2126. */
  2127. Size.prototype.getHashCode = function () {
  2128. var hash = this.width || 0;
  2129. hash = (hash * 397) ^ (this.height || 0);
  2130. return hash;
  2131. };
  2132. /**
  2133. * Updates the current size from the passed one.
  2134. * Returns the updated Size.
  2135. */
  2136. Size.prototype.copyFrom = function (src) {
  2137. this.width = src.width;
  2138. this.height = src.height;
  2139. };
  2140. /**
  2141. * Updates in place the current Size from the passed floats.
  2142. * Returns the updated Size.
  2143. */
  2144. Size.prototype.copyFromFloats = function (width, height) {
  2145. this.width = width;
  2146. this.height = height;
  2147. return this;
  2148. };
  2149. /**
  2150. * Updates in place the current Size from the passed floats.
  2151. * Returns the updated Size.
  2152. */
  2153. Size.prototype.set = function (width, height) {
  2154. return this.copyFromFloats(width, height);
  2155. };
  2156. /**
  2157. * Returns a new Size set with the multiplication result of the current Size and the passed floats.
  2158. */
  2159. Size.prototype.multiplyByFloats = function (w, h) {
  2160. return new Size(this.width * w, this.height * h);
  2161. };
  2162. /**
  2163. * Returns a new Size copied from the passed one.
  2164. */
  2165. Size.prototype.clone = function () {
  2166. return new Size(this.width, this.height);
  2167. };
  2168. /**
  2169. * Boolean : True if the current Size and the passed one width and height are strictly equal.
  2170. */
  2171. Size.prototype.equals = function (other) {
  2172. if (!other) {
  2173. return false;
  2174. }
  2175. return (this.width === other.width) && (this.height === other.height);
  2176. };
  2177. Object.defineProperty(Size.prototype, "surface", {
  2178. /**
  2179. * Returns the surface of the Size : width * height (float).
  2180. */
  2181. get: function () {
  2182. return this.width * this.height;
  2183. },
  2184. enumerable: true,
  2185. configurable: true
  2186. });
  2187. /**
  2188. * Returns a new Size set to (0.0, 0.0)
  2189. */
  2190. Size.Zero = function () {
  2191. return new Size(0.0, 0.0);
  2192. };
  2193. /**
  2194. * Returns a new Size set as the addition result of the current Size and the passed one.
  2195. */
  2196. Size.prototype.add = function (otherSize) {
  2197. var r = new Size(this.width + otherSize.width, this.height + otherSize.height);
  2198. return r;
  2199. };
  2200. /**
  2201. * Returns a new Size set as the subtraction result of the passed one from the current Size.
  2202. */
  2203. Size.prototype.subtract = function (otherSize) {
  2204. var r = new Size(this.width - otherSize.width, this.height - otherSize.height);
  2205. return r;
  2206. };
  2207. /**
  2208. * Returns a new Size set at the linear interpolation "amount" between "start" and "end".
  2209. */
  2210. Size.Lerp = function (start, end, amount) {
  2211. var w = start.width + ((end.width - start.width) * amount);
  2212. var h = start.height + ((end.height - start.height) * amount);
  2213. return new Size(w, h);
  2214. };
  2215. return Size;
  2216. }());
  2217. BABYLON.Size = Size;
  2218. var Quaternion = (function () {
  2219. /**
  2220. * Creates a new Quaternion from the passed floats.
  2221. */
  2222. function Quaternion(x, y, z, w) {
  2223. if (x === void 0) { x = 0.0; }
  2224. if (y === void 0) { y = 0.0; }
  2225. if (z === void 0) { z = 0.0; }
  2226. if (w === void 0) { w = 1.0; }
  2227. this.x = x;
  2228. this.y = y;
  2229. this.z = z;
  2230. this.w = w;
  2231. }
  2232. /**
  2233. * Returns a string with the Quaternion coordinates.
  2234. */
  2235. Quaternion.prototype.toString = function () {
  2236. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  2237. };
  2238. /**
  2239. * Returns the string "Quaternion".
  2240. */
  2241. Quaternion.prototype.getClassName = function () {
  2242. return "Quaternion";
  2243. };
  2244. /**
  2245. * Returns the Quaternion hash code.
  2246. */
  2247. Quaternion.prototype.getHashCode = function () {
  2248. var hash = this.x || 0;
  2249. hash = (hash * 397) ^ (this.y || 0);
  2250. hash = (hash * 397) ^ (this.z || 0);
  2251. hash = (hash * 397) ^ (this.w || 0);
  2252. return hash;
  2253. };
  2254. /**
  2255. * Returns a new array populated with 4 elements : the Quaternion coordinates.
  2256. */
  2257. Quaternion.prototype.asArray = function () {
  2258. return [this.x, this.y, this.z, this.w];
  2259. };
  2260. /**
  2261. * Boolean : True if the current Quaterion and the passed one coordinates are strictly equal.
  2262. */
  2263. Quaternion.prototype.equals = function (otherQuaternion) {
  2264. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  2265. };
  2266. /**
  2267. * Returns a new Quaternion copied from the current one.
  2268. */
  2269. Quaternion.prototype.clone = function () {
  2270. return new Quaternion(this.x, this.y, this.z, this.w);
  2271. };
  2272. /**
  2273. * Updates the current Quaternion from the passed one coordinates.
  2274. * Returns the updated Quaterion.
  2275. */
  2276. Quaternion.prototype.copyFrom = function (other) {
  2277. this.x = other.x;
  2278. this.y = other.y;
  2279. this.z = other.z;
  2280. this.w = other.w;
  2281. return this;
  2282. };
  2283. /**
  2284. * Updates the current Quaternion from the passed float coordinates.
  2285. * Returns the updated Quaterion.
  2286. */
  2287. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  2288. this.x = x;
  2289. this.y = y;
  2290. this.z = z;
  2291. this.w = w;
  2292. return this;
  2293. };
  2294. /**
  2295. * Updates the current Quaternion from the passed float coordinates.
  2296. * Returns the updated Quaterion.
  2297. */
  2298. Quaternion.prototype.set = function (x, y, z, w) {
  2299. return this.copyFromFloats(x, y, z, w);
  2300. };
  2301. /**
  2302. * Returns a new Quaternion as the addition result of the passed one and the current Quaternion.
  2303. */
  2304. Quaternion.prototype.add = function (other) {
  2305. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  2306. };
  2307. /**
  2308. * Returns a new Quaternion as the subtraction result of the passed one from the current Quaternion.
  2309. */
  2310. Quaternion.prototype.subtract = function (other) {
  2311. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  2312. };
  2313. /**
  2314. * Returns a new Quaternion set by multiplying the current Quaterion coordinates by the float "scale".
  2315. */
  2316. Quaternion.prototype.scale = function (value) {
  2317. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  2318. };
  2319. /**
  2320. * Returns a new Quaternion set as the quaternion mulplication result of the current one with the passed one "q1".
  2321. */
  2322. Quaternion.prototype.multiply = function (q1) {
  2323. var result = new Quaternion(0, 0, 0, 1.0);
  2324. this.multiplyToRef(q1, result);
  2325. return result;
  2326. };
  2327. /**
  2328. * Sets the passed "result" as the quaternion mulplication result of the current one with the passed one "q1".
  2329. * Returns the current Quaternion.
  2330. */
  2331. Quaternion.prototype.multiplyToRef = function (q1, result) {
  2332. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  2333. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  2334. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  2335. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  2336. result.copyFromFloats(x, y, z, w);
  2337. return this;
  2338. };
  2339. /**
  2340. * Updates the current Quaternion with the quaternion mulplication result of itself with the passed one "q1".
  2341. * Returns the updated Quaternion.
  2342. */
  2343. Quaternion.prototype.multiplyInPlace = function (q1) {
  2344. this.multiplyToRef(q1, this);
  2345. return this;
  2346. };
  2347. /**
  2348. * Sets the passed "ref" with the conjugation of the current Quaternion.
  2349. * Returns the current Quaternion.
  2350. */
  2351. Quaternion.prototype.conjugateToRef = function (ref) {
  2352. ref.copyFromFloats(-this.x, -this.y, -this.z, this.w);
  2353. return this;
  2354. };
  2355. /**
  2356. * Conjugates in place the current Quaternion.
  2357. * Returns the updated Quaternion.
  2358. */
  2359. Quaternion.prototype.conjugateInPlace = function () {
  2360. this.x *= -1;
  2361. this.y *= -1;
  2362. this.z *= -1;
  2363. return this;
  2364. };
  2365. /**
  2366. * Returns a new Quaternion as the conjugate of the current Quaternion.
  2367. */
  2368. Quaternion.prototype.conjugate = function () {
  2369. var result = new Quaternion(-this.x, -this.y, -this.z, this.w);
  2370. return result;
  2371. };
  2372. /**
  2373. * Returns the Quaternion length (float).
  2374. */
  2375. Quaternion.prototype.length = function () {
  2376. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  2377. };
  2378. /**
  2379. * Normalize in place the current Quaternion.
  2380. * Returns the updated Quaternion.
  2381. */
  2382. Quaternion.prototype.normalize = function () {
  2383. var length = 1.0 / this.length();
  2384. this.x *= length;
  2385. this.y *= length;
  2386. this.z *= length;
  2387. this.w *= length;
  2388. return this;
  2389. };
  2390. /**
  2391. * Returns a new Vector3 set with the Euler angles translated from the current Quaternion.
  2392. */
  2393. Quaternion.prototype.toEulerAngles = function (order) {
  2394. if (order === void 0) { order = "YZX"; }
  2395. var result = Vector3.Zero();
  2396. this.toEulerAnglesToRef(result, order);
  2397. return result;
  2398. };
  2399. /**
  2400. * Sets the passed vector3 "result" with the Euler angles translated from the current Quaternion.
  2401. * Returns the current Quaternion.
  2402. */
  2403. Quaternion.prototype.toEulerAnglesToRef = function (result, order) {
  2404. if (order === void 0) { order = "YZX"; }
  2405. var qz = this.z;
  2406. var qx = this.x;
  2407. var qy = this.y;
  2408. var qw = this.w;
  2409. var sqw = qw * qw;
  2410. var sqz = qz * qz;
  2411. var sqx = qx * qx;
  2412. var sqy = qy * qy;
  2413. var zAxisY = qy * qz - qx * qw;
  2414. var limit = .4999999;
  2415. if (zAxisY < -limit) {
  2416. result.y = 2 * Math.atan2(qy, qw);
  2417. result.x = Math.PI / 2;
  2418. result.z = 0;
  2419. }
  2420. else if (zAxisY > limit) {
  2421. result.y = 2 * Math.atan2(qy, qw);
  2422. result.x = -Math.PI / 2;
  2423. result.z = 0;
  2424. }
  2425. else {
  2426. result.z = Math.atan2(2.0 * (qx * qy + qz * qw), (-sqz - sqx + sqy + sqw));
  2427. result.x = Math.asin(-2.0 * (qz * qy - qx * qw));
  2428. result.y = Math.atan2(2.0 * (qz * qx + qy * qw), (sqz - sqx - sqy + sqw));
  2429. }
  2430. return this;
  2431. };
  2432. /**
  2433. * Updates the passed rotation matrix with the current Quaternion values.
  2434. * Returns the current Quaternion.
  2435. */
  2436. Quaternion.prototype.toRotationMatrix = function (result) {
  2437. var xx = this.x * this.x;
  2438. var yy = this.y * this.y;
  2439. var zz = this.z * this.z;
  2440. var xy = this.x * this.y;
  2441. var zw = this.z * this.w;
  2442. var zx = this.z * this.x;
  2443. var yw = this.y * this.w;
  2444. var yz = this.y * this.z;
  2445. var xw = this.x * this.w;
  2446. result.m[0] = 1.0 - (2.0 * (yy + zz));
  2447. result.m[1] = 2.0 * (xy + zw);
  2448. result.m[2] = 2.0 * (zx - yw);
  2449. result.m[3] = 0;
  2450. result.m[4] = 2.0 * (xy - zw);
  2451. result.m[5] = 1.0 - (2.0 * (zz + xx));
  2452. result.m[6] = 2.0 * (yz + xw);
  2453. result.m[7] = 0;
  2454. result.m[8] = 2.0 * (zx + yw);
  2455. result.m[9] = 2.0 * (yz - xw);
  2456. result.m[10] = 1.0 - (2.0 * (yy + xx));
  2457. result.m[11] = 0;
  2458. result.m[12] = 0;
  2459. result.m[13] = 0;
  2460. result.m[14] = 0;
  2461. result.m[15] = 1.0;
  2462. return this;
  2463. };
  2464. /**
  2465. * Updates the current Quaternion from the passed rotation matrix values.
  2466. * Returns the updated Quaternion.
  2467. */
  2468. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  2469. Quaternion.FromRotationMatrixToRef(matrix, this);
  2470. return this;
  2471. };
  2472. // Statics
  2473. /**
  2474. * Returns a new Quaternion set from the passed rotation matrix values.
  2475. */
  2476. Quaternion.FromRotationMatrix = function (matrix) {
  2477. var result = new Quaternion();
  2478. Quaternion.FromRotationMatrixToRef(matrix, result);
  2479. return result;
  2480. };
  2481. /**
  2482. * Updates the passed quaternion "result" with the passed rotation matrix values.
  2483. */
  2484. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  2485. var data = matrix.m;
  2486. var m11 = data[0], m12 = data[4], m13 = data[8];
  2487. var m21 = data[1], m22 = data[5], m23 = data[9];
  2488. var m31 = data[2], m32 = data[6], m33 = data[10];
  2489. var trace = m11 + m22 + m33;
  2490. var s;
  2491. if (trace > 0) {
  2492. s = 0.5 / Math.sqrt(trace + 1.0);
  2493. result.w = 0.25 / s;
  2494. result.x = (m32 - m23) * s;
  2495. result.y = (m13 - m31) * s;
  2496. result.z = (m21 - m12) * s;
  2497. }
  2498. else if (m11 > m22 && m11 > m33) {
  2499. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  2500. result.w = (m32 - m23) / s;
  2501. result.x = 0.25 * s;
  2502. result.y = (m12 + m21) / s;
  2503. result.z = (m13 + m31) / s;
  2504. }
  2505. else if (m22 > m33) {
  2506. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  2507. result.w = (m13 - m31) / s;
  2508. result.x = (m12 + m21) / s;
  2509. result.y = 0.25 * s;
  2510. result.z = (m23 + m32) / s;
  2511. }
  2512. else {
  2513. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  2514. result.w = (m21 - m12) / s;
  2515. result.x = (m13 + m31) / s;
  2516. result.y = (m23 + m32) / s;
  2517. result.z = 0.25 * s;
  2518. }
  2519. };
  2520. /**
  2521. * Returns a new Quaternion set to (0.0, 0.0, 0.0).
  2522. */
  2523. Quaternion.Zero = function () {
  2524. return new Quaternion(0.0, 0.0, 0.0, 0.0);
  2525. };
  2526. /**
  2527. * Returns a new Quaternion as the inverted current Quaternion.
  2528. */
  2529. Quaternion.Inverse = function (q) {
  2530. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  2531. };
  2532. /**
  2533. * Returns the identity Quaternion.
  2534. */
  2535. Quaternion.Identity = function () {
  2536. return new Quaternion(0.0, 0.0, 0.0, 1.0);
  2537. };
  2538. Quaternion.IsIdentity = function (quaternion) {
  2539. return quaternion && quaternion.x === 0 && quaternion.y === 0 && quaternion.z === 0 && quaternion.w === 1;
  2540. };
  2541. /**
  2542. * Returns a new Quaternion set from the passed axis (Vector3) and angle in radians (float).
  2543. */
  2544. Quaternion.RotationAxis = function (axis, angle) {
  2545. return Quaternion.RotationAxisToRef(axis, angle, new Quaternion());
  2546. };
  2547. /**
  2548. * Sets the passed quaternion "result" from the passed axis (Vector3) and angle in radians (float).
  2549. */
  2550. Quaternion.RotationAxisToRef = function (axis, angle, result) {
  2551. var sin = Math.sin(angle / 2);
  2552. axis.normalize();
  2553. result.w = Math.cos(angle / 2);
  2554. result.x = axis.x * sin;
  2555. result.y = axis.y * sin;
  2556. result.z = axis.z * sin;
  2557. return result;
  2558. };
  2559. /**
  2560. * Retuns a new Quaternion set from the starting index of the passed array.
  2561. */
  2562. Quaternion.FromArray = function (array, offset) {
  2563. if (!offset) {
  2564. offset = 0;
  2565. }
  2566. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  2567. };
  2568. /**
  2569. * Returns a new Quaternion set from the passed Euler float angles (y, x, z).
  2570. */
  2571. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  2572. var q = new Quaternion();
  2573. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, q);
  2574. return q;
  2575. };
  2576. /**
  2577. * Sets the passed quaternion "result" from the passed float Euler angles (y, x, z).
  2578. */
  2579. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  2580. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  2581. var halfRoll = roll * 0.5;
  2582. var halfPitch = pitch * 0.5;
  2583. var halfYaw = yaw * 0.5;
  2584. var sinRoll = Math.sin(halfRoll);
  2585. var cosRoll = Math.cos(halfRoll);
  2586. var sinPitch = Math.sin(halfPitch);
  2587. var cosPitch = Math.cos(halfPitch);
  2588. var sinYaw = Math.sin(halfYaw);
  2589. var cosYaw = Math.cos(halfYaw);
  2590. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  2591. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  2592. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  2593. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  2594. };
  2595. /**
  2596. * Returns a new Quaternion from the passed float Euler angles expressed in z-x-z orientation
  2597. */
  2598. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  2599. var result = new Quaternion();
  2600. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  2601. return result;
  2602. };
  2603. /**
  2604. * Sets the passed quaternion "result" from the passed float Euler angles expressed in z-x-z orientation
  2605. */
  2606. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  2607. // Produces a quaternion from Euler angles in the z-x-z orientation
  2608. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  2609. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  2610. var halfBeta = beta * 0.5;
  2611. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  2612. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  2613. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  2614. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  2615. };
  2616. /**
  2617. * Returns a new Quaternion as the quaternion rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system.
  2618. * cf to Vector3.RotationFromAxis() documentation.
  2619. * Note : axis1, axis2 and axis3 are normalized during this operation.
  2620. */
  2621. Quaternion.RotationQuaternionFromAxis = function (axis1, axis2, axis3, ref) {
  2622. var quat = new Quaternion(0.0, 0.0, 0.0, 0.0);
  2623. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  2624. return quat;
  2625. };
  2626. /**
  2627. * Sets the passed quaternion "ref" with the quaternion rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system.
  2628. * cf to Vector3.RotationFromAxis() documentation.
  2629. * Note : axis1, axis2 and axis3 are normalized during this operation.
  2630. */
  2631. Quaternion.RotationQuaternionFromAxisToRef = function (axis1, axis2, axis3, ref) {
  2632. var rotMat = MathTmp.Matrix[0];
  2633. BABYLON.Matrix.FromXYZAxesToRef(axis1.normalize(), axis2.normalize(), axis3.normalize(), rotMat);
  2634. BABYLON.Quaternion.FromRotationMatrixToRef(rotMat, ref);
  2635. };
  2636. Quaternion.Slerp = function (left, right, amount) {
  2637. var result = Quaternion.Identity();
  2638. Quaternion.SlerpToRef(left, right, amount, result);
  2639. return result;
  2640. };
  2641. Quaternion.SlerpToRef = function (left, right, amount, result) {
  2642. var num2;
  2643. var num3;
  2644. var num = amount;
  2645. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  2646. var flag = false;
  2647. if (num4 < 0) {
  2648. flag = true;
  2649. num4 = -num4;
  2650. }
  2651. if (num4 > 0.999999) {
  2652. num3 = 1 - num;
  2653. num2 = flag ? -num : num;
  2654. }
  2655. else {
  2656. var num5 = Math.acos(num4);
  2657. var num6 = (1.0 / Math.sin(num5));
  2658. num3 = (Math.sin((1.0 - num) * num5)) * num6;
  2659. num2 = flag ? ((-Math.sin(num * num5)) * num6) : ((Math.sin(num * num5)) * num6);
  2660. }
  2661. result.x = (num3 * left.x) + (num2 * right.x);
  2662. result.y = (num3 * left.y) + (num2 * right.y);
  2663. result.z = (num3 * left.z) + (num2 * right.z);
  2664. result.w = (num3 * left.w) + (num2 * right.w);
  2665. };
  2666. return Quaternion;
  2667. }());
  2668. BABYLON.Quaternion = Quaternion;
  2669. var Matrix = (function () {
  2670. function Matrix() {
  2671. this.m = new Float32Array(16);
  2672. }
  2673. // Properties
  2674. /**
  2675. * Boolean : True is the matrix is the identity matrix
  2676. */
  2677. Matrix.prototype.isIdentity = function () {
  2678. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[10] !== 1.0 || this.m[15] !== 1.0)
  2679. return false;
  2680. if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  2681. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  2682. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  2683. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0)
  2684. return false;
  2685. return true;
  2686. };
  2687. /**
  2688. * Returns the matrix determinant (float).
  2689. */
  2690. Matrix.prototype.determinant = function () {
  2691. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  2692. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  2693. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  2694. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  2695. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  2696. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  2697. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  2698. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  2699. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  2700. };
  2701. // Methods
  2702. /**
  2703. * Returns the matrix underlying array.
  2704. */
  2705. Matrix.prototype.toArray = function () {
  2706. return this.m;
  2707. };
  2708. /**
  2709. * Returns the matrix underlying array.
  2710. */
  2711. Matrix.prototype.asArray = function () {
  2712. return this.toArray();
  2713. };
  2714. /**
  2715. * Inverts in place the Matrix.
  2716. * Returns the Matrix inverted.
  2717. */
  2718. Matrix.prototype.invert = function () {
  2719. this.invertToRef(this);
  2720. return this;
  2721. };
  2722. /**
  2723. * Sets all the matrix elements to zero.
  2724. * Returns the Matrix.
  2725. */
  2726. Matrix.prototype.reset = function () {
  2727. for (var index = 0; index < 16; index++) {
  2728. this.m[index] = 0.0;
  2729. }
  2730. return this;
  2731. };
  2732. /**
  2733. * Returns a new Matrix as the addition result of the current Matrix and the passed one.
  2734. */
  2735. Matrix.prototype.add = function (other) {
  2736. var result = new Matrix();
  2737. this.addToRef(other, result);
  2738. return result;
  2739. };
  2740. /**
  2741. * Sets the passed matrix "result" with the ddition result of the current Matrix and the passed one.
  2742. * Returns the Matrix.
  2743. */
  2744. Matrix.prototype.addToRef = function (other, result) {
  2745. for (var index = 0; index < 16; index++) {
  2746. result.m[index] = this.m[index] + other.m[index];
  2747. }
  2748. return this;
  2749. };
  2750. /**
  2751. * Adds in place the passed matrix to the current Matrix.
  2752. * Returns the updated Matrix.
  2753. */
  2754. Matrix.prototype.addToSelf = function (other) {
  2755. for (var index = 0; index < 16; index++) {
  2756. this.m[index] += other.m[index];
  2757. }
  2758. return this;
  2759. };
  2760. /**
  2761. * Sets the passed matrix with the current inverted Matrix.
  2762. * Returns the unmodified current Matrix.
  2763. */
  2764. Matrix.prototype.invertToRef = function (other) {
  2765. var l1 = this.m[0];
  2766. var l2 = this.m[1];
  2767. var l3 = this.m[2];
  2768. var l4 = this.m[3];
  2769. var l5 = this.m[4];
  2770. var l6 = this.m[5];
  2771. var l7 = this.m[6];
  2772. var l8 = this.m[7];
  2773. var l9 = this.m[8];
  2774. var l10 = this.m[9];
  2775. var l11 = this.m[10];
  2776. var l12 = this.m[11];
  2777. var l13 = this.m[12];
  2778. var l14 = this.m[13];
  2779. var l15 = this.m[14];
  2780. var l16 = this.m[15];
  2781. var l17 = (l11 * l16) - (l12 * l15);
  2782. var l18 = (l10 * l16) - (l12 * l14);
  2783. var l19 = (l10 * l15) - (l11 * l14);
  2784. var l20 = (l9 * l16) - (l12 * l13);
  2785. var l21 = (l9 * l15) - (l11 * l13);
  2786. var l22 = (l9 * l14) - (l10 * l13);
  2787. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  2788. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  2789. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  2790. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  2791. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  2792. var l28 = (l7 * l16) - (l8 * l15);
  2793. var l29 = (l6 * l16) - (l8 * l14);
  2794. var l30 = (l6 * l15) - (l7 * l14);
  2795. var l31 = (l5 * l16) - (l8 * l13);
  2796. var l32 = (l5 * l15) - (l7 * l13);
  2797. var l33 = (l5 * l14) - (l6 * l13);
  2798. var l34 = (l7 * l12) - (l8 * l11);
  2799. var l35 = (l6 * l12) - (l8 * l10);
  2800. var l36 = (l6 * l11) - (l7 * l10);
  2801. var l37 = (l5 * l12) - (l8 * l9);
  2802. var l38 = (l5 * l11) - (l7 * l9);
  2803. var l39 = (l5 * l10) - (l6 * l9);
  2804. other.m[0] = l23 * l27;
  2805. other.m[4] = l24 * l27;
  2806. other.m[8] = l25 * l27;
  2807. other.m[12] = l26 * l27;
  2808. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  2809. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  2810. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  2811. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  2812. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  2813. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  2814. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  2815. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  2816. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  2817. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  2818. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  2819. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  2820. return this;
  2821. };
  2822. /**
  2823. * Inserts the translation vector (using 3 x floats) in the current Matrix.
  2824. * Returns the updated Matrix.
  2825. */
  2826. Matrix.prototype.setTranslationFromFloats = function (x, y, z) {
  2827. this.m[12] = x;
  2828. this.m[13] = y;
  2829. this.m[14] = z;
  2830. return this;
  2831. };
  2832. /**
  2833. * Inserts the translation vector in the current Matrix.
  2834. * Returns the updated Matrix.
  2835. */
  2836. Matrix.prototype.setTranslation = function (vector3) {
  2837. this.m[12] = vector3.x;
  2838. this.m[13] = vector3.y;
  2839. this.m[14] = vector3.z;
  2840. return this;
  2841. };
  2842. /**
  2843. * Returns a new Vector3 as the extracted translation from the Matrix.
  2844. */
  2845. Matrix.prototype.getTranslation = function () {
  2846. return new Vector3(this.m[12], this.m[13], this.m[14]);
  2847. };
  2848. /**
  2849. * Fill a Vector3 with the extracted translation from the Matrix.
  2850. */
  2851. Matrix.prototype.getTranslationToRef = function (result) {
  2852. result.x = this.m[12];
  2853. result.y = this.m[13];
  2854. result.z = this.m[14];
  2855. return this;
  2856. };
  2857. /**
  2858. * Remove rotation and scaling part from the Matrix.
  2859. * Returns the updated Matrix.
  2860. */
  2861. Matrix.prototype.removeRotationAndScaling = function () {
  2862. this.setRowFromFloats(0, 1, 0, 0, 0);
  2863. this.setRowFromFloats(1, 0, 1, 0, 0);
  2864. this.setRowFromFloats(2, 0, 0, 1, 0);
  2865. return this;
  2866. };
  2867. /**
  2868. * Returns a new Matrix set with the multiplication result of the current Matrix and the passed one.
  2869. */
  2870. Matrix.prototype.multiply = function (other) {
  2871. var result = new Matrix();
  2872. this.multiplyToRef(other, result);
  2873. return result;
  2874. };
  2875. /**
  2876. * Updates the current Matrix from the passed one values.
  2877. * Returns the updated Matrix.
  2878. */
  2879. Matrix.prototype.copyFrom = function (other) {
  2880. for (var index = 0; index < 16; index++) {
  2881. this.m[index] = other.m[index];
  2882. }
  2883. return this;
  2884. };
  2885. /**
  2886. * Populates the passed array from the starting index with the Matrix values.
  2887. * Returns the Matrix.
  2888. */
  2889. Matrix.prototype.copyToArray = function (array, offset) {
  2890. if (offset === void 0) { offset = 0; }
  2891. for (var index = 0; index < 16; index++) {
  2892. array[offset + index] = this.m[index];
  2893. }
  2894. return this;
  2895. };
  2896. /**
  2897. * Sets the passed matrix "result" with the multiplication result of the current Matrix and the passed one.
  2898. */
  2899. Matrix.prototype.multiplyToRef = function (other, result) {
  2900. this.multiplyToArray(other, result.m, 0);
  2901. return this;
  2902. };
  2903. /**
  2904. * Sets the Float32Array "result" from the passed index "offset" with the multiplication result of the current Matrix and the passed one.
  2905. */
  2906. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  2907. var tm0 = this.m[0];
  2908. var tm1 = this.m[1];
  2909. var tm2 = this.m[2];
  2910. var tm3 = this.m[3];
  2911. var tm4 = this.m[4];
  2912. var tm5 = this.m[5];
  2913. var tm6 = this.m[6];
  2914. var tm7 = this.m[7];
  2915. var tm8 = this.m[8];
  2916. var tm9 = this.m[9];
  2917. var tm10 = this.m[10];
  2918. var tm11 = this.m[11];
  2919. var tm12 = this.m[12];
  2920. var tm13 = this.m[13];
  2921. var tm14 = this.m[14];
  2922. var tm15 = this.m[15];
  2923. var om0 = other.m[0];
  2924. var om1 = other.m[1];
  2925. var om2 = other.m[2];
  2926. var om3 = other.m[3];
  2927. var om4 = other.m[4];
  2928. var om5 = other.m[5];
  2929. var om6 = other.m[6];
  2930. var om7 = other.m[7];
  2931. var om8 = other.m[8];
  2932. var om9 = other.m[9];
  2933. var om10 = other.m[10];
  2934. var om11 = other.m[11];
  2935. var om12 = other.m[12];
  2936. var om13 = other.m[13];
  2937. var om14 = other.m[14];
  2938. var om15 = other.m[15];
  2939. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  2940. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  2941. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  2942. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  2943. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  2944. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  2945. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  2946. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  2947. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  2948. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  2949. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  2950. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  2951. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  2952. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  2953. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  2954. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  2955. return this;
  2956. };
  2957. /**
  2958. * Boolean : True is the current Matrix and the passed one values are strictly equal.
  2959. */
  2960. Matrix.prototype.equals = function (value) {
  2961. return value &&
  2962. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  2963. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  2964. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  2965. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  2966. };
  2967. /**
  2968. * Returns a new Matrix from the current Matrix.
  2969. */
  2970. Matrix.prototype.clone = function () {
  2971. 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]);
  2972. };
  2973. /**
  2974. * Returns the string "Matrix"
  2975. */
  2976. Matrix.prototype.getClassName = function () {
  2977. return "Matrix";
  2978. };
  2979. /**
  2980. * Returns the Matrix hash code.
  2981. */
  2982. Matrix.prototype.getHashCode = function () {
  2983. var hash = this.m[0] || 0;
  2984. for (var i = 1; i < 16; i++) {
  2985. hash = (hash * 397) ^ (this.m[i] || 0);
  2986. }
  2987. return hash;
  2988. };
  2989. /**
  2990. * Decomposes the current Matrix into :
  2991. * - a scale vector3 passed as a reference to update,
  2992. * - a rotation quaternion passed as a reference to update,
  2993. * - a translation vector3 passed as a reference to update.
  2994. * Returns the boolean `true`.
  2995. */
  2996. Matrix.prototype.decompose = function (scale, rotation, translation) {
  2997. translation.x = this.m[12];
  2998. translation.y = this.m[13];
  2999. translation.z = this.m[14];
  3000. var xs = MathTools.Sign(this.m[0] * this.m[1] * this.m[2] * this.m[3]) < 0 ? -1 : 1;
  3001. var ys = MathTools.Sign(this.m[4] * this.m[5] * this.m[6] * this.m[7]) < 0 ? -1 : 1;
  3002. var zs = MathTools.Sign(this.m[8] * this.m[9] * this.m[10] * this.m[11]) < 0 ? -1 : 1;
  3003. scale.x = xs * Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  3004. scale.y = ys * Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  3005. scale.z = zs * Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  3006. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  3007. rotation.x = 0;
  3008. rotation.y = 0;
  3009. rotation.z = 0;
  3010. rotation.w = 1;
  3011. return false;
  3012. }
  3013. Matrix.FromValuesToRef(this.m[0] / scale.x, this.m[1] / scale.x, this.m[2] / scale.x, 0, this.m[4] / scale.y, this.m[5] / scale.y, this.m[6] / scale.y, 0, this.m[8] / scale.z, this.m[9] / scale.z, this.m[10] / scale.z, 0, 0, 0, 0, 1, MathTmp.Matrix[0]);
  3014. Quaternion.FromRotationMatrixToRef(MathTmp.Matrix[0], rotation);
  3015. return true;
  3016. };
  3017. /**
  3018. * Returns a new Matrix as the extracted rotation matrix from the current one.
  3019. */
  3020. Matrix.prototype.getRotationMatrix = function () {
  3021. var result = Matrix.Identity();
  3022. this.getRotationMatrixToRef(result);
  3023. return result;
  3024. };
  3025. /**
  3026. * Extracts the rotation matrix from the current one and sets it as the passed "result".
  3027. * Returns the current Matrix.
  3028. */
  3029. Matrix.prototype.getRotationMatrixToRef = function (result) {
  3030. var m = this.m;
  3031. var xs = m[0] * m[1] * m[2] * m[3] < 0 ? -1 : 1;
  3032. var ys = m[4] * m[5] * m[6] * m[7] < 0 ? -1 : 1;
  3033. var zs = m[8] * m[9] * m[10] * m[11] < 0 ? -1 : 1;
  3034. var sx = xs * Math.sqrt(m[0] * m[0] + m[1] * m[1] + m[2] * m[2]);
  3035. var sy = ys * Math.sqrt(m[4] * m[4] + m[5] * m[5] + m[6] * m[6]);
  3036. var sz = zs * Math.sqrt(m[8] * m[8] + m[9] * m[9] + m[10] * m[10]);
  3037. 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);
  3038. return this;
  3039. };
  3040. // Statics
  3041. /**
  3042. * Returns a new Matrix set from the starting index of the passed array.
  3043. */
  3044. Matrix.FromArray = function (array, offset) {
  3045. var result = new Matrix();
  3046. if (!offset) {
  3047. offset = 0;
  3048. }
  3049. Matrix.FromArrayToRef(array, offset, result);
  3050. return result;
  3051. };
  3052. /**
  3053. * Sets the passed "result" matrix from the starting index of the passed array.
  3054. */
  3055. Matrix.FromArrayToRef = function (array, offset, result) {
  3056. for (var index = 0; index < 16; index++) {
  3057. result.m[index] = array[index + offset];
  3058. }
  3059. };
  3060. /**
  3061. * Sets the passed "result" matrix from the starting index of the passed Float32Array by multiplying each element by the float "scale".
  3062. */
  3063. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  3064. for (var index = 0; index < 16; index++) {
  3065. result.m[index] = array[index + offset] * scale;
  3066. }
  3067. };
  3068. /**
  3069. * Sets the passed matrix "result" with the 16 passed floats.
  3070. */
  3071. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  3072. result.m[0] = initialM11;
  3073. result.m[1] = initialM12;
  3074. result.m[2] = initialM13;
  3075. result.m[3] = initialM14;
  3076. result.m[4] = initialM21;
  3077. result.m[5] = initialM22;
  3078. result.m[6] = initialM23;
  3079. result.m[7] = initialM24;
  3080. result.m[8] = initialM31;
  3081. result.m[9] = initialM32;
  3082. result.m[10] = initialM33;
  3083. result.m[11] = initialM34;
  3084. result.m[12] = initialM41;
  3085. result.m[13] = initialM42;
  3086. result.m[14] = initialM43;
  3087. result.m[15] = initialM44;
  3088. };
  3089. /**
  3090. * Returns the index-th row of the current matrix as a new Vector4.
  3091. */
  3092. Matrix.prototype.getRow = function (index) {
  3093. if (index < 0 || index > 3) {
  3094. return null;
  3095. }
  3096. var i = index * 4;
  3097. return new Vector4(this.m[i + 0], this.m[i + 1], this.m[i + 2], this.m[i + 3]);
  3098. };
  3099. /**
  3100. * Sets the index-th row of the current matrix with the passed Vector4 values.
  3101. * Returns the updated Matrix.
  3102. */
  3103. Matrix.prototype.setRow = function (index, row) {
  3104. if (index < 0 || index > 3) {
  3105. return this;
  3106. }
  3107. var i = index * 4;
  3108. this.m[i + 0] = row.x;
  3109. this.m[i + 1] = row.y;
  3110. this.m[i + 2] = row.z;
  3111. this.m[i + 3] = row.w;
  3112. return this;
  3113. };
  3114. /**
  3115. * Sets the index-th row of the current matrix with the passed 4 x float values.
  3116. * Returns the updated Matrix.
  3117. */
  3118. Matrix.prototype.setRowFromFloats = function (index, x, y, z, w) {
  3119. if (index < 0 || index > 3) {
  3120. return this;
  3121. }
  3122. var i = index * 4;
  3123. this.m[i + 0] = x;
  3124. this.m[i + 1] = y;
  3125. this.m[i + 2] = z;
  3126. this.m[i + 3] = w;
  3127. return this;
  3128. };
  3129. /**
  3130. * Returns a new Matrix set from the 16 passed floats.
  3131. */
  3132. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  3133. var result = new Matrix();
  3134. result.m[0] = initialM11;
  3135. result.m[1] = initialM12;
  3136. result.m[2] = initialM13;
  3137. result.m[3] = initialM14;
  3138. result.m[4] = initialM21;
  3139. result.m[5] = initialM22;
  3140. result.m[6] = initialM23;
  3141. result.m[7] = initialM24;
  3142. result.m[8] = initialM31;
  3143. result.m[9] = initialM32;
  3144. result.m[10] = initialM33;
  3145. result.m[11] = initialM34;
  3146. result.m[12] = initialM41;
  3147. result.m[13] = initialM42;
  3148. result.m[14] = initialM43;
  3149. result.m[15] = initialM44;
  3150. return result;
  3151. };
  3152. /**
  3153. * Returns a new Matrix composed by the passed scale (vector3), rotation (quaternion) and translation (vector3).
  3154. */
  3155. Matrix.Compose = function (scale, rotation, translation) {
  3156. var result = Matrix.Identity();
  3157. Matrix.ComposeToRef(scale, rotation, translation, result);
  3158. return result;
  3159. };
  3160. /**
  3161. * Update a Matrix with values composed by the passed scale (vector3), rotation (quaternion) and translation (vector3).
  3162. */
  3163. Matrix.ComposeToRef = function (scale, rotation, translation, result) {
  3164. Matrix.FromValuesToRef(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1, MathTmp.Matrix[1]);
  3165. rotation.toRotationMatrix(MathTmp.Matrix[0]);
  3166. MathTmp.Matrix[1].multiplyToRef(MathTmp.Matrix[0], result);
  3167. result.setTranslation(translation);
  3168. };
  3169. /**
  3170. * Returns a new indentity Matrix.
  3171. */
  3172. Matrix.Identity = function () {
  3173. return Matrix.FromValues(1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0);
  3174. };
  3175. /**
  3176. * Sets the passed "result" as an identity matrix.
  3177. */
  3178. Matrix.IdentityToRef = function (result) {
  3179. Matrix.FromValuesToRef(1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, result);
  3180. };
  3181. /**
  3182. * Returns a new zero Matrix.
  3183. */
  3184. Matrix.Zero = function () {
  3185. return Matrix.FromValues(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0);
  3186. };
  3187. /**
  3188. * Returns a new rotation matrix for "angle" radians around the X axis.
  3189. */
  3190. Matrix.RotationX = function (angle) {
  3191. var result = new Matrix();
  3192. Matrix.RotationXToRef(angle, result);
  3193. return result;
  3194. };
  3195. /**
  3196. * Returns a new Matrix as the passed inverted one.
  3197. */
  3198. Matrix.Invert = function (source) {
  3199. var result = new Matrix();
  3200. source.invertToRef(result);
  3201. return result;
  3202. };
  3203. /**
  3204. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the X axis.
  3205. */
  3206. Matrix.RotationXToRef = function (angle, result) {
  3207. var s = Math.sin(angle);
  3208. var c = Math.cos(angle);
  3209. result.m[0] = 1.0;
  3210. result.m[15] = 1.0;
  3211. result.m[5] = c;
  3212. result.m[10] = c;
  3213. result.m[9] = -s;
  3214. result.m[6] = s;
  3215. result.m[1] = 0.0;
  3216. result.m[2] = 0.0;
  3217. result.m[3] = 0.0;
  3218. result.m[4] = 0.0;
  3219. result.m[7] = 0.0;
  3220. result.m[8] = 0.0;
  3221. result.m[11] = 0.0;
  3222. result.m[12] = 0.0;
  3223. result.m[13] = 0.0;
  3224. result.m[14] = 0.0;
  3225. };
  3226. /**
  3227. * Returns a new rotation matrix for "angle" radians around the Y axis.
  3228. */
  3229. Matrix.RotationY = function (angle) {
  3230. var result = new Matrix();
  3231. Matrix.RotationYToRef(angle, result);
  3232. return result;
  3233. };
  3234. /**
  3235. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the Y axis.
  3236. */
  3237. Matrix.RotationYToRef = function (angle, result) {
  3238. var s = Math.sin(angle);
  3239. var c = Math.cos(angle);
  3240. result.m[5] = 1.0;
  3241. result.m[15] = 1.0;
  3242. result.m[0] = c;
  3243. result.m[2] = -s;
  3244. result.m[8] = s;
  3245. result.m[10] = c;
  3246. result.m[1] = 0.0;
  3247. result.m[3] = 0.0;
  3248. result.m[4] = 0.0;
  3249. result.m[6] = 0.0;
  3250. result.m[7] = 0.0;
  3251. result.m[9] = 0.0;
  3252. result.m[11] = 0.0;
  3253. result.m[12] = 0.0;
  3254. result.m[13] = 0.0;
  3255. result.m[14] = 0.0;
  3256. };
  3257. /**
  3258. * Returns a new rotation matrix for "angle" radians around the Z axis.
  3259. */
  3260. Matrix.RotationZ = function (angle) {
  3261. var result = new Matrix();
  3262. Matrix.RotationZToRef(angle, result);
  3263. return result;
  3264. };
  3265. /**
  3266. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the Z axis.
  3267. */
  3268. Matrix.RotationZToRef = function (angle, result) {
  3269. var s = Math.sin(angle);
  3270. var c = Math.cos(angle);
  3271. result.m[10] = 1.0;
  3272. result.m[15] = 1.0;
  3273. result.m[0] = c;
  3274. result.m[1] = s;
  3275. result.m[4] = -s;
  3276. result.m[5] = c;
  3277. result.m[2] = 0.0;
  3278. result.m[3] = 0.0;
  3279. result.m[6] = 0.0;
  3280. result.m[7] = 0.0;
  3281. result.m[8] = 0.0;
  3282. result.m[9] = 0.0;
  3283. result.m[11] = 0.0;
  3284. result.m[12] = 0.0;
  3285. result.m[13] = 0.0;
  3286. result.m[14] = 0.0;
  3287. };
  3288. /**
  3289. * Returns a new rotation matrix for "angle" radians around the passed axis.
  3290. */
  3291. Matrix.RotationAxis = function (axis, angle) {
  3292. var result = Matrix.Zero();
  3293. Matrix.RotationAxisToRef(axis, angle, result);
  3294. return result;
  3295. };
  3296. /**
  3297. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the passed axis.
  3298. */
  3299. Matrix.RotationAxisToRef = function (axis, angle, result) {
  3300. var s = Math.sin(-angle);
  3301. var c = Math.cos(-angle);
  3302. var c1 = 1 - c;
  3303. axis.normalize();
  3304. result.m[0] = (axis.x * axis.x) * c1 + c;
  3305. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  3306. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  3307. result.m[3] = 0.0;
  3308. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  3309. result.m[5] = (axis.y * axis.y) * c1 + c;
  3310. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  3311. result.m[7] = 0.0;
  3312. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  3313. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  3314. result.m[10] = (axis.z * axis.z) * c1 + c;
  3315. result.m[11] = 0.0;
  3316. result.m[15] = 1.0;
  3317. };
  3318. /**
  3319. * Returns a new Matrix as a rotation matrix from the Euler angles (y, x, z).
  3320. */
  3321. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  3322. var result = new Matrix();
  3323. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  3324. return result;
  3325. };
  3326. /**
  3327. * Sets the passed matrix "result" as a rotation matrix from the Euler angles (y, x, z).
  3328. */
  3329. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  3330. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  3331. this._tempQuaternion.toRotationMatrix(result);
  3332. };
  3333. /**
  3334. * Returns a new Matrix as a scaling matrix from the passed floats (x, y, z).
  3335. */
  3336. Matrix.Scaling = function (x, y, z) {
  3337. var result = Matrix.Zero();
  3338. Matrix.ScalingToRef(x, y, z, result);
  3339. return result;
  3340. };
  3341. /**
  3342. * Sets the passed matrix "result" as a scaling matrix from the passed floats (x, y, z).
  3343. */
  3344. Matrix.ScalingToRef = function (x, y, z, result) {
  3345. result.m[0] = x;
  3346. result.m[1] = 0.0;
  3347. result.m[2] = 0.0;
  3348. result.m[3] = 0.0;
  3349. result.m[4] = 0.0;
  3350. result.m[5] = y;
  3351. result.m[6] = 0.0;
  3352. result.m[7] = 0.0;
  3353. result.m[8] = 0.0;
  3354. result.m[9] = 0.0;
  3355. result.m[10] = z;
  3356. result.m[11] = 0.0;
  3357. result.m[12] = 0.0;
  3358. result.m[13] = 0.0;
  3359. result.m[14] = 0.0;
  3360. result.m[15] = 1.0;
  3361. };
  3362. /**
  3363. * Returns a new Matrix as a translation matrix from the passed floats (x, y, z).
  3364. */
  3365. Matrix.Translation = function (x, y, z) {
  3366. var result = Matrix.Identity();
  3367. Matrix.TranslationToRef(x, y, z, result);
  3368. return result;
  3369. };
  3370. /**
  3371. * Sets the passed matrix "result" as a translation matrix from the passed floats (x, y, z).
  3372. */
  3373. Matrix.TranslationToRef = function (x, y, z, result) {
  3374. Matrix.FromValuesToRef(1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, x, y, z, 1.0, result);
  3375. };
  3376. /**
  3377. * Returns a new Matrix whose values are the interpolated values for "gradien" (float) between the ones of the matrices "startValue" and "endValue".
  3378. */
  3379. Matrix.Lerp = function (startValue, endValue, gradient) {
  3380. var result = Matrix.Zero();
  3381. for (var index = 0; index < 16; index++) {
  3382. result.m[index] = startValue.m[index] * (1.0 - gradient) + endValue.m[index] * gradient;
  3383. }
  3384. return result;
  3385. };
  3386. /**
  3387. * Returns a new Matrix whose values are computed by :
  3388. * - decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices,
  3389. * - interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end,
  3390. * - recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices.
  3391. */
  3392. Matrix.DecomposeLerp = function (startValue, endValue, gradient) {
  3393. var startScale = new Vector3(0, 0, 0);
  3394. var startRotation = new Quaternion();
  3395. var startTranslation = new Vector3(0, 0, 0);
  3396. startValue.decompose(startScale, startRotation, startTranslation);
  3397. var endScale = new Vector3(0, 0, 0);
  3398. var endRotation = new Quaternion();
  3399. var endTranslation = new Vector3(0, 0, 0);
  3400. endValue.decompose(endScale, endRotation, endTranslation);
  3401. var resultScale = Vector3.Lerp(startScale, endScale, gradient);
  3402. var resultRotation = Quaternion.Slerp(startRotation, endRotation, gradient);
  3403. var resultTranslation = Vector3.Lerp(startTranslation, endTranslation, gradient);
  3404. return Matrix.Compose(resultScale, resultRotation, resultTranslation);
  3405. };
  3406. /**
  3407. * Returns a new rotation Matrix used to rotate a mesh so as it looks at the target Vector3, from the eye Vector3, the UP vector3 being orientated like "up".
  3408. * This methods works for a Left-Handed system.
  3409. */
  3410. Matrix.LookAtLH = function (eye, target, up) {
  3411. var result = Matrix.Zero();
  3412. Matrix.LookAtLHToRef(eye, target, up, result);
  3413. return result;
  3414. };
  3415. /**
  3416. * Sets the passed "result" Matrix as a rotation matrix used to rotate a mesh so as it looks at the target Vector3, from the eye Vector3, the UP vector3 being orientated like "up".
  3417. * This methods works for a Left-Handed system.
  3418. */
  3419. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  3420. // Z axis
  3421. target.subtractToRef(eye, this._zAxis);
  3422. this._zAxis.normalize();
  3423. // X axis
  3424. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  3425. if (this._xAxis.lengthSquared() === 0) {
  3426. this._xAxis.x = 1.0;
  3427. }
  3428. else {
  3429. this._xAxis.normalize();
  3430. }
  3431. // Y axis
  3432. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  3433. this._yAxis.normalize();
  3434. // Eye angles
  3435. var ex = -Vector3.Dot(this._xAxis, eye);
  3436. var ey = -Vector3.Dot(this._yAxis, eye);
  3437. var ez = -Vector3.Dot(this._zAxis, eye);
  3438. 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);
  3439. };
  3440. /**
  3441. * Returns a new rotation Matrix used to rotate a mesh so as it looks at the target Vector3, from the eye Vector3, the UP vector3 being orientated like "up".
  3442. * This methods works for a Right-Handed system.
  3443. */
  3444. Matrix.LookAtRH = function (eye, target, up) {
  3445. var result = Matrix.Zero();
  3446. Matrix.LookAtRHToRef(eye, target, up, result);
  3447. return result;
  3448. };
  3449. /**
  3450. * Sets the passed "result" Matrix as a rotation matrix used to rotate a mesh so as it looks at the target Vector3, from the eye Vector3, the UP vector3 being orientated like "up".
  3451. * This methods works for a Left-Handed system.
  3452. */
  3453. Matrix.LookAtRHToRef = function (eye, target, up, result) {
  3454. // Z axis
  3455. eye.subtractToRef(target, this._zAxis);
  3456. this._zAxis.normalize();
  3457. // X axis
  3458. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  3459. if (this._xAxis.lengthSquared() === 0) {
  3460. this._xAxis.x = 1.0;
  3461. }
  3462. else {
  3463. this._xAxis.normalize();
  3464. }
  3465. // Y axis
  3466. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  3467. this._yAxis.normalize();
  3468. // Eye angles
  3469. var ex = -Vector3.Dot(this._xAxis, eye);
  3470. var ey = -Vector3.Dot(this._yAxis, eye);
  3471. var ez = -Vector3.Dot(this._zAxis, eye);
  3472. 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);
  3473. };
  3474. /**
  3475. * Returns a new Matrix as a left-handed orthographic projection matrix computed from the passed floats : width and height of the projection plane, z near and far limits.
  3476. */
  3477. Matrix.OrthoLH = function (width, height, znear, zfar) {
  3478. var matrix = Matrix.Zero();
  3479. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  3480. return matrix;
  3481. };
  3482. /**
  3483. * Sets the passed matrix "result" as a left-handed orthographic projection matrix computed from the passed floats : width and height of the projection plane, z near and far limits.
  3484. */
  3485. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  3486. var n = znear;
  3487. var f = zfar;
  3488. var a = 2.0 / width;
  3489. var b = 2.0 / height;
  3490. var c = 2.0 / (f - n);
  3491. var d = -(f + n) / (f - n);
  3492. BABYLON.Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, 0.0, 0.0, 0.0, d, 1.0, result);
  3493. };
  3494. /**
  3495. * Returns a new Matrix as a left-handed orthographic projection matrix computed from the passed floats : left, right, top and bottom being the coordinates of the projection plane, z near and far limits.
  3496. */
  3497. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  3498. var matrix = Matrix.Zero();
  3499. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  3500. return matrix;
  3501. };
  3502. /**
  3503. * Sets the passed matrix "result" as a left-handed orthographic projection matrix computed from the passed floats : left, right, top and bottom being the coordinates of the projection plane, z near and far limits.
  3504. */
  3505. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  3506. var n = znear;
  3507. var f = zfar;
  3508. var a = 2.0 / (right - left);
  3509. var b = 2.0 / (top - bottom);
  3510. var c = 2.0 / (f - n);
  3511. var d = -(f + n) / (f - n);
  3512. var i0 = (left + right) / (left - right);
  3513. var i1 = (top + bottom) / (bottom - top);
  3514. BABYLON.Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, 0.0, i0, i1, d, 1.0, result);
  3515. };
  3516. /**
  3517. * Returns a new Matrix as a right-handed orthographic projection matrix computed from the passed floats : left, right, top and bottom being the coordinates of the projection plane, z near and far limits.
  3518. */
  3519. Matrix.OrthoOffCenterRH = function (left, right, bottom, top, znear, zfar) {
  3520. var matrix = Matrix.Zero();
  3521. Matrix.OrthoOffCenterRHToRef(left, right, bottom, top, znear, zfar, matrix);
  3522. return matrix;
  3523. };
  3524. /**
  3525. * Sets the passed matrix "result" as a right-handed orthographic projection matrix computed from the passed floats : left, right, top and bottom being the coordinates of the projection plane, z near and far limits.
  3526. */
  3527. Matrix.OrthoOffCenterRHToRef = function (left, right, bottom, top, znear, zfar, result) {
  3528. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, result);
  3529. result.m[10] *= -1.0;
  3530. };
  3531. /**
  3532. * Returns a new Matrix as a left-handed perspective projection matrix computed from the passed floats : width and height of the projection plane, z near and far limits.
  3533. */
  3534. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  3535. var matrix = Matrix.Zero();
  3536. var n = znear;
  3537. var f = zfar;
  3538. var a = 2.0 * n / width;
  3539. var b = 2.0 * n / height;
  3540. var c = (f + n) / (f - n);
  3541. var d = -2.0 * f * n / (f - n);
  3542. BABYLON.Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, 1.0, 0.0, 0.0, d, 0.0, matrix);
  3543. return matrix;
  3544. };
  3545. /**
  3546. * Returns a new Matrix as a left-handed perspective projection matrix computed from the passed floats : vertical angle of view (fov), width/height ratio (aspect), z near and far limits.
  3547. */
  3548. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  3549. var matrix = Matrix.Zero();
  3550. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  3551. return matrix;
  3552. };
  3553. /**
  3554. * Sets the passed matrix "result" as a left-handed perspective projection matrix computed from the passed floats : vertical angle of view (fov), width/height ratio (aspect), z near and far limits.
  3555. */
  3556. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  3557. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  3558. var n = znear;
  3559. var f = zfar;
  3560. var t = 1.0 / (Math.tan(fov * 0.5));
  3561. var a = isVerticalFovFixed ? (t / aspect) : t;
  3562. var b = isVerticalFovFixed ? t : (t * aspect);
  3563. var c = (f + n) / (f - n);
  3564. var d = -2.0 * f * n / (f - n);
  3565. BABYLON.Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, 1.0, 0.0, 0.0, d, 0.0, result);
  3566. };
  3567. /**
  3568. * Returns a new Matrix as a right-handed perspective projection matrix computed from the passed floats : vertical angle of view (fov), width/height ratio (aspect), z near and far limits.
  3569. */
  3570. Matrix.PerspectiveFovRH = function (fov, aspect, znear, zfar) {
  3571. var matrix = Matrix.Zero();
  3572. Matrix.PerspectiveFovRHToRef(fov, aspect, znear, zfar, matrix);
  3573. return matrix;
  3574. };
  3575. /**
  3576. * Sets the passed matrix "result" as a right-handed perspective projection matrix computed from the passed floats : vertical angle of view (fov), width/height ratio (aspect), z near and far limits.
  3577. */
  3578. Matrix.PerspectiveFovRHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  3579. //alternatively this could be expressed as:
  3580. // m = PerspectiveFovLHToRef
  3581. // m[10] *= -1.0;
  3582. // m[11] *= -1.0;
  3583. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  3584. var n = znear;
  3585. var f = zfar;
  3586. var t = 1.0 / (Math.tan(fov * 0.5));
  3587. var a = isVerticalFovFixed ? (t / aspect) : t;
  3588. var b = isVerticalFovFixed ? t : (t * aspect);
  3589. var c = -(f + n) / (f - n);
  3590. var d = -2 * f * n / (f - n);
  3591. BABYLON.Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, -1.0, 0.0, 0.0, d, 0.0, result);
  3592. };
  3593. /**
  3594. * Sets the passed matrix "result" as a left-handed perspective projection matrix for WebVR computed from the passed floats : vertical angle of view (fov), width/height ratio (aspect), z near and far limits.
  3595. */
  3596. Matrix.PerspectiveFovWebVRToRef = function (fov, znear, zfar, result, rightHanded) {
  3597. if (rightHanded === void 0) { rightHanded = false; }
  3598. var rightHandedFactor = rightHanded ? -1 : 1;
  3599. var upTan = Math.tan(fov.upDegrees * Math.PI / 180.0);
  3600. var downTan = Math.tan(fov.downDegrees * Math.PI / 180.0);
  3601. var leftTan = Math.tan(fov.leftDegrees * Math.PI / 180.0);
  3602. var rightTan = Math.tan(fov.rightDegrees * Math.PI / 180.0);
  3603. var xScale = 2.0 / (leftTan + rightTan);
  3604. var yScale = 2.0 / (upTan + downTan);
  3605. result.m[0] = xScale;
  3606. result.m[1] = result.m[2] = result.m[3] = result.m[4] = 0.0;
  3607. result.m[5] = yScale;
  3608. result.m[6] = result.m[7] = 0.0;
  3609. result.m[8] = ((leftTan - rightTan) * xScale * 0.5) * rightHandedFactor;
  3610. result.m[9] = -((upTan - downTan) * yScale * 0.5) * rightHandedFactor;
  3611. result.m[10] = -(znear + zfar) / (zfar - znear) * rightHandedFactor;
  3612. // result.m[10] = -zfar / (znear - zfar);
  3613. result.m[11] = 1.0 * rightHandedFactor;
  3614. result.m[12] = result.m[13] = result.m[15] = 0.0;
  3615. result.m[14] = -(2.0 * zfar * znear) / (zfar - znear);
  3616. // result.m[14] = (znear * zfar) / (znear - zfar);
  3617. };
  3618. /**
  3619. * Returns the final transformation matrix : world * view * projection * viewport
  3620. */
  3621. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  3622. var cw = viewport.width;
  3623. var ch = viewport.height;
  3624. var cx = viewport.x;
  3625. var cy = viewport.y;
  3626. var viewportMatrix = Matrix.FromValues(cw / 2.0, 0.0, 0.0, 0.0, 0.0, -ch / 2.0, 0.0, 0.0, 0.0, 0.0, zmax - zmin, 0.0, cx + cw / 2.0, ch / 2.0 + cy, zmin, 1);
  3627. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  3628. };
  3629. /**
  3630. * Returns a new Float32Array array with 4 elements : the 2x2 matrix extracted from the passed Matrix.
  3631. */
  3632. Matrix.GetAsMatrix2x2 = function (matrix) {
  3633. return new Float32Array([
  3634. matrix.m[0], matrix.m[1],
  3635. matrix.m[4], matrix.m[5]
  3636. ]);
  3637. };
  3638. /**
  3639. * Returns a new Float32Array array with 9 elements : the 3x3 matrix extracted from the passed Matrix.
  3640. */
  3641. Matrix.GetAsMatrix3x3 = function (matrix) {
  3642. return new Float32Array([
  3643. matrix.m[0], matrix.m[1], matrix.m[2],
  3644. matrix.m[4], matrix.m[5], matrix.m[6],
  3645. matrix.m[8], matrix.m[9], matrix.m[10]
  3646. ]);
  3647. };
  3648. /**
  3649. * Compute the transpose of the passed Matrix.
  3650. * Returns a new Matrix.
  3651. */
  3652. Matrix.Transpose = function (matrix) {
  3653. var result = new Matrix();
  3654. result.m[0] = matrix.m[0];
  3655. result.m[1] = matrix.m[4];
  3656. result.m[2] = matrix.m[8];
  3657. result.m[3] = matrix.m[12];
  3658. result.m[4] = matrix.m[1];
  3659. result.m[5] = matrix.m[5];
  3660. result.m[6] = matrix.m[9];
  3661. result.m[7] = matrix.m[13];
  3662. result.m[8] = matrix.m[2];
  3663. result.m[9] = matrix.m[6];
  3664. result.m[10] = matrix.m[10];
  3665. result.m[11] = matrix.m[14];
  3666. result.m[12] = matrix.m[3];
  3667. result.m[13] = matrix.m[7];
  3668. result.m[14] = matrix.m[11];
  3669. result.m[15] = matrix.m[15];
  3670. return result;
  3671. };
  3672. /**
  3673. * Returns a new Matrix as the reflection matrix across the passed plane.
  3674. */
  3675. Matrix.Reflection = function (plane) {
  3676. var matrix = new Matrix();
  3677. Matrix.ReflectionToRef(plane, matrix);
  3678. return matrix;
  3679. };
  3680. /**
  3681. * Sets the passed matrix "result" as the reflection matrix across the passed plane.
  3682. */
  3683. Matrix.ReflectionToRef = function (plane, result) {
  3684. plane.normalize();
  3685. var x = plane.normal.x;
  3686. var y = plane.normal.y;
  3687. var z = plane.normal.z;
  3688. var temp = -2 * x;
  3689. var temp2 = -2 * y;
  3690. var temp3 = -2 * z;
  3691. result.m[0] = (temp * x) + 1;
  3692. result.m[1] = temp2 * x;
  3693. result.m[2] = temp3 * x;
  3694. result.m[3] = 0.0;
  3695. result.m[4] = temp * y;
  3696. result.m[5] = (temp2 * y) + 1;
  3697. result.m[6] = temp3 * y;
  3698. result.m[7] = 0.0;
  3699. result.m[8] = temp * z;
  3700. result.m[9] = temp2 * z;
  3701. result.m[10] = (temp3 * z) + 1;
  3702. result.m[11] = 0.0;
  3703. result.m[12] = temp * plane.d;
  3704. result.m[13] = temp2 * plane.d;
  3705. result.m[14] = temp3 * plane.d;
  3706. result.m[15] = 1.0;
  3707. };
  3708. /**
  3709. * Sets the passed matrix "mat" as a rotation matrix composed from the 3 passed left handed axis.
  3710. */
  3711. Matrix.FromXYZAxesToRef = function (xaxis, yaxis, zaxis, mat) {
  3712. mat.m[0] = xaxis.x;
  3713. mat.m[1] = xaxis.y;
  3714. mat.m[2] = xaxis.z;
  3715. mat.m[3] = 0.0;
  3716. mat.m[4] = yaxis.x;
  3717. mat.m[5] = yaxis.y;
  3718. mat.m[6] = yaxis.z;
  3719. mat.m[7] = 0.0;
  3720. mat.m[8] = zaxis.x;
  3721. mat.m[9] = zaxis.y;
  3722. mat.m[10] = zaxis.z;
  3723. mat.m[11] = 0.0;
  3724. mat.m[12] = 0.0;
  3725. mat.m[13] = 0.0;
  3726. mat.m[14] = 0.0;
  3727. mat.m[15] = 1.0;
  3728. };
  3729. /**
  3730. * Sets the passed matrix "result" as a rotation matrix according to the passed quaternion.
  3731. */
  3732. Matrix.FromQuaternionToRef = function (quat, result) {
  3733. var xx = quat.x * quat.x;
  3734. var yy = quat.y * quat.y;
  3735. var zz = quat.z * quat.z;
  3736. var xy = quat.x * quat.y;
  3737. var zw = quat.z * quat.w;
  3738. var zx = quat.z * quat.x;
  3739. var yw = quat.y * quat.w;
  3740. var yz = quat.y * quat.z;
  3741. var xw = quat.x * quat.w;
  3742. result.m[0] = 1.0 - (2.0 * (yy + zz));
  3743. result.m[1] = 2.0 * (xy + zw);
  3744. result.m[2] = 2.0 * (zx - yw);
  3745. result.m[3] = 0.0;
  3746. result.m[4] = 2.0 * (xy - zw);
  3747. result.m[5] = 1.0 - (2.0 * (zz + xx));
  3748. result.m[6] = 2.0 * (yz + xw);
  3749. result.m[7] = 0.0;
  3750. result.m[8] = 2.0 * (zx + yw);
  3751. result.m[9] = 2.0 * (yz - xw);
  3752. result.m[10] = 1.0 - (2.0 * (yy + xx));
  3753. result.m[11] = 0.0;
  3754. result.m[12] = 0.0;
  3755. result.m[13] = 0.0;
  3756. result.m[14] = 0.0;
  3757. result.m[15] = 1.0;
  3758. };
  3759. return Matrix;
  3760. }());
  3761. Matrix._tempQuaternion = new Quaternion();
  3762. Matrix._xAxis = Vector3.Zero();
  3763. Matrix._yAxis = Vector3.Zero();
  3764. Matrix._zAxis = Vector3.Zero();
  3765. BABYLON.Matrix = Matrix;
  3766. var Plane = (function () {
  3767. /**
  3768. * Creates a Plane object according to the passed floats a, b, c, d and the plane equation : ax + by + cz + d = 0
  3769. */
  3770. function Plane(a, b, c, d) {
  3771. this.normal = new Vector3(a, b, c);
  3772. this.d = d;
  3773. }
  3774. /**
  3775. * Returns the plane coordinates as a new array of 4 elements [a, b, c, d].
  3776. */
  3777. Plane.prototype.asArray = function () {
  3778. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  3779. };
  3780. // Methods
  3781. /**
  3782. * Returns a new plane copied from the current Plane.
  3783. */
  3784. Plane.prototype.clone = function () {
  3785. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  3786. };
  3787. /**
  3788. * Returns the string "Plane".
  3789. */
  3790. Plane.prototype.getClassName = function () {
  3791. return "Plane";
  3792. };
  3793. /**
  3794. * Returns the Plane hash code.
  3795. */
  3796. Plane.prototype.getHashCode = function () {
  3797. var hash = this.normal.getHashCode();
  3798. hash = (hash * 397) ^ (this.d || 0);
  3799. return hash;
  3800. };
  3801. /**
  3802. * Normalize the current Plane in place.
  3803. * Returns the updated Plane.
  3804. */
  3805. Plane.prototype.normalize = function () {
  3806. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  3807. var magnitude = 0.0;
  3808. if (norm !== 0) {
  3809. magnitude = 1.0 / norm;
  3810. }
  3811. this.normal.x *= magnitude;
  3812. this.normal.y *= magnitude;
  3813. this.normal.z *= magnitude;
  3814. this.d *= magnitude;
  3815. return this;
  3816. };
  3817. /**
  3818. * Returns a new Plane as the result of the transformation of the current Plane by the passed matrix.
  3819. */
  3820. Plane.prototype.transform = function (transformation) {
  3821. var transposedMatrix = Matrix.Transpose(transformation);
  3822. var x = this.normal.x;
  3823. var y = this.normal.y;
  3824. var z = this.normal.z;
  3825. var d = this.d;
  3826. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  3827. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  3828. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  3829. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  3830. return new Plane(normalX, normalY, normalZ, finalD);
  3831. };
  3832. /**
  3833. * Returns the dot product (float) of the point coordinates and the plane normal.
  3834. */
  3835. Plane.prototype.dotCoordinate = function (point) {
  3836. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  3837. };
  3838. /**
  3839. * Updates the current Plane from the plane defined by the three passed points.
  3840. * Returns the updated Plane.
  3841. */
  3842. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  3843. var x1 = point2.x - point1.x;
  3844. var y1 = point2.y - point1.y;
  3845. var z1 = point2.z - point1.z;
  3846. var x2 = point3.x - point1.x;
  3847. var y2 = point3.y - point1.y;
  3848. var z2 = point3.z - point1.z;
  3849. var yz = (y1 * z2) - (z1 * y2);
  3850. var xz = (z1 * x2) - (x1 * z2);
  3851. var xy = (x1 * y2) - (y1 * x2);
  3852. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  3853. var invPyth;
  3854. if (pyth !== 0) {
  3855. invPyth = 1.0 / pyth;
  3856. }
  3857. else {
  3858. invPyth = 0.0;
  3859. }
  3860. this.normal.x = yz * invPyth;
  3861. this.normal.y = xz * invPyth;
  3862. this.normal.z = xy * invPyth;
  3863. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  3864. return this;
  3865. };
  3866. /**
  3867. * Boolean : True is the vector "direction" is the same side than the plane normal.
  3868. */
  3869. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  3870. var dot = Vector3.Dot(this.normal, direction);
  3871. return (dot <= epsilon);
  3872. };
  3873. /**
  3874. * Returns the signed distance (float) from the passed point to the Plane.
  3875. */
  3876. Plane.prototype.signedDistanceTo = function (point) {
  3877. return Vector3.Dot(point, this.normal) + this.d;
  3878. };
  3879. // Statics
  3880. /**
  3881. * Returns a new Plane from the passed array.
  3882. */
  3883. Plane.FromArray = function (array) {
  3884. return new Plane(array[0], array[1], array[2], array[3]);
  3885. };
  3886. /**
  3887. * Returns a new Plane defined by the three passed points.
  3888. */
  3889. Plane.FromPoints = function (point1, point2, point3) {
  3890. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  3891. result.copyFromPoints(point1, point2, point3);
  3892. return result;
  3893. };
  3894. /**
  3895. * Returns a new Plane the normal vector to this plane at the passed origin point.
  3896. * Note : the vector "normal" is updated because normalized.
  3897. */
  3898. Plane.FromPositionAndNormal = function (origin, normal) {
  3899. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  3900. normal.normalize();
  3901. result.normal = normal;
  3902. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  3903. return result;
  3904. };
  3905. /**
  3906. * Returns the signed distance between the plane defined by the normal vector at the "origin"" point and the passed other point.
  3907. */
  3908. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  3909. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  3910. return Vector3.Dot(point, normal) + d;
  3911. };
  3912. return Plane;
  3913. }());
  3914. BABYLON.Plane = Plane;
  3915. var Viewport = (function () {
  3916. /**
  3917. * Creates a Viewport object located at (x, y) and sized (width, height).
  3918. */
  3919. function Viewport(x, y, width, height) {
  3920. this.x = x;
  3921. this.y = y;
  3922. this.width = width;
  3923. this.height = height;
  3924. }
  3925. Viewport.prototype.toGlobal = function (renderWidth, renderHeight) {
  3926. return new Viewport(this.x * renderWidth, this.y * renderHeight, this.width * renderWidth, this.height * renderHeight);
  3927. };
  3928. /**
  3929. * Returns a new Viewport copied from the current one.
  3930. */
  3931. Viewport.prototype.clone = function () {
  3932. return new Viewport(this.x, this.y, this.width, this.height);
  3933. };
  3934. return Viewport;
  3935. }());
  3936. BABYLON.Viewport = Viewport;
  3937. var Frustum = (function () {
  3938. function Frustum() {
  3939. }
  3940. /**
  3941. * Returns a new array of 6 Frustum planes computed by the passed transformation matrix.
  3942. */
  3943. Frustum.GetPlanes = function (transform) {
  3944. var frustumPlanes = [];
  3945. for (var index = 0; index < 6; index++) {
  3946. frustumPlanes.push(new Plane(0.0, 0.0, 0.0, 0.0));
  3947. }
  3948. Frustum.GetPlanesToRef(transform, frustumPlanes);
  3949. return frustumPlanes;
  3950. };
  3951. /**
  3952. * Sets the passed array "frustumPlanes" with the 6 Frustum planes computed by the passed transformation matrix.
  3953. */
  3954. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  3955. // Near
  3956. frustumPlanes[0].normal.x = transform.m[3] + transform.m[2];
  3957. frustumPlanes[0].normal.y = transform.m[7] + transform.m[6];
  3958. frustumPlanes[0].normal.z = transform.m[11] + transform.m[10];
  3959. frustumPlanes[0].d = transform.m[15] + transform.m[14];
  3960. frustumPlanes[0].normalize();
  3961. // Far
  3962. frustumPlanes[1].normal.x = transform.m[3] - transform.m[2];
  3963. frustumPlanes[1].normal.y = transform.m[7] - transform.m[6];
  3964. frustumPlanes[1].normal.z = transform.m[11] - transform.m[10];
  3965. frustumPlanes[1].d = transform.m[15] - transform.m[14];
  3966. frustumPlanes[1].normalize();
  3967. // Left
  3968. frustumPlanes[2].normal.x = transform.m[3] + transform.m[0];
  3969. frustumPlanes[2].normal.y = transform.m[7] + transform.m[4];
  3970. frustumPlanes[2].normal.z = transform.m[11] + transform.m[8];
  3971. frustumPlanes[2].d = transform.m[15] + transform.m[12];
  3972. frustumPlanes[2].normalize();
  3973. // Right
  3974. frustumPlanes[3].normal.x = transform.m[3] - transform.m[0];
  3975. frustumPlanes[3].normal.y = transform.m[7] - transform.m[4];
  3976. frustumPlanes[3].normal.z = transform.m[11] - transform.m[8];
  3977. frustumPlanes[3].d = transform.m[15] - transform.m[12];
  3978. frustumPlanes[3].normalize();
  3979. // Top
  3980. frustumPlanes[4].normal.x = transform.m[3] - transform.m[1];
  3981. frustumPlanes[4].normal.y = transform.m[7] - transform.m[5];
  3982. frustumPlanes[4].normal.z = transform.m[11] - transform.m[9];
  3983. frustumPlanes[4].d = transform.m[15] - transform.m[13];
  3984. frustumPlanes[4].normalize();
  3985. // Bottom
  3986. frustumPlanes[5].normal.x = transform.m[3] + transform.m[1];
  3987. frustumPlanes[5].normal.y = transform.m[7] + transform.m[5];
  3988. frustumPlanes[5].normal.z = transform.m[11] + transform.m[9];
  3989. frustumPlanes[5].d = transform.m[15] + transform.m[13];
  3990. frustumPlanes[5].normalize();
  3991. };
  3992. return Frustum;
  3993. }());
  3994. BABYLON.Frustum = Frustum;
  3995. var Space;
  3996. (function (Space) {
  3997. Space[Space["LOCAL"] = 0] = "LOCAL";
  3998. Space[Space["WORLD"] = 1] = "WORLD";
  3999. Space[Space["BONE"] = 2] = "BONE";
  4000. })(Space = BABYLON.Space || (BABYLON.Space = {}));
  4001. var Axis = (function () {
  4002. function Axis() {
  4003. }
  4004. return Axis;
  4005. }());
  4006. Axis.X = new Vector3(1.0, 0.0, 0.0);
  4007. Axis.Y = new Vector3(0.0, 1.0, 0.0);
  4008. Axis.Z = new Vector3(0.0, 0.0, 1.0);
  4009. BABYLON.Axis = Axis;
  4010. ;
  4011. var BezierCurve = (function () {
  4012. function BezierCurve() {
  4013. }
  4014. /**
  4015. * Returns the cubic Bezier interpolated value (float) at "t" (float) from the passed x1, y1, x2, y2 floats.
  4016. */
  4017. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  4018. // Extract X (which is equal to time here)
  4019. var f0 = 1 - 3 * x2 + 3 * x1;
  4020. var f1 = 3 * x2 - 6 * x1;
  4021. var f2 = 3 * x1;
  4022. var refinedT = t;
  4023. for (var i = 0; i < 5; i++) {
  4024. var refinedT2 = refinedT * refinedT;
  4025. var refinedT3 = refinedT2 * refinedT;
  4026. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  4027. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  4028. refinedT -= (x - t) * slope;
  4029. refinedT = Math.min(1, Math.max(0, refinedT));
  4030. }
  4031. // Resolve cubic bezier for the given x
  4032. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  4033. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  4034. Math.pow(refinedT, 3);
  4035. };
  4036. return BezierCurve;
  4037. }());
  4038. BABYLON.BezierCurve = BezierCurve;
  4039. var Orientation;
  4040. (function (Orientation) {
  4041. Orientation[Orientation["CW"] = 0] = "CW";
  4042. Orientation[Orientation["CCW"] = 1] = "CCW";
  4043. })(Orientation = BABYLON.Orientation || (BABYLON.Orientation = {}));
  4044. var Angle = (function () {
  4045. /**
  4046. * Creates an Angle object of "radians" radians (float).
  4047. */
  4048. function Angle(radians) {
  4049. var _this = this;
  4050. /**
  4051. * Returns the Angle value in degrees (float).
  4052. */
  4053. this.degrees = function () { return _this._radians * 180.0 / Math.PI; };
  4054. /**
  4055. * Returns the Angle value in radians (float).
  4056. */
  4057. this.radians = function () { return _this._radians; };
  4058. this._radians = radians;
  4059. if (this._radians < 0.0)
  4060. this._radians += (2.0 * Math.PI);
  4061. }
  4062. /**
  4063. * Returns a new Angle object valued with the angle value in radians between the two passed vectors.
  4064. */
  4065. Angle.BetweenTwoPoints = function (a, b) {
  4066. var delta = b.subtract(a);
  4067. var theta = Math.atan2(delta.y, delta.x);
  4068. return new Angle(theta);
  4069. };
  4070. /**
  4071. * Returns a new Angle object from the passed float in radians.
  4072. */
  4073. Angle.FromRadians = function (radians) {
  4074. return new Angle(radians);
  4075. };
  4076. /**
  4077. * Returns a new Angle object from the passed float in degrees.
  4078. */
  4079. Angle.FromDegrees = function (degrees) {
  4080. return new Angle(degrees * Math.PI / 180.0);
  4081. };
  4082. return Angle;
  4083. }());
  4084. BABYLON.Angle = Angle;
  4085. var Arc2 = (function () {
  4086. /**
  4087. * Creates an Arc object from the three passed points : start, middle and end.
  4088. */
  4089. function Arc2(startPoint, midPoint, endPoint) {
  4090. this.startPoint = startPoint;
  4091. this.midPoint = midPoint;
  4092. this.endPoint = endPoint;
  4093. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  4094. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  4095. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  4096. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  4097. 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);
  4098. this.radius = this.centerPoint.subtract(this.startPoint).length();
  4099. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  4100. var a1 = this.startAngle.degrees();
  4101. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  4102. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  4103. // angles correction
  4104. if (a2 - a1 > +180.0)
  4105. a2 -= 360.0;
  4106. if (a2 - a1 < -180.0)
  4107. a2 += 360.0;
  4108. if (a3 - a2 > +180.0)
  4109. a3 -= 360.0;
  4110. if (a3 - a2 < -180.0)
  4111. a3 += 360.0;
  4112. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  4113. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  4114. }
  4115. return Arc2;
  4116. }());
  4117. BABYLON.Arc2 = Arc2;
  4118. var Path2 = (function () {
  4119. /**
  4120. * Creates a Path2 object from the starting 2D coordinates x and y.
  4121. */
  4122. function Path2(x, y) {
  4123. this._points = new Array();
  4124. this._length = 0.0;
  4125. this.closed = false;
  4126. this._points.push(new Vector2(x, y));
  4127. }
  4128. /**
  4129. * Adds a new segment until the passed coordinates (x, y) to the current Path2.
  4130. * Returns the updated Path2.
  4131. */
  4132. Path2.prototype.addLineTo = function (x, y) {
  4133. if (closed) {
  4134. //Tools.Error("cannot add lines to closed paths");
  4135. return this;
  4136. }
  4137. var newPoint = new Vector2(x, y);
  4138. var previousPoint = this._points[this._points.length - 1];
  4139. this._points.push(newPoint);
  4140. this._length += newPoint.subtract(previousPoint).length();
  4141. return this;
  4142. };
  4143. /**
  4144. * Adds _numberOfSegments_ segments according to the arc definition (middle point coordinates, end point coordinates, the arc start point being the current Path2 last point) to the current Path2.
  4145. * Returns the updated Path2.
  4146. */
  4147. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  4148. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  4149. if (closed) {
  4150. //Tools.Error("cannot add arcs to closed paths");
  4151. return this;
  4152. }
  4153. var startPoint = this._points[this._points.length - 1];
  4154. var midPoint = new Vector2(midX, midY);
  4155. var endPoint = new Vector2(endX, endY);
  4156. var arc = new Arc2(startPoint, midPoint, endPoint);
  4157. var increment = arc.angle.radians() / numberOfSegments;
  4158. if (arc.orientation === Orientation.CW)
  4159. increment *= -1;
  4160. var currentAngle = arc.startAngle.radians() + increment;
  4161. for (var i = 0; i < numberOfSegments; i++) {
  4162. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  4163. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  4164. this.addLineTo(x, y);
  4165. currentAngle += increment;
  4166. }
  4167. return this;
  4168. };
  4169. /**
  4170. * Closes the Path2.
  4171. * Returns the Path2.
  4172. */
  4173. Path2.prototype.close = function () {
  4174. this.closed = true;
  4175. return this;
  4176. };
  4177. /**
  4178. * Returns the Path2 total length (float).
  4179. */
  4180. Path2.prototype.length = function () {
  4181. var result = this._length;
  4182. if (!this.closed) {
  4183. var lastPoint = this._points[this._points.length - 1];
  4184. var firstPoint = this._points[0];
  4185. result += (firstPoint.subtract(lastPoint).length());
  4186. }
  4187. return result;
  4188. };
  4189. /**
  4190. * Returns the Path2 internal array of points.
  4191. */
  4192. Path2.prototype.getPoints = function () {
  4193. return this._points;
  4194. };
  4195. /**
  4196. * Returns a new Vector2 located at a percentage of the Path2 total length on this path.
  4197. */
  4198. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  4199. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  4200. //Tools.Error("normalized length position should be between 0 and 1.");
  4201. return Vector2.Zero();
  4202. }
  4203. var lengthPosition = normalizedLengthPosition * this.length();
  4204. var previousOffset = 0;
  4205. for (var i = 0; i < this._points.length; i++) {
  4206. var j = (i + 1) % this._points.length;
  4207. var a = this._points[i];
  4208. var b = this._points[j];
  4209. var bToA = b.subtract(a);
  4210. var nextOffset = (bToA.length() + previousOffset);
  4211. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  4212. var dir = bToA.normalize();
  4213. var localOffset = lengthPosition - previousOffset;
  4214. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  4215. }
  4216. previousOffset = nextOffset;
  4217. }
  4218. //Tools.Error("internal error");
  4219. return Vector2.Zero();
  4220. };
  4221. /**
  4222. * Returns a new Path2 starting at the coordinates (x, y).
  4223. */
  4224. Path2.StartingAt = function (x, y) {
  4225. return new Path2(x, y);
  4226. };
  4227. return Path2;
  4228. }());
  4229. BABYLON.Path2 = Path2;
  4230. var Path3D = (function () {
  4231. /**
  4232. * new Path3D(path, normal, raw)
  4233. * Creates a Path3D. A Path3D is a logical math object, so not a mesh.
  4234. * please read the description in the tutorial : http://doc.babylonjs.com/tutorials/How_to_use_Path3D
  4235. * path : an array of Vector3, the curve axis of the Path3D
  4236. * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  4237. * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  4238. */
  4239. function Path3D(path, firstNormal, raw) {
  4240. this.path = path;
  4241. this._curve = new Array();
  4242. this._distances = new Array();
  4243. this._tangents = new Array();
  4244. this._normals = new Array();
  4245. this._binormals = new Array();
  4246. for (var p = 0; p < path.length; p++) {
  4247. this._curve[p] = path[p].clone(); // hard copy
  4248. }
  4249. this._raw = raw || false;
  4250. this._compute(firstNormal);
  4251. }
  4252. /**
  4253. * Returns the Path3D array of successive Vector3 designing its curve.
  4254. */
  4255. Path3D.prototype.getCurve = function () {
  4256. return this._curve;
  4257. };
  4258. /**
  4259. * Returns an array populated with tangent vectors on each Path3D curve point.
  4260. */
  4261. Path3D.prototype.getTangents = function () {
  4262. return this._tangents;
  4263. };
  4264. /**
  4265. * Returns an array populated with normal vectors on each Path3D curve point.
  4266. */
  4267. Path3D.prototype.getNormals = function () {
  4268. return this._normals;
  4269. };
  4270. /**
  4271. * Returns an array populated with binormal vectors on each Path3D curve point.
  4272. */
  4273. Path3D.prototype.getBinormals = function () {
  4274. return this._binormals;
  4275. };
  4276. /**
  4277. * Returns an array populated with distances (float) of the i-th point from the first curve point.
  4278. */
  4279. Path3D.prototype.getDistances = function () {
  4280. return this._distances;
  4281. };
  4282. /**
  4283. * Forces the Path3D tangent, normal, binormal and distance recomputation.
  4284. * Returns the same object updated.
  4285. */
  4286. Path3D.prototype.update = function (path, firstNormal) {
  4287. for (var p = 0; p < path.length; p++) {
  4288. this._curve[p].x = path[p].x;
  4289. this._curve[p].y = path[p].y;
  4290. this._curve[p].z = path[p].z;
  4291. }
  4292. this._compute(firstNormal);
  4293. return this;
  4294. };
  4295. // private function compute() : computes tangents, normals and binormals
  4296. Path3D.prototype._compute = function (firstNormal) {
  4297. var l = this._curve.length;
  4298. // first and last tangents
  4299. this._tangents[0] = this._getFirstNonNullVector(0);
  4300. if (!this._raw) {
  4301. this._tangents[0].normalize();
  4302. }
  4303. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  4304. if (!this._raw) {
  4305. this._tangents[l - 1].normalize();
  4306. }
  4307. // normals and binormals at first point : arbitrary vector with _normalVector()
  4308. var tg0 = this._tangents[0];
  4309. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  4310. this._normals[0] = pp0;
  4311. if (!this._raw) {
  4312. this._normals[0].normalize();
  4313. }
  4314. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  4315. if (!this._raw) {
  4316. this._binormals[0].normalize();
  4317. }
  4318. this._distances[0] = 0.0;
  4319. // normals and binormals : next points
  4320. var prev; // previous vector (segment)
  4321. var cur; // current vector (segment)
  4322. var curTang; // current tangent
  4323. // previous normal
  4324. var prevBinor; // previous binormal
  4325. for (var i = 1; i < l; i++) {
  4326. // tangents
  4327. prev = this._getLastNonNullVector(i);
  4328. if (i < l - 1) {
  4329. cur = this._getFirstNonNullVector(i);
  4330. this._tangents[i] = prev.add(cur);
  4331. this._tangents[i].normalize();
  4332. }
  4333. this._distances[i] = this._distances[i - 1] + prev.length();
  4334. // normals and binormals
  4335. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  4336. curTang = this._tangents[i];
  4337. prevBinor = this._binormals[i - 1];
  4338. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  4339. if (!this._raw) {
  4340. this._normals[i].normalize();
  4341. }
  4342. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  4343. if (!this._raw) {
  4344. this._binormals[i].normalize();
  4345. }
  4346. }
  4347. };
  4348. // private function getFirstNonNullVector(index)
  4349. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  4350. Path3D.prototype._getFirstNonNullVector = function (index) {
  4351. var i = 1;
  4352. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  4353. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  4354. i++;
  4355. nNVector = this._curve[index + i].subtract(this._curve[index]);
  4356. }
  4357. return nNVector;
  4358. };
  4359. // private function getLastNonNullVector(index)
  4360. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  4361. Path3D.prototype._getLastNonNullVector = function (index) {
  4362. var i = 1;
  4363. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  4364. while (nLVector.length() === 0 && index > i + 1) {
  4365. i++;
  4366. nLVector = this._curve[index].subtract(this._curve[index - i]);
  4367. }
  4368. return nLVector;
  4369. };
  4370. // private function normalVector(v0, vt, va) :
  4371. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  4372. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  4373. Path3D.prototype._normalVector = function (v0, vt, va) {
  4374. var normal0;
  4375. var tgl = vt.length();
  4376. if (tgl === 0.0) {
  4377. tgl = 1.0;
  4378. }
  4379. if (va === undefined || va === null) {
  4380. var point;
  4381. if (!MathTools.WithinEpsilon(Math.abs(vt.y) / tgl, 1.0, BABYLON.Epsilon)) {
  4382. point = new Vector3(0.0, -1.0, 0.0);
  4383. }
  4384. else if (!MathTools.WithinEpsilon(Math.abs(vt.x) / tgl, 1.0, BABYLON.Epsilon)) {
  4385. point = new Vector3(1.0, 0.0, 0.0);
  4386. }
  4387. else if (!MathTools.WithinEpsilon(Math.abs(vt.z) / tgl, 1.0, BABYLON.Epsilon)) {
  4388. point = new Vector3(0.0, 0.0, 1.0);
  4389. }
  4390. normal0 = Vector3.Cross(vt, point);
  4391. }
  4392. else {
  4393. normal0 = Vector3.Cross(vt, va);
  4394. Vector3.CrossToRef(normal0, vt, normal0);
  4395. }
  4396. normal0.normalize();
  4397. return normal0;
  4398. };
  4399. return Path3D;
  4400. }());
  4401. BABYLON.Path3D = Path3D;
  4402. var Curve3 = (function () {
  4403. /**
  4404. * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
  4405. * A Curve3 is designed from a series of successive Vector3.
  4406. * Tuto : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#curve3-object
  4407. */
  4408. function Curve3(points) {
  4409. this._length = 0.0;
  4410. this._points = points;
  4411. this._length = this._computeLength(points);
  4412. }
  4413. /**
  4414. * Returns a Curve3 object along a Quadratic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#quadratic-bezier-curve
  4415. * @param v0 (Vector3) the origin point of the Quadratic Bezier
  4416. * @param v1 (Vector3) the control point
  4417. * @param v2 (Vector3) the end point of the Quadratic Bezier
  4418. * @param nbPoints (integer) the wanted number of points in the curve
  4419. */
  4420. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  4421. nbPoints = nbPoints > 2 ? nbPoints : 3;
  4422. var bez = new Array();
  4423. var equation = function (t, val0, val1, val2) {
  4424. var res = (1.0 - t) * (1.0 - t) * val0 + 2.0 * t * (1.0 - t) * val1 + t * t * val2;
  4425. return res;
  4426. };
  4427. for (var i = 0; i <= nbPoints; i++) {
  4428. 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)));
  4429. }
  4430. return new Curve3(bez);
  4431. };
  4432. /**
  4433. * Returns a Curve3 object along a Cubic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#cubic-bezier-curve
  4434. * @param v0 (Vector3) the origin point of the Cubic Bezier
  4435. * @param v1 (Vector3) the first control point
  4436. * @param v2 (Vector3) the second control point
  4437. * @param v3 (Vector3) the end point of the Cubic Bezier
  4438. * @param nbPoints (integer) the wanted number of points in the curve
  4439. */
  4440. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  4441. nbPoints = nbPoints > 3 ? nbPoints : 4;
  4442. var bez = new Array();
  4443. var equation = function (t, val0, val1, val2, val3) {
  4444. 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;
  4445. return res;
  4446. };
  4447. for (var i = 0; i <= nbPoints; i++) {
  4448. 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)));
  4449. }
  4450. return new Curve3(bez);
  4451. };
  4452. /**
  4453. * Returns a Curve3 object along a Hermite Spline curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#hermite-spline
  4454. * @param p1 (Vector3) the origin point of the Hermite Spline
  4455. * @param t1 (Vector3) the tangent vector at the origin point
  4456. * @param p2 (Vector3) the end point of the Hermite Spline
  4457. * @param t2 (Vector3) the tangent vector at the end point
  4458. * @param nbPoints (integer) the wanted number of points in the curve
  4459. */
  4460. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  4461. var hermite = new Array();
  4462. var step = 1.0 / nbPoints;
  4463. for (var i = 0; i <= nbPoints; i++) {
  4464. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  4465. }
  4466. return new Curve3(hermite);
  4467. };
  4468. /**
  4469. * Returns a Curve3 object along a CatmullRom Spline curve :
  4470. * @param points (array of Vector3) the points the spline must pass through. At least, four points required.
  4471. * @param nbPoints (integer) the wanted number of points between each curve control points.
  4472. */
  4473. Curve3.CreateCatmullRomSpline = function (points, nbPoints) {
  4474. var totalPoints = new Array();
  4475. totalPoints.push(points[0].clone());
  4476. Array.prototype.push.apply(totalPoints, points);
  4477. totalPoints.push(points[points.length - 1].clone());
  4478. var catmullRom = new Array();
  4479. var step = 1.0 / nbPoints;
  4480. for (var i = 0; i < totalPoints.length - 3; i++) {
  4481. var amount = 0.0;
  4482. for (var c = 0; c < nbPoints; c++) {
  4483. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  4484. amount += step;
  4485. }
  4486. }
  4487. i--;
  4488. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  4489. return new Curve3(catmullRom);
  4490. };
  4491. /**
  4492. * Returns the Curve3 stored array of successive Vector3
  4493. */
  4494. Curve3.prototype.getPoints = function () {
  4495. return this._points;
  4496. };
  4497. /**
  4498. * Returns the computed length (float) of the curve.
  4499. */
  4500. Curve3.prototype.length = function () {
  4501. return this._length;
  4502. };
  4503. /**
  4504. * Returns a new instance of Curve3 object : var curve = curveA.continue(curveB);
  4505. * This new Curve3 is built by translating and sticking the curveB at the end of the curveA.
  4506. * curveA and curveB keep unchanged.
  4507. */
  4508. Curve3.prototype.continue = function (curve) {
  4509. var lastPoint = this._points[this._points.length - 1];
  4510. var continuedPoints = this._points.slice();
  4511. var curvePoints = curve.getPoints();
  4512. for (var i = 1; i < curvePoints.length; i++) {
  4513. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  4514. }
  4515. var continuedCurve = new Curve3(continuedPoints);
  4516. return continuedCurve;
  4517. };
  4518. Curve3.prototype._computeLength = function (path) {
  4519. var l = 0;
  4520. for (var i = 1; i < path.length; i++) {
  4521. l += (path[i].subtract(path[i - 1])).length();
  4522. }
  4523. return l;
  4524. };
  4525. return Curve3;
  4526. }());
  4527. BABYLON.Curve3 = Curve3;
  4528. // SphericalHarmonics
  4529. var SphericalHarmonics = (function () {
  4530. function SphericalHarmonics() {
  4531. this.L00 = Vector3.Zero();
  4532. this.L1_1 = Vector3.Zero();
  4533. this.L10 = Vector3.Zero();
  4534. this.L11 = Vector3.Zero();
  4535. this.L2_2 = Vector3.Zero();
  4536. this.L2_1 = Vector3.Zero();
  4537. this.L20 = Vector3.Zero();
  4538. this.L21 = Vector3.Zero();
  4539. this.L22 = Vector3.Zero();
  4540. }
  4541. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  4542. var colorVector = new Vector3(color.r, color.g, color.b);
  4543. var c = colorVector.scale(deltaSolidAngle);
  4544. this.L00 = this.L00.add(c.scale(0.282095));
  4545. this.L1_1 = this.L1_1.add(c.scale(0.488603 * direction.y));
  4546. this.L10 = this.L10.add(c.scale(0.488603 * direction.z));
  4547. this.L11 = this.L11.add(c.scale(0.488603 * direction.x));
  4548. this.L2_2 = this.L2_2.add(c.scale(1.092548 * direction.x * direction.y));
  4549. this.L2_1 = this.L2_1.add(c.scale(1.092548 * direction.y * direction.z));
  4550. this.L21 = this.L21.add(c.scale(1.092548 * direction.x * direction.z));
  4551. this.L20 = this.L20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  4552. this.L22 = this.L22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  4553. };
  4554. SphericalHarmonics.prototype.scale = function (scale) {
  4555. this.L00 = this.L00.scale(scale);
  4556. this.L1_1 = this.L1_1.scale(scale);
  4557. this.L10 = this.L10.scale(scale);
  4558. this.L11 = this.L11.scale(scale);
  4559. this.L2_2 = this.L2_2.scale(scale);
  4560. this.L2_1 = this.L2_1.scale(scale);
  4561. this.L20 = this.L20.scale(scale);
  4562. this.L21 = this.L21.scale(scale);
  4563. this.L22 = this.L22.scale(scale);
  4564. };
  4565. return SphericalHarmonics;
  4566. }());
  4567. BABYLON.SphericalHarmonics = SphericalHarmonics;
  4568. // SphericalPolynomial
  4569. var SphericalPolynomial = (function () {
  4570. function SphericalPolynomial() {
  4571. this.x = Vector3.Zero();
  4572. this.y = Vector3.Zero();
  4573. this.z = Vector3.Zero();
  4574. this.xx = Vector3.Zero();
  4575. this.yy = Vector3.Zero();
  4576. this.zz = Vector3.Zero();
  4577. this.xy = Vector3.Zero();
  4578. this.yz = Vector3.Zero();
  4579. this.zx = Vector3.Zero();
  4580. }
  4581. SphericalPolynomial.prototype.addAmbient = function (color) {
  4582. var colorVector = new Vector3(color.r, color.g, color.b);
  4583. this.xx = this.xx.add(colorVector);
  4584. this.yy = this.yy.add(colorVector);
  4585. this.zz = this.zz.add(colorVector);
  4586. };
  4587. SphericalPolynomial.getSphericalPolynomialFromHarmonics = function (harmonics) {
  4588. var result = new SphericalPolynomial();
  4589. result.x = harmonics.L11.scale(1.02333);
  4590. result.y = harmonics.L1_1.scale(1.02333);
  4591. result.z = harmonics.L10.scale(1.02333);
  4592. result.xx = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).add(harmonics.L22.scale(0.429043));
  4593. result.yy = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).subtract(harmonics.L22.scale(0.429043));
  4594. result.zz = harmonics.L00.scale(0.886277).add(harmonics.L20.scale(0.495417));
  4595. result.yz = harmonics.L2_1.scale(0.858086);
  4596. result.zx = harmonics.L21.scale(0.858086);
  4597. result.xy = harmonics.L2_2.scale(0.858086);
  4598. return result;
  4599. };
  4600. return SphericalPolynomial;
  4601. }());
  4602. BABYLON.SphericalPolynomial = SphericalPolynomial;
  4603. // Vertex formats
  4604. var PositionNormalVertex = (function () {
  4605. function PositionNormalVertex(position, normal) {
  4606. if (position === void 0) { position = Vector3.Zero(); }
  4607. if (normal === void 0) { normal = Vector3.Up(); }
  4608. this.position = position;
  4609. this.normal = normal;
  4610. }
  4611. PositionNormalVertex.prototype.clone = function () {
  4612. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  4613. };
  4614. return PositionNormalVertex;
  4615. }());
  4616. BABYLON.PositionNormalVertex = PositionNormalVertex;
  4617. var PositionNormalTextureVertex = (function () {
  4618. function PositionNormalTextureVertex(position, normal, uv) {
  4619. if (position === void 0) { position = Vector3.Zero(); }
  4620. if (normal === void 0) { normal = Vector3.Up(); }
  4621. if (uv === void 0) { uv = Vector2.Zero(); }
  4622. this.position = position;
  4623. this.normal = normal;
  4624. this.uv = uv;
  4625. }
  4626. PositionNormalTextureVertex.prototype.clone = function () {
  4627. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  4628. };
  4629. return PositionNormalTextureVertex;
  4630. }());
  4631. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  4632. // Temporary pre-allocated objects for engine internal use
  4633. // usage in any internal function :
  4634. // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3
  4635. // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
  4636. var Tmp = (function () {
  4637. function Tmp() {
  4638. }
  4639. return Tmp;
  4640. }());
  4641. Tmp.Color3 = [Color3.Black(), Color3.Black(), Color3.Black()];
  4642. Tmp.Vector2 = [Vector2.Zero(), Vector2.Zero(), Vector2.Zero()]; // 3 temp Vector2 at once should be enough
  4643. Tmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(),
  4644. Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()]; // 9 temp Vector3 at once should be enough
  4645. Tmp.Vector4 = [Vector4.Zero(), Vector4.Zero(), Vector4.Zero()]; // 3 temp Vector4 at once should be enough
  4646. Tmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero()]; // 2 temp Quaternion at once should be enough
  4647. Tmp.Matrix = [Matrix.Zero(), Matrix.Zero(),
  4648. Matrix.Zero(), Matrix.Zero(),
  4649. Matrix.Zero(), Matrix.Zero(),
  4650. Matrix.Zero(), Matrix.Zero()]; // 6 temp Matrices at once should be enough
  4651. BABYLON.Tmp = Tmp;
  4652. // Same as Tmp but not exported to keep it onyl for math functions to avoid conflicts
  4653. var MathTmp = (function () {
  4654. function MathTmp() {
  4655. }
  4656. return MathTmp;
  4657. }());
  4658. MathTmp.Vector3 = [Vector3.Zero()];
  4659. MathTmp.Matrix = [Matrix.Zero(), Matrix.Zero()];
  4660. MathTmp.Quaternion = [Quaternion.Zero()];
  4661. })(BABYLON || (BABYLON = {}));
  4662. //# sourceMappingURL=babylon.math.js.map
  4663. //# sourceMappingURL=babylon.mixins.js.map
  4664. var BABYLON;
  4665. (function (BABYLON) {
  4666. function generateSerializableMember(type, sourceName) {
  4667. return function (target, propertyKey) {
  4668. if (!target.__serializableMembers) {
  4669. target.__serializableMembers = {};
  4670. }
  4671. if (!target.__serializableMembers[propertyKey]) {
  4672. target.__serializableMembers[propertyKey] = { type: type, sourceName: sourceName };
  4673. }
  4674. };
  4675. }
  4676. function serialize(sourceName) {
  4677. return generateSerializableMember(0, sourceName); // value member
  4678. }
  4679. BABYLON.serialize = serialize;
  4680. function serializeAsTexture(sourceName) {
  4681. return generateSerializableMember(1, sourceName); // texture member
  4682. }
  4683. BABYLON.serializeAsTexture = serializeAsTexture;
  4684. function serializeAsColor3(sourceName) {
  4685. return generateSerializableMember(2, sourceName); // color3 member
  4686. }
  4687. BABYLON.serializeAsColor3 = serializeAsColor3;
  4688. function serializeAsFresnelParameters(sourceName) {
  4689. return generateSerializableMember(3, sourceName); // fresnel parameters member
  4690. }
  4691. BABYLON.serializeAsFresnelParameters = serializeAsFresnelParameters;
  4692. function serializeAsVector2(sourceName) {
  4693. return generateSerializableMember(4, sourceName); // vector2 member
  4694. }
  4695. BABYLON.serializeAsVector2 = serializeAsVector2;
  4696. function serializeAsVector3(sourceName) {
  4697. return generateSerializableMember(5, sourceName); // vector3 member
  4698. }
  4699. BABYLON.serializeAsVector3 = serializeAsVector3;
  4700. function serializeAsMeshReference(sourceName) {
  4701. return generateSerializableMember(6, sourceName); // mesh reference member
  4702. }
  4703. BABYLON.serializeAsMeshReference = serializeAsMeshReference;
  4704. function serializeAsColorCurves(sourceName) {
  4705. return generateSerializableMember(7, sourceName); // color curves
  4706. }
  4707. BABYLON.serializeAsColorCurves = serializeAsColorCurves;
  4708. var SerializationHelper = (function () {
  4709. function SerializationHelper() {
  4710. }
  4711. SerializationHelper.Serialize = function (entity, serializationObject) {
  4712. if (!serializationObject) {
  4713. serializationObject = {};
  4714. }
  4715. // Tags
  4716. serializationObject.tags = BABYLON.Tags.GetTags(entity);
  4717. // Properties
  4718. for (var property in entity.__serializableMembers) {
  4719. var propertyDescriptor = entity.__serializableMembers[property];
  4720. var targetPropertyName = propertyDescriptor.sourceName || property;
  4721. var propertyType = propertyDescriptor.type;
  4722. var sourceProperty = entity[property];
  4723. if (sourceProperty !== undefined && sourceProperty !== null) {
  4724. switch (propertyType) {
  4725. case 0:
  4726. serializationObject[targetPropertyName] = sourceProperty;
  4727. break;
  4728. case 1:
  4729. serializationObject[targetPropertyName] = sourceProperty.serialize();
  4730. break;
  4731. case 2:
  4732. serializationObject[targetPropertyName] = sourceProperty.asArray();
  4733. break;
  4734. case 3:
  4735. serializationObject[targetPropertyName] = sourceProperty.serialize();
  4736. break;
  4737. case 4:
  4738. serializationObject[targetPropertyName] = sourceProperty.asArray();
  4739. break;
  4740. case 5:
  4741. serializationObject[targetPropertyName] = sourceProperty.asArray();
  4742. break;
  4743. case 6:
  4744. serializationObject[targetPropertyName] = sourceProperty.id;
  4745. break;
  4746. case 7:
  4747. serializationObject[targetPropertyName] = sourceProperty.serialize();
  4748. break;
  4749. }
  4750. }
  4751. }
  4752. return serializationObject;
  4753. };
  4754. SerializationHelper.Parse = function (creationFunction, source, scene, rootUrl) {
  4755. var destination = creationFunction();
  4756. // Tags
  4757. BABYLON.Tags.AddTagsTo(destination, source.tags);
  4758. // Properties
  4759. for (var property in destination.__serializableMembers) {
  4760. var propertyDescriptor = destination.__serializableMembers[property];
  4761. var sourceProperty = source[propertyDescriptor.sourceName || property];
  4762. var propertyType = propertyDescriptor.type;
  4763. if (sourceProperty !== undefined && sourceProperty !== null) {
  4764. switch (propertyType) {
  4765. case 0:
  4766. destination[property] = sourceProperty;
  4767. break;
  4768. case 1:
  4769. destination[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl);
  4770. break;
  4771. case 2:
  4772. destination[property] = BABYLON.Color3.FromArray(sourceProperty);
  4773. break;
  4774. case 3:
  4775. destination[property] = BABYLON.FresnelParameters.Parse(sourceProperty);
  4776. break;
  4777. case 4:
  4778. destination[property] = BABYLON.Vector2.FromArray(sourceProperty);
  4779. break;
  4780. case 5:
  4781. destination[property] = BABYLON.Vector3.FromArray(sourceProperty);
  4782. break;
  4783. case 6:
  4784. destination[property] = scene.getLastMeshByID(sourceProperty);
  4785. break;
  4786. case 7:
  4787. destination[property] = BABYLON.ColorCurves.Parse(sourceProperty);
  4788. break;
  4789. }
  4790. }
  4791. }
  4792. return destination;
  4793. };
  4794. SerializationHelper.Clone = function (creationFunction, source) {
  4795. var destination = creationFunction();
  4796. // Tags
  4797. BABYLON.Tags.AddTagsTo(destination, source.tags);
  4798. // Properties
  4799. for (var property in destination.__serializableMembers) {
  4800. var propertyDescriptor = destination.__serializableMembers[property];
  4801. var sourceProperty = source[property];
  4802. var propertyType = propertyDescriptor.type;
  4803. if (sourceProperty !== undefined && sourceProperty !== null) {
  4804. switch (propertyType) {
  4805. case 0: // Value
  4806. case 6:
  4807. destination[property] = sourceProperty;
  4808. break;
  4809. case 1: // Texture
  4810. case 2: // Color3
  4811. case 3: // FresnelParameters
  4812. case 4: // Vector2
  4813. case 5: // Vector3
  4814. case 7:
  4815. destination[property] = sourceProperty.clone();
  4816. break;
  4817. }
  4818. }
  4819. }
  4820. return destination;
  4821. };
  4822. return SerializationHelper;
  4823. }());
  4824. BABYLON.SerializationHelper = SerializationHelper;
  4825. })(BABYLON || (BABYLON = {}));
  4826. //# sourceMappingURL=babylon.decorators.js.map
  4827. var BABYLON;
  4828. (function (BABYLON) {
  4829. /**
  4830. * A class serves as a medium between the observable and its observers
  4831. */
  4832. var EventState = (function () {
  4833. /**
  4834. * If the callback of a given Observer set skipNextObservers to true the following observers will be ignored
  4835. */
  4836. function EventState(mask, skipNextObservers) {
  4837. if (skipNextObservers === void 0) { skipNextObservers = false; }
  4838. this.initalize(mask, skipNextObservers);
  4839. }
  4840. EventState.prototype.initalize = function (mask, skipNextObservers) {
  4841. if (skipNextObservers === void 0) { skipNextObservers = false; }
  4842. this.mask = mask;
  4843. this.skipNextObservers = skipNextObservers;
  4844. return this;
  4845. };
  4846. return EventState;
  4847. }());
  4848. BABYLON.EventState = EventState;
  4849. /**
  4850. * Represent an Observer registered to a given Observable object.
  4851. */
  4852. var Observer = (function () {
  4853. function Observer(callback, mask) {
  4854. this.callback = callback;
  4855. this.mask = mask;
  4856. }
  4857. return Observer;
  4858. }());
  4859. BABYLON.Observer = Observer;
  4860. /**
  4861. * The Observable class is a simple implementation of the Observable pattern.
  4862. * 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.
  4863. * This enable a more fine grained execution without having to rely on multiple different Observable objects.
  4864. * 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).
  4865. * 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.
  4866. */
  4867. var Observable = (function () {
  4868. function Observable() {
  4869. this._observers = new Array();
  4870. this._eventState = new EventState(0);
  4871. }
  4872. /**
  4873. * Create a new Observer with the specified callback
  4874. * @param callback the callback that will be executed for that Observer
  4875. * @param mask the mask used to filter observers
  4876. * @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.
  4877. */
  4878. Observable.prototype.add = function (callback, mask, insertFirst) {
  4879. if (mask === void 0) { mask = -1; }
  4880. if (insertFirst === void 0) { insertFirst = false; }
  4881. if (!callback) {
  4882. return null;
  4883. }
  4884. var observer = new Observer(callback, mask);
  4885. if (insertFirst) {
  4886. this._observers.unshift(observer);
  4887. }
  4888. else {
  4889. this._observers.push(observer);
  4890. }
  4891. return observer;
  4892. };
  4893. /**
  4894. * Remove an Observer from the Observable object
  4895. * @param observer the instance of the Observer to remove. If it doesn't belong to this Observable, false will be returned.
  4896. */
  4897. Observable.prototype.remove = function (observer) {
  4898. var index = this._observers.indexOf(observer);
  4899. if (index !== -1) {
  4900. this._observers.splice(index, 1);
  4901. return true;
  4902. }
  4903. return false;
  4904. };
  4905. /**
  4906. * Remove a callback from the Observable object
  4907. * @param callback the callback to remove. If it doesn't belong to this Observable, false will be returned.
  4908. */
  4909. Observable.prototype.removeCallback = function (callback) {
  4910. for (var index = 0; index < this._observers.length; index++) {
  4911. if (this._observers[index].callback === callback) {
  4912. this._observers.splice(index, 1);
  4913. return true;
  4914. }
  4915. }
  4916. return false;
  4917. };
  4918. /**
  4919. * Notify all Observers by calling their respective callback with the given data
  4920. * Will return true if all observers were executed, false if an observer set skipNextObservers to true, then prevent the subsequent ones to execute
  4921. * @param eventData
  4922. * @param mask
  4923. */
  4924. Observable.prototype.notifyObservers = function (eventData, mask) {
  4925. if (mask === void 0) { mask = -1; }
  4926. var state = this._eventState;
  4927. state.mask = mask;
  4928. state.skipNextObservers = false;
  4929. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  4930. var obs = _a[_i];
  4931. if (obs.mask & mask) {
  4932. obs.callback(eventData, state);
  4933. }
  4934. if (state.skipNextObservers) {
  4935. return false;
  4936. }
  4937. }
  4938. return true;
  4939. };
  4940. /**
  4941. * return true is the Observable has at least one Observer registered
  4942. */
  4943. Observable.prototype.hasObservers = function () {
  4944. return this._observers.length > 0;
  4945. };
  4946. /**
  4947. * Clear the list of observers
  4948. */
  4949. Observable.prototype.clear = function () {
  4950. this._observers = new Array();
  4951. };
  4952. /**
  4953. * Clone the current observable
  4954. */
  4955. Observable.prototype.clone = function () {
  4956. var result = new Observable();
  4957. result._observers = this._observers.slice(0);
  4958. return result;
  4959. };
  4960. /**
  4961. * Does this observable handles observer registered with a given mask
  4962. * @param {number} trigger - the mask to be tested
  4963. * @return {boolean} whether or not one observer registered with the given mask is handeled
  4964. **/
  4965. Observable.prototype.hasSpecificMask = function (mask) {
  4966. if (mask === void 0) { mask = -1; }
  4967. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  4968. var obs = _a[_i];
  4969. if (obs.mask & mask && obs.mask === mask) {
  4970. return true;
  4971. }
  4972. }
  4973. return false;
  4974. };
  4975. return Observable;
  4976. }());
  4977. BABYLON.Observable = Observable;
  4978. })(BABYLON || (BABYLON = {}));
  4979. //# sourceMappingURL=babylon.observable.js.map
  4980. var BABYLON;
  4981. (function (BABYLON) {
  4982. var Database = (function () {
  4983. function Database(urlToScene, callbackManifestChecked) {
  4984. // Handling various flavors of prefixed version of IndexedDB
  4985. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  4986. this.callbackManifestChecked = callbackManifestChecked;
  4987. this.currentSceneUrl = Database.ReturnFullUrlLocation(urlToScene);
  4988. this.db = null;
  4989. this.enableSceneOffline = false;
  4990. this.enableTexturesOffline = false;
  4991. this.manifestVersionFound = 0;
  4992. this.mustUpdateRessources = false;
  4993. this.hasReachedQuota = false;
  4994. if (!Database.IDBStorageEnabled) {
  4995. this.callbackManifestChecked(true);
  4996. }
  4997. else {
  4998. this.checkManifestFile();
  4999. }
  5000. }
  5001. Database.prototype.checkManifestFile = function () {
  5002. var _this = this;
  5003. function noManifestFile() {
  5004. that.enableSceneOffline = false;
  5005. that.enableTexturesOffline = false;
  5006. that.callbackManifestChecked(false);
  5007. }
  5008. var that = this;
  5009. var timeStampUsed = false;
  5010. var manifestURL = this.currentSceneUrl + ".manifest";
  5011. var xhr = new XMLHttpRequest();
  5012. if (navigator.onLine) {
  5013. // Adding a timestamp to by-pass browsers' cache
  5014. timeStampUsed = true;
  5015. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  5016. }
  5017. xhr.open("GET", manifestURL, true);
  5018. xhr.addEventListener("load", function () {
  5019. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  5020. try {
  5021. var manifestFile = JSON.parse(xhr.response);
  5022. _this.enableSceneOffline = manifestFile.enableSceneOffline;
  5023. _this.enableTexturesOffline = manifestFile.enableTexturesOffline;
  5024. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  5025. _this.manifestVersionFound = manifestFile.version;
  5026. }
  5027. if (_this.callbackManifestChecked) {
  5028. _this.callbackManifestChecked(true);
  5029. }
  5030. }
  5031. catch (ex) {
  5032. noManifestFile();
  5033. }
  5034. }
  5035. else {
  5036. noManifestFile();
  5037. }
  5038. }, false);
  5039. xhr.addEventListener("error", function (event) {
  5040. if (timeStampUsed) {
  5041. timeStampUsed = false;
  5042. // Let's retry without the timeStamp
  5043. // It could fail when coupled with HTML5 Offline API
  5044. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  5045. xhr.open("GET", retryManifestURL, true);
  5046. xhr.send();
  5047. }
  5048. else {
  5049. noManifestFile();
  5050. }
  5051. }, false);
  5052. try {
  5053. xhr.send();
  5054. }
  5055. catch (ex) {
  5056. BABYLON.Tools.Error("Error on XHR send request.");
  5057. that.callbackManifestChecked(false);
  5058. }
  5059. };
  5060. Database.prototype.openAsync = function (successCallback, errorCallback) {
  5061. var _this = this;
  5062. function handleError() {
  5063. that.isSupported = false;
  5064. if (errorCallback)
  5065. errorCallback();
  5066. }
  5067. var that = this;
  5068. if (!this.idbFactory || !(this.enableSceneOffline || this.enableTexturesOffline)) {
  5069. // Your browser doesn't support IndexedDB
  5070. this.isSupported = false;
  5071. if (errorCallback)
  5072. errorCallback();
  5073. }
  5074. else {
  5075. // If the DB hasn't been opened or created yet
  5076. if (!this.db) {
  5077. this.hasReachedQuota = false;
  5078. this.isSupported = true;
  5079. var request = this.idbFactory.open("babylonjs", 1);
  5080. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  5081. request.onerror = function (event) {
  5082. handleError();
  5083. };
  5084. // executes when a version change transaction cannot complete due to other active transactions
  5085. request.onblocked = function (event) {
  5086. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  5087. handleError();
  5088. };
  5089. // DB has been opened successfully
  5090. request.onsuccess = function (event) {
  5091. _this.db = request.result;
  5092. successCallback();
  5093. };
  5094. // Initialization of the DB. Creating Scenes & Textures stores
  5095. request.onupgradeneeded = function (event) {
  5096. _this.db = (event.target).result;
  5097. try {
  5098. var scenesStore = _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  5099. var versionsStore = _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  5100. var texturesStore = _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  5101. }
  5102. catch (ex) {
  5103. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  5104. handleError();
  5105. }
  5106. };
  5107. }
  5108. else {
  5109. if (successCallback)
  5110. successCallback();
  5111. }
  5112. }
  5113. };
  5114. Database.prototype.loadImageFromDB = function (url, image) {
  5115. var _this = this;
  5116. var completeURL = Database.ReturnFullUrlLocation(url);
  5117. var saveAndLoadImage = function () {
  5118. if (!_this.hasReachedQuota && _this.db !== null) {
  5119. // the texture is not yet in the DB, let's try to save it
  5120. _this._saveImageIntoDBAsync(completeURL, image);
  5121. }
  5122. else {
  5123. image.src = url;
  5124. }
  5125. };
  5126. if (!this.mustUpdateRessources) {
  5127. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  5128. }
  5129. else {
  5130. saveAndLoadImage();
  5131. }
  5132. };
  5133. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  5134. if (this.isSupported && this.db !== null) {
  5135. var texture;
  5136. var transaction = this.db.transaction(["textures"]);
  5137. transaction.onabort = function (event) {
  5138. image.src = url;
  5139. };
  5140. transaction.oncomplete = function (event) {
  5141. var blobTextureURL;
  5142. if (texture) {
  5143. var URL = window.URL || window.webkitURL;
  5144. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  5145. image.onerror = function () {
  5146. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  5147. image.src = url;
  5148. };
  5149. image.src = blobTextureURL;
  5150. }
  5151. else {
  5152. notInDBCallback();
  5153. }
  5154. };
  5155. var getRequest = transaction.objectStore("textures").get(url);
  5156. getRequest.onsuccess = function (event) {
  5157. texture = (event.target).result;
  5158. };
  5159. getRequest.onerror = function (event) {
  5160. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  5161. image.src = url;
  5162. };
  5163. }
  5164. else {
  5165. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  5166. image.src = url;
  5167. }
  5168. };
  5169. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  5170. var _this = this;
  5171. if (this.isSupported) {
  5172. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  5173. var generateBlobUrl = function () {
  5174. var blobTextureURL;
  5175. if (blob) {
  5176. var URL = window.URL || window.webkitURL;
  5177. try {
  5178. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  5179. }
  5180. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  5181. catch (ex) {
  5182. blobTextureURL = URL.createObjectURL(blob);
  5183. }
  5184. }
  5185. image.src = blobTextureURL;
  5186. };
  5187. if (Database.IsUASupportingBlobStorage) {
  5188. var xhr = new XMLHttpRequest(), blob;
  5189. xhr.open("GET", url, true);
  5190. xhr.responseType = "blob";
  5191. xhr.addEventListener("load", function () {
  5192. if (xhr.status === 200) {
  5193. // Blob as response (XHR2)
  5194. blob = xhr.response;
  5195. var transaction = _this.db.transaction(["textures"], "readwrite");
  5196. // the transaction could abort because of a QuotaExceededError error
  5197. transaction.onabort = function (event) {
  5198. try {
  5199. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  5200. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  5201. _this.hasReachedQuota = true;
  5202. }
  5203. }
  5204. catch (ex) { }
  5205. generateBlobUrl();
  5206. };
  5207. transaction.oncomplete = function (event) {
  5208. generateBlobUrl();
  5209. };
  5210. var newTexture = { textureUrl: url, data: blob };
  5211. try {
  5212. // Put the blob into the dabase
  5213. var addRequest = transaction.objectStore("textures").put(newTexture);
  5214. addRequest.onsuccess = function (event) {
  5215. };
  5216. addRequest.onerror = function (event) {
  5217. generateBlobUrl();
  5218. };
  5219. }
  5220. catch (ex) {
  5221. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  5222. if (ex.code === 25) {
  5223. Database.IsUASupportingBlobStorage = false;
  5224. }
  5225. image.src = url;
  5226. }
  5227. }
  5228. else {
  5229. image.src = url;
  5230. }
  5231. }, false);
  5232. xhr.addEventListener("error", function (event) {
  5233. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  5234. image.src = url;
  5235. }, false);
  5236. xhr.send();
  5237. }
  5238. else {
  5239. image.src = url;
  5240. }
  5241. }
  5242. else {
  5243. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  5244. image.src = url;
  5245. }
  5246. };
  5247. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  5248. var _this = this;
  5249. var updateVersion = function (event) {
  5250. // the version is not yet in the DB or we need to update it
  5251. _this._saveVersionIntoDBAsync(url, versionLoaded);
  5252. };
  5253. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  5254. };
  5255. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  5256. var _this = this;
  5257. if (this.isSupported) {
  5258. var version;
  5259. try {
  5260. var transaction = this.db.transaction(["versions"]);
  5261. transaction.oncomplete = function (event) {
  5262. if (version) {
  5263. // If the version in the JSON file is > than the version in DB
  5264. if (_this.manifestVersionFound > version.data) {
  5265. _this.mustUpdateRessources = true;
  5266. updateInDBCallback();
  5267. }
  5268. else {
  5269. callback(version.data);
  5270. }
  5271. }
  5272. else {
  5273. _this.mustUpdateRessources = true;
  5274. updateInDBCallback();
  5275. }
  5276. };
  5277. transaction.onabort = function (event) {
  5278. callback(-1);
  5279. };
  5280. var getRequest = transaction.objectStore("versions").get(url);
  5281. getRequest.onsuccess = function (event) {
  5282. version = (event.target).result;
  5283. };
  5284. getRequest.onerror = function (event) {
  5285. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  5286. callback(-1);
  5287. };
  5288. }
  5289. catch (ex) {
  5290. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  5291. callback(-1);
  5292. }
  5293. }
  5294. else {
  5295. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  5296. callback(-1);
  5297. }
  5298. };
  5299. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  5300. var _this = this;
  5301. if (this.isSupported && !this.hasReachedQuota) {
  5302. try {
  5303. // Open a transaction to the database
  5304. var transaction = this.db.transaction(["versions"], "readwrite");
  5305. // the transaction could abort because of a QuotaExceededError error
  5306. transaction.onabort = function (event) {
  5307. try {
  5308. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  5309. _this.hasReachedQuota = true;
  5310. }
  5311. }
  5312. catch (ex) { }
  5313. callback(-1);
  5314. };
  5315. transaction.oncomplete = function (event) {
  5316. callback(_this.manifestVersionFound);
  5317. };
  5318. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  5319. // Put the scene into the database
  5320. var addRequest = transaction.objectStore("versions").put(newVersion);
  5321. addRequest.onsuccess = function (event) {
  5322. };
  5323. addRequest.onerror = function (event) {
  5324. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  5325. };
  5326. }
  5327. catch (ex) {
  5328. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  5329. callback(-1);
  5330. }
  5331. }
  5332. else {
  5333. callback(-1);
  5334. }
  5335. };
  5336. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  5337. var _this = this;
  5338. var completeUrl = Database.ReturnFullUrlLocation(url);
  5339. var saveAndLoadFile = function (event) {
  5340. // the scene is not yet in the DB, let's try to save it
  5341. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  5342. };
  5343. this._checkVersionFromDB(completeUrl, function (version) {
  5344. if (version !== -1) {
  5345. if (!_this.mustUpdateRessources) {
  5346. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  5347. }
  5348. else {
  5349. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  5350. }
  5351. }
  5352. else {
  5353. errorCallback();
  5354. }
  5355. });
  5356. };
  5357. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  5358. if (this.isSupported) {
  5359. var targetStore;
  5360. if (url.indexOf(".babylon") !== -1) {
  5361. targetStore = "scenes";
  5362. }
  5363. else {
  5364. targetStore = "textures";
  5365. }
  5366. var file;
  5367. var transaction = this.db.transaction([targetStore]);
  5368. transaction.oncomplete = function (event) {
  5369. if (file) {
  5370. callback(file.data);
  5371. }
  5372. else {
  5373. notInDBCallback();
  5374. }
  5375. };
  5376. transaction.onabort = function (event) {
  5377. notInDBCallback();
  5378. };
  5379. var getRequest = transaction.objectStore(targetStore).get(url);
  5380. getRequest.onsuccess = function (event) {
  5381. file = (event.target).result;
  5382. };
  5383. getRequest.onerror = function (event) {
  5384. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  5385. notInDBCallback();
  5386. };
  5387. }
  5388. else {
  5389. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  5390. callback();
  5391. }
  5392. };
  5393. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  5394. var _this = this;
  5395. if (this.isSupported) {
  5396. var targetStore;
  5397. if (url.indexOf(".babylon") !== -1) {
  5398. targetStore = "scenes";
  5399. }
  5400. else {
  5401. targetStore = "textures";
  5402. }
  5403. // Create XHR
  5404. var xhr = new XMLHttpRequest(), fileData;
  5405. xhr.open("GET", url, true);
  5406. if (useArrayBuffer) {
  5407. xhr.responseType = "arraybuffer";
  5408. }
  5409. xhr.onprogress = progressCallback;
  5410. xhr.addEventListener("load", function () {
  5411. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  5412. // Blob as response (XHR2)
  5413. //fileData = xhr.responseText;
  5414. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  5415. if (!_this.hasReachedQuota) {
  5416. // Open a transaction to the database
  5417. var transaction = _this.db.transaction([targetStore], "readwrite");
  5418. // the transaction could abort because of a QuotaExceededError error
  5419. transaction.onabort = function (event) {
  5420. try {
  5421. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  5422. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  5423. _this.hasReachedQuota = true;
  5424. }
  5425. }
  5426. catch (ex) { }
  5427. callback(fileData);
  5428. };
  5429. transaction.oncomplete = function (event) {
  5430. callback(fileData);
  5431. };
  5432. var newFile;
  5433. if (targetStore === "scenes") {
  5434. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  5435. }
  5436. else {
  5437. newFile = { textureUrl: url, data: fileData };
  5438. }
  5439. try {
  5440. // Put the scene into the database
  5441. var addRequest = transaction.objectStore(targetStore).put(newFile);
  5442. addRequest.onsuccess = function (event) {
  5443. };
  5444. addRequest.onerror = function (event) {
  5445. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  5446. };
  5447. }
  5448. catch (ex) {
  5449. callback(fileData);
  5450. }
  5451. }
  5452. else {
  5453. callback(fileData);
  5454. }
  5455. }
  5456. else {
  5457. callback();
  5458. }
  5459. }, false);
  5460. xhr.addEventListener("error", function (event) {
  5461. BABYLON.Tools.Error("error on XHR request.");
  5462. callback();
  5463. }, false);
  5464. xhr.send();
  5465. }
  5466. else {
  5467. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  5468. callback();
  5469. }
  5470. };
  5471. return Database;
  5472. }());
  5473. Database.IsUASupportingBlobStorage = true;
  5474. Database.IDBStorageEnabled = true;
  5475. Database.parseURL = function (url) {
  5476. var a = document.createElement('a');
  5477. a.href = url;
  5478. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  5479. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  5480. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  5481. return absLocation;
  5482. };
  5483. Database.ReturnFullUrlLocation = function (url) {
  5484. if (url.indexOf("http:/") === -1 && url.indexOf("https:/") === -1) {
  5485. return (Database.parseURL(window.location.href) + url);
  5486. }
  5487. else {
  5488. return url;
  5489. }
  5490. };
  5491. BABYLON.Database = Database;
  5492. })(BABYLON || (BABYLON = {}));
  5493. //# sourceMappingURL=babylon.database.js.map
  5494. var BABYLON;
  5495. (function (BABYLON) {
  5496. var Internals;
  5497. (function (Internals) {
  5498. /*
  5499. * Based on jsTGALoader - Javascript loader for TGA file
  5500. * By Vincent Thibault
  5501. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  5502. */
  5503. var TGATools = (function () {
  5504. function TGATools() {
  5505. }
  5506. TGATools.GetTGAHeader = function (data) {
  5507. var offset = 0;
  5508. var header = {
  5509. id_length: data[offset++],
  5510. colormap_type: data[offset++],
  5511. image_type: data[offset++],
  5512. colormap_index: data[offset++] | data[offset++] << 8,
  5513. colormap_length: data[offset++] | data[offset++] << 8,
  5514. colormap_size: data[offset++],
  5515. origin: [
  5516. data[offset++] | data[offset++] << 8,
  5517. data[offset++] | data[offset++] << 8
  5518. ],
  5519. width: data[offset++] | data[offset++] << 8,
  5520. height: data[offset++] | data[offset++] << 8,
  5521. pixel_size: data[offset++],
  5522. flags: data[offset++]
  5523. };
  5524. return header;
  5525. };
  5526. TGATools.UploadContent = function (gl, data) {
  5527. // Not enough data to contain header ?
  5528. if (data.length < 19) {
  5529. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  5530. return;
  5531. }
  5532. // Read Header
  5533. var offset = 18;
  5534. var header = TGATools.GetTGAHeader(data);
  5535. // Assume it's a valid Targa file.
  5536. if (header.id_length + offset > data.length) {
  5537. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  5538. return;
  5539. }
  5540. // Skip not needed data
  5541. offset += header.id_length;
  5542. var use_rle = false;
  5543. var use_pal = false;
  5544. var use_rgb = false;
  5545. var use_grey = false;
  5546. // Get some informations.
  5547. switch (header.image_type) {
  5548. case TGATools._TYPE_RLE_INDEXED:
  5549. use_rle = true;
  5550. case TGATools._TYPE_INDEXED:
  5551. use_pal = true;
  5552. break;
  5553. case TGATools._TYPE_RLE_RGB:
  5554. use_rle = true;
  5555. case TGATools._TYPE_RGB:
  5556. use_rgb = true;
  5557. break;
  5558. case TGATools._TYPE_RLE_GREY:
  5559. use_rle = true;
  5560. case TGATools._TYPE_GREY:
  5561. use_grey = true;
  5562. break;
  5563. }
  5564. var pixel_data;
  5565. var numAlphaBits = header.flags & 0xf;
  5566. var pixel_size = header.pixel_size >> 3;
  5567. var pixel_total = header.width * header.height * pixel_size;
  5568. // Read palettes
  5569. var palettes;
  5570. if (use_pal) {
  5571. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  5572. }
  5573. // Read LRE
  5574. if (use_rle) {
  5575. pixel_data = new Uint8Array(pixel_total);
  5576. var c, count, i;
  5577. var localOffset = 0;
  5578. var pixels = new Uint8Array(pixel_size);
  5579. while (offset < pixel_total && localOffset < pixel_total) {
  5580. c = data[offset++];
  5581. count = (c & 0x7f) + 1;
  5582. // RLE pixels
  5583. if (c & 0x80) {
  5584. // Bind pixel tmp array
  5585. for (i = 0; i < pixel_size; ++i) {
  5586. pixels[i] = data[offset++];
  5587. }
  5588. // Copy pixel array
  5589. for (i = 0; i < count; ++i) {
  5590. pixel_data.set(pixels, localOffset + i * pixel_size);
  5591. }
  5592. localOffset += pixel_size * count;
  5593. }
  5594. else {
  5595. count *= pixel_size;
  5596. for (i = 0; i < count; ++i) {
  5597. pixel_data[localOffset + i] = data[offset++];
  5598. }
  5599. localOffset += count;
  5600. }
  5601. }
  5602. }
  5603. else {
  5604. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  5605. }
  5606. // Load to texture
  5607. var x_start, y_start, x_step, y_step, y_end, x_end;
  5608. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  5609. default:
  5610. case TGATools._ORIGIN_UL:
  5611. x_start = 0;
  5612. x_step = 1;
  5613. x_end = header.width;
  5614. y_start = 0;
  5615. y_step = 1;
  5616. y_end = header.height;
  5617. break;
  5618. case TGATools._ORIGIN_BL:
  5619. x_start = 0;
  5620. x_step = 1;
  5621. x_end = header.width;
  5622. y_start = header.height - 1;
  5623. y_step = -1;
  5624. y_end = -1;
  5625. break;
  5626. case TGATools._ORIGIN_UR:
  5627. x_start = header.width - 1;
  5628. x_step = -1;
  5629. x_end = -1;
  5630. y_start = 0;
  5631. y_step = 1;
  5632. y_end = header.height;
  5633. break;
  5634. case TGATools._ORIGIN_BR:
  5635. x_start = header.width - 1;
  5636. x_step = -1;
  5637. x_end = -1;
  5638. y_start = header.height - 1;
  5639. y_step = -1;
  5640. y_end = -1;
  5641. break;
  5642. }
  5643. // Load the specify method
  5644. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  5645. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  5646. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  5647. };
  5648. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  5649. var image = pixel_data, colormap = palettes;
  5650. var width = header.width, height = header.height;
  5651. var color, i = 0, x, y;
  5652. var imageData = new Uint8Array(width * height * 4);
  5653. for (y = y_start; y !== y_end; y += y_step) {
  5654. for (x = x_start; x !== x_end; x += x_step, i++) {
  5655. color = image[i];
  5656. imageData[(x + width * y) * 4 + 3] = 255;
  5657. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  5658. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  5659. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  5660. }
  5661. }
  5662. return imageData;
  5663. };
  5664. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  5665. var image = pixel_data;
  5666. var width = header.width, height = header.height;
  5667. var color, i = 0, x, y;
  5668. var imageData = new Uint8Array(width * height * 4);
  5669. for (y = y_start; y !== y_end; y += y_step) {
  5670. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  5671. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  5672. imageData[(x + width * y) * 4 + 0] = (color & 0x7C00) >> 7;
  5673. imageData[(x + width * y) * 4 + 1] = (color & 0x03E0) >> 2;
  5674. imageData[(x + width * y) * 4 + 2] = (color & 0x001F) >> 3;
  5675. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  5676. }
  5677. }
  5678. return imageData;
  5679. };
  5680. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  5681. var image = pixel_data;
  5682. var width = header.width, height = header.height;
  5683. var i = 0, x, y;
  5684. var imageData = new Uint8Array(width * height * 4);
  5685. for (y = y_start; y !== y_end; y += y_step) {
  5686. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  5687. imageData[(x + width * y) * 4 + 3] = 255;
  5688. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  5689. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  5690. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  5691. }
  5692. }
  5693. return imageData;
  5694. };
  5695. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  5696. var image = pixel_data;
  5697. var width = header.width, height = header.height;
  5698. var i = 0, x, y;
  5699. var imageData = new Uint8Array(width * height * 4);
  5700. for (y = y_start; y !== y_end; y += y_step) {
  5701. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  5702. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  5703. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  5704. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  5705. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  5706. }
  5707. }
  5708. return imageData;
  5709. };
  5710. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  5711. var image = pixel_data;
  5712. var width = header.width, height = header.height;
  5713. var color, i = 0, x, y;
  5714. var imageData = new Uint8Array(width * height * 4);
  5715. for (y = y_start; y !== y_end; y += y_step) {
  5716. for (x = x_start; x !== x_end; x += x_step, i++) {
  5717. color = image[i];
  5718. imageData[(x + width * y) * 4 + 0] = color;
  5719. imageData[(x + width * y) * 4 + 1] = color;
  5720. imageData[(x + width * y) * 4 + 2] = color;
  5721. imageData[(x + width * y) * 4 + 3] = 255;
  5722. }
  5723. }
  5724. return imageData;
  5725. };
  5726. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  5727. var image = pixel_data;
  5728. var width = header.width, height = header.height;
  5729. var i = 0, x, y;
  5730. var imageData = new Uint8Array(width * height * 4);
  5731. for (y = y_start; y !== y_end; y += y_step) {
  5732. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  5733. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  5734. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  5735. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  5736. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  5737. }
  5738. }
  5739. return imageData;
  5740. };
  5741. return TGATools;
  5742. }());
  5743. TGATools._TYPE_NO_DATA = 0;
  5744. TGATools._TYPE_INDEXED = 1;
  5745. TGATools._TYPE_RGB = 2;
  5746. TGATools._TYPE_GREY = 3;
  5747. TGATools._TYPE_RLE_INDEXED = 9;
  5748. TGATools._TYPE_RLE_RGB = 10;
  5749. TGATools._TYPE_RLE_GREY = 11;
  5750. TGATools._ORIGIN_MASK = 0x30;
  5751. TGATools._ORIGIN_SHIFT = 0x04;
  5752. TGATools._ORIGIN_BL = 0x00;
  5753. TGATools._ORIGIN_BR = 0x01;
  5754. TGATools._ORIGIN_UL = 0x02;
  5755. TGATools._ORIGIN_UR = 0x03;
  5756. Internals.TGATools = TGATools;
  5757. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  5758. })(BABYLON || (BABYLON = {}));
  5759. //# sourceMappingURL=babylon.tools.tga.js.map
  5760. var BABYLON;
  5761. (function (BABYLON) {
  5762. var SmartArray = (function () {
  5763. function SmartArray(capacity) {
  5764. this.length = 0;
  5765. this._duplicateId = 0;
  5766. this.data = new Array(capacity);
  5767. this._id = SmartArray._GlobalId++;
  5768. }
  5769. SmartArray.prototype.push = function (value) {
  5770. this.data[this.length++] = value;
  5771. if (this.length > this.data.length) {
  5772. this.data.length *= 2;
  5773. }
  5774. if (!value.__smartArrayFlags) {
  5775. value.__smartArrayFlags = {};
  5776. }
  5777. value.__smartArrayFlags[this._id] = this._duplicateId;
  5778. };
  5779. SmartArray.prototype.forEach = function (func) {
  5780. for (var index = 0; index < this.length; index++) {
  5781. func(this.data[index]);
  5782. }
  5783. };
  5784. SmartArray.prototype.pushNoDuplicate = function (value) {
  5785. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  5786. return false;
  5787. }
  5788. this.push(value);
  5789. return true;
  5790. };
  5791. SmartArray.prototype.sort = function (compareFn) {
  5792. this.data.sort(compareFn);
  5793. };
  5794. SmartArray.prototype.reset = function () {
  5795. this.length = 0;
  5796. this._duplicateId++;
  5797. };
  5798. SmartArray.prototype.dispose = function () {
  5799. this.reset();
  5800. this.data.length = 0;
  5801. };
  5802. SmartArray.prototype.concat = function (array) {
  5803. if (array.length === 0) {
  5804. return;
  5805. }
  5806. if (this.length + array.length > this.data.length) {
  5807. this.data.length = (this.length + array.length) * 2;
  5808. }
  5809. for (var index = 0; index < array.length; index++) {
  5810. this.data[this.length++] = (array.data || array)[index];
  5811. }
  5812. };
  5813. SmartArray.prototype.concatWithNoDuplicate = function (array) {
  5814. if (array.length === 0) {
  5815. return;
  5816. }
  5817. if (this.length + array.length > this.data.length) {
  5818. this.data.length = (this.length + array.length) * 2;
  5819. }
  5820. for (var index = 0; index < array.length; index++) {
  5821. var item = (array.data || array)[index];
  5822. this.pushNoDuplicate(item);
  5823. }
  5824. };
  5825. SmartArray.prototype.indexOf = function (value) {
  5826. var position = this.data.indexOf(value);
  5827. if (position >= this.length) {
  5828. return -1;
  5829. }
  5830. return position;
  5831. };
  5832. return SmartArray;
  5833. }());
  5834. // Statics
  5835. SmartArray._GlobalId = 0;
  5836. BABYLON.SmartArray = SmartArray;
  5837. })(BABYLON || (BABYLON = {}));
  5838. //# sourceMappingURL=babylon.smartArray.js.map
  5839. var BABYLON;
  5840. (function (BABYLON) {
  5841. /**
  5842. * This class implement a typical dictionary using a string as key and the generic type T as value.
  5843. * The underlying implementation relies on an associative array to ensure the best performances.
  5844. * The value can be anything including 'null' but except 'undefined'
  5845. */
  5846. var StringDictionary = (function () {
  5847. function StringDictionary() {
  5848. this._count = 0;
  5849. this._data = {};
  5850. }
  5851. /**
  5852. * This will clear this dictionary and copy the content from the 'source' one.
  5853. * If the T value is a custom object, it won't be copied/cloned, the same object will be used
  5854. * @param source the dictionary to take the content from and copy to this dictionary
  5855. */
  5856. StringDictionary.prototype.copyFrom = function (source) {
  5857. var _this = this;
  5858. this.clear();
  5859. source.forEach(function (t, v) { return _this.add(t, v); });
  5860. };
  5861. /**
  5862. * Get a value based from its key
  5863. * @param key the given key to get the matching value from
  5864. * @return the value if found, otherwise undefined is returned
  5865. */
  5866. StringDictionary.prototype.get = function (key) {
  5867. var val = this._data[key];
  5868. if (val !== undefined) {
  5869. return val;
  5870. }
  5871. return undefined;
  5872. };
  5873. /**
  5874. * Get a value from its key or add it if it doesn't exist.
  5875. * This method will ensure you that a given key/data will be present in the dictionary.
  5876. * @param key the given key to get the matching value from
  5877. * @param factory the factory that will create the value if the key is not present in the dictionary.
  5878. * The factory will only be invoked if there's no data for the given key.
  5879. * @return the value corresponding to the key.
  5880. */
  5881. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  5882. var val = this.get(key);
  5883. if (val !== undefined) {
  5884. return val;
  5885. }
  5886. val = factory(key);
  5887. if (val) {
  5888. this.add(key, val);
  5889. }
  5890. return val;
  5891. };
  5892. /**
  5893. * Get a value from its key if present in the dictionary otherwise add it
  5894. * @param key the key to get the value from
  5895. * @param val if there's no such key/value pair in the dictionary add it with this value
  5896. * @return the value corresponding to the key
  5897. */
  5898. StringDictionary.prototype.getOrAdd = function (key, val) {
  5899. var curVal = this.get(key);
  5900. if (curVal !== undefined) {
  5901. return curVal;
  5902. }
  5903. this.add(key, val);
  5904. return val;
  5905. };
  5906. /**
  5907. * Check if there's a given key in the dictionary
  5908. * @param key the key to check for
  5909. * @return true if the key is present, false otherwise
  5910. */
  5911. StringDictionary.prototype.contains = function (key) {
  5912. return this._data[key] !== undefined;
  5913. };
  5914. /**
  5915. * Add a new key and its corresponding value
  5916. * @param key the key to add
  5917. * @param value the value corresponding to the key
  5918. * @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
  5919. */
  5920. StringDictionary.prototype.add = function (key, value) {
  5921. if (this._data[key] !== undefined) {
  5922. return false;
  5923. }
  5924. this._data[key] = value;
  5925. ++this._count;
  5926. return true;
  5927. };
  5928. StringDictionary.prototype.set = function (key, value) {
  5929. if (this._data[key] === undefined) {
  5930. return false;
  5931. }
  5932. this._data[key] = value;
  5933. return true;
  5934. };
  5935. /**
  5936. * Get the element of the given key and remove it from the dictionary
  5937. * @param key
  5938. */
  5939. StringDictionary.prototype.getAndRemove = function (key) {
  5940. var val = this.get(key);
  5941. if (val !== undefined) {
  5942. delete this._data[key];
  5943. --this._count;
  5944. return val;
  5945. }
  5946. return null;
  5947. };
  5948. /**
  5949. * Remove a key/value from the dictionary.
  5950. * @param key the key to remove
  5951. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  5952. */
  5953. StringDictionary.prototype.remove = function (key) {
  5954. if (this.contains(key)) {
  5955. delete this._data[key];
  5956. --this._count;
  5957. return true;
  5958. }
  5959. return false;
  5960. };
  5961. /**
  5962. * Clear the whole content of the dictionary
  5963. */
  5964. StringDictionary.prototype.clear = function () {
  5965. this._data = {};
  5966. this._count = 0;
  5967. };
  5968. Object.defineProperty(StringDictionary.prototype, "count", {
  5969. get: function () {
  5970. return this._count;
  5971. },
  5972. enumerable: true,
  5973. configurable: true
  5974. });
  5975. /**
  5976. * Execute a callback on each key/val of the dictionary.
  5977. * Note that you can remove any element in this dictionary in the callback implementation
  5978. * @param callback the callback to execute on a given key/value pair
  5979. */
  5980. StringDictionary.prototype.forEach = function (callback) {
  5981. for (var cur in this._data) {
  5982. var val = this._data[cur];
  5983. callback(cur, val);
  5984. }
  5985. };
  5986. /**
  5987. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  5988. * If the callback returns null or undefined the method will iterate to the next key/value pair
  5989. * Note that you can remove any element in this dictionary in the callback implementation
  5990. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  5991. */
  5992. StringDictionary.prototype.first = function (callback) {
  5993. for (var cur in this._data) {
  5994. var val = this._data[cur];
  5995. var res = callback(cur, val);
  5996. if (res) {
  5997. return res;
  5998. }
  5999. }
  6000. return null;
  6001. };
  6002. return StringDictionary;
  6003. }());
  6004. BABYLON.StringDictionary = StringDictionary;
  6005. })(BABYLON || (BABYLON = {}));
  6006. //# sourceMappingURL=babylon.stringDictionary.js.map
  6007. var BABYLON;
  6008. (function (BABYLON) {
  6009. // Screenshots
  6010. var screenshotCanvas;
  6011. var cloneValue = function (source, destinationObject) {
  6012. if (!source)
  6013. return null;
  6014. if (source instanceof BABYLON.Mesh) {
  6015. return null;
  6016. }
  6017. if (source instanceof BABYLON.SubMesh) {
  6018. return source.clone(destinationObject);
  6019. }
  6020. else if (source.clone) {
  6021. return source.clone();
  6022. }
  6023. return null;
  6024. };
  6025. var Tools = (function () {
  6026. function Tools() {
  6027. }
  6028. ;
  6029. Tools.Instantiate = function (className) {
  6030. var arr = className.split(".");
  6031. var fn = (window || this);
  6032. for (var i = 0, len = arr.length; i < len; i++) {
  6033. fn = fn[arr[i]];
  6034. }
  6035. if (typeof fn !== "function") {
  6036. return null;
  6037. }
  6038. return fn;
  6039. };
  6040. Tools.SetImmediate = function (action) {
  6041. if (window.setImmediate) {
  6042. window.setImmediate(action);
  6043. }
  6044. else {
  6045. setTimeout(action, 1);
  6046. }
  6047. };
  6048. Tools.IsExponentOfTwo = function (value) {
  6049. var count = 1;
  6050. do {
  6051. count *= 2;
  6052. } while (count < value);
  6053. return count === value;
  6054. };
  6055. Tools.GetExponentOfTwo = function (value, max) {
  6056. var count = 1;
  6057. do {
  6058. count *= 2;
  6059. } while (count < value);
  6060. if (count > max)
  6061. count = max;
  6062. return count;
  6063. };
  6064. Tools.GetFilename = function (path) {
  6065. var index = path.lastIndexOf("/");
  6066. if (index < 0)
  6067. return path;
  6068. return path.substring(index + 1);
  6069. };
  6070. Tools.GetDOMTextContent = function (element) {
  6071. var result = "";
  6072. var child = element.firstChild;
  6073. while (child) {
  6074. if (child.nodeType === 3) {
  6075. result += child.textContent;
  6076. }
  6077. child = child.nextSibling;
  6078. }
  6079. return result;
  6080. };
  6081. Tools.ToDegrees = function (angle) {
  6082. return angle * 180 / Math.PI;
  6083. };
  6084. Tools.ToRadians = function (angle) {
  6085. return angle * Math.PI / 180;
  6086. };
  6087. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  6088. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  6089. var output = "";
  6090. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  6091. var i = 0;
  6092. var bytes = new Uint8Array(buffer);
  6093. while (i < bytes.length) {
  6094. chr1 = bytes[i++];
  6095. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  6096. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  6097. enc1 = chr1 >> 2;
  6098. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  6099. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  6100. enc4 = chr3 & 63;
  6101. if (isNaN(chr2)) {
  6102. enc3 = enc4 = 64;
  6103. }
  6104. else if (isNaN(chr3)) {
  6105. enc4 = 64;
  6106. }
  6107. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  6108. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  6109. }
  6110. return "data:image/png;base64," + output;
  6111. };
  6112. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {
  6113. if (bias === void 0) { bias = null; }
  6114. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  6115. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  6116. for (var index = indexStart; index < indexStart + indexCount; index++) {
  6117. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  6118. minimum = BABYLON.Vector3.Minimize(current, minimum);
  6119. maximum = BABYLON.Vector3.Maximize(current, maximum);
  6120. }
  6121. if (bias) {
  6122. minimum.x -= minimum.x * bias.x + bias.y;
  6123. minimum.y -= minimum.y * bias.x + bias.y;
  6124. minimum.z -= minimum.z * bias.x + bias.y;
  6125. maximum.x += maximum.x * bias.x + bias.y;
  6126. maximum.y += maximum.y * bias.x + bias.y;
  6127. maximum.z += maximum.z * bias.x + bias.y;
  6128. }
  6129. return {
  6130. minimum: minimum,
  6131. maximum: maximum
  6132. };
  6133. };
  6134. Tools.ExtractMinAndMax = function (positions, start, count, bias, stride) {
  6135. if (bias === void 0) { bias = null; }
  6136. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  6137. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  6138. if (!stride) {
  6139. stride = 3;
  6140. }
  6141. for (var index = start; index < start + count; index++) {
  6142. var current = new BABYLON.Vector3(positions[index * stride], positions[index * stride + 1], positions[index * stride + 2]);
  6143. minimum = BABYLON.Vector3.Minimize(current, minimum);
  6144. maximum = BABYLON.Vector3.Maximize(current, maximum);
  6145. }
  6146. if (bias) {
  6147. minimum.x -= minimum.x * bias.x + bias.y;
  6148. minimum.y -= minimum.y * bias.x + bias.y;
  6149. minimum.z -= minimum.z * bias.x + bias.y;
  6150. maximum.x += maximum.x * bias.x + bias.y;
  6151. maximum.y += maximum.y * bias.x + bias.y;
  6152. maximum.z += maximum.z * bias.x + bias.y;
  6153. }
  6154. return {
  6155. minimum: minimum,
  6156. maximum: maximum
  6157. };
  6158. };
  6159. Tools.Vector2ArrayFeeder = function (array) {
  6160. return function (index) {
  6161. var isFloatArray = (array.BYTES_PER_ELEMENT !== undefined);
  6162. var length = isFloatArray ? array.length / 2 : array.length;
  6163. if (index >= length) {
  6164. return null;
  6165. }
  6166. if (isFloatArray) {
  6167. var fa = array;
  6168. return new BABYLON.Vector2(fa[index * 2 + 0], fa[index * 2 + 1]);
  6169. }
  6170. var a = array;
  6171. return a[index];
  6172. };
  6173. };
  6174. Tools.ExtractMinAndMaxVector2 = function (feeder, bias) {
  6175. if (bias === void 0) { bias = null; }
  6176. var minimum = new BABYLON.Vector2(Number.MAX_VALUE, Number.MAX_VALUE);
  6177. var maximum = new BABYLON.Vector2(-Number.MAX_VALUE, -Number.MAX_VALUE);
  6178. var i = 0;
  6179. var cur = feeder(i++);
  6180. while (cur) {
  6181. minimum = BABYLON.Vector2.Minimize(cur, minimum);
  6182. maximum = BABYLON.Vector2.Maximize(cur, maximum);
  6183. cur = feeder(i++);
  6184. }
  6185. if (bias) {
  6186. minimum.x -= minimum.x * bias.x + bias.y;
  6187. minimum.y -= minimum.y * bias.x + bias.y;
  6188. maximum.x += maximum.x * bias.x + bias.y;
  6189. maximum.y += maximum.y * bias.x + bias.y;
  6190. }
  6191. return {
  6192. minimum: minimum,
  6193. maximum: maximum
  6194. };
  6195. };
  6196. Tools.MakeArray = function (obj, allowsNullUndefined) {
  6197. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  6198. return undefined;
  6199. return Array.isArray(obj) ? obj : [obj];
  6200. };
  6201. // Misc.
  6202. Tools.GetPointerPrefix = function () {
  6203. var eventPrefix = "pointer";
  6204. // Check if pointer events are supported
  6205. if (!window.PointerEvent && !navigator.pointerEnabled) {
  6206. eventPrefix = "mouse";
  6207. }
  6208. return eventPrefix;
  6209. };
  6210. /**
  6211. * @param func - the function to be called
  6212. * @param requester - the object that will request the next frame. Falls back to window.
  6213. */
  6214. Tools.QueueNewFrame = function (func, requester) {
  6215. if (requester === void 0) { requester = window; }
  6216. //if WebVR is enabled AND presenting, requestAnimationFrame is triggered when enabled.
  6217. /*if(requester.isPresenting) {
  6218. return;
  6219. } else*/ if (requester.requestAnimationFrame)
  6220. requester.requestAnimationFrame(func);
  6221. else if (requester.msRequestAnimationFrame)
  6222. requester.msRequestAnimationFrame(func);
  6223. else if (requester.webkitRequestAnimationFrame)
  6224. requester.webkitRequestAnimationFrame(func);
  6225. else if (requester.mozRequestAnimationFrame)
  6226. requester.mozRequestAnimationFrame(func);
  6227. else if (requester.oRequestAnimationFrame)
  6228. requester.oRequestAnimationFrame(func);
  6229. else {
  6230. window.setTimeout(func, 16);
  6231. }
  6232. };
  6233. Tools.RequestFullscreen = function (element) {
  6234. var requestFunction = element.requestFullscreen || element.msRequestFullscreen || element.webkitRequestFullscreen || element.mozRequestFullScreen;
  6235. if (!requestFunction)
  6236. return;
  6237. requestFunction.call(element);
  6238. };
  6239. Tools.ExitFullscreen = function () {
  6240. if (document.exitFullscreen) {
  6241. document.exitFullscreen();
  6242. }
  6243. else if (document.mozCancelFullScreen) {
  6244. document.mozCancelFullScreen();
  6245. }
  6246. else if (document.webkitCancelFullScreen) {
  6247. document.webkitCancelFullScreen();
  6248. }
  6249. else if (document.msCancelFullScreen) {
  6250. document.msCancelFullScreen();
  6251. }
  6252. };
  6253. Tools.SetCorsBehavior = function (url, img) {
  6254. if (Tools.CorsBehavior) {
  6255. switch (typeof (Tools.CorsBehavior)) {
  6256. case "function":
  6257. var result = Tools.CorsBehavior(url);
  6258. if (result) {
  6259. img.crossOrigin = result;
  6260. }
  6261. break;
  6262. case "string":
  6263. default:
  6264. img.crossOrigin = Tools.CorsBehavior;
  6265. break;
  6266. }
  6267. }
  6268. };
  6269. // External files
  6270. Tools.CleanUrl = function (url) {
  6271. url = url.replace(/#/mg, "%23");
  6272. return url;
  6273. };
  6274. Tools.LoadImage = function (url, onload, onerror, database) {
  6275. if (url instanceof ArrayBuffer) {
  6276. url = Tools.EncodeArrayBufferTobase64(url);
  6277. }
  6278. url = Tools.CleanUrl(url);
  6279. var img = new Image();
  6280. if (url.substr(0, 5) !== "data:") {
  6281. Tools.SetCorsBehavior(url, img);
  6282. }
  6283. img.onload = function () {
  6284. onload(img);
  6285. };
  6286. img.onerror = function (err) {
  6287. Tools.Error("Error while trying to load image: " + url);
  6288. if (Tools.UseFallbackTexture) {
  6289. img.src = Tools.fallbackTexture;
  6290. onload(img);
  6291. }
  6292. else {
  6293. onerror();
  6294. }
  6295. };
  6296. var noIndexedDB = function () {
  6297. img.src = url;
  6298. };
  6299. var loadFromIndexedDB = function () {
  6300. database.loadImageFromDB(url, img);
  6301. };
  6302. //ANY database to do!
  6303. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  6304. database.openAsync(loadFromIndexedDB, noIndexedDB);
  6305. }
  6306. else {
  6307. if (url.indexOf("file:") === -1) {
  6308. noIndexedDB();
  6309. }
  6310. else {
  6311. var textureName = url.substring(5).toLowerCase();
  6312. if (BABYLON.FilesInput.FilesTextures[textureName]) {
  6313. try {
  6314. var blobURL;
  6315. try {
  6316. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName], { oneTimeOnly: true });
  6317. }
  6318. catch (ex) {
  6319. // Chrome doesn't support oneTimeOnly parameter
  6320. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName]);
  6321. }
  6322. img.src = blobURL;
  6323. }
  6324. catch (e) {
  6325. img.src = null;
  6326. }
  6327. }
  6328. else {
  6329. Tools.Error("Image: " + textureName + " not found. Did you forget to provide it?");
  6330. img.src = Tools.fallbackTexture;
  6331. }
  6332. }
  6333. }
  6334. return img;
  6335. };
  6336. //ANY
  6337. Tools.LoadFile = function (url, callback, progressCallBack, database, useArrayBuffer, onError) {
  6338. url = Tools.CleanUrl(url);
  6339. var noIndexedDB = function () {
  6340. var request = new XMLHttpRequest();
  6341. var loadUrl = Tools.BaseUrl + url;
  6342. request.open('GET', loadUrl, true);
  6343. if (useArrayBuffer) {
  6344. request.responseType = "arraybuffer";
  6345. }
  6346. request.onprogress = progressCallBack;
  6347. request.onreadystatechange = function () {
  6348. if (request.readyState === 4) {
  6349. request.onreadystatechange = null; //some browsers have issues where onreadystatechange can be called multiple times with the same value
  6350. if (request.status >= 200 && request.status < 300 || (navigator.isCocoonJS && (request.status === 0))) {
  6351. callback(!useArrayBuffer ? request.responseText : request.response);
  6352. }
  6353. else {
  6354. if (onError) {
  6355. onError();
  6356. }
  6357. else {
  6358. throw new Error("Error status: " + request.status + " - Unable to load " + loadUrl);
  6359. }
  6360. }
  6361. }
  6362. };
  6363. request.send(null);
  6364. };
  6365. var loadFromIndexedDB = function () {
  6366. database.loadFileFromDB(url, callback, progressCallBack, noIndexedDB, useArrayBuffer);
  6367. };
  6368. if (url.indexOf("file:") !== -1) {
  6369. var fileName = url.substring(5).toLowerCase();
  6370. if (BABYLON.FilesInput.FilesToLoad[fileName]) {
  6371. Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], callback, progressCallBack, useArrayBuffer);
  6372. }
  6373. else {
  6374. Tools.Error("File: " + fileName + " not found. Did you forget to provide it?");
  6375. }
  6376. }
  6377. else {
  6378. // Caching all files
  6379. if (database && database.enableSceneOffline) {
  6380. database.openAsync(loadFromIndexedDB, noIndexedDB);
  6381. }
  6382. else {
  6383. noIndexedDB();
  6384. }
  6385. }
  6386. };
  6387. /**
  6388. * Load a script (identified by an url). When the url returns, the
  6389. * content of this file is added into a new script element, attached to the DOM (body element)
  6390. */
  6391. Tools.LoadScript = function (scriptUrl, onSuccess, onError) {
  6392. var head = document.getElementsByTagName('head')[0];
  6393. var script = document.createElement('script');
  6394. script.type = 'text/javascript';
  6395. script.src = scriptUrl;
  6396. var self = this;
  6397. script.onload = function () {
  6398. if (onSuccess) {
  6399. onSuccess();
  6400. }
  6401. };
  6402. script.onerror = function () {
  6403. if (onError) {
  6404. onError();
  6405. }
  6406. };
  6407. head.appendChild(script);
  6408. };
  6409. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  6410. var reader = new FileReader();
  6411. reader.onload = function (e) {
  6412. //target doesn't have result from ts 1.3
  6413. callback(e.target['result']);
  6414. };
  6415. reader.onprogress = progressCallback;
  6416. reader.readAsDataURL(fileToLoad);
  6417. };
  6418. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  6419. var reader = new FileReader();
  6420. reader.onerror = function (e) {
  6421. Tools.Log("Error while reading file: " + fileToLoad.name);
  6422. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  6423. };
  6424. reader.onload = function (e) {
  6425. //target doesn't have result from ts 1.3
  6426. callback(e.target['result']);
  6427. };
  6428. reader.onprogress = progressCallBack;
  6429. if (!useArrayBuffer) {
  6430. // Asynchronous read
  6431. reader.readAsText(fileToLoad);
  6432. }
  6433. else {
  6434. reader.readAsArrayBuffer(fileToLoad);
  6435. }
  6436. };
  6437. //returns a downloadable url to a file content.
  6438. Tools.FileAsURL = function (content) {
  6439. var fileBlob = new Blob([content]);
  6440. var url = window.URL || window.webkitURL;
  6441. var link = url.createObjectURL(fileBlob);
  6442. return link;
  6443. };
  6444. // Misc.
  6445. Tools.Format = function (value, decimals) {
  6446. if (decimals === void 0) { decimals = 2; }
  6447. return value.toFixed(decimals);
  6448. };
  6449. Tools.CheckExtends = function (v, min, max) {
  6450. if (v.x < min.x)
  6451. min.x = v.x;
  6452. if (v.y < min.y)
  6453. min.y = v.y;
  6454. if (v.z < min.z)
  6455. min.z = v.z;
  6456. if (v.x > max.x)
  6457. max.x = v.x;
  6458. if (v.y > max.y)
  6459. max.y = v.y;
  6460. if (v.z > max.z)
  6461. max.z = v.z;
  6462. };
  6463. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  6464. for (var prop in source) {
  6465. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  6466. continue;
  6467. }
  6468. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  6469. continue;
  6470. }
  6471. var sourceValue = source[prop];
  6472. var typeOfSourceValue = typeof sourceValue;
  6473. if (typeOfSourceValue === "function") {
  6474. continue;
  6475. }
  6476. if (typeOfSourceValue === "object") {
  6477. if (sourceValue instanceof Array) {
  6478. destination[prop] = [];
  6479. if (sourceValue.length > 0) {
  6480. if (typeof sourceValue[0] == "object") {
  6481. for (var index = 0; index < sourceValue.length; index++) {
  6482. var clonedValue = cloneValue(sourceValue[index], destination);
  6483. if (destination[prop].indexOf(clonedValue) === -1) {
  6484. destination[prop].push(clonedValue);
  6485. }
  6486. }
  6487. }
  6488. else {
  6489. destination[prop] = sourceValue.slice(0);
  6490. }
  6491. }
  6492. }
  6493. else {
  6494. destination[prop] = cloneValue(sourceValue, destination);
  6495. }
  6496. }
  6497. else {
  6498. destination[prop] = sourceValue;
  6499. }
  6500. }
  6501. };
  6502. Tools.IsEmpty = function (obj) {
  6503. for (var i in obj) {
  6504. return false;
  6505. }
  6506. return true;
  6507. };
  6508. Tools.RegisterTopRootEvents = function (events) {
  6509. for (var index = 0; index < events.length; index++) {
  6510. var event = events[index];
  6511. window.addEventListener(event.name, event.handler, false);
  6512. try {
  6513. if (window.parent) {
  6514. window.parent.addEventListener(event.name, event.handler, false);
  6515. }
  6516. }
  6517. catch (e) {
  6518. }
  6519. }
  6520. };
  6521. Tools.UnregisterTopRootEvents = function (events) {
  6522. for (var index = 0; index < events.length; index++) {
  6523. var event = events[index];
  6524. window.removeEventListener(event.name, event.handler);
  6525. try {
  6526. if (window.parent) {
  6527. window.parent.removeEventListener(event.name, event.handler);
  6528. }
  6529. }
  6530. catch (e) {
  6531. }
  6532. }
  6533. };
  6534. Tools.DumpFramebuffer = function (width, height, engine, successCallback, mimeType) {
  6535. if (mimeType === void 0) { mimeType = "image/png"; }
  6536. // Read the contents of the framebuffer
  6537. var numberOfChannelsByLine = width * 4;
  6538. var halfHeight = height / 2;
  6539. //Reading datas from WebGL
  6540. var data = engine.readPixels(0, 0, width, height);
  6541. //To flip image on Y axis.
  6542. for (var i = 0; i < halfHeight; i++) {
  6543. for (var j = 0; j < numberOfChannelsByLine; j++) {
  6544. var currentCell = j + i * numberOfChannelsByLine;
  6545. var targetLine = height - i - 1;
  6546. var targetCell = j + targetLine * numberOfChannelsByLine;
  6547. var temp = data[currentCell];
  6548. data[currentCell] = data[targetCell];
  6549. data[targetCell] = temp;
  6550. }
  6551. }
  6552. // Create a 2D canvas to store the result
  6553. if (!screenshotCanvas) {
  6554. screenshotCanvas = document.createElement('canvas');
  6555. }
  6556. screenshotCanvas.width = width;
  6557. screenshotCanvas.height = height;
  6558. var context = screenshotCanvas.getContext('2d');
  6559. // Copy the pixels to a 2D canvas
  6560. var imageData = context.createImageData(width, height);
  6561. var castData = (imageData.data);
  6562. castData.set(data);
  6563. context.putImageData(imageData, 0, 0);
  6564. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  6565. };
  6566. Tools.EncodeScreenshotCanvasData = function (successCallback, mimeType) {
  6567. if (mimeType === void 0) { mimeType = "image/png"; }
  6568. var base64Image = screenshotCanvas.toDataURL(mimeType);
  6569. if (successCallback) {
  6570. successCallback(base64Image);
  6571. }
  6572. else {
  6573. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  6574. if (("download" in document.createElement("a"))) {
  6575. var a = window.document.createElement("a");
  6576. a.href = base64Image;
  6577. var date = new Date();
  6578. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(-2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  6579. a.setAttribute("download", "screenshot_" + stringDate + ".png");
  6580. window.document.body.appendChild(a);
  6581. a.addEventListener("click", function () {
  6582. a.parentElement.removeChild(a);
  6583. });
  6584. a.click();
  6585. }
  6586. else {
  6587. var newWindow = window.open("");
  6588. var img = newWindow.document.createElement("img");
  6589. img.src = base64Image;
  6590. newWindow.document.body.appendChild(img);
  6591. }
  6592. }
  6593. };
  6594. Tools.CreateScreenshot = function (engine, camera, size, successCallback, mimeType) {
  6595. if (mimeType === void 0) { mimeType = "image/png"; }
  6596. var width;
  6597. var height;
  6598. // If a precision value is specified
  6599. if (size.precision) {
  6600. width = Math.round(engine.getRenderWidth() * size.precision);
  6601. height = Math.round(width / engine.getAspectRatio(camera));
  6602. }
  6603. else if (size.width && size.height) {
  6604. width = size.width;
  6605. height = size.height;
  6606. }
  6607. else if (size.width && !size.height) {
  6608. width = size.width;
  6609. height = Math.round(width / engine.getAspectRatio(camera));
  6610. }
  6611. else if (size.height && !size.width) {
  6612. height = size.height;
  6613. width = Math.round(height * engine.getAspectRatio(camera));
  6614. }
  6615. else if (!isNaN(size)) {
  6616. height = size;
  6617. width = size;
  6618. }
  6619. else {
  6620. Tools.Error("Invalid 'size' parameter !");
  6621. return;
  6622. }
  6623. if (!screenshotCanvas) {
  6624. screenshotCanvas = document.createElement('canvas');
  6625. }
  6626. screenshotCanvas.width = width;
  6627. screenshotCanvas.height = height;
  6628. var renderContext = screenshotCanvas.getContext("2d");
  6629. var ratio = engine.getRenderWidth() / engine.getRenderHeight();
  6630. var newWidth = width;
  6631. var newHeight = newWidth / ratio;
  6632. if (newHeight > height) {
  6633. newHeight = height;
  6634. newWidth = newHeight * ratio;
  6635. }
  6636. var offsetX = Math.max(0, width - newWidth) / 2;
  6637. var offsetY = Math.max(0, height - newHeight) / 2;
  6638. renderContext.drawImage(engine.getRenderingCanvas(), offsetX, offsetY, newWidth, newHeight);
  6639. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  6640. };
  6641. Tools.CreateScreenshotUsingRenderTarget = function (engine, camera, size, successCallback, mimeType, samples) {
  6642. if (mimeType === void 0) { mimeType = "image/png"; }
  6643. if (samples === void 0) { samples = 1; }
  6644. var width;
  6645. var height;
  6646. //If a precision value is specified
  6647. if (size.precision) {
  6648. width = Math.round(engine.getRenderWidth() * size.precision);
  6649. height = Math.round(width / engine.getAspectRatio(camera));
  6650. size = { width: width, height: height };
  6651. }
  6652. else if (size.width && size.height) {
  6653. width = size.width;
  6654. height = size.height;
  6655. }
  6656. else if (size.width && !size.height) {
  6657. width = size.width;
  6658. height = Math.round(width / engine.getAspectRatio(camera));
  6659. size = { width: width, height: height };
  6660. }
  6661. else if (size.height && !size.width) {
  6662. height = size.height;
  6663. width = Math.round(height * engine.getAspectRatio(camera));
  6664. size = { width: width, height: height };
  6665. }
  6666. else if (!isNaN(size)) {
  6667. height = size;
  6668. width = size;
  6669. }
  6670. else {
  6671. Tools.Error("Invalid 'size' parameter !");
  6672. return;
  6673. }
  6674. var scene = camera.getScene();
  6675. var previousCamera = null;
  6676. if (scene.activeCamera !== camera) {
  6677. previousCamera = scene.activeCamera;
  6678. scene.activeCamera = camera;
  6679. }
  6680. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  6681. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  6682. texture.renderList = scene.meshes;
  6683. texture.samples = samples;
  6684. texture.onAfterRenderObservable.add(function () {
  6685. Tools.DumpFramebuffer(width, height, engine, successCallback, mimeType);
  6686. });
  6687. scene.incrementRenderId();
  6688. scene.resetCachedMaterial();
  6689. texture.render(true);
  6690. texture.dispose();
  6691. if (previousCamera) {
  6692. scene.activeCamera = previousCamera;
  6693. }
  6694. camera.getProjectionMatrix(true); // Force cache refresh;
  6695. };
  6696. // XHR response validator for local file scenario
  6697. Tools.ValidateXHRData = function (xhr, dataType) {
  6698. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  6699. if (dataType === void 0) { dataType = 7; }
  6700. try {
  6701. if (dataType & 1) {
  6702. if (xhr.responseText && xhr.responseText.length > 0) {
  6703. return true;
  6704. }
  6705. else if (dataType === 1) {
  6706. return false;
  6707. }
  6708. }
  6709. if (dataType & 2) {
  6710. // Check header width and height since there is no "TGA" magic number
  6711. var tgaHeader = BABYLON.Internals.TGATools.GetTGAHeader(xhr.response);
  6712. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  6713. return true;
  6714. }
  6715. else if (dataType === 2) {
  6716. return false;
  6717. }
  6718. }
  6719. if (dataType & 4) {
  6720. // Check for the "DDS" magic number
  6721. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  6722. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  6723. return true;
  6724. }
  6725. else {
  6726. return false;
  6727. }
  6728. }
  6729. }
  6730. catch (e) {
  6731. }
  6732. return false;
  6733. };
  6734. /**
  6735. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  6736. * Be aware Math.random() could cause collisions, but:
  6737. * "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"
  6738. */
  6739. Tools.RandomId = function () {
  6740. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  6741. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  6742. return v.toString(16);
  6743. });
  6744. };
  6745. Object.defineProperty(Tools, "NoneLogLevel", {
  6746. get: function () {
  6747. return Tools._NoneLogLevel;
  6748. },
  6749. enumerable: true,
  6750. configurable: true
  6751. });
  6752. Object.defineProperty(Tools, "MessageLogLevel", {
  6753. get: function () {
  6754. return Tools._MessageLogLevel;
  6755. },
  6756. enumerable: true,
  6757. configurable: true
  6758. });
  6759. Object.defineProperty(Tools, "WarningLogLevel", {
  6760. get: function () {
  6761. return Tools._WarningLogLevel;
  6762. },
  6763. enumerable: true,
  6764. configurable: true
  6765. });
  6766. Object.defineProperty(Tools, "ErrorLogLevel", {
  6767. get: function () {
  6768. return Tools._ErrorLogLevel;
  6769. },
  6770. enumerable: true,
  6771. configurable: true
  6772. });
  6773. Object.defineProperty(Tools, "AllLogLevel", {
  6774. get: function () {
  6775. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  6776. },
  6777. enumerable: true,
  6778. configurable: true
  6779. });
  6780. Tools._AddLogEntry = function (entry) {
  6781. Tools._LogCache = entry + Tools._LogCache;
  6782. if (Tools.OnNewCacheEntry) {
  6783. Tools.OnNewCacheEntry(entry);
  6784. }
  6785. };
  6786. Tools._FormatMessage = function (message) {
  6787. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  6788. var date = new Date();
  6789. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  6790. };
  6791. Tools._LogDisabled = function (message) {
  6792. // nothing to do
  6793. };
  6794. Tools._LogEnabled = function (message) {
  6795. var formattedMessage = Tools._FormatMessage(message);
  6796. console.log("BJS - " + formattedMessage);
  6797. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  6798. Tools._AddLogEntry(entry);
  6799. };
  6800. Tools._WarnDisabled = function (message) {
  6801. // nothing to do
  6802. };
  6803. Tools._WarnEnabled = function (message) {
  6804. var formattedMessage = Tools._FormatMessage(message);
  6805. console.warn("BJS - " + formattedMessage);
  6806. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  6807. Tools._AddLogEntry(entry);
  6808. };
  6809. Tools._ErrorDisabled = function (message) {
  6810. // nothing to do
  6811. };
  6812. Tools._ErrorEnabled = function (message) {
  6813. Tools.errorsCount++;
  6814. var formattedMessage = Tools._FormatMessage(message);
  6815. console.error("BJS - " + formattedMessage);
  6816. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  6817. Tools._AddLogEntry(entry);
  6818. };
  6819. Object.defineProperty(Tools, "LogCache", {
  6820. get: function () {
  6821. return Tools._LogCache;
  6822. },
  6823. enumerable: true,
  6824. configurable: true
  6825. });
  6826. Tools.ClearLogCache = function () {
  6827. Tools._LogCache = "";
  6828. Tools.errorsCount = 0;
  6829. };
  6830. Object.defineProperty(Tools, "LogLevels", {
  6831. set: function (level) {
  6832. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  6833. Tools.Log = Tools._LogEnabled;
  6834. }
  6835. else {
  6836. Tools.Log = Tools._LogDisabled;
  6837. }
  6838. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  6839. Tools.Warn = Tools._WarnEnabled;
  6840. }
  6841. else {
  6842. Tools.Warn = Tools._WarnDisabled;
  6843. }
  6844. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  6845. Tools.Error = Tools._ErrorEnabled;
  6846. }
  6847. else {
  6848. Tools.Error = Tools._ErrorDisabled;
  6849. }
  6850. },
  6851. enumerable: true,
  6852. configurable: true
  6853. });
  6854. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  6855. get: function () {
  6856. return Tools._PerformanceNoneLogLevel;
  6857. },
  6858. enumerable: true,
  6859. configurable: true
  6860. });
  6861. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  6862. get: function () {
  6863. return Tools._PerformanceUserMarkLogLevel;
  6864. },
  6865. enumerable: true,
  6866. configurable: true
  6867. });
  6868. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  6869. get: function () {
  6870. return Tools._PerformanceConsoleLogLevel;
  6871. },
  6872. enumerable: true,
  6873. configurable: true
  6874. });
  6875. Object.defineProperty(Tools, "PerformanceLogLevel", {
  6876. set: function (level) {
  6877. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  6878. Tools.StartPerformanceCounter = Tools._StartUserMark;
  6879. Tools.EndPerformanceCounter = Tools._EndUserMark;
  6880. return;
  6881. }
  6882. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  6883. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  6884. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  6885. return;
  6886. }
  6887. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  6888. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  6889. },
  6890. enumerable: true,
  6891. configurable: true
  6892. });
  6893. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  6894. };
  6895. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  6896. };
  6897. Tools._StartUserMark = function (counterName, condition) {
  6898. if (condition === void 0) { condition = true; }
  6899. if (!condition || !Tools._performance.mark) {
  6900. return;
  6901. }
  6902. Tools._performance.mark(counterName + "-Begin");
  6903. };
  6904. Tools._EndUserMark = function (counterName, condition) {
  6905. if (condition === void 0) { condition = true; }
  6906. if (!condition || !Tools._performance.mark) {
  6907. return;
  6908. }
  6909. Tools._performance.mark(counterName + "-End");
  6910. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  6911. };
  6912. Tools._StartPerformanceConsole = function (counterName, condition) {
  6913. if (condition === void 0) { condition = true; }
  6914. if (!condition) {
  6915. return;
  6916. }
  6917. Tools._StartUserMark(counterName, condition);
  6918. if (console.time) {
  6919. console.time(counterName);
  6920. }
  6921. };
  6922. Tools._EndPerformanceConsole = function (counterName, condition) {
  6923. if (condition === void 0) { condition = true; }
  6924. if (!condition) {
  6925. return;
  6926. }
  6927. Tools._EndUserMark(counterName, condition);
  6928. if (console.time) {
  6929. console.timeEnd(counterName);
  6930. }
  6931. };
  6932. Object.defineProperty(Tools, "Now", {
  6933. get: function () {
  6934. if (window.performance && window.performance.now) {
  6935. return window.performance.now();
  6936. }
  6937. return new Date().getTime();
  6938. },
  6939. enumerable: true,
  6940. configurable: true
  6941. });
  6942. /**
  6943. * This method will return the name of the class used to create the instance of the given object.
  6944. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  6945. * @param object the object to get the class name from
  6946. * @return the name of the class, will be "object" for a custom data type not using the @className decorator
  6947. */
  6948. Tools.getClassName = function (object, isType) {
  6949. if (isType === void 0) { isType = false; }
  6950. var name = null;
  6951. if (!isType && object.getClassName) {
  6952. name = object.getClassName();
  6953. }
  6954. else {
  6955. if (object instanceof Object) {
  6956. var classObj = isType ? object : Object.getPrototypeOf(object);
  6957. name = classObj.constructor["__bjsclassName__"];
  6958. }
  6959. if (!name) {
  6960. name = typeof object;
  6961. }
  6962. }
  6963. return name;
  6964. };
  6965. Tools.first = function (array, predicate) {
  6966. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  6967. var el = array_1[_i];
  6968. if (predicate(el)) {
  6969. return el;
  6970. }
  6971. }
  6972. };
  6973. /**
  6974. * This method will return the name of the full name of the class, including its owning module (if any).
  6975. * 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).
  6976. * @param object the object to get the class name from
  6977. * @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.
  6978. */
  6979. Tools.getFullClassName = function (object, isType) {
  6980. if (isType === void 0) { isType = false; }
  6981. var className = null;
  6982. var moduleName = null;
  6983. if (!isType && object.getClassName) {
  6984. className = object.getClassName();
  6985. }
  6986. else {
  6987. if (object instanceof Object) {
  6988. var classObj = isType ? object : Object.getPrototypeOf(object);
  6989. className = classObj.constructor["__bjsclassName__"];
  6990. moduleName = classObj.constructor["__bjsmoduleName__"];
  6991. }
  6992. if (!className) {
  6993. className = typeof object;
  6994. }
  6995. }
  6996. if (!className) {
  6997. return null;
  6998. }
  6999. return ((moduleName != null) ? (moduleName + ".") : "") + className;
  7000. };
  7001. /**
  7002. * 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.
  7003. * @param array
  7004. */
  7005. Tools.arrayOrStringFeeder = function (array) {
  7006. return function (index) {
  7007. if (index >= array.length) {
  7008. return null;
  7009. }
  7010. var val = array.charCodeAt ? array.charCodeAt(index) : array[index];
  7011. if (val && val.getHashCode) {
  7012. val = val.getHashCode();
  7013. }
  7014. if (typeof val === "string") {
  7015. return Tools.hashCodeFromStream(Tools.arrayOrStringFeeder(val));
  7016. }
  7017. return val;
  7018. };
  7019. };
  7020. /**
  7021. * Compute the hashCode of a stream of number
  7022. * To compute the HashCode on a string or an Array of data types implementing the getHashCode() method, use the arrayOrStringFeeder method.
  7023. * @param feeder a callback that will be called until it returns null, each valid returned values will be used to compute the hash code.
  7024. * @return the hash code computed
  7025. */
  7026. Tools.hashCodeFromStream = function (feeder) {
  7027. // Based from here: http://stackoverflow.com/a/7616484/802124
  7028. var hash = 0;
  7029. var index = 0;
  7030. var chr = feeder(index++);
  7031. while (chr != null) {
  7032. hash = ((hash << 5) - hash) + chr;
  7033. hash |= 0; // Convert to 32bit integer
  7034. chr = feeder(index++);
  7035. }
  7036. return hash;
  7037. };
  7038. return Tools;
  7039. }());
  7040. Tools.BaseUrl = "";
  7041. Tools.CorsBehavior = "anonymous";
  7042. Tools.UseFallbackTexture = true;
  7043. // Used in case of a texture loading problem
  7044. 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";
  7045. // Logs
  7046. Tools._NoneLogLevel = 0;
  7047. Tools._MessageLogLevel = 1;
  7048. Tools._WarningLogLevel = 2;
  7049. Tools._ErrorLogLevel = 4;
  7050. Tools._LogCache = "";
  7051. Tools.errorsCount = 0;
  7052. Tools.Log = Tools._LogEnabled;
  7053. Tools.Warn = Tools._WarnEnabled;
  7054. Tools.Error = Tools._ErrorEnabled;
  7055. // Performances
  7056. Tools._PerformanceNoneLogLevel = 0;
  7057. Tools._PerformanceUserMarkLogLevel = 1;
  7058. Tools._PerformanceConsoleLogLevel = 2;
  7059. Tools._performance = window.performance;
  7060. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  7061. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  7062. BABYLON.Tools = Tools;
  7063. /**
  7064. * This class is used to track a performance counter which is number based.
  7065. * The user has access to many properties which give statistics of different nature
  7066. *
  7067. * The implementer can track two kinds of Performance Counter: time and count
  7068. * 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.
  7069. * 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.
  7070. */
  7071. var PerfCounter = (function () {
  7072. function PerfCounter() {
  7073. this._startMonitoringTime = 0;
  7074. this._min = 0;
  7075. this._max = 0;
  7076. this._average = 0;
  7077. this._lastSecAverage = 0;
  7078. this._current = 0;
  7079. this._totalValueCount = 0;
  7080. this._totalAccumulated = 0;
  7081. this._lastSecAccumulated = 0;
  7082. this._lastSecTime = 0;
  7083. this._lastSecValueCount = 0;
  7084. }
  7085. Object.defineProperty(PerfCounter.prototype, "min", {
  7086. /**
  7087. * Returns the smallest value ever
  7088. */
  7089. get: function () {
  7090. return this._min;
  7091. },
  7092. enumerable: true,
  7093. configurable: true
  7094. });
  7095. Object.defineProperty(PerfCounter.prototype, "max", {
  7096. /**
  7097. * Returns the biggest value ever
  7098. */
  7099. get: function () {
  7100. return this._max;
  7101. },
  7102. enumerable: true,
  7103. configurable: true
  7104. });
  7105. Object.defineProperty(PerfCounter.prototype, "average", {
  7106. /**
  7107. * Returns the average value since the performance counter is running
  7108. */
  7109. get: function () {
  7110. return this._average;
  7111. },
  7112. enumerable: true,
  7113. configurable: true
  7114. });
  7115. Object.defineProperty(PerfCounter.prototype, "lastSecAverage", {
  7116. /**
  7117. * Returns the average value of the last second the counter was monitored
  7118. */
  7119. get: function () {
  7120. return this._lastSecAverage;
  7121. },
  7122. enumerable: true,
  7123. configurable: true
  7124. });
  7125. Object.defineProperty(PerfCounter.prototype, "current", {
  7126. /**
  7127. * Returns the current value
  7128. */
  7129. get: function () {
  7130. return this._current;
  7131. },
  7132. enumerable: true,
  7133. configurable: true
  7134. });
  7135. Object.defineProperty(PerfCounter.prototype, "total", {
  7136. get: function () {
  7137. return this._totalAccumulated;
  7138. },
  7139. enumerable: true,
  7140. configurable: true
  7141. });
  7142. /**
  7143. * Call this method to start monitoring a new frame.
  7144. * 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.
  7145. */
  7146. PerfCounter.prototype.fetchNewFrame = function () {
  7147. this._totalValueCount++;
  7148. this._current = 0;
  7149. this._lastSecValueCount++;
  7150. };
  7151. /**
  7152. * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)
  7153. * @param newCount the count value to add to the monitored count
  7154. * @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.
  7155. */
  7156. PerfCounter.prototype.addCount = function (newCount, fetchResult) {
  7157. if (!PerfCounter.Enabled) {
  7158. return;
  7159. }
  7160. this._current += newCount;
  7161. if (fetchResult) {
  7162. this._fetchResult();
  7163. }
  7164. };
  7165. /**
  7166. * Start monitoring this performance counter
  7167. */
  7168. PerfCounter.prototype.beginMonitoring = function () {
  7169. if (!PerfCounter.Enabled) {
  7170. return;
  7171. }
  7172. this._startMonitoringTime = Tools.Now;
  7173. };
  7174. /**
  7175. * Compute the time lapsed since the previous beginMonitoring() call.
  7176. * @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
  7177. */
  7178. PerfCounter.prototype.endMonitoring = function (newFrame) {
  7179. if (newFrame === void 0) { newFrame = true; }
  7180. if (!PerfCounter.Enabled) {
  7181. return;
  7182. }
  7183. if (newFrame) {
  7184. this.fetchNewFrame();
  7185. }
  7186. var currentTime = Tools.Now;
  7187. this._current = currentTime - this._startMonitoringTime;
  7188. if (newFrame) {
  7189. this._fetchResult();
  7190. }
  7191. };
  7192. PerfCounter.prototype._fetchResult = function () {
  7193. this._totalAccumulated += this._current;
  7194. this._lastSecAccumulated += this._current;
  7195. // Min/Max update
  7196. this._min = Math.min(this._min, this._current);
  7197. this._max = Math.max(this._max, this._current);
  7198. this._average = this._totalAccumulated / this._totalValueCount;
  7199. // Reset last sec?
  7200. var now = Tools.Now;
  7201. if ((now - this._lastSecTime) > 1000) {
  7202. this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
  7203. this._lastSecTime = now;
  7204. this._lastSecAccumulated = 0;
  7205. this._lastSecValueCount = 0;
  7206. }
  7207. };
  7208. return PerfCounter;
  7209. }());
  7210. PerfCounter.Enabled = true;
  7211. BABYLON.PerfCounter = PerfCounter;
  7212. /**
  7213. * Use this className as a decorator on a given class definition to add it a name and optionally its module.
  7214. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  7215. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  7216. * @param name The name of the class, case should be preserved
  7217. * @param module The name of the Module hosting the class, optional, but strongly recommended to specify if possible. Case should be preserved.
  7218. */
  7219. function className(name, module) {
  7220. return function (target) {
  7221. target["__bjsclassName__"] = name;
  7222. target["__bjsmoduleName__"] = (module != null) ? module : null;
  7223. };
  7224. }
  7225. BABYLON.className = className;
  7226. /**
  7227. * An implementation of a loop for asynchronous functions.
  7228. */
  7229. var AsyncLoop = (function () {
  7230. /**
  7231. * Constroctor.
  7232. * @param iterations the number of iterations.
  7233. * @param _fn the function to run each iteration
  7234. * @param _successCallback the callback that will be called upon succesful execution
  7235. * @param offset starting offset.
  7236. */
  7237. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  7238. if (offset === void 0) { offset = 0; }
  7239. this.iterations = iterations;
  7240. this._fn = _fn;
  7241. this._successCallback = _successCallback;
  7242. this.index = offset - 1;
  7243. this._done = false;
  7244. }
  7245. /**
  7246. * Execute the next iteration. Must be called after the last iteration was finished.
  7247. */
  7248. AsyncLoop.prototype.executeNext = function () {
  7249. if (!this._done) {
  7250. if (this.index + 1 < this.iterations) {
  7251. ++this.index;
  7252. this._fn(this);
  7253. }
  7254. else {
  7255. this.breakLoop();
  7256. }
  7257. }
  7258. };
  7259. /**
  7260. * Break the loop and run the success callback.
  7261. */
  7262. AsyncLoop.prototype.breakLoop = function () {
  7263. this._done = true;
  7264. this._successCallback();
  7265. };
  7266. /**
  7267. * Helper function
  7268. */
  7269. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  7270. if (offset === void 0) { offset = 0; }
  7271. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  7272. loop.executeNext();
  7273. return loop;
  7274. };
  7275. /**
  7276. * A for-loop that will run a given number of iterations synchronous and the rest async.
  7277. * @param iterations total number of iterations
  7278. * @param syncedIterations number of synchronous iterations in each async iteration.
  7279. * @param fn the function to call each iteration.
  7280. * @param callback a success call back that will be called when iterating stops.
  7281. * @param breakFunction a break condition (optional)
  7282. * @param timeout timeout settings for the setTimeout function. default - 0.
  7283. * @constructor
  7284. */
  7285. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  7286. if (timeout === void 0) { timeout = 0; }
  7287. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  7288. if (breakFunction && breakFunction())
  7289. loop.breakLoop();
  7290. else {
  7291. setTimeout(function () {
  7292. for (var i = 0; i < syncedIterations; ++i) {
  7293. var iteration = (loop.index * syncedIterations) + i;
  7294. if (iteration >= iterations)
  7295. break;
  7296. fn(iteration);
  7297. if (breakFunction && breakFunction()) {
  7298. loop.breakLoop();
  7299. break;
  7300. }
  7301. }
  7302. loop.executeNext();
  7303. }, timeout);
  7304. }
  7305. }, callback);
  7306. };
  7307. return AsyncLoop;
  7308. }());
  7309. BABYLON.AsyncLoop = AsyncLoop;
  7310. })(BABYLON || (BABYLON = {}));
  7311. //# sourceMappingURL=babylon.tools.js.map
  7312. var BABYLON;
  7313. (function (BABYLON) {
  7314. var Internals;
  7315. (function (Internals) {
  7316. var _AlphaState = (function () {
  7317. /**
  7318. * Initializes the state.
  7319. */
  7320. function _AlphaState() {
  7321. this._isAlphaBlendDirty = false;
  7322. this._isBlendFunctionParametersDirty = false;
  7323. this._alphaBlend = false;
  7324. this._blendFunctionParameters = new Array(4);
  7325. this.reset();
  7326. }
  7327. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  7328. get: function () {
  7329. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  7330. },
  7331. enumerable: true,
  7332. configurable: true
  7333. });
  7334. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  7335. get: function () {
  7336. return this._alphaBlend;
  7337. },
  7338. set: function (value) {
  7339. if (this._alphaBlend === value) {
  7340. return;
  7341. }
  7342. this._alphaBlend = value;
  7343. this._isAlphaBlendDirty = true;
  7344. },
  7345. enumerable: true,
  7346. configurable: true
  7347. });
  7348. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  7349. if (this._blendFunctionParameters[0] === value0 &&
  7350. this._blendFunctionParameters[1] === value1 &&
  7351. this._blendFunctionParameters[2] === value2 &&
  7352. this._blendFunctionParameters[3] === value3) {
  7353. return;
  7354. }
  7355. this._blendFunctionParameters[0] = value0;
  7356. this._blendFunctionParameters[1] = value1;
  7357. this._blendFunctionParameters[2] = value2;
  7358. this._blendFunctionParameters[3] = value3;
  7359. this._isBlendFunctionParametersDirty = true;
  7360. };
  7361. _AlphaState.prototype.reset = function () {
  7362. this._alphaBlend = false;
  7363. this._blendFunctionParameters[0] = null;
  7364. this._blendFunctionParameters[1] = null;
  7365. this._blendFunctionParameters[2] = null;
  7366. this._blendFunctionParameters[3] = null;
  7367. this._isAlphaBlendDirty = true;
  7368. this._isBlendFunctionParametersDirty = false;
  7369. };
  7370. _AlphaState.prototype.apply = function (gl) {
  7371. if (!this.isDirty) {
  7372. return;
  7373. }
  7374. // Alpha blend
  7375. if (this._isAlphaBlendDirty) {
  7376. if (this._alphaBlend) {
  7377. gl.enable(gl.BLEND);
  7378. }
  7379. else {
  7380. gl.disable(gl.BLEND);
  7381. }
  7382. this._isAlphaBlendDirty = false;
  7383. }
  7384. // Alpha function
  7385. if (this._isBlendFunctionParametersDirty) {
  7386. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  7387. this._isBlendFunctionParametersDirty = false;
  7388. }
  7389. };
  7390. return _AlphaState;
  7391. }());
  7392. Internals._AlphaState = _AlphaState;
  7393. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  7394. })(BABYLON || (BABYLON = {}));
  7395. //# sourceMappingURL=babylon.alphaCullingState.js.map
  7396. var BABYLON;
  7397. (function (BABYLON) {
  7398. var Internals;
  7399. (function (Internals) {
  7400. var _DepthCullingState = (function () {
  7401. /**
  7402. * Initializes the state.
  7403. */
  7404. function _DepthCullingState() {
  7405. this._isDepthTestDirty = false;
  7406. this._isDepthMaskDirty = false;
  7407. this._isDepthFuncDirty = false;
  7408. this._isCullFaceDirty = false;
  7409. this._isCullDirty = false;
  7410. this._isZOffsetDirty = false;
  7411. this.reset();
  7412. }
  7413. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  7414. get: function () {
  7415. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty;
  7416. },
  7417. enumerable: true,
  7418. configurable: true
  7419. });
  7420. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  7421. get: function () {
  7422. return this._zOffset;
  7423. },
  7424. set: function (value) {
  7425. if (this._zOffset === value) {
  7426. return;
  7427. }
  7428. this._zOffset = value;
  7429. this._isZOffsetDirty = true;
  7430. },
  7431. enumerable: true,
  7432. configurable: true
  7433. });
  7434. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  7435. get: function () {
  7436. return this._cullFace;
  7437. },
  7438. set: function (value) {
  7439. if (this._cullFace === value) {
  7440. return;
  7441. }
  7442. this._cullFace = value;
  7443. this._isCullFaceDirty = true;
  7444. },
  7445. enumerable: true,
  7446. configurable: true
  7447. });
  7448. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  7449. get: function () {
  7450. return this._cull;
  7451. },
  7452. set: function (value) {
  7453. if (this._cull === value) {
  7454. return;
  7455. }
  7456. this._cull = value;
  7457. this._isCullDirty = true;
  7458. },
  7459. enumerable: true,
  7460. configurable: true
  7461. });
  7462. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  7463. get: function () {
  7464. return this._depthFunc;
  7465. },
  7466. set: function (value) {
  7467. if (this._depthFunc === value) {
  7468. return;
  7469. }
  7470. this._depthFunc = value;
  7471. this._isDepthFuncDirty = true;
  7472. },
  7473. enumerable: true,
  7474. configurable: true
  7475. });
  7476. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  7477. get: function () {
  7478. return this._depthMask;
  7479. },
  7480. set: function (value) {
  7481. if (this._depthMask === value) {
  7482. return;
  7483. }
  7484. this._depthMask = value;
  7485. this._isDepthMaskDirty = true;
  7486. },
  7487. enumerable: true,
  7488. configurable: true
  7489. });
  7490. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  7491. get: function () {
  7492. return this._depthTest;
  7493. },
  7494. set: function (value) {
  7495. if (this._depthTest === value) {
  7496. return;
  7497. }
  7498. this._depthTest = value;
  7499. this._isDepthTestDirty = true;
  7500. },
  7501. enumerable: true,
  7502. configurable: true
  7503. });
  7504. _DepthCullingState.prototype.reset = function () {
  7505. this._depthMask = true;
  7506. this._depthTest = true;
  7507. this._depthFunc = null;
  7508. this._cullFace = null;
  7509. this._cull = null;
  7510. this._zOffset = 0;
  7511. this._isDepthTestDirty = true;
  7512. this._isDepthMaskDirty = true;
  7513. this._isDepthFuncDirty = false;
  7514. this._isCullFaceDirty = false;
  7515. this._isCullDirty = false;
  7516. this._isZOffsetDirty = false;
  7517. };
  7518. _DepthCullingState.prototype.apply = function (gl) {
  7519. if (!this.isDirty) {
  7520. return;
  7521. }
  7522. // Cull
  7523. if (this._isCullDirty) {
  7524. if (this.cull) {
  7525. gl.enable(gl.CULL_FACE);
  7526. }
  7527. else {
  7528. gl.disable(gl.CULL_FACE);
  7529. }
  7530. this._isCullDirty = false;
  7531. }
  7532. // Cull face
  7533. if (this._isCullFaceDirty) {
  7534. gl.cullFace(this.cullFace);
  7535. this._isCullFaceDirty = false;
  7536. }
  7537. // Depth mask
  7538. if (this._isDepthMaskDirty) {
  7539. gl.depthMask(this.depthMask);
  7540. this._isDepthMaskDirty = false;
  7541. }
  7542. // Depth test
  7543. if (this._isDepthTestDirty) {
  7544. if (this.depthTest) {
  7545. gl.enable(gl.DEPTH_TEST);
  7546. }
  7547. else {
  7548. gl.disable(gl.DEPTH_TEST);
  7549. }
  7550. this._isDepthTestDirty = false;
  7551. }
  7552. // Depth func
  7553. if (this._isDepthFuncDirty) {
  7554. gl.depthFunc(this.depthFunc);
  7555. this._isDepthFuncDirty = false;
  7556. }
  7557. // zOffset
  7558. if (this._isZOffsetDirty) {
  7559. if (this.zOffset) {
  7560. gl.enable(gl.POLYGON_OFFSET_FILL);
  7561. gl.polygonOffset(this.zOffset, 0);
  7562. }
  7563. else {
  7564. gl.disable(gl.POLYGON_OFFSET_FILL);
  7565. }
  7566. this._isZOffsetDirty = false;
  7567. }
  7568. };
  7569. return _DepthCullingState;
  7570. }());
  7571. Internals._DepthCullingState = _DepthCullingState;
  7572. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  7573. })(BABYLON || (BABYLON = {}));
  7574. //# sourceMappingURL=babylon.depthCullingState.js.map
  7575. var BABYLON;
  7576. (function (BABYLON) {
  7577. var Internals;
  7578. (function (Internals) {
  7579. var _StencilState = (function () {
  7580. function _StencilState() {
  7581. this._isStencilTestDirty = false;
  7582. this._isStencilMaskDirty = false;
  7583. this._isStencilFuncDirty = false;
  7584. this._isStencilOpDirty = false;
  7585. this.reset();
  7586. }
  7587. Object.defineProperty(_StencilState.prototype, "isDirty", {
  7588. get: function () {
  7589. return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty;
  7590. },
  7591. enumerable: true,
  7592. configurable: true
  7593. });
  7594. Object.defineProperty(_StencilState.prototype, "stencilFunc", {
  7595. get: function () {
  7596. return this._stencilFunc;
  7597. },
  7598. set: function (value) {
  7599. if (this._stencilFunc === value) {
  7600. return;
  7601. }
  7602. this._stencilFunc = value;
  7603. this._isStencilFuncDirty = true;
  7604. },
  7605. enumerable: true,
  7606. configurable: true
  7607. });
  7608. Object.defineProperty(_StencilState.prototype, "stencilFuncRef", {
  7609. get: function () {
  7610. return this._stencilFuncRef;
  7611. },
  7612. set: function (value) {
  7613. if (this._stencilFuncRef === value) {
  7614. return;
  7615. }
  7616. this._stencilFuncRef = value;
  7617. this._isStencilFuncDirty = true;
  7618. },
  7619. enumerable: true,
  7620. configurable: true
  7621. });
  7622. Object.defineProperty(_StencilState.prototype, "stencilFuncMask", {
  7623. get: function () {
  7624. return this._stencilFuncMask;
  7625. },
  7626. set: function (value) {
  7627. if (this._stencilFuncMask === value) {
  7628. return;
  7629. }
  7630. this._stencilFuncMask = value;
  7631. this._isStencilFuncDirty = true;
  7632. },
  7633. enumerable: true,
  7634. configurable: true
  7635. });
  7636. Object.defineProperty(_StencilState.prototype, "stencilOpStencilFail", {
  7637. get: function () {
  7638. return this._stencilOpStencilFail;
  7639. },
  7640. set: function (value) {
  7641. if (this._stencilOpStencilFail === value) {
  7642. return;
  7643. }
  7644. this._stencilOpStencilFail = value;
  7645. this._isStencilOpDirty = true;
  7646. },
  7647. enumerable: true,
  7648. configurable: true
  7649. });
  7650. Object.defineProperty(_StencilState.prototype, "stencilOpDepthFail", {
  7651. get: function () {
  7652. return this._stencilOpDepthFail;
  7653. },
  7654. set: function (value) {
  7655. if (this._stencilOpDepthFail === value) {
  7656. return;
  7657. }
  7658. this._stencilOpDepthFail = value;
  7659. this._isStencilOpDirty = true;
  7660. },
  7661. enumerable: true,
  7662. configurable: true
  7663. });
  7664. Object.defineProperty(_StencilState.prototype, "stencilOpStencilDepthPass", {
  7665. get: function () {
  7666. return this._stencilOpStencilDepthPass;
  7667. },
  7668. set: function (value) {
  7669. if (this._stencilOpStencilDepthPass === value) {
  7670. return;
  7671. }
  7672. this._stencilOpStencilDepthPass = value;
  7673. this._isStencilOpDirty = true;
  7674. },
  7675. enumerable: true,
  7676. configurable: true
  7677. });
  7678. Object.defineProperty(_StencilState.prototype, "stencilMask", {
  7679. get: function () {
  7680. return this._stencilMask;
  7681. },
  7682. set: function (value) {
  7683. if (this._stencilMask === value) {
  7684. return;
  7685. }
  7686. this._stencilMask = value;
  7687. this._isStencilMaskDirty = true;
  7688. },
  7689. enumerable: true,
  7690. configurable: true
  7691. });
  7692. Object.defineProperty(_StencilState.prototype, "stencilTest", {
  7693. get: function () {
  7694. return this._stencilTest;
  7695. },
  7696. set: function (value) {
  7697. if (this._stencilTest === value) {
  7698. return;
  7699. }
  7700. this._stencilTest = value;
  7701. this._isStencilTestDirty = true;
  7702. },
  7703. enumerable: true,
  7704. configurable: true
  7705. });
  7706. _StencilState.prototype.reset = function () {
  7707. this._stencilTest = false;
  7708. this._stencilMask = 0xFF;
  7709. this._stencilFunc = BABYLON.Engine.ALWAYS;
  7710. this._stencilFuncRef = 1;
  7711. this._stencilFuncMask = 0xFF;
  7712. this._stencilOpStencilFail = BABYLON.Engine.KEEP;
  7713. this._stencilOpDepthFail = BABYLON.Engine.KEEP;
  7714. this._stencilOpStencilDepthPass = BABYLON.Engine.REPLACE;
  7715. this._isStencilTestDirty = true;
  7716. this._isStencilMaskDirty = true;
  7717. this._isStencilFuncDirty = true;
  7718. this._isStencilOpDirty = true;
  7719. };
  7720. _StencilState.prototype.apply = function (gl) {
  7721. if (!this.isDirty) {
  7722. return;
  7723. }
  7724. // Stencil test
  7725. if (this._isStencilTestDirty) {
  7726. if (this.stencilTest) {
  7727. gl.enable(gl.STENCIL_TEST);
  7728. }
  7729. else {
  7730. gl.disable(gl.STENCIL_TEST);
  7731. }
  7732. this._isStencilTestDirty = false;
  7733. }
  7734. // Stencil mask
  7735. if (this._isStencilMaskDirty) {
  7736. gl.stencilMask(this.stencilMask);
  7737. this._isStencilMaskDirty = false;
  7738. }
  7739. // Stencil func
  7740. if (this._isStencilFuncDirty) {
  7741. gl.stencilFunc(this.stencilFunc, this.stencilFuncRef, this.stencilFuncMask);
  7742. this._isStencilFuncDirty = false;
  7743. }
  7744. // Stencil op
  7745. if (this._isStencilOpDirty) {
  7746. gl.stencilOp(this.stencilOpStencilFail, this.stencilOpDepthFail, this.stencilOpStencilDepthPass);
  7747. this._isStencilOpDirty = false;
  7748. }
  7749. };
  7750. return _StencilState;
  7751. }());
  7752. Internals._StencilState = _StencilState;
  7753. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  7754. })(BABYLON || (BABYLON = {}));
  7755. //# sourceMappingURL=babylon.stencilState.js.map
  7756. var BABYLON;
  7757. (function (BABYLON) {
  7758. var compileShader = function (gl, source, type, defines, shaderVersion) {
  7759. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  7760. gl.shaderSource(shader, shaderVersion + (defines ? defines + "\n" : "") + source);
  7761. gl.compileShader(shader);
  7762. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  7763. throw new Error(gl.getShaderInfoLog(shader));
  7764. }
  7765. return shader;
  7766. };
  7767. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  7768. var magFilter = gl.NEAREST;
  7769. var minFilter = gl.NEAREST;
  7770. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  7771. magFilter = gl.LINEAR;
  7772. if (generateMipMaps) {
  7773. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  7774. }
  7775. else {
  7776. minFilter = gl.LINEAR;
  7777. }
  7778. }
  7779. else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  7780. magFilter = gl.LINEAR;
  7781. if (generateMipMaps) {
  7782. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  7783. }
  7784. else {
  7785. minFilter = gl.LINEAR;
  7786. }
  7787. }
  7788. else if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  7789. magFilter = gl.NEAREST;
  7790. if (generateMipMaps) {
  7791. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  7792. }
  7793. else {
  7794. minFilter = gl.NEAREST;
  7795. }
  7796. }
  7797. return {
  7798. min: minFilter,
  7799. mag: magFilter
  7800. };
  7801. };
  7802. var prepareWebGLTexture = function (texture, gl, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  7803. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  7804. var engine = scene.getEngine();
  7805. var potWidth = BABYLON.Tools.GetExponentOfTwo(width, engine.getCaps().maxTextureSize);
  7806. var potHeight = BABYLON.Tools.GetExponentOfTwo(height, engine.getCaps().maxTextureSize);
  7807. engine._bindTextureDirectly(gl.TEXTURE_2D, texture);
  7808. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  7809. texture._baseWidth = width;
  7810. texture._baseHeight = height;
  7811. texture._width = potWidth;
  7812. texture._height = potHeight;
  7813. texture.isReady = true;
  7814. processFunction(potWidth, potHeight);
  7815. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  7816. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  7817. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  7818. if (!noMipmap && !isCompressed) {
  7819. gl.generateMipmap(gl.TEXTURE_2D);
  7820. }
  7821. engine._bindTextureDirectly(gl.TEXTURE_2D, null);
  7822. engine.resetTextureCache();
  7823. scene._removePendingData(texture);
  7824. texture.onLoadedCallbacks.forEach(function (callback) {
  7825. callback();
  7826. });
  7827. texture.onLoadedCallbacks = [];
  7828. };
  7829. var partialLoad = function (url, index, loadedImages, scene, onfinish, onErrorCallBack) {
  7830. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  7831. var img;
  7832. var onload = function () {
  7833. loadedImages[index] = img;
  7834. loadedImages._internalCount++;
  7835. scene._removePendingData(img);
  7836. if (loadedImages._internalCount === 6) {
  7837. onfinish(loadedImages);
  7838. }
  7839. };
  7840. var onerror = function () {
  7841. scene._removePendingData(img);
  7842. if (onErrorCallBack) {
  7843. onErrorCallBack();
  7844. }
  7845. };
  7846. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  7847. scene._addPendingData(img);
  7848. };
  7849. var cascadeLoad = function (rootUrl, scene, onfinish, files, onError) {
  7850. if (onError === void 0) { onError = null; }
  7851. var loadedImages = [];
  7852. loadedImages._internalCount = 0;
  7853. for (var index = 0; index < 6; index++) {
  7854. partialLoad(files[index], index, loadedImages, scene, onfinish, onError);
  7855. }
  7856. };
  7857. var InstancingAttributeInfo = (function () {
  7858. function InstancingAttributeInfo() {
  7859. }
  7860. return InstancingAttributeInfo;
  7861. }());
  7862. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  7863. var EngineCapabilities = (function () {
  7864. function EngineCapabilities() {
  7865. }
  7866. return EngineCapabilities;
  7867. }());
  7868. BABYLON.EngineCapabilities = EngineCapabilities;
  7869. /**
  7870. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
  7871. */
  7872. var Engine = (function () {
  7873. /**
  7874. * @constructor
  7875. * @param {HTMLCanvasElement} canvas - the canvas to be used for rendering
  7876. * @param {boolean} [antialias] - enable antialias
  7877. * @param options - further options to be sent to the getContext function
  7878. */
  7879. function Engine(canvas, antialias, options, adaptToDeviceRatio) {
  7880. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = false; }
  7881. var _this = this;
  7882. // Public members
  7883. this.isFullscreen = false;
  7884. this.isPointerLock = false;
  7885. this.cullBackFaces = true;
  7886. this.renderEvenInBackground = true;
  7887. this.preventCacheWipeBetweenFrames = false;
  7888. // To enable/disable IDB support and avoid XHR on .manifest
  7889. this.enableOfflineSupport = true;
  7890. this.scenes = new Array();
  7891. this._windowIsBackground = false;
  7892. this._webGLVersion = 1.0;
  7893. this._badOS = false;
  7894. this._drawCalls = new BABYLON.PerfCounter();
  7895. this._renderingQueueLaunched = false;
  7896. this._activeRenderLoops = [];
  7897. // FPS
  7898. this.fpsRange = 60;
  7899. this.previousFramesDuration = [];
  7900. this.fps = 60;
  7901. this.deltaTime = 0;
  7902. // States
  7903. this._depthCullingState = new BABYLON.Internals._DepthCullingState();
  7904. this._stencilState = new BABYLON.Internals._StencilState();
  7905. this._alphaState = new BABYLON.Internals._AlphaState();
  7906. this._alphaMode = Engine.ALPHA_DISABLE;
  7907. // Cache
  7908. this._loadedTexturesCache = new Array();
  7909. this._maxTextureChannels = 16;
  7910. this._activeTexturesCache = new Array(this._maxTextureChannels);
  7911. this._compiledEffects = {};
  7912. this._vertexAttribArraysEnabled = [];
  7913. this._uintIndicesCurrentlySet = false;
  7914. this._currentBoundBuffer = new Array();
  7915. this._currentBufferPointers = [];
  7916. this._currentInstanceLocations = new Array();
  7917. this._currentInstanceBuffers = new Array();
  7918. this._vaoRecordInProgress = false;
  7919. this._mustWipeVertexAttributes = false;
  7920. // Hardware supported Compressed Textures
  7921. this._texturesSupported = new Array();
  7922. this._onVRFullScreenTriggered = function () {
  7923. if (_this._vrDisplayEnabled && _this._vrDisplayEnabled.isPresenting) {
  7924. //get the old size before we change
  7925. _this._oldSize = new BABYLON.Size(_this.getRenderWidth(), _this.getRenderHeight());
  7926. _this._oldHardwareScaleFactor = _this.getHardwareScalingLevel();
  7927. //get the width and height, change the render size
  7928. var leftEye = _this._vrDisplayEnabled.getEyeParameters('left');
  7929. var width, height;
  7930. _this.setHardwareScalingLevel(1);
  7931. _this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  7932. }
  7933. else {
  7934. //When the specs are implemented, need to uncomment this.
  7935. //this._vrDisplayEnabled.cancelAnimationFrame(this._vrAnimationFrameHandler);
  7936. _this.setHardwareScalingLevel(_this._oldHardwareScaleFactor);
  7937. _this.setSize(_this._oldSize.width, _this._oldSize.height);
  7938. _this._vrDisplayEnabled = undefined;
  7939. }
  7940. };
  7941. this._renderingCanvas = canvas;
  7942. Engine.Instances.push(this);
  7943. this._externalData = new BABYLON.StringDictionary();
  7944. options = options || {};
  7945. if (antialias != null) {
  7946. options.antialias = antialias;
  7947. }
  7948. if (options.preserveDrawingBuffer === undefined) {
  7949. options.preserveDrawingBuffer = false;
  7950. }
  7951. if (options.audioEngine === undefined) {
  7952. options.audioEngine = true;
  7953. }
  7954. if (options.stencil === undefined) {
  7955. options.stencil = true;
  7956. }
  7957. // GL
  7958. if (!options.disableWebGL2Support) {
  7959. try {
  7960. this._gl = (canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  7961. if (this._gl) {
  7962. this._webGLVersion = 2.0;
  7963. }
  7964. }
  7965. catch (e) {
  7966. }
  7967. }
  7968. if (!this._gl) {
  7969. if (!canvas) {
  7970. throw new Error("The provided canvas is null or undefined.");
  7971. }
  7972. try {
  7973. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  7974. }
  7975. catch (e) {
  7976. throw new Error("WebGL not supported");
  7977. }
  7978. }
  7979. if (!this._gl) {
  7980. throw new Error("WebGL not supported");
  7981. }
  7982. this._onBlur = function () {
  7983. _this._windowIsBackground = true;
  7984. };
  7985. this._onFocus = function () {
  7986. _this._windowIsBackground = false;
  7987. };
  7988. window.addEventListener("blur", this._onBlur);
  7989. window.addEventListener("focus", this._onFocus);
  7990. // Viewport
  7991. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  7992. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  7993. this.resize();
  7994. // Caps
  7995. this._isStencilEnable = options.stencil;
  7996. this._caps = new EngineCapabilities();
  7997. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  7998. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  7999. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  8000. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  8001. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  8002. this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS);
  8003. this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  8004. this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS);
  8005. // Infos
  8006. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  8007. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  8008. if (rendererInfo != null) {
  8009. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  8010. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  8011. }
  8012. if (!this._glVendor) {
  8013. this._glVendor = "Unknown vendor";
  8014. }
  8015. if (!this._glRenderer) {
  8016. this._glRenderer = "Unknown renderer";
  8017. }
  8018. // Extensions
  8019. this._caps.standardDerivatives = this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null);
  8020. this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc');
  8021. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  8022. this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  8023. this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1');
  8024. this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc') ||
  8025. this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // also a requirement of OpenGL ES 3
  8026. this._caps.atc = this._gl.getExtension('WEBGL_compressed_texture_atc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_atc');
  8027. 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');
  8028. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  8029. this._caps.uintIndices = this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null;
  8030. this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null;
  8031. this._caps.highPrecisionShaderSupported = true;
  8032. this._caps.drawBuffersExtension = this._webGLVersion > 1 || this._gl.getExtension('WEBGL_draw_buffers');
  8033. // Checks if some of the format renders first to allow the use of webgl inspector.
  8034. this._caps.colorBufferFloat = this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float');
  8035. this._caps.textureFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float');
  8036. this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear');
  8037. this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer();
  8038. this._caps.textureHalfFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float');
  8039. this._caps.textureHalfFloatLinearFiltering = this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'));
  8040. this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
  8041. this._caps.textureLOD = this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod');
  8042. // Vertex array object
  8043. if (this._webGLVersion > 1) {
  8044. this._caps.vertexArrayObject = true;
  8045. }
  8046. else {
  8047. var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object');
  8048. if (vertexArrayObjectExtension != null) {
  8049. this._caps.vertexArrayObject = true;
  8050. this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
  8051. this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
  8052. this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
  8053. }
  8054. else {
  8055. this._caps.vertexArrayObject = false;
  8056. }
  8057. }
  8058. // Instances count
  8059. if (this._webGLVersion > 1) {
  8060. this._caps.instancedArrays = true;
  8061. }
  8062. else {
  8063. var instanceExtension = this._gl.getExtension('ANGLE_instanced_arrays');
  8064. if (instanceExtension != null) {
  8065. this._caps.instancedArrays = true;
  8066. this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
  8067. this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
  8068. this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
  8069. }
  8070. else {
  8071. this._caps.instancedArrays = false;
  8072. }
  8073. }
  8074. // Intelligently add supported compressed formats in order to check for.
  8075. // Check for ASTC support first as it is most powerful and to be very cross platform.
  8076. // Next PVRTC & DXT, which are probably superior to ETC1/2.
  8077. // Likely no hardware which supports both PVR & DXT, so order matters little.
  8078. // ETC2 is newer and handles ETC1 (no alpha capability), so check for first.
  8079. // ATC before ETC1, since both old (widely supported), but ATC supports alpha, but ETC1 does not
  8080. if (this._caps.astc)
  8081. this.texturesSupported.push('-astc.ktx');
  8082. if (this._caps.s3tc)
  8083. this.texturesSupported.push('-dxt.ktx');
  8084. if (this._caps.pvrtc)
  8085. this.texturesSupported.push('-pvrtc.ktx');
  8086. if (this._caps.etc2)
  8087. this.texturesSupported.push('-etc2.ktx');
  8088. if (this._caps.atc)
  8089. this.texturesSupported.push('-atc.ktx');
  8090. if (this._caps.etc1)
  8091. this.texturesSupported.push('-etc1.ktx');
  8092. if (this._gl.getShaderPrecisionFormat) {
  8093. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  8094. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  8095. }
  8096. // Depth buffer
  8097. this.setDepthBuffer(true);
  8098. this.setDepthFunctionToLessOrEqual();
  8099. this.setDepthWrite(true);
  8100. // Fullscreen
  8101. this._onFullscreenChange = function () {
  8102. if (document.fullscreen !== undefined) {
  8103. _this.isFullscreen = document.fullscreen;
  8104. }
  8105. else if (document.mozFullScreen !== undefined) {
  8106. _this.isFullscreen = document.mozFullScreen;
  8107. }
  8108. else if (document.webkitIsFullScreen !== undefined) {
  8109. _this.isFullscreen = document.webkitIsFullScreen;
  8110. }
  8111. else if (document.msIsFullScreen !== undefined) {
  8112. _this.isFullscreen = document.msIsFullScreen;
  8113. }
  8114. // Pointer lock
  8115. if (_this.isFullscreen && _this._pointerLockRequested) {
  8116. canvas.requestPointerLock = canvas.requestPointerLock ||
  8117. canvas.msRequestPointerLock ||
  8118. canvas.mozRequestPointerLock ||
  8119. canvas.webkitRequestPointerLock;
  8120. if (canvas.requestPointerLock) {
  8121. canvas.requestPointerLock();
  8122. }
  8123. }
  8124. };
  8125. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  8126. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  8127. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  8128. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  8129. // Pointer lock
  8130. this._onPointerLockChange = function () {
  8131. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  8132. document.webkitPointerLockElement === canvas ||
  8133. document.msPointerLockElement === canvas ||
  8134. document.pointerLockElement === canvas);
  8135. };
  8136. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  8137. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  8138. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  8139. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  8140. if (options.audioEngine && BABYLON.AudioEngine && !Engine.audioEngine) {
  8141. Engine.audioEngine = new BABYLON.AudioEngine();
  8142. }
  8143. //default loading screen
  8144. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  8145. //Load WebVR Devices
  8146. if (options.autoEnableWebVR) {
  8147. this.initWebVR();
  8148. }
  8149. //Detect if we are running on a faulty buggy OS.
  8150. var regexp = /AppleWebKit.*10.[\d] Mobile/;
  8151. //ua sniffing is the tool of the devil.
  8152. this._badOS = regexp.test(navigator.userAgent);
  8153. BABYLON.Tools.Log("Babylon.js engine (v" + Engine.Version + ") launched");
  8154. }
  8155. Object.defineProperty(Engine, "LastCreatedEngine", {
  8156. get: function () {
  8157. if (Engine.Instances.length === 0) {
  8158. return null;
  8159. }
  8160. return Engine.Instances[Engine.Instances.length - 1];
  8161. },
  8162. enumerable: true,
  8163. configurable: true
  8164. });
  8165. Object.defineProperty(Engine, "LastCreatedScene", {
  8166. get: function () {
  8167. var lastCreatedEngine = Engine.LastCreatedEngine;
  8168. if (!lastCreatedEngine) {
  8169. return null;
  8170. }
  8171. if (lastCreatedEngine.scenes.length === 0) {
  8172. return null;
  8173. }
  8174. return lastCreatedEngine.scenes[lastCreatedEngine.scenes.length - 1];
  8175. },
  8176. enumerable: true,
  8177. configurable: true
  8178. });
  8179. Object.defineProperty(Engine, "NEVER", {
  8180. get: function () {
  8181. return Engine._NEVER;
  8182. },
  8183. enumerable: true,
  8184. configurable: true
  8185. });
  8186. Object.defineProperty(Engine, "ALWAYS", {
  8187. get: function () {
  8188. return Engine._ALWAYS;
  8189. },
  8190. enumerable: true,
  8191. configurable: true
  8192. });
  8193. Object.defineProperty(Engine, "LESS", {
  8194. get: function () {
  8195. return Engine._LESS;
  8196. },
  8197. enumerable: true,
  8198. configurable: true
  8199. });
  8200. Object.defineProperty(Engine, "EQUAL", {
  8201. get: function () {
  8202. return Engine._EQUAL;
  8203. },
  8204. enumerable: true,
  8205. configurable: true
  8206. });
  8207. Object.defineProperty(Engine, "LEQUAL", {
  8208. get: function () {
  8209. return Engine._LEQUAL;
  8210. },
  8211. enumerable: true,
  8212. configurable: true
  8213. });
  8214. Object.defineProperty(Engine, "GREATER", {
  8215. get: function () {
  8216. return Engine._GREATER;
  8217. },
  8218. enumerable: true,
  8219. configurable: true
  8220. });
  8221. Object.defineProperty(Engine, "GEQUAL", {
  8222. get: function () {
  8223. return Engine._GEQUAL;
  8224. },
  8225. enumerable: true,
  8226. configurable: true
  8227. });
  8228. Object.defineProperty(Engine, "NOTEQUAL", {
  8229. get: function () {
  8230. return Engine._NOTEQUAL;
  8231. },
  8232. enumerable: true,
  8233. configurable: true
  8234. });
  8235. Object.defineProperty(Engine, "KEEP", {
  8236. get: function () {
  8237. return Engine._KEEP;
  8238. },
  8239. enumerable: true,
  8240. configurable: true
  8241. });
  8242. Object.defineProperty(Engine, "REPLACE", {
  8243. get: function () {
  8244. return Engine._REPLACE;
  8245. },
  8246. enumerable: true,
  8247. configurable: true
  8248. });
  8249. Object.defineProperty(Engine, "INCR", {
  8250. get: function () {
  8251. return Engine._INCR;
  8252. },
  8253. enumerable: true,
  8254. configurable: true
  8255. });
  8256. Object.defineProperty(Engine, "DECR", {
  8257. get: function () {
  8258. return Engine._DECR;
  8259. },
  8260. enumerable: true,
  8261. configurable: true
  8262. });
  8263. Object.defineProperty(Engine, "INVERT", {
  8264. get: function () {
  8265. return Engine._INVERT;
  8266. },
  8267. enumerable: true,
  8268. configurable: true
  8269. });
  8270. Object.defineProperty(Engine, "INCR_WRAP", {
  8271. get: function () {
  8272. return Engine._INCR_WRAP;
  8273. },
  8274. enumerable: true,
  8275. configurable: true
  8276. });
  8277. Object.defineProperty(Engine, "DECR_WRAP", {
  8278. get: function () {
  8279. return Engine._DECR_WRAP;
  8280. },
  8281. enumerable: true,
  8282. configurable: true
  8283. });
  8284. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  8285. get: function () {
  8286. return Engine._ALPHA_DISABLE;
  8287. },
  8288. enumerable: true,
  8289. configurable: true
  8290. });
  8291. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  8292. get: function () {
  8293. return Engine._ALPHA_ONEONE;
  8294. },
  8295. enumerable: true,
  8296. configurable: true
  8297. });
  8298. Object.defineProperty(Engine, "ALPHA_ADD", {
  8299. get: function () {
  8300. return Engine._ALPHA_ADD;
  8301. },
  8302. enumerable: true,
  8303. configurable: true
  8304. });
  8305. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  8306. get: function () {
  8307. return Engine._ALPHA_COMBINE;
  8308. },
  8309. enumerable: true,
  8310. configurable: true
  8311. });
  8312. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  8313. get: function () {
  8314. return Engine._ALPHA_SUBTRACT;
  8315. },
  8316. enumerable: true,
  8317. configurable: true
  8318. });
  8319. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  8320. get: function () {
  8321. return Engine._ALPHA_MULTIPLY;
  8322. },
  8323. enumerable: true,
  8324. configurable: true
  8325. });
  8326. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  8327. get: function () {
  8328. return Engine._ALPHA_MAXIMIZED;
  8329. },
  8330. enumerable: true,
  8331. configurable: true
  8332. });
  8333. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED", {
  8334. get: function () {
  8335. return Engine._ALPHA_PREMULTIPLIED;
  8336. },
  8337. enumerable: true,
  8338. configurable: true
  8339. });
  8340. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  8341. get: function () {
  8342. return Engine._DELAYLOADSTATE_NONE;
  8343. },
  8344. enumerable: true,
  8345. configurable: true
  8346. });
  8347. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  8348. get: function () {
  8349. return Engine._DELAYLOADSTATE_LOADED;
  8350. },
  8351. enumerable: true,
  8352. configurable: true
  8353. });
  8354. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  8355. get: function () {
  8356. return Engine._DELAYLOADSTATE_LOADING;
  8357. },
  8358. enumerable: true,
  8359. configurable: true
  8360. });
  8361. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  8362. get: function () {
  8363. return Engine._DELAYLOADSTATE_NOTLOADED;
  8364. },
  8365. enumerable: true,
  8366. configurable: true
  8367. });
  8368. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  8369. get: function () {
  8370. return Engine._TEXTUREFORMAT_ALPHA;
  8371. },
  8372. enumerable: true,
  8373. configurable: true
  8374. });
  8375. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  8376. get: function () {
  8377. return Engine._TEXTUREFORMAT_LUMINANCE;
  8378. },
  8379. enumerable: true,
  8380. configurable: true
  8381. });
  8382. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  8383. get: function () {
  8384. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  8385. },
  8386. enumerable: true,
  8387. configurable: true
  8388. });
  8389. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  8390. get: function () {
  8391. return Engine._TEXTUREFORMAT_RGB;
  8392. },
  8393. enumerable: true,
  8394. configurable: true
  8395. });
  8396. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  8397. get: function () {
  8398. return Engine._TEXTUREFORMAT_RGBA;
  8399. },
  8400. enumerable: true,
  8401. configurable: true
  8402. });
  8403. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  8404. get: function () {
  8405. return Engine._TEXTURETYPE_UNSIGNED_INT;
  8406. },
  8407. enumerable: true,
  8408. configurable: true
  8409. });
  8410. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  8411. get: function () {
  8412. return Engine._TEXTURETYPE_FLOAT;
  8413. },
  8414. enumerable: true,
  8415. configurable: true
  8416. });
  8417. Object.defineProperty(Engine, "TEXTURETYPE_HALF_FLOAT", {
  8418. get: function () {
  8419. return Engine._TEXTURETYPE_HALF_FLOAT;
  8420. },
  8421. enumerable: true,
  8422. configurable: true
  8423. });
  8424. Object.defineProperty(Engine, "Version", {
  8425. get: function () {
  8426. return "3.0-alpha";
  8427. },
  8428. enumerable: true,
  8429. configurable: true
  8430. });
  8431. Object.defineProperty(Engine.prototype, "texturesSupported", {
  8432. get: function () {
  8433. return this._texturesSupported;
  8434. },
  8435. enumerable: true,
  8436. configurable: true
  8437. });
  8438. Object.defineProperty(Engine.prototype, "textureFormatInUse", {
  8439. get: function () {
  8440. return this._textureFormatInUse;
  8441. },
  8442. enumerable: true,
  8443. configurable: true
  8444. });
  8445. Object.defineProperty(Engine.prototype, "webGLVersion", {
  8446. get: function () {
  8447. return this._webGLVersion;
  8448. },
  8449. enumerable: true,
  8450. configurable: true
  8451. });
  8452. Object.defineProperty(Engine.prototype, "isStencilEnable", {
  8453. /**
  8454. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  8455. */
  8456. get: function () {
  8457. return this._isStencilEnable;
  8458. },
  8459. enumerable: true,
  8460. configurable: true
  8461. });
  8462. Engine.prototype._prepareWorkingCanvas = function () {
  8463. if (this._workingCanvas) {
  8464. return;
  8465. }
  8466. this._workingCanvas = document.createElement("canvas");
  8467. this._workingContext = this._workingCanvas.getContext("2d");
  8468. };
  8469. Engine.prototype.resetTextureCache = function () {
  8470. for (var index = 0; index < this._maxTextureChannels; index++) {
  8471. this._activeTexturesCache[index] = null;
  8472. }
  8473. };
  8474. Engine.prototype.getGlInfo = function () {
  8475. return {
  8476. vendor: this._glVendor,
  8477. renderer: this._glRenderer,
  8478. version: this._glVersion
  8479. };
  8480. };
  8481. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  8482. if (useScreen === void 0) { useScreen = false; }
  8483. var viewport = camera.viewport;
  8484. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  8485. };
  8486. Engine.prototype.getRenderWidth = function (useScreen) {
  8487. if (useScreen === void 0) { useScreen = false; }
  8488. if (!useScreen && this._currentRenderTarget) {
  8489. return this._currentRenderTarget._width;
  8490. }
  8491. return this._renderingCanvas.width;
  8492. };
  8493. Engine.prototype.getRenderHeight = function (useScreen) {
  8494. if (useScreen === void 0) { useScreen = false; }
  8495. if (!useScreen && this._currentRenderTarget) {
  8496. return this._currentRenderTarget._height;
  8497. }
  8498. return this._renderingCanvas.height;
  8499. };
  8500. Engine.prototype.getRenderingCanvas = function () {
  8501. return this._renderingCanvas;
  8502. };
  8503. Engine.prototype.getRenderingCanvasClientRect = function () {
  8504. return this._renderingCanvas.getBoundingClientRect();
  8505. };
  8506. Engine.prototype.setHardwareScalingLevel = function (level) {
  8507. this._hardwareScalingLevel = level;
  8508. this.resize();
  8509. };
  8510. Engine.prototype.getHardwareScalingLevel = function () {
  8511. return this._hardwareScalingLevel;
  8512. };
  8513. Engine.prototype.getLoadedTexturesCache = function () {
  8514. return this._loadedTexturesCache;
  8515. };
  8516. Engine.prototype.getCaps = function () {
  8517. return this._caps;
  8518. };
  8519. Object.defineProperty(Engine.prototype, "drawCalls", {
  8520. get: function () {
  8521. return this._drawCalls.current;
  8522. },
  8523. enumerable: true,
  8524. configurable: true
  8525. });
  8526. Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
  8527. get: function () {
  8528. return this._drawCalls;
  8529. },
  8530. enumerable: true,
  8531. configurable: true
  8532. });
  8533. Engine.prototype.getDepthFunction = function () {
  8534. return this._depthCullingState.depthFunc;
  8535. };
  8536. Engine.prototype.setDepthFunction = function (depthFunc) {
  8537. this._depthCullingState.depthFunc = depthFunc;
  8538. };
  8539. Engine.prototype.setDepthFunctionToGreater = function () {
  8540. this._depthCullingState.depthFunc = this._gl.GREATER;
  8541. };
  8542. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  8543. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  8544. };
  8545. Engine.prototype.setDepthFunctionToLess = function () {
  8546. this._depthCullingState.depthFunc = this._gl.LESS;
  8547. };
  8548. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  8549. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  8550. };
  8551. Engine.prototype.getStencilBuffer = function () {
  8552. return this._stencilState.stencilTest;
  8553. };
  8554. Engine.prototype.setStencilBuffer = function (enable) {
  8555. this._stencilState.stencilTest = enable;
  8556. };
  8557. Engine.prototype.getStencilMask = function () {
  8558. return this._stencilState.stencilMask;
  8559. };
  8560. Engine.prototype.setStencilMask = function (mask) {
  8561. this._stencilState.stencilMask = mask;
  8562. };
  8563. Engine.prototype.getStencilFunction = function () {
  8564. return this._stencilState.stencilFunc;
  8565. };
  8566. Engine.prototype.getStencilFunctionReference = function () {
  8567. return this._stencilState.stencilFuncRef;
  8568. };
  8569. Engine.prototype.getStencilFunctionMask = function () {
  8570. return this._stencilState.stencilFuncMask;
  8571. };
  8572. Engine.prototype.setStencilFunction = function (stencilFunc) {
  8573. this._stencilState.stencilFunc = stencilFunc;
  8574. };
  8575. Engine.prototype.setStencilFunctionReference = function (reference) {
  8576. this._stencilState.stencilFuncRef = reference;
  8577. };
  8578. Engine.prototype.setStencilFunctionMask = function (mask) {
  8579. this._stencilState.stencilFuncMask = mask;
  8580. };
  8581. Engine.prototype.getStencilOperationFail = function () {
  8582. return this._stencilState.stencilOpStencilFail;
  8583. };
  8584. Engine.prototype.getStencilOperationDepthFail = function () {
  8585. return this._stencilState.stencilOpDepthFail;
  8586. };
  8587. Engine.prototype.getStencilOperationPass = function () {
  8588. return this._stencilState.stencilOpStencilDepthPass;
  8589. };
  8590. Engine.prototype.setStencilOperationFail = function (operation) {
  8591. this._stencilState.stencilOpStencilFail = operation;
  8592. };
  8593. Engine.prototype.setStencilOperationDepthFail = function (operation) {
  8594. this._stencilState.stencilOpDepthFail = operation;
  8595. };
  8596. Engine.prototype.setStencilOperationPass = function (operation) {
  8597. this._stencilState.stencilOpStencilDepthPass = operation;
  8598. };
  8599. /**
  8600. * stop executing a render loop function and remove it from the execution array
  8601. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  8602. */
  8603. Engine.prototype.stopRenderLoop = function (renderFunction) {
  8604. if (!renderFunction) {
  8605. this._activeRenderLoops = [];
  8606. return;
  8607. }
  8608. var index = this._activeRenderLoops.indexOf(renderFunction);
  8609. if (index >= 0) {
  8610. this._activeRenderLoops.splice(index, 1);
  8611. }
  8612. };
  8613. Engine.prototype._renderLoop = function () {
  8614. var shouldRender = true;
  8615. if (!this.renderEvenInBackground && this._windowIsBackground) {
  8616. shouldRender = false;
  8617. }
  8618. if (shouldRender) {
  8619. // Start new frame
  8620. this.beginFrame();
  8621. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  8622. var renderFunction = this._activeRenderLoops[index];
  8623. renderFunction();
  8624. }
  8625. // Present
  8626. this.endFrame();
  8627. }
  8628. if (this._activeRenderLoops.length > 0) {
  8629. // Register new frame
  8630. BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction, this._vrDisplayEnabled);
  8631. }
  8632. else {
  8633. this._renderingQueueLaunched = false;
  8634. }
  8635. };
  8636. /**
  8637. * Register and execute a render loop. The engine can have more than one render function.
  8638. * @param {Function} renderFunction - the function to continuously execute starting the next render loop.
  8639. * @example
  8640. * engine.runRenderLoop(function () {
  8641. * scene.render()
  8642. * })
  8643. */
  8644. Engine.prototype.runRenderLoop = function (renderFunction) {
  8645. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  8646. return;
  8647. }
  8648. this._activeRenderLoops.push(renderFunction);
  8649. if (!this._renderingQueueLaunched) {
  8650. this._renderingQueueLaunched = true;
  8651. this._bindedRenderFunction = this._renderLoop.bind(this);
  8652. BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  8653. }
  8654. };
  8655. /**
  8656. * Toggle full screen mode.
  8657. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  8658. * @param {any} options - an options object to be sent to the requestFullscreen function
  8659. */
  8660. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  8661. if (this.isFullscreen) {
  8662. BABYLON.Tools.ExitFullscreen();
  8663. }
  8664. else {
  8665. this._pointerLockRequested = requestPointerLock;
  8666. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  8667. }
  8668. };
  8669. Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
  8670. if (stencil === void 0) { stencil = false; }
  8671. this.applyStates();
  8672. var mode = 0;
  8673. if (backBuffer && color) {
  8674. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  8675. mode |= this._gl.COLOR_BUFFER_BIT;
  8676. }
  8677. if (depth) {
  8678. this._gl.clearDepth(1.0);
  8679. mode |= this._gl.DEPTH_BUFFER_BIT;
  8680. }
  8681. if (stencil) {
  8682. this._gl.clearStencil(0);
  8683. mode |= this._gl.STENCIL_BUFFER_BIT;
  8684. }
  8685. this._gl.clear(mode);
  8686. };
  8687. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  8688. var gl = this._gl;
  8689. // Save state
  8690. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  8691. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  8692. // Change state
  8693. gl.enable(gl.SCISSOR_TEST);
  8694. gl.scissor(x, y, width, height);
  8695. // Clear
  8696. this.clear(clearColor, true, true, true);
  8697. // Restore state
  8698. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  8699. if (curScissor === true) {
  8700. gl.enable(gl.SCISSOR_TEST);
  8701. }
  8702. else {
  8703. gl.disable(gl.SCISSOR_TEST);
  8704. }
  8705. };
  8706. /**
  8707. * Set the WebGL's viewport
  8708. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  8709. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  8710. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  8711. */
  8712. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  8713. var width = requiredWidth || (navigator.isCocoonJS ? window.innerWidth : this.getRenderWidth());
  8714. var height = requiredHeight || (navigator.isCocoonJS ? window.innerHeight : this.getRenderHeight());
  8715. var x = viewport.x || 0;
  8716. var y = viewport.y || 0;
  8717. this._cachedViewport = viewport;
  8718. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  8719. };
  8720. /**
  8721. * Directly set the WebGL Viewport
  8722. * The x, y, width & height are directly passed to the WebGL call
  8723. * @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.
  8724. */
  8725. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  8726. var currentViewport = this._cachedViewport;
  8727. this._cachedViewport = null;
  8728. this._gl.viewport(x, y, width, height);
  8729. return currentViewport;
  8730. };
  8731. Engine.prototype.beginFrame = function () {
  8732. this._measureFps();
  8733. };
  8734. Engine.prototype.endFrame = function () {
  8735. //force a flush in case we are using a bad OS.
  8736. if (this._badOS) {
  8737. this.flushFramebuffer();
  8738. }
  8739. //submit frame to the vr device, if enabled
  8740. if (this._vrDisplayEnabled && this._vrDisplayEnabled.isPresenting) {
  8741. this._vrDisplayEnabled.submitFrame();
  8742. }
  8743. };
  8744. /**
  8745. * resize the view according to the canvas' size.
  8746. * @example
  8747. * window.addEventListener("resize", function () {
  8748. * engine.resize();
  8749. * });
  8750. */
  8751. Engine.prototype.resize = function () {
  8752. // We're not resizing the size of the canvas while in VR mode & presenting
  8753. if (!(this._vrDisplayEnabled && this._vrDisplayEnabled.isPresenting)) {
  8754. var width = navigator.isCocoonJS ? window.innerWidth : this._renderingCanvas.clientWidth;
  8755. var height = navigator.isCocoonJS ? window.innerHeight : this._renderingCanvas.clientHeight;
  8756. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  8757. }
  8758. };
  8759. /**
  8760. * force a specific size of the canvas
  8761. * @param {number} width - the new canvas' width
  8762. * @param {number} height - the new canvas' height
  8763. */
  8764. Engine.prototype.setSize = function (width, height) {
  8765. this._renderingCanvas.width = width;
  8766. this._renderingCanvas.height = height;
  8767. for (var index = 0; index < this.scenes.length; index++) {
  8768. var scene = this.scenes[index];
  8769. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  8770. var cam = scene.cameras[camIndex];
  8771. cam._currentRenderId = 0;
  8772. }
  8773. }
  8774. };
  8775. //WebVR functions
  8776. Engine.prototype.initWebVR = function () {
  8777. if (!this.vrDisplaysPromise) {
  8778. this._getVRDisplays();
  8779. }
  8780. };
  8781. Engine.prototype.enableVR = function (vrDevice) {
  8782. this._vrDisplayEnabled = vrDevice;
  8783. this._vrDisplayEnabled.requestPresent([{ source: this.getRenderingCanvas() }]).then(this._onVRFullScreenTriggered);
  8784. };
  8785. Engine.prototype.disableVR = function () {
  8786. if (this._vrDisplayEnabled) {
  8787. this._vrDisplayEnabled.exitPresent().then(this._onVRFullScreenTriggered);
  8788. }
  8789. };
  8790. Engine.prototype._getVRDisplays = function () {
  8791. var _this = this;
  8792. var getWebVRDevices = function (devices) {
  8793. var size = devices.length;
  8794. var i = 0;
  8795. _this._vrDisplays = devices.filter(function (device) {
  8796. return devices[i] instanceof VRDisplay;
  8797. });
  8798. return _this._vrDisplays;
  8799. };
  8800. //using a key due to typescript
  8801. if (navigator.getVRDisplays) {
  8802. this.vrDisplaysPromise = navigator.getVRDisplays().then(getWebVRDevices);
  8803. }
  8804. };
  8805. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight) {
  8806. this._currentRenderTarget = texture;
  8807. this.bindUnboundFramebuffer(texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer);
  8808. var gl = this._gl;
  8809. if (texture.isCube) {
  8810. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture, 0);
  8811. }
  8812. gl.viewport(0, 0, requiredWidth || texture._width, requiredHeight || texture._height);
  8813. this.wipeCaches();
  8814. };
  8815. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  8816. if (this._currentFramebuffer !== framebuffer) {
  8817. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  8818. this._currentFramebuffer = framebuffer;
  8819. }
  8820. };
  8821. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  8822. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  8823. this._currentRenderTarget = null;
  8824. // If MSAA, we need to bitblt back to main texture
  8825. var gl = this._gl;
  8826. if (texture._MSAAFramebuffer) {
  8827. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, texture._MSAAFramebuffer);
  8828. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, texture._framebuffer);
  8829. gl.blitFramebuffer(0, 0, texture._width, texture._height, 0, 0, texture._width, texture._height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  8830. }
  8831. if (texture.generateMipMaps && !disableGenerateMipMaps) {
  8832. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  8833. gl.generateMipmap(gl.TEXTURE_2D);
  8834. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  8835. }
  8836. if (onBeforeUnbind) {
  8837. if (texture._MSAAFramebuffer) {
  8838. // Bind the correct framebuffer
  8839. this.bindUnboundFramebuffer(texture._framebuffer);
  8840. }
  8841. onBeforeUnbind();
  8842. }
  8843. this.bindUnboundFramebuffer(null);
  8844. };
  8845. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  8846. if (texture.generateMipMaps) {
  8847. var gl = this._gl;
  8848. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  8849. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  8850. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  8851. }
  8852. };
  8853. Engine.prototype.flushFramebuffer = function () {
  8854. this._gl.flush();
  8855. };
  8856. Engine.prototype.restoreDefaultFramebuffer = function () {
  8857. this._currentRenderTarget = null;
  8858. this.bindUnboundFramebuffer(null);
  8859. this.setViewport(this._cachedViewport);
  8860. this.wipeCaches();
  8861. };
  8862. // VBOs
  8863. Engine.prototype._resetVertexBufferBinding = function () {
  8864. this.bindArrayBuffer(null);
  8865. this._cachedVertexBuffers = null;
  8866. };
  8867. Engine.prototype.createVertexBuffer = function (vertices) {
  8868. var vbo = this._gl.createBuffer();
  8869. this.bindArrayBuffer(vbo);
  8870. if (vertices instanceof Float32Array) {
  8871. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.STATIC_DRAW);
  8872. }
  8873. else {
  8874. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  8875. }
  8876. this._resetVertexBufferBinding();
  8877. vbo.references = 1;
  8878. return vbo;
  8879. };
  8880. Engine.prototype.createDynamicVertexBuffer = function (vertices) {
  8881. var vbo = this._gl.createBuffer();
  8882. this.bindArrayBuffer(vbo);
  8883. if (vertices instanceof Float32Array) {
  8884. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.DYNAMIC_DRAW);
  8885. }
  8886. else {
  8887. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.DYNAMIC_DRAW);
  8888. }
  8889. this._resetVertexBufferBinding();
  8890. vbo.references = 1;
  8891. return vbo;
  8892. };
  8893. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset, count) {
  8894. this.bindArrayBuffer(vertexBuffer);
  8895. if (offset === undefined) {
  8896. offset = 0;
  8897. }
  8898. if (count === undefined) {
  8899. if (vertices instanceof Float32Array) {
  8900. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  8901. }
  8902. else {
  8903. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  8904. }
  8905. }
  8906. else {
  8907. if (vertices instanceof Float32Array) {
  8908. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, vertices.subarray(offset, offset + count));
  8909. }
  8910. else {
  8911. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(vertices).subarray(offset, offset + count));
  8912. }
  8913. }
  8914. this._resetVertexBufferBinding();
  8915. };
  8916. Engine.prototype._resetIndexBufferBinding = function () {
  8917. this.bindIndexBuffer(null);
  8918. this._cachedIndexBuffer = null;
  8919. };
  8920. Engine.prototype.createIndexBuffer = function (indices) {
  8921. var vbo = this._gl.createBuffer();
  8922. this.bindIndexBuffer(vbo);
  8923. // Check for 32 bits indices
  8924. var arrayBuffer;
  8925. var need32Bits = false;
  8926. if (indices instanceof Uint16Array) {
  8927. arrayBuffer = indices;
  8928. }
  8929. else {
  8930. //check 32 bit support
  8931. if (this._caps.uintIndices) {
  8932. if (indices instanceof Uint32Array) {
  8933. arrayBuffer = indices;
  8934. need32Bits = true;
  8935. }
  8936. else {
  8937. //number[] or Int32Array, check if 32 bit is necessary
  8938. for (var index = 0; index < indices.length; index++) {
  8939. if (indices[index] > 65535) {
  8940. need32Bits = true;
  8941. break;
  8942. }
  8943. }
  8944. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  8945. }
  8946. }
  8947. else {
  8948. //no 32 bit support, force conversion to 16 bit (values greater 16 bit are lost)
  8949. arrayBuffer = new Uint16Array(indices);
  8950. }
  8951. }
  8952. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.STATIC_DRAW);
  8953. this._resetIndexBufferBinding();
  8954. vbo.references = 1;
  8955. vbo.is32Bits = need32Bits;
  8956. return vbo;
  8957. };
  8958. Engine.prototype.bindArrayBuffer = function (buffer) {
  8959. if (!this._vaoRecordInProgress) {
  8960. this._unBindVertexArrayObject();
  8961. }
  8962. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  8963. };
  8964. Engine.prototype.bindIndexBuffer = function (buffer) {
  8965. if (!this._vaoRecordInProgress) {
  8966. this._unBindVertexArrayObject();
  8967. }
  8968. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  8969. };
  8970. Engine.prototype.bindBuffer = function (buffer, target) {
  8971. if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
  8972. this._gl.bindBuffer(target, buffer);
  8973. this._currentBoundBuffer[target] = buffer;
  8974. }
  8975. };
  8976. Engine.prototype.updateArrayBuffer = function (data) {
  8977. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  8978. };
  8979. Engine.prototype.vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  8980. var pointer = this._currentBufferPointers[indx];
  8981. var changed = false;
  8982. if (!pointer) {
  8983. changed = true;
  8984. this._currentBufferPointers[indx] = { indx: indx, size: size, type: type, normalized: normalized, stride: stride, offset: offset, buffer: buffer };
  8985. }
  8986. else {
  8987. if (pointer.buffer !== buffer) {
  8988. pointer.buffer = buffer;
  8989. changed = true;
  8990. }
  8991. if (pointer.size !== size) {
  8992. pointer.size = size;
  8993. changed = true;
  8994. }
  8995. if (pointer.type !== type) {
  8996. pointer.type = type;
  8997. changed = true;
  8998. }
  8999. if (pointer.normalized !== normalized) {
  9000. pointer.normalized = normalized;
  9001. changed = true;
  9002. }
  9003. if (pointer.stride !== stride) {
  9004. pointer.stride = stride;
  9005. changed = true;
  9006. }
  9007. if (pointer.offset !== offset) {
  9008. pointer.offset = offset;
  9009. changed = true;
  9010. }
  9011. }
  9012. if (changed || this._vaoRecordInProgress) {
  9013. this.bindArrayBuffer(buffer);
  9014. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  9015. }
  9016. };
  9017. Engine.prototype._bindIndexBufferWithCache = function (indexBuffer) {
  9018. if (indexBuffer == null) {
  9019. return;
  9020. }
  9021. if (this._cachedIndexBuffer !== indexBuffer) {
  9022. this._cachedIndexBuffer = indexBuffer;
  9023. this.bindIndexBuffer(indexBuffer);
  9024. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  9025. }
  9026. };
  9027. Engine.prototype._bindVertexBuffersAttributes = function (vertexBuffers, effect) {
  9028. var attributes = effect.getAttributesNames();
  9029. if (!this._vaoRecordInProgress) {
  9030. this._unBindVertexArrayObject();
  9031. }
  9032. this.unbindAllAttributes();
  9033. for (var index = 0; index < attributes.length; index++) {
  9034. var order = effect.getAttributeLocation(index);
  9035. if (order >= 0) {
  9036. var vertexBuffer = vertexBuffers[attributes[index]];
  9037. if (!vertexBuffer) {
  9038. continue;
  9039. }
  9040. this._gl.enableVertexAttribArray(order);
  9041. if (!this._vaoRecordInProgress) {
  9042. this._vertexAttribArraysEnabled[order] = true;
  9043. }
  9044. var buffer = vertexBuffer.getBuffer();
  9045. this.vertexAttribPointer(buffer, order, vertexBuffer.getSize(), this._gl.FLOAT, false, vertexBuffer.getStrideSize() * 4, vertexBuffer.getOffset() * 4);
  9046. if (vertexBuffer.getIsInstanced()) {
  9047. this._gl.vertexAttribDivisor(order, 1);
  9048. if (!this._vaoRecordInProgress) {
  9049. this._currentInstanceLocations.push(order);
  9050. this._currentInstanceBuffers.push(buffer);
  9051. }
  9052. }
  9053. }
  9054. }
  9055. };
  9056. Engine.prototype.recordVertexArrayObject = function (vertexBuffers, indexBuffer, effect) {
  9057. var vao = this._gl.createVertexArray();
  9058. this._vaoRecordInProgress = true;
  9059. this._gl.bindVertexArray(vao);
  9060. this._mustWipeVertexAttributes = true;
  9061. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  9062. this.bindIndexBuffer(indexBuffer);
  9063. this._vaoRecordInProgress = false;
  9064. this._gl.bindVertexArray(null);
  9065. return vao;
  9066. };
  9067. Engine.prototype.bindVertexArrayObject = function (vertexArrayObject, indexBuffer) {
  9068. if (this._cachedVertexArrayObject !== vertexArrayObject) {
  9069. this._cachedVertexArrayObject = vertexArrayObject;
  9070. this._gl.bindVertexArray(vertexArrayObject);
  9071. this._cachedVertexBuffers = null;
  9072. this._cachedIndexBuffer = null;
  9073. this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
  9074. this._mustWipeVertexAttributes = true;
  9075. }
  9076. };
  9077. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  9078. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  9079. this._cachedVertexBuffers = vertexBuffer;
  9080. this._cachedEffectForVertexBuffers = effect;
  9081. var attributesCount = effect.getAttributesCount();
  9082. this._unBindVertexArrayObject();
  9083. this.unbindAllAttributes();
  9084. var offset = 0;
  9085. for (var index = 0; index < attributesCount; index++) {
  9086. if (index < vertexDeclaration.length) {
  9087. var order = effect.getAttributeLocation(index);
  9088. if (order >= 0) {
  9089. this._gl.enableVertexAttribArray(order);
  9090. this._vertexAttribArraysEnabled[order] = true;
  9091. this.vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  9092. }
  9093. offset += vertexDeclaration[index] * 4;
  9094. }
  9095. }
  9096. }
  9097. this._bindIndexBufferWithCache(indexBuffer);
  9098. };
  9099. Engine.prototype._unBindVertexArrayObject = function () {
  9100. if (!this._cachedVertexArrayObject) {
  9101. return;
  9102. }
  9103. this._cachedVertexArrayObject = null;
  9104. this._gl.bindVertexArray(null);
  9105. };
  9106. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  9107. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  9108. this._cachedVertexBuffers = vertexBuffers;
  9109. this._cachedEffectForVertexBuffers = effect;
  9110. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  9111. }
  9112. this._bindIndexBufferWithCache(indexBuffer);
  9113. };
  9114. Engine.prototype.unbindInstanceAttributes = function () {
  9115. var boundBuffer;
  9116. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  9117. var instancesBuffer = this._currentInstanceBuffers[i];
  9118. if (boundBuffer != instancesBuffer) {
  9119. boundBuffer = instancesBuffer;
  9120. this.bindArrayBuffer(instancesBuffer);
  9121. }
  9122. var offsetLocation = this._currentInstanceLocations[i];
  9123. this._gl.vertexAttribDivisor(offsetLocation, 0);
  9124. }
  9125. this._currentInstanceBuffers.length = 0;
  9126. this._currentInstanceLocations.length = 0;
  9127. };
  9128. Engine.prototype.releaseVertexArrayObject = function (vao) {
  9129. this._gl.deleteVertexArray(vao);
  9130. };
  9131. Engine.prototype._releaseBuffer = function (buffer) {
  9132. buffer.references--;
  9133. if (buffer.references === 0) {
  9134. this._gl.deleteBuffer(buffer);
  9135. return true;
  9136. }
  9137. return false;
  9138. };
  9139. Engine.prototype.createInstancesBuffer = function (capacity) {
  9140. var buffer = this._gl.createBuffer();
  9141. buffer.capacity = capacity;
  9142. this.bindArrayBuffer(buffer);
  9143. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  9144. return buffer;
  9145. };
  9146. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  9147. this._gl.deleteBuffer(buffer);
  9148. };
  9149. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  9150. this.bindArrayBuffer(instancesBuffer);
  9151. if (data) {
  9152. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  9153. }
  9154. if (offsetLocations[0].index !== undefined) {
  9155. var stride = 0;
  9156. for (var i = 0; i < offsetLocations.length; i++) {
  9157. var ai = offsetLocations[i];
  9158. stride += ai.attributeSize * 4;
  9159. }
  9160. for (var i = 0; i < offsetLocations.length; i++) {
  9161. var ai = offsetLocations[i];
  9162. if (!this._vertexAttribArraysEnabled[ai.index]) {
  9163. this._gl.enableVertexAttribArray(ai.index);
  9164. this._vertexAttribArraysEnabled[ai.index] = true;
  9165. }
  9166. this.vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  9167. this._gl.vertexAttribDivisor(ai.index, 1);
  9168. this._currentInstanceLocations.push(ai.index);
  9169. this._currentInstanceBuffers.push(instancesBuffer);
  9170. }
  9171. }
  9172. else {
  9173. for (var index = 0; index < 4; index++) {
  9174. var offsetLocation = offsetLocations[index];
  9175. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  9176. this._gl.enableVertexAttribArray(offsetLocation);
  9177. this._vertexAttribArraysEnabled[offsetLocation] = true;
  9178. }
  9179. this.vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  9180. this._gl.vertexAttribDivisor(offsetLocation, 1);
  9181. this._currentInstanceLocations.push(offsetLocation);
  9182. this._currentInstanceBuffers.push(instancesBuffer);
  9183. }
  9184. }
  9185. };
  9186. Engine.prototype.applyStates = function () {
  9187. this._depthCullingState.apply(this._gl);
  9188. this._stencilState.apply(this._gl);
  9189. this._alphaState.apply(this._gl);
  9190. };
  9191. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  9192. // Apply states
  9193. this.applyStates();
  9194. this._drawCalls.addCount(1, false);
  9195. // Render
  9196. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  9197. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  9198. if (instancesCount) {
  9199. this._gl.drawElementsInstanced(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult, instancesCount);
  9200. return;
  9201. }
  9202. this._gl.drawElements(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult);
  9203. };
  9204. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  9205. // Apply states
  9206. this.applyStates();
  9207. this._drawCalls.addCount(1, false);
  9208. if (instancesCount) {
  9209. this._gl.drawArraysInstanced(this._gl.POINTS, verticesStart, verticesCount, instancesCount);
  9210. return;
  9211. }
  9212. this._gl.drawArrays(this._gl.POINTS, verticesStart, verticesCount);
  9213. };
  9214. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  9215. // Apply states
  9216. this.applyStates();
  9217. this._drawCalls.addCount(1, false);
  9218. if (instancesCount) {
  9219. this._gl.drawArraysInstanced(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount, instancesCount);
  9220. return;
  9221. }
  9222. this._gl.drawArrays(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount);
  9223. };
  9224. // Shaders
  9225. Engine.prototype._releaseEffect = function (effect) {
  9226. if (this._compiledEffects[effect._key]) {
  9227. delete this._compiledEffects[effect._key];
  9228. if (effect.getProgram()) {
  9229. this._gl.deleteProgram(effect.getProgram());
  9230. }
  9231. }
  9232. };
  9233. Engine.prototype.createEffect = function (baseName, attributesNames, uniformsNames, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  9234. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  9235. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  9236. var name = vertex + "+" + fragment + "@" + defines;
  9237. if (this._compiledEffects[name]) {
  9238. return this._compiledEffects[name];
  9239. }
  9240. var effect = new BABYLON.Effect(baseName, attributesNames, uniformsNames, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  9241. effect._key = name;
  9242. this._compiledEffects[name] = effect;
  9243. return effect;
  9244. };
  9245. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  9246. if (uniformsNames === void 0) { uniformsNames = []; }
  9247. if (samplers === void 0) { samplers = []; }
  9248. if (defines === void 0) { defines = ""; }
  9249. return this.createEffect({
  9250. vertex: "particles",
  9251. fragmentElement: fragmentName
  9252. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  9253. };
  9254. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context) {
  9255. context = context || this._gl;
  9256. var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n" : "";
  9257. var vertexShader = compileShader(context, vertexCode, "vertex", defines, shaderVersion);
  9258. var fragmentShader = compileShader(context, fragmentCode, "fragment", defines, shaderVersion);
  9259. var shaderProgram = context.createProgram();
  9260. context.attachShader(shaderProgram, vertexShader);
  9261. context.attachShader(shaderProgram, fragmentShader);
  9262. context.linkProgram(shaderProgram);
  9263. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  9264. if (!linked) {
  9265. var error = context.getProgramInfoLog(shaderProgram);
  9266. if (error) {
  9267. throw new Error(error);
  9268. }
  9269. }
  9270. context.deleteShader(vertexShader);
  9271. context.deleteShader(fragmentShader);
  9272. return shaderProgram;
  9273. };
  9274. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  9275. var results = [];
  9276. for (var index = 0; index < uniformsNames.length; index++) {
  9277. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  9278. }
  9279. return results;
  9280. };
  9281. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  9282. var results = [];
  9283. for (var index = 0; index < attributesNames.length; index++) {
  9284. try {
  9285. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  9286. }
  9287. catch (e) {
  9288. results.push(-1);
  9289. }
  9290. }
  9291. return results;
  9292. };
  9293. Engine.prototype.enableEffect = function (effect) {
  9294. // Use program
  9295. this.setProgram(effect.getProgram());
  9296. this._currentEffect = effect;
  9297. if (effect.onBind) {
  9298. effect.onBind(effect);
  9299. }
  9300. };
  9301. Engine.prototype.setIntArray = function (uniform, array) {
  9302. if (!uniform)
  9303. return;
  9304. this._gl.uniform1iv(uniform, array);
  9305. };
  9306. Engine.prototype.setIntArray2 = function (uniform, array) {
  9307. if (!uniform || array.length % 2 !== 0)
  9308. return;
  9309. this._gl.uniform2iv(uniform, array);
  9310. };
  9311. Engine.prototype.setIntArray3 = function (uniform, array) {
  9312. if (!uniform || array.length % 3 !== 0)
  9313. return;
  9314. this._gl.uniform3iv(uniform, array);
  9315. };
  9316. Engine.prototype.setIntArray4 = function (uniform, array) {
  9317. if (!uniform || array.length % 4 !== 0)
  9318. return;
  9319. this._gl.uniform4iv(uniform, array);
  9320. };
  9321. Engine.prototype.setFloatArray = function (uniform, array) {
  9322. if (!uniform)
  9323. return;
  9324. this._gl.uniform1fv(uniform, array);
  9325. };
  9326. Engine.prototype.setFloatArray2 = function (uniform, array) {
  9327. if (!uniform || array.length % 2 !== 0)
  9328. return;
  9329. this._gl.uniform2fv(uniform, array);
  9330. };
  9331. Engine.prototype.setFloatArray3 = function (uniform, array) {
  9332. if (!uniform || array.length % 3 !== 0)
  9333. return;
  9334. this._gl.uniform3fv(uniform, array);
  9335. };
  9336. Engine.prototype.setFloatArray4 = function (uniform, array) {
  9337. if (!uniform || array.length % 4 !== 0)
  9338. return;
  9339. this._gl.uniform4fv(uniform, array);
  9340. };
  9341. Engine.prototype.setArray = function (uniform, array) {
  9342. if (!uniform)
  9343. return;
  9344. this._gl.uniform1fv(uniform, array);
  9345. };
  9346. Engine.prototype.setArray2 = function (uniform, array) {
  9347. if (!uniform || array.length % 2 !== 0)
  9348. return;
  9349. this._gl.uniform2fv(uniform, array);
  9350. };
  9351. Engine.prototype.setArray3 = function (uniform, array) {
  9352. if (!uniform || array.length % 3 !== 0)
  9353. return;
  9354. this._gl.uniform3fv(uniform, array);
  9355. };
  9356. Engine.prototype.setArray4 = function (uniform, array) {
  9357. if (!uniform || array.length % 4 !== 0)
  9358. return;
  9359. this._gl.uniform4fv(uniform, array);
  9360. };
  9361. Engine.prototype.setMatrices = function (uniform, matrices) {
  9362. if (!uniform)
  9363. return;
  9364. this._gl.uniformMatrix4fv(uniform, false, matrices);
  9365. };
  9366. Engine.prototype.setMatrix = function (uniform, matrix) {
  9367. if (!uniform)
  9368. return;
  9369. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  9370. };
  9371. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  9372. if (!uniform)
  9373. return;
  9374. this._gl.uniformMatrix3fv(uniform, false, matrix);
  9375. };
  9376. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  9377. if (!uniform)
  9378. return;
  9379. this._gl.uniformMatrix2fv(uniform, false, matrix);
  9380. };
  9381. Engine.prototype.setFloat = function (uniform, value) {
  9382. if (!uniform)
  9383. return;
  9384. this._gl.uniform1f(uniform, value);
  9385. };
  9386. Engine.prototype.setFloat2 = function (uniform, x, y) {
  9387. if (!uniform)
  9388. return;
  9389. this._gl.uniform2f(uniform, x, y);
  9390. };
  9391. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  9392. if (!uniform)
  9393. return;
  9394. this._gl.uniform3f(uniform, x, y, z);
  9395. };
  9396. Engine.prototype.setBool = function (uniform, bool) {
  9397. if (!uniform)
  9398. return;
  9399. this._gl.uniform1i(uniform, bool);
  9400. };
  9401. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  9402. if (!uniform)
  9403. return;
  9404. this._gl.uniform4f(uniform, x, y, z, w);
  9405. };
  9406. Engine.prototype.setColor3 = function (uniform, color3) {
  9407. if (!uniform)
  9408. return;
  9409. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  9410. };
  9411. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  9412. if (!uniform)
  9413. return;
  9414. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  9415. };
  9416. // States
  9417. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  9418. if (zOffset === void 0) { zOffset = 0; }
  9419. if (reverseSide === void 0) { reverseSide = false; }
  9420. // Culling
  9421. var showSide = reverseSide ? this._gl.FRONT : this._gl.BACK;
  9422. var hideSide = reverseSide ? this._gl.BACK : this._gl.FRONT;
  9423. var cullFace = this.cullBackFaces ? showSide : hideSide;
  9424. if (this._depthCullingState.cull !== culling || force || this._depthCullingState.cullFace !== cullFace) {
  9425. if (culling) {
  9426. this._depthCullingState.cullFace = cullFace;
  9427. this._depthCullingState.cull = true;
  9428. }
  9429. else {
  9430. this._depthCullingState.cull = false;
  9431. }
  9432. }
  9433. // Z offset
  9434. this._depthCullingState.zOffset = zOffset;
  9435. };
  9436. Engine.prototype.setDepthBuffer = function (enable) {
  9437. this._depthCullingState.depthTest = enable;
  9438. };
  9439. Engine.prototype.getDepthWrite = function () {
  9440. return this._depthCullingState.depthMask;
  9441. };
  9442. Engine.prototype.setDepthWrite = function (enable) {
  9443. this._depthCullingState.depthMask = enable;
  9444. };
  9445. Engine.prototype.setColorWrite = function (enable) {
  9446. this._gl.colorMask(enable, enable, enable, enable);
  9447. };
  9448. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  9449. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  9450. if (this._alphaMode === mode) {
  9451. return;
  9452. }
  9453. switch (mode) {
  9454. case Engine.ALPHA_DISABLE:
  9455. this._alphaState.alphaBlend = false;
  9456. break;
  9457. case Engine.ALPHA_PREMULTIPLIED:
  9458. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  9459. this._alphaState.alphaBlend = true;
  9460. break;
  9461. case Engine.ALPHA_COMBINE:
  9462. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  9463. this._alphaState.alphaBlend = true;
  9464. break;
  9465. case Engine.ALPHA_ONEONE:
  9466. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  9467. this._alphaState.alphaBlend = true;
  9468. break;
  9469. case Engine.ALPHA_ADD:
  9470. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  9471. this._alphaState.alphaBlend = true;
  9472. break;
  9473. case Engine.ALPHA_SUBTRACT:
  9474. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  9475. this._alphaState.alphaBlend = true;
  9476. break;
  9477. case Engine.ALPHA_MULTIPLY:
  9478. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  9479. this._alphaState.alphaBlend = true;
  9480. break;
  9481. case Engine.ALPHA_MAXIMIZED:
  9482. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  9483. this._alphaState.alphaBlend = true;
  9484. break;
  9485. }
  9486. if (!noDepthWriteChange) {
  9487. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  9488. }
  9489. this._alphaMode = mode;
  9490. };
  9491. Engine.prototype.getAlphaMode = function () {
  9492. return this._alphaMode;
  9493. };
  9494. Engine.prototype.setAlphaTesting = function (enable) {
  9495. this._alphaTest = enable;
  9496. };
  9497. Engine.prototype.getAlphaTesting = function () {
  9498. return this._alphaTest;
  9499. };
  9500. // Textures
  9501. Engine.prototype.wipeCaches = function () {
  9502. if (this.preventCacheWipeBetweenFrames) {
  9503. return;
  9504. }
  9505. this.resetTextureCache();
  9506. this._currentEffect = null;
  9507. this._stencilState.reset();
  9508. this._depthCullingState.reset();
  9509. this.setDepthFunctionToLessOrEqual();
  9510. this._alphaState.reset();
  9511. this._cachedVertexBuffers = null;
  9512. this._cachedIndexBuffer = null;
  9513. this._cachedEffectForVertexBuffers = null;
  9514. this._unBindVertexArrayObject();
  9515. this.bindIndexBuffer(null);
  9516. this.bindArrayBuffer(null);
  9517. };
  9518. /**
  9519. * Set the compressed texture format to use, based on the formats you have, and the formats
  9520. * supported by the hardware / browser.
  9521. *
  9522. * Khronos Texture Container (.ktx) files are used to support this. This format has the
  9523. * advantage of being specifically designed for OpenGL. Header elements directly correspond
  9524. * to API arguments needed to compressed textures. This puts the burden on the container
  9525. * generator to house the arcane code for determining these for current & future formats.
  9526. *
  9527. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  9528. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  9529. *
  9530. * Note: The result of this call is not taken into account when a texture is base64.
  9531. *
  9532. * @param {Array<string>} formatsAvailable- The list of those format families you have created
  9533. * on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.)
  9534. *
  9535. * Current families are astc, dxt, pvrtc, etc2, atc, & etc1.
  9536. * @returns The extension selected.
  9537. */
  9538. Engine.prototype.setTextureFormatToUse = function (formatsAvailable) {
  9539. for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
  9540. for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
  9541. if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
  9542. return this._textureFormatInUse = this._texturesSupported[i];
  9543. }
  9544. }
  9545. }
  9546. // actively set format to nothing, to allow this to be called more than once
  9547. // and possibly fail the 2nd time
  9548. return this._textureFormatInUse = null;
  9549. };
  9550. Engine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  9551. var _this = this;
  9552. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  9553. if (onLoad === void 0) { onLoad = null; }
  9554. if (onError === void 0) { onError = null; }
  9555. if (buffer === void 0) { buffer = null; }
  9556. var texture = fallBack ? fallBack : this._gl.createTexture();
  9557. var extension;
  9558. var isKTX = false;
  9559. var fromData = false;
  9560. var url = String(urlArg);
  9561. if (url.substr(0, 5) === "data:") {
  9562. fromData = true;
  9563. }
  9564. if (!fromData) {
  9565. var lastDot = url.lastIndexOf('.');
  9566. extension = url.substring(lastDot).toLowerCase();
  9567. if (this._textureFormatInUse && !fromData && !fallBack) {
  9568. extension = this._textureFormatInUse;
  9569. url = url.substring(0, lastDot) + this._textureFormatInUse;
  9570. isKTX = true;
  9571. }
  9572. }
  9573. else {
  9574. var oldUrl = url;
  9575. fromData = oldUrl.split(':');
  9576. url = oldUrl;
  9577. extension = fromData[1].substr(fromData[1].length - 4, 4).toLowerCase();
  9578. }
  9579. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  9580. var isTGA = (extension === ".tga");
  9581. scene._addPendingData(texture);
  9582. texture.url = url;
  9583. texture.noMipmap = noMipmap;
  9584. texture.references = 1;
  9585. texture.samplingMode = samplingMode;
  9586. texture.onLoadedCallbacks = [];
  9587. if (onLoad) {
  9588. texture.onLoadedCallbacks.push(onLoad);
  9589. }
  9590. if (!fallBack)
  9591. this._loadedTexturesCache.push(texture);
  9592. var onerror = function () {
  9593. scene._removePendingData(texture);
  9594. // fallback for when compressed file not found to try again. For instance, etc1 does not have an alpha capable type
  9595. if (isKTX) {
  9596. _this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, texture);
  9597. }
  9598. else if (onError) {
  9599. onError();
  9600. }
  9601. };
  9602. var callback;
  9603. if (isKTX || isTGA || isDDS) {
  9604. if (isKTX) {
  9605. callback = function (data) {
  9606. var ktx = new BABYLON.Internals.KhronosTextureContainer(data, 1);
  9607. prepareWebGLTexture(texture, _this._gl, scene, ktx.pixelWidth, ktx.pixelHeight, invertY, false, true, function () {
  9608. ktx.uploadLevels(_this._gl, !noMipmap);
  9609. }, samplingMode);
  9610. };
  9611. }
  9612. else if (isTGA) {
  9613. callback = function (arrayBuffer) {
  9614. var data = new Uint8Array(arrayBuffer);
  9615. var header = BABYLON.Internals.TGATools.GetTGAHeader(data);
  9616. prepareWebGLTexture(texture, _this._gl, scene, header.width, header.height, invertY, noMipmap, false, function () {
  9617. BABYLON.Internals.TGATools.UploadContent(_this._gl, data);
  9618. }, samplingMode);
  9619. };
  9620. }
  9621. else if (isDDS) {
  9622. callback = function (data) {
  9623. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  9624. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  9625. prepareWebGLTexture(texture, _this._gl, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  9626. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 1);
  9627. }, samplingMode);
  9628. };
  9629. }
  9630. if (!(fromData instanceof Array))
  9631. BABYLON.Tools.LoadFile(url, function (data) {
  9632. callback(data);
  9633. }, null, scene.database, true, onerror);
  9634. else
  9635. callback(buffer);
  9636. }
  9637. else {
  9638. var onload = function (img) {
  9639. prepareWebGLTexture(texture, _this._gl, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight) {
  9640. var isPot = (img.width === potWidth && img.height === potHeight);
  9641. if (!isPot) {
  9642. _this._prepareWorkingCanvas();
  9643. _this._workingCanvas.width = potWidth;
  9644. _this._workingCanvas.height = potHeight;
  9645. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  9646. _this._workingContext.imageSmoothingEnabled = false;
  9647. _this._workingContext.mozImageSmoothingEnabled = false;
  9648. _this._workingContext.oImageSmoothingEnabled = false;
  9649. _this._workingContext.webkitImageSmoothingEnabled = false;
  9650. _this._workingContext.msImageSmoothingEnabled = false;
  9651. }
  9652. _this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  9653. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  9654. _this._workingContext.imageSmoothingEnabled = true;
  9655. _this._workingContext.mozImageSmoothingEnabled = true;
  9656. _this._workingContext.oImageSmoothingEnabled = true;
  9657. _this._workingContext.webkitImageSmoothingEnabled = true;
  9658. _this._workingContext.msImageSmoothingEnabled = true;
  9659. }
  9660. }
  9661. var internalFormat = format ? _this._getInternalFormat(format) : _this._gl.RGBA;
  9662. _this._gl.texImage2D(_this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, _this._gl.UNSIGNED_BYTE, isPot ? img : _this._workingCanvas);
  9663. }, samplingMode);
  9664. };
  9665. if (!(fromData instanceof Array))
  9666. BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  9667. else
  9668. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene.database);
  9669. }
  9670. return texture;
  9671. };
  9672. Engine.prototype._getInternalFormat = function (format) {
  9673. var internalFormat = this._gl.RGBA;
  9674. switch (format) {
  9675. case Engine.TEXTUREFORMAT_ALPHA:
  9676. internalFormat = this._gl.ALPHA;
  9677. break;
  9678. case Engine.TEXTUREFORMAT_LUMINANCE:
  9679. internalFormat = this._gl.LUMINANCE;
  9680. break;
  9681. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  9682. internalFormat = this._gl.LUMINANCE_ALPHA;
  9683. break;
  9684. case Engine.TEXTUREFORMAT_RGB:
  9685. internalFormat = this._gl.RGB;
  9686. break;
  9687. case Engine.TEXTUREFORMAT_RGBA:
  9688. internalFormat = this._gl.RGBA;
  9689. break;
  9690. }
  9691. return internalFormat;
  9692. };
  9693. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression) {
  9694. if (compression === void 0) { compression = null; }
  9695. var internalFormat = this._getInternalFormat(format);
  9696. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  9697. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  9698. if (texture._width % 4 !== 0) {
  9699. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  9700. }
  9701. if (compression) {
  9702. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture._width, texture._height, 0, data);
  9703. }
  9704. else {
  9705. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, texture._width, texture._height, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  9706. }
  9707. if (texture.generateMipMaps) {
  9708. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  9709. }
  9710. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  9711. this.resetTextureCache();
  9712. texture.isReady = true;
  9713. };
  9714. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression) {
  9715. if (compression === void 0) { compression = null; }
  9716. var texture = this._gl.createTexture();
  9717. texture._baseWidth = width;
  9718. texture._baseHeight = height;
  9719. texture._width = width;
  9720. texture._height = height;
  9721. texture.references = 1;
  9722. this.updateRawTexture(texture, data, format, invertY, compression);
  9723. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  9724. // Filters
  9725. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  9726. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  9727. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  9728. if (generateMipMaps) {
  9729. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  9730. }
  9731. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  9732. texture.samplingMode = samplingMode;
  9733. this._loadedTexturesCache.push(texture);
  9734. return texture;
  9735. };
  9736. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  9737. var texture = this._gl.createTexture();
  9738. texture._baseWidth = width;
  9739. texture._baseHeight = height;
  9740. if (generateMipMaps) {
  9741. width = BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize);
  9742. height = BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize);
  9743. }
  9744. this.resetTextureCache();
  9745. texture._width = width;
  9746. texture._height = height;
  9747. texture.isReady = false;
  9748. texture.generateMipMaps = generateMipMaps;
  9749. texture.references = 1;
  9750. texture.samplingMode = samplingMode;
  9751. this.updateTextureSamplingMode(samplingMode, texture);
  9752. this._loadedTexturesCache.push(texture);
  9753. return texture;
  9754. };
  9755. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  9756. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  9757. if (texture.isCube) {
  9758. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture);
  9759. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  9760. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  9761. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  9762. }
  9763. else {
  9764. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  9765. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  9766. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  9767. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  9768. }
  9769. texture.samplingMode = samplingMode;
  9770. };
  9771. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  9772. if (premulAlpha === void 0) { premulAlpha = false; }
  9773. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  9774. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  9775. if (premulAlpha) {
  9776. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  9777. }
  9778. var internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  9779. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, this._gl.UNSIGNED_BYTE, canvas);
  9780. if (texture.generateMipMaps) {
  9781. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  9782. }
  9783. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  9784. if (premulAlpha) {
  9785. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  9786. }
  9787. this.resetTextureCache();
  9788. texture.isReady = true;
  9789. };
  9790. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  9791. if (texture._isDisabled) {
  9792. return;
  9793. }
  9794. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  9795. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  9796. try {
  9797. // Testing video texture support
  9798. if (this._videoTextureSupported === undefined) {
  9799. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  9800. if (this._gl.getError() !== 0) {
  9801. this._videoTextureSupported = false;
  9802. }
  9803. else {
  9804. this._videoTextureSupported = true;
  9805. }
  9806. }
  9807. // Copy video through the current working canvas if video texture is not supported
  9808. if (!this._videoTextureSupported) {
  9809. if (!texture._workingCanvas) {
  9810. texture._workingCanvas = document.createElement("canvas");
  9811. texture._workingContext = texture._workingCanvas.getContext("2d");
  9812. texture._workingCanvas.width = texture._width;
  9813. texture._workingCanvas.height = texture._height;
  9814. }
  9815. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture._width, texture._height);
  9816. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  9817. }
  9818. else {
  9819. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  9820. }
  9821. if (texture.generateMipMaps) {
  9822. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  9823. }
  9824. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  9825. this.resetTextureCache();
  9826. texture.isReady = true;
  9827. }
  9828. catch (ex) {
  9829. // Something unexpected
  9830. // Let's disable the texture
  9831. texture._isDisabled = true;
  9832. }
  9833. };
  9834. Engine.prototype.createRenderTargetTexture = function (size, options) {
  9835. // old version had a "generateMipMaps" arg instead of options.
  9836. // if options.generateMipMaps is undefined, consider that options itself if the generateMipmaps value
  9837. // in the same way, generateDepthBuffer is defaulted to true
  9838. var generateMipMaps = false;
  9839. var generateDepthBuffer = true;
  9840. var generateStencilBuffer = false;
  9841. var type = Engine.TEXTURETYPE_UNSIGNED_INT;
  9842. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  9843. if (options !== undefined) {
  9844. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipMaps;
  9845. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  9846. generateStencilBuffer = generateDepthBuffer && options.generateStencilBuffer;
  9847. type = options.type === undefined ? type : options.type;
  9848. if (options.samplingMode !== undefined) {
  9849. samplingMode = options.samplingMode;
  9850. }
  9851. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  9852. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  9853. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  9854. }
  9855. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  9856. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  9857. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  9858. }
  9859. }
  9860. var gl = this._gl;
  9861. var texture = gl.createTexture();
  9862. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  9863. var width = size.width || size;
  9864. var height = size.height || size;
  9865. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  9866. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  9867. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  9868. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  9869. }
  9870. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  9871. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  9872. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  9873. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  9874. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  9875. // Create the framebuffer
  9876. var framebuffer = gl.createFramebuffer();
  9877. this.bindUnboundFramebuffer(framebuffer);
  9878. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  9879. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  9880. if (generateMipMaps) {
  9881. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  9882. }
  9883. // Unbind
  9884. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  9885. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  9886. this.bindUnboundFramebuffer(null);
  9887. texture._framebuffer = framebuffer;
  9888. texture._baseWidth = width;
  9889. texture._baseHeight = height;
  9890. texture._width = width;
  9891. texture._height = height;
  9892. texture.isReady = true;
  9893. texture.samples = 1;
  9894. texture.generateMipMaps = generateMipMaps;
  9895. texture.references = 1;
  9896. texture.samplingMode = samplingMode;
  9897. texture.type = type;
  9898. texture._generateDepthBuffer = generateDepthBuffer;
  9899. texture._generateStencilBuffer = generateStencilBuffer;
  9900. this.resetTextureCache();
  9901. this._loadedTexturesCache.push(texture);
  9902. return texture;
  9903. };
  9904. Engine.prototype._setupFramebufferDepthAttachments = function (generateStencilBuffer, generateDepthBuffer, width, height, samples) {
  9905. if (samples === void 0) { samples = 1; }
  9906. var depthStencilBuffer = null;
  9907. var gl = this._gl;
  9908. // Create the depth/stencil buffer
  9909. if (generateStencilBuffer) {
  9910. depthStencilBuffer = gl.createRenderbuffer();
  9911. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  9912. if (samples > 1) {
  9913. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_STENCIL, width, height);
  9914. }
  9915. else {
  9916. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  9917. }
  9918. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  9919. }
  9920. else if (generateDepthBuffer) {
  9921. depthStencilBuffer = gl.createRenderbuffer();
  9922. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  9923. if (samples > 1) {
  9924. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_COMPONENT16, width, height);
  9925. }
  9926. else {
  9927. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  9928. }
  9929. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  9930. }
  9931. return depthStencilBuffer;
  9932. };
  9933. Engine.prototype.updateRenderTargetTextureSampleCount = function (texture, samples) {
  9934. if (this.webGLVersion < 2) {
  9935. return 1;
  9936. }
  9937. if (texture.samples === samples) {
  9938. return samples;
  9939. }
  9940. var gl = this._gl;
  9941. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  9942. // Dispose previous render buffers
  9943. if (texture._depthStencilBuffer) {
  9944. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  9945. }
  9946. if (texture._MSAAFramebuffer) {
  9947. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  9948. }
  9949. if (texture._MSAARenderBuffer) {
  9950. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  9951. }
  9952. if (samples > 1) {
  9953. texture._MSAAFramebuffer = gl.createFramebuffer();
  9954. this.bindUnboundFramebuffer(texture._MSAAFramebuffer);
  9955. var colorRenderbuffer = gl.createRenderbuffer();
  9956. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  9957. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.RGBA8, texture._width, texture._height);
  9958. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer);
  9959. texture._MSAARenderBuffer = colorRenderbuffer;
  9960. }
  9961. else {
  9962. this.bindUnboundFramebuffer(texture._framebuffer);
  9963. }
  9964. texture.samples = samples;
  9965. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(texture._generateStencilBuffer, texture._generateDepthBuffer, texture._width, texture._height, samples);
  9966. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  9967. this.bindUnboundFramebuffer(null);
  9968. return samples;
  9969. };
  9970. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  9971. var gl = this._gl;
  9972. var texture = gl.createTexture();
  9973. var generateMipMaps = true;
  9974. var generateDepthBuffer = true;
  9975. var generateStencilBuffer = false;
  9976. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  9977. if (options !== undefined) {
  9978. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipMaps;
  9979. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  9980. generateStencilBuffer = generateDepthBuffer && options.generateStencilBuffer;
  9981. if (options.samplingMode !== undefined) {
  9982. samplingMode = options.samplingMode;
  9983. }
  9984. }
  9985. texture.isCube = true;
  9986. texture.references = 1;
  9987. texture.generateMipMaps = generateMipMaps;
  9988. texture.references = 1;
  9989. texture.samples = 1;
  9990. texture.samplingMode = samplingMode;
  9991. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  9992. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  9993. for (var face = 0; face < 6; face++) {
  9994. gl.texImage2D((gl.TEXTURE_CUBE_MAP_POSITIVE_X + face), 0, gl.RGBA, size, size, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
  9995. }
  9996. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  9997. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  9998. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  9999. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10000. // Create the framebuffer
  10001. var framebuffer = gl.createFramebuffer();
  10002. this.bindUnboundFramebuffer(framebuffer);
  10003. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, size, size);
  10004. // Mipmaps
  10005. if (texture.generateMipMaps) {
  10006. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  10007. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  10008. }
  10009. // Unbind
  10010. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  10011. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  10012. this.bindUnboundFramebuffer(null);
  10013. texture._framebuffer = framebuffer;
  10014. texture._width = size;
  10015. texture._height = size;
  10016. texture.isReady = true;
  10017. this.resetTextureCache();
  10018. this._loadedTexturesCache.push(texture);
  10019. return texture;
  10020. };
  10021. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError, format) {
  10022. var _this = this;
  10023. if (onLoad === void 0) { onLoad = null; }
  10024. if (onError === void 0) { onError = null; }
  10025. var gl = this._gl;
  10026. var texture = gl.createTexture();
  10027. texture.isCube = true;
  10028. texture.url = rootUrl;
  10029. texture.references = 1;
  10030. texture.onLoadedCallbacks = [];
  10031. var isKTX = false;
  10032. var lastDot = rootUrl.lastIndexOf('.');
  10033. var extension = rootUrl.substring(lastDot).toLowerCase();
  10034. if (this._textureFormatInUse) {
  10035. extension = this._textureFormatInUse;
  10036. rootUrl = rootUrl.substring(0, lastDot) + this._textureFormatInUse;
  10037. isKTX = true;
  10038. }
  10039. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  10040. if (isKTX) {
  10041. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  10042. var ktx = new BABYLON.Internals.KhronosTextureContainer(data, 6);
  10043. var loadMipmap = ktx.numberOfMipmapLevels > 1 && !noMipmap;
  10044. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  10045. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  10046. ktx.uploadLevels(_this._gl, !noMipmap);
  10047. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  10048. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  10049. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10050. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10051. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  10052. _this.resetTextureCache();
  10053. texture._width = ktx.pixelWidth;
  10054. texture._height = ktx.pixelHeight;
  10055. texture.isReady = true;
  10056. }, null, null, true, onError);
  10057. }
  10058. else if (isDDS) {
  10059. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  10060. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  10061. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  10062. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  10063. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  10064. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 6);
  10065. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  10066. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  10067. }
  10068. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  10069. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  10070. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10071. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10072. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  10073. _this.resetTextureCache();
  10074. texture._width = info.width;
  10075. texture._height = info.height;
  10076. texture.isReady = true;
  10077. }, null, null, true, onError);
  10078. }
  10079. else {
  10080. cascadeLoad(rootUrl, scene, function (imgs) {
  10081. var width = BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize);
  10082. var height = width;
  10083. _this._prepareWorkingCanvas();
  10084. _this._workingCanvas.width = width;
  10085. _this._workingCanvas.height = height;
  10086. var faces = [
  10087. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  10088. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  10089. ];
  10090. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  10091. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  10092. var internalFormat = format ? _this._getInternalFormat(format) : _this._gl.RGBA;
  10093. for (var index = 0; index < faces.length; index++) {
  10094. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  10095. gl.texImage2D(faces[index], 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  10096. }
  10097. if (!noMipmap) {
  10098. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  10099. }
  10100. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  10101. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  10102. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10103. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10104. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  10105. _this.resetTextureCache();
  10106. texture._width = width;
  10107. texture._height = height;
  10108. texture.isReady = true;
  10109. texture.onLoadedCallbacks.forEach(function (callback) {
  10110. callback();
  10111. });
  10112. if (onLoad) {
  10113. onLoad();
  10114. }
  10115. }, files, onError);
  10116. }
  10117. this._loadedTexturesCache.push(texture);
  10118. return texture;
  10119. };
  10120. Engine.prototype.updateTextureSize = function (texture, width, height) {
  10121. texture._width = width;
  10122. texture._height = height;
  10123. texture._size = width * height;
  10124. texture._baseWidth = width;
  10125. texture._baseHeight = height;
  10126. };
  10127. Engine.prototype.createRawCubeTexture = function (url, scene, size, format, type, noMipmap, callback, mipmmapGenerator, onLoad, onError) {
  10128. var _this = this;
  10129. if (onLoad === void 0) { onLoad = null; }
  10130. if (onError === void 0) { onError = null; }
  10131. var gl = this._gl;
  10132. var texture = gl.createTexture();
  10133. scene._addPendingData(texture);
  10134. texture.isCube = true;
  10135. texture.references = 1;
  10136. texture.url = url;
  10137. var textureType = gl.UNSIGNED_BYTE;
  10138. if (type === Engine.TEXTURETYPE_FLOAT) {
  10139. textureType = gl.FLOAT;
  10140. }
  10141. var internalFormat = this._getInternalFormat(format);
  10142. var needConversion = false;
  10143. if (internalFormat === gl.RGB) {
  10144. internalFormat = gl.RGBA;
  10145. needConversion = true;
  10146. }
  10147. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  10148. var width = size;
  10149. var height = width;
  10150. var isPot = (BABYLON.Tools.IsExponentOfTwo(width) && BABYLON.Tools.IsExponentOfTwo(height));
  10151. texture._width = width;
  10152. texture._height = height;
  10153. var onerror = function () {
  10154. scene._removePendingData(texture);
  10155. if (onError) {
  10156. onError();
  10157. }
  10158. };
  10159. var internalCallback = function (data) {
  10160. var rgbeDataArrays = callback(data);
  10161. var facesIndex = [
  10162. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  10163. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  10164. ];
  10165. width = texture._width;
  10166. height = texture._height;
  10167. isPot = (BABYLON.Tools.IsExponentOfTwo(width) && BABYLON.Tools.IsExponentOfTwo(height));
  10168. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  10169. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  10170. if (mipmmapGenerator) {
  10171. var arrayTemp = [];
  10172. // Data are known to be in +X +Y +Z -X -Y -Z
  10173. // mipmmapGenerator data is expected to be order in +X -X +Y -Y +Z -Z
  10174. arrayTemp.push(rgbeDataArrays[0]); // +X
  10175. arrayTemp.push(rgbeDataArrays[3]); // -X
  10176. arrayTemp.push(rgbeDataArrays[1]); // +Y
  10177. arrayTemp.push(rgbeDataArrays[4]); // -Y
  10178. arrayTemp.push(rgbeDataArrays[2]); // +Z
  10179. arrayTemp.push(rgbeDataArrays[5]); // -Z
  10180. var mipData = mipmmapGenerator(arrayTemp);
  10181. // mipData is order in +X -X +Y -Y +Z -Z
  10182. var mipFaces = [0, 2, 4, 1, 3, 5];
  10183. for (var level = 0; level < mipData.length; level++) {
  10184. var mipSize = width >> level;
  10185. for (var mipIndex in mipFaces) {
  10186. var mipFaceData = mipData[level][mipFaces[mipIndex]];
  10187. if (needConversion) {
  10188. mipFaceData = _this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
  10189. }
  10190. gl.texImage2D(facesIndex[mipIndex], level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);
  10191. }
  10192. }
  10193. }
  10194. else {
  10195. // Data are known to be in +X +Y +Z -X -Y -Z
  10196. for (var index = 0; index < facesIndex.length; index++) {
  10197. var faceData = rgbeDataArrays[index];
  10198. if (needConversion) {
  10199. faceData = _this._convertRGBtoRGBATextureData(faceData, width, height, type);
  10200. }
  10201. gl.texImage2D(facesIndex[index], 0, internalSizedFomat, width, height, 0, internalFormat, textureType, faceData);
  10202. }
  10203. if (!noMipmap && isPot) {
  10204. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  10205. }
  10206. else {
  10207. noMipmap = true;
  10208. }
  10209. }
  10210. if (textureType === gl.FLOAT && !_this._caps.textureFloatLinearFiltering) {
  10211. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  10212. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  10213. }
  10214. else if (textureType === Engine.HALF_FLOAT_OES && !_this._caps.textureHalfFloatLinearFiltering) {
  10215. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  10216. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  10217. }
  10218. else {
  10219. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  10220. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  10221. }
  10222. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10223. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10224. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  10225. texture.isReady = true;
  10226. _this.resetTextureCache();
  10227. scene._removePendingData(texture);
  10228. if (onLoad) {
  10229. onLoad();
  10230. }
  10231. };
  10232. BABYLON.Tools.LoadFile(url, function (data) {
  10233. internalCallback(data);
  10234. }, onerror, scene.database, true);
  10235. return texture;
  10236. };
  10237. ;
  10238. Engine.prototype._convertRGBtoRGBATextureData = function (rgbData, width, height, textureType) {
  10239. // Create new RGBA data container.
  10240. var rgbaData;
  10241. if (textureType === Engine.TEXTURETYPE_FLOAT) {
  10242. rgbaData = new Float32Array(width * height * 4);
  10243. }
  10244. else {
  10245. rgbaData = new Uint32Array(width * height * 4);
  10246. }
  10247. // Convert each pixel.
  10248. for (var x = 0; x < width; x++) {
  10249. for (var y = 0; y < height; y++) {
  10250. var index = (y * width + x) * 3;
  10251. var newIndex = (y * width + x) * 4;
  10252. // Map Old Value to new value.
  10253. rgbaData[newIndex + 0] = rgbData[index + 0];
  10254. rgbaData[newIndex + 1] = rgbData[index + 1];
  10255. rgbaData[newIndex + 2] = rgbData[index + 2];
  10256. // Add fully opaque alpha channel.
  10257. rgbaData[newIndex + 3] = 1;
  10258. }
  10259. }
  10260. return rgbaData;
  10261. };
  10262. Engine.prototype._releaseTexture = function (texture) {
  10263. var gl = this._gl;
  10264. if (texture._framebuffer) {
  10265. gl.deleteFramebuffer(texture._framebuffer);
  10266. }
  10267. if (texture._depthStencilBuffer) {
  10268. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  10269. }
  10270. if (texture._MSAAFramebuffer) {
  10271. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  10272. }
  10273. if (texture._MSAARenderBuffer) {
  10274. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  10275. }
  10276. gl.deleteTexture(texture);
  10277. // Unbind channels
  10278. this.unbindAllTextures();
  10279. var index = this._loadedTexturesCache.indexOf(texture);
  10280. if (index !== -1) {
  10281. this._loadedTexturesCache.splice(index, 1);
  10282. }
  10283. };
  10284. Engine.prototype.setProgram = function (program) {
  10285. if (this._currentProgram !== program) {
  10286. this._gl.useProgram(program);
  10287. this._currentProgram = program;
  10288. }
  10289. };
  10290. Engine.prototype.bindSamplers = function (effect) {
  10291. this.setProgram(effect.getProgram());
  10292. var samplers = effect.getSamplers();
  10293. for (var index = 0; index < samplers.length; index++) {
  10294. var uniform = effect.getUniform(samplers[index]);
  10295. this._gl.uniform1i(uniform, index);
  10296. }
  10297. this._currentEffect = null;
  10298. };
  10299. Engine.prototype.activateTexture = function (texture) {
  10300. if (this._activeTexture !== texture) {
  10301. this._gl.activeTexture(texture);
  10302. this._activeTexture = texture;
  10303. }
  10304. };
  10305. Engine.prototype._bindTextureDirectly = function (target, texture) {
  10306. if (this._activeTexturesCache[this._activeTexture] !== texture) {
  10307. this._gl.bindTexture(target, texture);
  10308. this._activeTexturesCache[this._activeTexture] = texture;
  10309. }
  10310. };
  10311. Engine.prototype._bindTexture = function (channel, texture) {
  10312. if (channel < 0) {
  10313. return;
  10314. }
  10315. this.activateTexture(this._gl.TEXTURE0 + channel);
  10316. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  10317. };
  10318. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  10319. this._bindTexture(channel, postProcess._textures.data[postProcess._currentRenderTextureInd]);
  10320. };
  10321. Engine.prototype.unbindAllTextures = function () {
  10322. for (var channel = 0; channel < this._caps.maxTexturesImageUnits; channel++) {
  10323. this.activateTexture(this._gl["TEXTURE" + channel]);
  10324. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  10325. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  10326. }
  10327. };
  10328. Engine.prototype.setTexture = function (channel, uniform, texture) {
  10329. if (channel < 0) {
  10330. return;
  10331. }
  10332. this._gl.uniform1i(uniform, channel);
  10333. this._setTexture(channel, texture);
  10334. };
  10335. Engine.prototype._setTexture = function (channel, texture) {
  10336. // Not ready?
  10337. if (!texture || !texture.isReady()) {
  10338. if (this._activeTexturesCache[channel] != null) {
  10339. this.activateTexture(this._gl["TEXTURE" + channel]);
  10340. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  10341. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  10342. }
  10343. return;
  10344. }
  10345. // Video
  10346. var alreadyActivated = false;
  10347. if (texture instanceof BABYLON.VideoTexture) {
  10348. this.activateTexture(this._gl["TEXTURE" + channel]);
  10349. alreadyActivated = true;
  10350. texture.update();
  10351. }
  10352. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  10353. texture.delayLoad();
  10354. return;
  10355. }
  10356. var internalTexture = texture.getInternalTexture();
  10357. if (this._activeTexturesCache[channel] === internalTexture) {
  10358. return;
  10359. }
  10360. if (!alreadyActivated) {
  10361. this.activateTexture(this._gl["TEXTURE" + channel]);
  10362. }
  10363. if (internalTexture.isCube) {
  10364. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture);
  10365. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  10366. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  10367. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  10368. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  10369. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  10370. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  10371. }
  10372. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  10373. }
  10374. else {
  10375. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture);
  10376. if (internalTexture._cachedWrapU !== texture.wrapU) {
  10377. internalTexture._cachedWrapU = texture.wrapU;
  10378. switch (texture.wrapU) {
  10379. case BABYLON.Texture.WRAP_ADDRESSMODE:
  10380. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  10381. break;
  10382. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  10383. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  10384. break;
  10385. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  10386. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  10387. break;
  10388. }
  10389. }
  10390. if (internalTexture._cachedWrapV !== texture.wrapV) {
  10391. internalTexture._cachedWrapV = texture.wrapV;
  10392. switch (texture.wrapV) {
  10393. case BABYLON.Texture.WRAP_ADDRESSMODE:
  10394. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  10395. break;
  10396. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  10397. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  10398. break;
  10399. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  10400. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  10401. break;
  10402. }
  10403. }
  10404. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  10405. }
  10406. };
  10407. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  10408. if (channel < 0) {
  10409. return;
  10410. }
  10411. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  10412. this._textureUnits = new Int32Array(textures.length);
  10413. }
  10414. for (var i = 0; i < textures.length; i++) {
  10415. this._textureUnits[i] = channel + i;
  10416. }
  10417. this._gl.uniform1iv(uniform, this._textureUnits);
  10418. for (var index = 0; index < textures.length; index++) {
  10419. this._setTexture(channel + index, textures[index]);
  10420. }
  10421. };
  10422. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  10423. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  10424. var value = texture.anisotropicFilteringLevel;
  10425. if (texture.getInternalTexture().samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  10426. value = 1;
  10427. }
  10428. if (anisotropicFilterExtension && texture._cachedAnisotropicFilteringLevel !== value) {
  10429. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
  10430. texture._cachedAnisotropicFilteringLevel = value;
  10431. }
  10432. };
  10433. Engine.prototype.readPixels = function (x, y, width, height) {
  10434. var data = new Uint8Array(height * width * 4);
  10435. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  10436. return data;
  10437. };
  10438. /**
  10439. * Add an externaly attached data from its key.
  10440. * This method call will fail and return false, if such key already exists.
  10441. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  10442. * @param key the unique key that identifies the data
  10443. * @param data the data object to associate to the key for this Engine instance
  10444. * @return true if no such key were already present and the data was added successfully, false otherwise
  10445. */
  10446. Engine.prototype.addExternalData = function (key, data) {
  10447. return this._externalData.add(key, data);
  10448. };
  10449. /**
  10450. * Get an externaly attached data from its key
  10451. * @param key the unique key that identifies the data
  10452. * @return the associated data, if present (can be null), or undefined if not present
  10453. */
  10454. Engine.prototype.getExternalData = function (key) {
  10455. return this._externalData.get(key);
  10456. };
  10457. /**
  10458. * Get an externaly attached data from its key, create it using a factory if it's not already present
  10459. * @param key the unique key that identifies the data
  10460. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  10461. * @return the associated data, can be null if the factory returned null.
  10462. */
  10463. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  10464. return this._externalData.getOrAddWithFactory(key, factory);
  10465. };
  10466. /**
  10467. * Remove an externaly attached data from the Engine instance
  10468. * @param key the unique key that identifies the data
  10469. * @return true if the data was successfully removed, false if it doesn't exist
  10470. */
  10471. Engine.prototype.removeExternalData = function (key) {
  10472. return this._externalData.remove(key);
  10473. };
  10474. Engine.prototype.releaseInternalTexture = function (texture) {
  10475. if (!texture) {
  10476. return;
  10477. }
  10478. texture.references--;
  10479. // Final reference ?
  10480. if (texture.references === 0) {
  10481. var texturesCache = this.getLoadedTexturesCache();
  10482. var index = texturesCache.indexOf(texture);
  10483. if (index > -1) {
  10484. texturesCache.splice(index, 1);
  10485. }
  10486. this._releaseTexture(texture);
  10487. }
  10488. };
  10489. Engine.prototype.unbindAllAttributes = function () {
  10490. if (this._mustWipeVertexAttributes) {
  10491. this._mustWipeVertexAttributes = false;
  10492. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  10493. this._gl.disableVertexAttribArray(i);
  10494. this._vertexAttribArraysEnabled[i] = false;
  10495. this._currentBufferPointers[i] = null;
  10496. }
  10497. return;
  10498. }
  10499. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  10500. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  10501. continue;
  10502. }
  10503. this._gl.disableVertexAttribArray(i);
  10504. this._vertexAttribArraysEnabled[i] = false;
  10505. this._currentBufferPointers[i] = null;
  10506. }
  10507. };
  10508. // Dispose
  10509. Engine.prototype.dispose = function () {
  10510. this.hideLoadingUI();
  10511. this.stopRenderLoop();
  10512. // Release scenes
  10513. while (this.scenes.length) {
  10514. this.scenes[0].dispose();
  10515. }
  10516. // Release audio engine
  10517. Engine.audioEngine.dispose();
  10518. // Release effects
  10519. for (var name in this._compiledEffects) {
  10520. this._gl.deleteProgram(this._compiledEffects[name]._program);
  10521. }
  10522. // Unbind
  10523. this.unbindAllAttributes();
  10524. this._gl = null;
  10525. //WebVR
  10526. this.disableVR();
  10527. // Events
  10528. window.removeEventListener("blur", this._onBlur);
  10529. window.removeEventListener("focus", this._onFocus);
  10530. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  10531. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  10532. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  10533. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  10534. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  10535. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  10536. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  10537. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  10538. // Remove from Instances
  10539. var index = Engine.Instances.indexOf(this);
  10540. if (index >= 0) {
  10541. Engine.Instances.splice(index, 1);
  10542. }
  10543. };
  10544. // Loading screen
  10545. Engine.prototype.displayLoadingUI = function () {
  10546. this._loadingScreen.displayLoadingUI();
  10547. };
  10548. Engine.prototype.hideLoadingUI = function () {
  10549. this._loadingScreen.hideLoadingUI();
  10550. };
  10551. Object.defineProperty(Engine.prototype, "loadingScreen", {
  10552. get: function () {
  10553. return this._loadingScreen;
  10554. },
  10555. set: function (loadingScreen) {
  10556. this._loadingScreen = loadingScreen;
  10557. },
  10558. enumerable: true,
  10559. configurable: true
  10560. });
  10561. Object.defineProperty(Engine.prototype, "loadingUIText", {
  10562. set: function (text) {
  10563. this._loadingScreen.loadingUIText = text;
  10564. },
  10565. enumerable: true,
  10566. configurable: true
  10567. });
  10568. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  10569. set: function (color) {
  10570. this._loadingScreen.loadingUIBackgroundColor = color;
  10571. },
  10572. enumerable: true,
  10573. configurable: true
  10574. });
  10575. Engine.prototype.attachContextLostEvent = function (callback) {
  10576. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  10577. };
  10578. Engine.prototype.attachContextRestoredEvent = function (callback) {
  10579. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  10580. };
  10581. Engine.prototype.getVertexShaderSource = function (program) {
  10582. var shaders = this._gl.getAttachedShaders(program);
  10583. return this._gl.getShaderSource(shaders[0]);
  10584. };
  10585. Engine.prototype.getFragmentShaderSource = function (program) {
  10586. var shaders = this._gl.getAttachedShaders(program);
  10587. return this._gl.getShaderSource(shaders[1]);
  10588. };
  10589. // FPS
  10590. Engine.prototype.getFps = function () {
  10591. return this.fps;
  10592. };
  10593. Engine.prototype.getDeltaTime = function () {
  10594. return this.deltaTime;
  10595. };
  10596. Engine.prototype._measureFps = function () {
  10597. this.previousFramesDuration.push(BABYLON.Tools.Now);
  10598. var length = this.previousFramesDuration.length;
  10599. if (length >= 2) {
  10600. this.deltaTime = this.previousFramesDuration[length - 1] - this.previousFramesDuration[length - 2];
  10601. }
  10602. if (length >= this.fpsRange) {
  10603. if (length > this.fpsRange) {
  10604. this.previousFramesDuration.splice(0, 1);
  10605. length = this.previousFramesDuration.length;
  10606. }
  10607. var sum = 0;
  10608. for (var id = 0; id < length - 1; id++) {
  10609. sum += this.previousFramesDuration[id + 1] - this.previousFramesDuration[id];
  10610. }
  10611. this.fps = 1000.0 / (sum / (length - 1));
  10612. }
  10613. };
  10614. Engine.prototype._canRenderToFloatFramebuffer = function () {
  10615. if (this._webGLVersion > 1) {
  10616. return this._caps.colorBufferFloat;
  10617. }
  10618. return this._canRenderToFramebuffer(BABYLON.Engine.TEXTURETYPE_FLOAT);
  10619. };
  10620. Engine.prototype._canRenderToHalfFloatFramebuffer = function () {
  10621. if (this._webGLVersion > 1) {
  10622. return this._caps.colorBufferFloat;
  10623. }
  10624. return this._canRenderToFramebuffer(BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  10625. };
  10626. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  10627. Engine.prototype._canRenderToFramebuffer = function (type) {
  10628. var gl = this._gl;
  10629. //clear existing errors
  10630. while (gl.getError() !== gl.NO_ERROR) { }
  10631. var successful = true;
  10632. var texture = gl.createTexture();
  10633. gl.bindTexture(gl.TEXTURE_2D, texture);
  10634. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  10635. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  10636. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  10637. var fb = gl.createFramebuffer();
  10638. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  10639. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  10640. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  10641. successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
  10642. successful = successful && (gl.getError() === gl.NO_ERROR);
  10643. //try render by clearing frame buffer's color buffer
  10644. if (successful) {
  10645. gl.clear(gl.COLOR_BUFFER_BIT);
  10646. successful = successful && (gl.getError() === gl.NO_ERROR);
  10647. }
  10648. //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
  10649. if (successful) {
  10650. //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
  10651. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  10652. var readFormat = gl.RGBA;
  10653. var readType = gl.UNSIGNED_BYTE;
  10654. var buffer = new Uint8Array(4);
  10655. gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
  10656. successful = successful && (gl.getError() === gl.NO_ERROR);
  10657. }
  10658. //clean up
  10659. gl.deleteTexture(texture);
  10660. gl.deleteFramebuffer(fb);
  10661. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  10662. //clear accumulated errors
  10663. while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
  10664. return successful;
  10665. };
  10666. Engine.prototype._getWebGLTextureType = function (type) {
  10667. if (type === Engine.TEXTURETYPE_FLOAT) {
  10668. return this._gl.FLOAT;
  10669. }
  10670. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  10671. // Add Half Float Constant.
  10672. return Engine.HALF_FLOAT_OES;
  10673. }
  10674. return this._gl.UNSIGNED_BYTE;
  10675. };
  10676. ;
  10677. Engine.prototype._getRGBABufferInternalSizedFormat = function (type) {
  10678. if (this._webGLVersion === 1) {
  10679. return this._gl.RGBA;
  10680. }
  10681. if (type === Engine.TEXTURETYPE_FLOAT) {
  10682. return Engine.RGBA32F;
  10683. }
  10684. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  10685. return Engine.RGBA16F;
  10686. }
  10687. return this._gl.RGBA;
  10688. };
  10689. ;
  10690. // Statics
  10691. Engine.isSupported = function () {
  10692. try {
  10693. // Avoid creating an unsized context for CocoonJS, since size determined on first creation. Is not resizable
  10694. if (navigator.isCocoonJS) {
  10695. return true;
  10696. }
  10697. var tempcanvas = document.createElement("canvas");
  10698. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  10699. return gl != null && !!window.WebGLRenderingContext;
  10700. }
  10701. catch (e) {
  10702. return false;
  10703. }
  10704. };
  10705. return Engine;
  10706. }());
  10707. Engine.Instances = new Array();
  10708. // Const statics
  10709. Engine._ALPHA_DISABLE = 0;
  10710. Engine._ALPHA_ADD = 1;
  10711. Engine._ALPHA_COMBINE = 2;
  10712. Engine._ALPHA_SUBTRACT = 3;
  10713. Engine._ALPHA_MULTIPLY = 4;
  10714. Engine._ALPHA_MAXIMIZED = 5;
  10715. Engine._ALPHA_ONEONE = 6;
  10716. Engine._ALPHA_PREMULTIPLIED = 7;
  10717. Engine._DELAYLOADSTATE_NONE = 0;
  10718. Engine._DELAYLOADSTATE_LOADED = 1;
  10719. Engine._DELAYLOADSTATE_LOADING = 2;
  10720. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  10721. Engine._TEXTUREFORMAT_ALPHA = 0;
  10722. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  10723. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  10724. Engine._TEXTUREFORMAT_RGB = 4;
  10725. Engine._TEXTUREFORMAT_RGBA = 5;
  10726. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  10727. Engine._TEXTURETYPE_FLOAT = 1;
  10728. Engine._TEXTURETYPE_HALF_FLOAT = 2;
  10729. // Depht or Stencil test Constants.
  10730. Engine._NEVER = 0x0200; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn.
  10731. 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.
  10732. 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.
  10733. 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.
  10734. 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.
  10735. 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.
  10736. 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.
  10737. 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.
  10738. Engine.HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).
  10739. Engine.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.
  10740. Engine.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
  10741. // Stencil Actions Constants.
  10742. Engine._KEEP = 0x1E00;
  10743. Engine._REPLACE = 0x1E01;
  10744. Engine._INCR = 0x1E02;
  10745. Engine._DECR = 0x1E03;
  10746. Engine._INVERT = 0x150A;
  10747. Engine._INCR_WRAP = 0x8507;
  10748. Engine._DECR_WRAP = 0x8508;
  10749. // Updatable statics so stick with vars here
  10750. Engine.CollisionsEpsilon = 0.001;
  10751. Engine.CodeRepository = "src/";
  10752. Engine.ShadersRepository = "src/Shaders/";
  10753. BABYLON.Engine = Engine;
  10754. })(BABYLON || (BABYLON = {}));
  10755. //# sourceMappingURL=babylon.engine.js.map
  10756. /// <reference path="Tools\babylon.decorators.ts" />
  10757. var BABYLON;
  10758. (function (BABYLON) {
  10759. /**
  10760. * Node is the basic class for all scene objects (Mesh, Light Camera).
  10761. */
  10762. var Node = (function () {
  10763. /**
  10764. * @constructor
  10765. * @param {string} name - the name and id to be given to this node
  10766. * @param {BABYLON.Scene} the scene this node will be added to
  10767. */
  10768. function Node(name, scene) {
  10769. this.state = "";
  10770. this.metadata = null;
  10771. this.doNotSerialize = false;
  10772. this.animations = new Array();
  10773. this._ranges = {};
  10774. this._childrenFlag = -1;
  10775. this._isEnabled = true;
  10776. this._isReady = true;
  10777. this._currentRenderId = -1;
  10778. this._parentRenderId = -1;
  10779. /**
  10780. * An event triggered when the mesh is disposed.
  10781. * @type {BABYLON.Observable}
  10782. */
  10783. this.onDisposeObservable = new BABYLON.Observable();
  10784. this.name = name;
  10785. this.id = name;
  10786. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  10787. this._initCache();
  10788. }
  10789. Object.defineProperty(Node.prototype, "parent", {
  10790. get: function () {
  10791. return this._parentNode;
  10792. },
  10793. set: function (parent) {
  10794. if (this._parentNode === parent) {
  10795. return;
  10796. }
  10797. if (this._parentNode) {
  10798. var index = this._parentNode._children.indexOf(this);
  10799. if (index !== -1) {
  10800. this._parentNode._children.splice(index, 1);
  10801. }
  10802. }
  10803. this._parentNode = parent;
  10804. if (this._parentNode) {
  10805. if (!this._parentNode._children) {
  10806. this._parentNode._children = new Array();
  10807. }
  10808. this._parentNode._children.push(this);
  10809. }
  10810. },
  10811. enumerable: true,
  10812. configurable: true
  10813. });
  10814. Node.prototype.getClassName = function () {
  10815. return "Node";
  10816. };
  10817. Object.defineProperty(Node.prototype, "onDispose", {
  10818. set: function (callback) {
  10819. if (this._onDisposeObserver) {
  10820. this.onDisposeObservable.remove(this._onDisposeObserver);
  10821. }
  10822. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  10823. },
  10824. enumerable: true,
  10825. configurable: true
  10826. });
  10827. Node.prototype.getScene = function () {
  10828. return this._scene;
  10829. };
  10830. Node.prototype.getEngine = function () {
  10831. return this._scene.getEngine();
  10832. };
  10833. // override it in derived class
  10834. Node.prototype.getWorldMatrix = function () {
  10835. return BABYLON.Matrix.Identity();
  10836. };
  10837. // override it in derived class if you add new variables to the cache
  10838. // and call the parent class method
  10839. Node.prototype._initCache = function () {
  10840. this._cache = {};
  10841. this._cache.parent = undefined;
  10842. };
  10843. Node.prototype.updateCache = function (force) {
  10844. if (!force && this.isSynchronized())
  10845. return;
  10846. this._cache.parent = this.parent;
  10847. this._updateCache();
  10848. };
  10849. // override it in derived class if you add new variables to the cache
  10850. // and call the parent class method if !ignoreParentClass
  10851. Node.prototype._updateCache = function (ignoreParentClass) {
  10852. };
  10853. // override it in derived class if you add new variables to the cache
  10854. Node.prototype._isSynchronized = function () {
  10855. return true;
  10856. };
  10857. Node.prototype._markSyncedWithParent = function () {
  10858. this._parentRenderId = this.parent._currentRenderId;
  10859. };
  10860. Node.prototype.isSynchronizedWithParent = function () {
  10861. if (!this.parent) {
  10862. return true;
  10863. }
  10864. if (this._parentRenderId !== this.parent._currentRenderId) {
  10865. return false;
  10866. }
  10867. return this.parent.isSynchronized();
  10868. };
  10869. Node.prototype.isSynchronized = function (updateCache) {
  10870. var check = this.hasNewParent();
  10871. check = check || !this.isSynchronizedWithParent();
  10872. check = check || !this._isSynchronized();
  10873. if (updateCache)
  10874. this.updateCache(true);
  10875. return !check;
  10876. };
  10877. Node.prototype.hasNewParent = function (update) {
  10878. if (this._cache.parent === this.parent)
  10879. return false;
  10880. if (update)
  10881. this._cache.parent = this.parent;
  10882. return true;
  10883. };
  10884. /**
  10885. * Is this node ready to be used/rendered
  10886. * @return {boolean} is it ready
  10887. */
  10888. Node.prototype.isReady = function () {
  10889. return this._isReady;
  10890. };
  10891. /**
  10892. * Is this node enabled.
  10893. * If the node has a parent and is enabled, the parent will be inspected as well.
  10894. * @return {boolean} whether this node (and its parent) is enabled.
  10895. * @see setEnabled
  10896. */
  10897. Node.prototype.isEnabled = function () {
  10898. if (!this._isEnabled) {
  10899. return false;
  10900. }
  10901. if (this.parent) {
  10902. return this.parent.isEnabled();
  10903. }
  10904. return true;
  10905. };
  10906. /**
  10907. * Set the enabled state of this node.
  10908. * @param {boolean} value - the new enabled state
  10909. * @see isEnabled
  10910. */
  10911. Node.prototype.setEnabled = function (value) {
  10912. this._isEnabled = value;
  10913. };
  10914. /**
  10915. * Is this node a descendant of the given node.
  10916. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined.
  10917. * @param {BABYLON.Node} ancestor - The parent node to inspect
  10918. * @see parent
  10919. */
  10920. Node.prototype.isDescendantOf = function (ancestor) {
  10921. if (this.parent) {
  10922. if (this.parent === ancestor) {
  10923. return true;
  10924. }
  10925. return this.parent.isDescendantOf(ancestor);
  10926. }
  10927. return false;
  10928. };
  10929. /**
  10930. * Evaluate the list of children and determine if they should be considered as descendants considering the given criterias
  10931. * @param {BABYLON.Node[]} results the result array containing the nodes matching the given criterias
  10932. * @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.
  10933. * @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.
  10934. */
  10935. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  10936. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  10937. if (!this._children) {
  10938. return;
  10939. }
  10940. for (var index = 0; index < this._children.length; index++) {
  10941. var item = this._children[index];
  10942. if (!predicate || predicate(item)) {
  10943. results.push(item);
  10944. }
  10945. if (!directDescendantsOnly) {
  10946. item._getDescendants(results, false, predicate);
  10947. }
  10948. }
  10949. };
  10950. /**
  10951. * Will return all nodes that have this node as ascendant.
  10952. * @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.
  10953. * @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.
  10954. * @return {BABYLON.Node[]} all children nodes of all types.
  10955. */
  10956. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  10957. var results = [];
  10958. this._getDescendants(results, directDescendantsOnly, predicate);
  10959. return results;
  10960. };
  10961. /**
  10962. * Get all child-meshes of this node.
  10963. */
  10964. Node.prototype.getChildMeshes = function (directDecendantsOnly, predicate) {
  10965. var results = [];
  10966. this._getDescendants(results, directDecendantsOnly, function (node) {
  10967. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  10968. });
  10969. return results;
  10970. };
  10971. /**
  10972. * Get all direct children of this node.
  10973. */
  10974. Node.prototype.getChildren = function (predicate) {
  10975. return this.getDescendants(true, predicate);
  10976. };
  10977. Node.prototype._setReady = function (state) {
  10978. if (state === this._isReady) {
  10979. return;
  10980. }
  10981. if (!state) {
  10982. this._isReady = false;
  10983. return;
  10984. }
  10985. this._isReady = true;
  10986. if (this.onReady) {
  10987. this.onReady(this);
  10988. }
  10989. };
  10990. Node.prototype.getAnimationByName = function (name) {
  10991. for (var i = 0; i < this.animations.length; i++) {
  10992. var animation = this.animations[i];
  10993. if (animation.name === name) {
  10994. return animation;
  10995. }
  10996. }
  10997. return null;
  10998. };
  10999. Node.prototype.createAnimationRange = function (name, from, to) {
  11000. // check name not already in use
  11001. if (!this._ranges[name]) {
  11002. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  11003. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  11004. if (this.animations[i]) {
  11005. this.animations[i].createRange(name, from, to);
  11006. }
  11007. }
  11008. }
  11009. };
  11010. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  11011. if (deleteFrames === void 0) { deleteFrames = true; }
  11012. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  11013. if (this.animations[i]) {
  11014. this.animations[i].deleteRange(name, deleteFrames);
  11015. }
  11016. }
  11017. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  11018. };
  11019. Node.prototype.getAnimationRange = function (name) {
  11020. return this._ranges[name];
  11021. };
  11022. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  11023. var range = this.getAnimationRange(name);
  11024. if (!range) {
  11025. return null;
  11026. }
  11027. this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  11028. };
  11029. Node.prototype.serializeAnimationRanges = function () {
  11030. var serializationRanges = [];
  11031. for (var name in this._ranges) {
  11032. var range = {};
  11033. range.name = name;
  11034. range.from = this._ranges[name].from;
  11035. range.to = this._ranges[name].to;
  11036. serializationRanges.push(range);
  11037. }
  11038. return serializationRanges;
  11039. };
  11040. Node.prototype.dispose = function () {
  11041. this.parent = null;
  11042. // Callback
  11043. this.onDisposeObservable.notifyObservers(this);
  11044. this.onDisposeObservable.clear();
  11045. };
  11046. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  11047. if (parsedNode.ranges) {
  11048. for (var index = 0; index < parsedNode.ranges.length; index++) {
  11049. var data = parsedNode.ranges[index];
  11050. node.createAnimationRange(data.name, data.from, data.to);
  11051. }
  11052. }
  11053. };
  11054. return Node;
  11055. }());
  11056. __decorate([
  11057. BABYLON.serialize()
  11058. ], Node.prototype, "name", void 0);
  11059. __decorate([
  11060. BABYLON.serialize()
  11061. ], Node.prototype, "id", void 0);
  11062. __decorate([
  11063. BABYLON.serialize()
  11064. ], Node.prototype, "uniqueId", void 0);
  11065. __decorate([
  11066. BABYLON.serialize()
  11067. ], Node.prototype, "state", void 0);
  11068. __decorate([
  11069. BABYLON.serialize()
  11070. ], Node.prototype, "metadata", void 0);
  11071. BABYLON.Node = Node;
  11072. })(BABYLON || (BABYLON = {}));
  11073. //# sourceMappingURL=babylon.node.js.map
  11074. var BABYLON;
  11075. (function (BABYLON) {
  11076. var FilesInput = (function () {
  11077. /// Register to core BabylonJS object: engine, scene, rendering canvas, callback function when the scene will be loaded,
  11078. /// loading progress callback and optionnal addionnal logic to call in the rendering loop
  11079. function FilesInput(p_engine, p_scene, p_canvas, p_sceneLoadedCallback, p_progressCallback, p_additionnalRenderLoopLogicCallback, p_textureLoadingCallback, p_startingProcessingFilesCallback) {
  11080. this._engine = p_engine;
  11081. this._canvas = p_canvas;
  11082. this._currentScene = p_scene;
  11083. this._sceneLoadedCallback = p_sceneLoadedCallback;
  11084. this._progressCallback = p_progressCallback;
  11085. this._additionnalRenderLoopLogicCallback = p_additionnalRenderLoopLogicCallback;
  11086. this._textureLoadingCallback = p_textureLoadingCallback;
  11087. this._startingProcessingFilesCallback = p_startingProcessingFilesCallback;
  11088. }
  11089. FilesInput.prototype.monitorElementForDragNDrop = function (p_elementToMonitor) {
  11090. var _this = this;
  11091. if (p_elementToMonitor) {
  11092. this._elementToMonitor = p_elementToMonitor;
  11093. this._elementToMonitor.addEventListener("dragenter", function (e) { _this.drag(e); }, false);
  11094. this._elementToMonitor.addEventListener("dragover", function (e) { _this.drag(e); }, false);
  11095. this._elementToMonitor.addEventListener("drop", function (e) { _this.drop(e); }, false);
  11096. }
  11097. };
  11098. FilesInput.prototype.renderFunction = function () {
  11099. if (this._additionnalRenderLoopLogicCallback) {
  11100. this._additionnalRenderLoopLogicCallback();
  11101. }
  11102. if (this._currentScene) {
  11103. if (this._textureLoadingCallback) {
  11104. var remaining = this._currentScene.getWaitingItemsCount();
  11105. if (remaining > 0) {
  11106. this._textureLoadingCallback(remaining);
  11107. }
  11108. }
  11109. this._currentScene.render();
  11110. }
  11111. };
  11112. FilesInput.prototype.drag = function (e) {
  11113. e.stopPropagation();
  11114. e.preventDefault();
  11115. };
  11116. FilesInput.prototype.drop = function (eventDrop) {
  11117. eventDrop.stopPropagation();
  11118. eventDrop.preventDefault();
  11119. this.loadFiles(eventDrop);
  11120. };
  11121. FilesInput.prototype.loadFiles = function (event) {
  11122. if (this._startingProcessingFilesCallback)
  11123. this._startingProcessingFilesCallback();
  11124. // Handling data transfer via drag'n'drop
  11125. if (event && event.dataTransfer && event.dataTransfer.files) {
  11126. this._filesToLoad = event.dataTransfer.files;
  11127. }
  11128. // Handling files from input files
  11129. if (event && event.target && event.target.files) {
  11130. this._filesToLoad = event.target.files;
  11131. }
  11132. if (this._filesToLoad && this._filesToLoad.length > 0) {
  11133. for (var i = 0; i < this._filesToLoad.length; i++) {
  11134. var name_1 = this._filesToLoad[i].name.toLowerCase();
  11135. var extension = name_1.split('.').pop();
  11136. var type = this._filesToLoad[i].type;
  11137. if (extension === "jpg" || extension === "png" || extension === "bmp" || extension === "jpeg" ||
  11138. type === "image/jpeg" || type === "image/png" || type === "image/bmp") {
  11139. FilesInput.FilesTextures[name_1] = this._filesToLoad[i];
  11140. }
  11141. else {
  11142. if ((extension === "babylon" || extension === "stl" || extension === "obj")
  11143. && name_1.indexOf(".binary.babylon") === -1 && name_1.indexOf(".incremental.babylon") === -1) {
  11144. this._sceneFileToLoad = this._filesToLoad[i];
  11145. }
  11146. else {
  11147. FilesInput.FilesToLoad[name_1] = this._filesToLoad[i];
  11148. }
  11149. }
  11150. }
  11151. this.reload();
  11152. }
  11153. };
  11154. FilesInput.prototype.reload = function () {
  11155. var _this = this;
  11156. var that = this;
  11157. // If a ".babylon" file has been provided
  11158. if (this._sceneFileToLoad) {
  11159. if (this._currentScene) {
  11160. if (BABYLON.Tools.errorsCount > 0) {
  11161. BABYLON.Tools.ClearLogCache();
  11162. BABYLON.Tools.Log("Babylon.js engine (v" + BABYLON.Engine.Version + ") launched");
  11163. }
  11164. this._engine.stopRenderLoop();
  11165. this._currentScene.dispose();
  11166. }
  11167. BABYLON.SceneLoader.Load("file:", this._sceneFileToLoad, this._engine, function (newScene) {
  11168. that._currentScene = newScene;
  11169. // Wait for textures and shaders to be ready
  11170. that._currentScene.executeWhenReady(function () {
  11171. // Attach camera to canvas inputs
  11172. if (!that._currentScene.activeCamera || that._currentScene.lights.length === 0) {
  11173. that._currentScene.createDefaultCameraOrLight();
  11174. }
  11175. that._currentScene.activeCamera.attachControl(that._canvas);
  11176. if (that._sceneLoadedCallback) {
  11177. that._sceneLoadedCallback(_this._sceneFileToLoad, that._currentScene);
  11178. }
  11179. that._engine.runRenderLoop(function () { that.renderFunction(); });
  11180. });
  11181. }, function (progress) {
  11182. if (_this._progressCallback) {
  11183. _this._progressCallback(progress);
  11184. }
  11185. });
  11186. }
  11187. else {
  11188. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  11189. }
  11190. };
  11191. return FilesInput;
  11192. }());
  11193. FilesInput.FilesTextures = new Array();
  11194. FilesInput.FilesToLoad = new Array();
  11195. BABYLON.FilesInput = FilesInput;
  11196. })(BABYLON || (BABYLON = {}));
  11197. //# sourceMappingURL=babylon.filesInput.js.map
  11198. var BABYLON;
  11199. (function (BABYLON) {
  11200. var IntersectionInfo = (function () {
  11201. function IntersectionInfo(bu, bv, distance) {
  11202. this.bu = bu;
  11203. this.bv = bv;
  11204. this.distance = distance;
  11205. this.faceId = 0;
  11206. this.subMeshId = 0;
  11207. }
  11208. return IntersectionInfo;
  11209. }());
  11210. BABYLON.IntersectionInfo = IntersectionInfo;
  11211. var PickingInfo = (function () {
  11212. function PickingInfo() {
  11213. this.hit = false;
  11214. this.distance = 0;
  11215. this.pickedPoint = null;
  11216. this.pickedMesh = null;
  11217. this.bu = 0;
  11218. this.bv = 0;
  11219. this.faceId = -1;
  11220. this.subMeshId = 0;
  11221. this.pickedSprite = null;
  11222. }
  11223. // Methods
  11224. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  11225. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  11226. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  11227. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  11228. return null;
  11229. }
  11230. var indices = this.pickedMesh.getIndices();
  11231. var result;
  11232. if (useVerticesNormals) {
  11233. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  11234. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  11235. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  11236. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  11237. normal0 = normal0.scale(this.bu);
  11238. normal1 = normal1.scale(this.bv);
  11239. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  11240. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  11241. }
  11242. else {
  11243. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  11244. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  11245. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  11246. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  11247. var p1p2 = vertex1.subtract(vertex2);
  11248. var p3p2 = vertex3.subtract(vertex2);
  11249. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  11250. }
  11251. if (useWorldCoordinates) {
  11252. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  11253. }
  11254. return BABYLON.Vector3.Normalize(result);
  11255. };
  11256. PickingInfo.prototype.getTextureCoordinates = function () {
  11257. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  11258. return null;
  11259. }
  11260. var indices = this.pickedMesh.getIndices();
  11261. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  11262. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  11263. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  11264. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  11265. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  11266. uv1 = uv1.scale(this.bu);
  11267. uv2 = uv2.scale(this.bv);
  11268. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  11269. };
  11270. return PickingInfo;
  11271. }());
  11272. BABYLON.PickingInfo = PickingInfo;
  11273. })(BABYLON || (BABYLON = {}));
  11274. //# sourceMappingURL=babylon.pickingInfo.js.map
  11275. var BABYLON;
  11276. (function (BABYLON) {
  11277. var BoundingSphere = (function () {
  11278. function BoundingSphere(minimum, maximum) {
  11279. this.minimum = minimum;
  11280. this.maximum = maximum;
  11281. this._tempRadiusVector = BABYLON.Vector3.Zero();
  11282. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  11283. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  11284. this.radius = distance * 0.5;
  11285. this.centerWorld = BABYLON.Vector3.Zero();
  11286. this._update(BABYLON.Matrix.Identity());
  11287. }
  11288. // Methods
  11289. BoundingSphere.prototype._update = function (world) {
  11290. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  11291. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  11292. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  11293. };
  11294. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  11295. for (var i = 0; i < 6; i++) {
  11296. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  11297. return false;
  11298. }
  11299. return true;
  11300. };
  11301. BoundingSphere.prototype.intersectsPoint = function (point) {
  11302. var x = this.centerWorld.x - point.x;
  11303. var y = this.centerWorld.y - point.y;
  11304. var z = this.centerWorld.z - point.z;
  11305. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  11306. if (Math.abs(this.radiusWorld - distance) < BABYLON.Epsilon)
  11307. return false;
  11308. return true;
  11309. };
  11310. // Statics
  11311. BoundingSphere.Intersects = function (sphere0, sphere1) {
  11312. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  11313. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  11314. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  11315. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  11316. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  11317. return false;
  11318. return true;
  11319. };
  11320. return BoundingSphere;
  11321. }());
  11322. BABYLON.BoundingSphere = BoundingSphere;
  11323. })(BABYLON || (BABYLON = {}));
  11324. //# sourceMappingURL=babylon.boundingSphere.js.map
  11325. var BABYLON;
  11326. (function (BABYLON) {
  11327. var BoundingBox = (function () {
  11328. function BoundingBox(minimum, maximum) {
  11329. this.minimum = minimum;
  11330. this.maximum = maximum;
  11331. this.vectors = new Array();
  11332. this.vectorsWorld = new Array();
  11333. // Bounding vectors
  11334. this.vectors.push(this.minimum.clone());
  11335. this.vectors.push(this.maximum.clone());
  11336. this.vectors.push(this.minimum.clone());
  11337. this.vectors[2].x = this.maximum.x;
  11338. this.vectors.push(this.minimum.clone());
  11339. this.vectors[3].y = this.maximum.y;
  11340. this.vectors.push(this.minimum.clone());
  11341. this.vectors[4].z = this.maximum.z;
  11342. this.vectors.push(this.maximum.clone());
  11343. this.vectors[5].z = this.minimum.z;
  11344. this.vectors.push(this.maximum.clone());
  11345. this.vectors[6].x = this.minimum.x;
  11346. this.vectors.push(this.maximum.clone());
  11347. this.vectors[7].y = this.minimum.y;
  11348. // OBB
  11349. this.center = this.maximum.add(this.minimum).scale(0.5);
  11350. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  11351. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  11352. // World
  11353. for (var index = 0; index < this.vectors.length; index++) {
  11354. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  11355. }
  11356. this.minimumWorld = BABYLON.Vector3.Zero();
  11357. this.maximumWorld = BABYLON.Vector3.Zero();
  11358. this.centerWorld = BABYLON.Vector3.Zero();
  11359. this.extendSizeWorld = BABYLON.Vector3.Zero();
  11360. this._update(BABYLON.Matrix.Identity());
  11361. }
  11362. // Methods
  11363. BoundingBox.prototype.getWorldMatrix = function () {
  11364. return this._worldMatrix;
  11365. };
  11366. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  11367. this._worldMatrix.copyFrom(matrix);
  11368. return this;
  11369. };
  11370. BoundingBox.prototype._update = function (world) {
  11371. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  11372. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  11373. for (var index = 0; index < this.vectors.length; index++) {
  11374. var v = this.vectorsWorld[index];
  11375. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  11376. if (v.x < this.minimumWorld.x)
  11377. this.minimumWorld.x = v.x;
  11378. if (v.y < this.minimumWorld.y)
  11379. this.minimumWorld.y = v.y;
  11380. if (v.z < this.minimumWorld.z)
  11381. this.minimumWorld.z = v.z;
  11382. if (v.x > this.maximumWorld.x)
  11383. this.maximumWorld.x = v.x;
  11384. if (v.y > this.maximumWorld.y)
  11385. this.maximumWorld.y = v.y;
  11386. if (v.z > this.maximumWorld.z)
  11387. this.maximumWorld.z = v.z;
  11388. }
  11389. // Extend
  11390. this.maximumWorld.subtractToRef(this.minimumWorld, this.extendSizeWorld);
  11391. this.extendSizeWorld.scaleInPlace(0.5);
  11392. // OBB
  11393. this.maximumWorld.addToRef(this.minimumWorld, this.centerWorld);
  11394. this.centerWorld.scaleInPlace(0.5);
  11395. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  11396. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  11397. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  11398. this._worldMatrix = world;
  11399. };
  11400. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  11401. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  11402. };
  11403. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  11404. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  11405. };
  11406. BoundingBox.prototype.intersectsPoint = function (point) {
  11407. var delta = -BABYLON.Epsilon;
  11408. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  11409. return false;
  11410. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  11411. return false;
  11412. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  11413. return false;
  11414. return true;
  11415. };
  11416. BoundingBox.prototype.intersectsSphere = function (sphere) {
  11417. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  11418. };
  11419. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  11420. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  11421. return false;
  11422. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  11423. return false;
  11424. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  11425. return false;
  11426. return true;
  11427. };
  11428. // Statics
  11429. BoundingBox.Intersects = function (box0, box1) {
  11430. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  11431. return false;
  11432. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  11433. return false;
  11434. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  11435. return false;
  11436. return true;
  11437. };
  11438. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  11439. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  11440. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  11441. return (num <= (sphereRadius * sphereRadius));
  11442. };
  11443. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  11444. for (var p = 0; p < 6; p++) {
  11445. for (var i = 0; i < 8; i++) {
  11446. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  11447. return false;
  11448. }
  11449. }
  11450. }
  11451. return true;
  11452. };
  11453. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  11454. for (var p = 0; p < 6; p++) {
  11455. var inCount = 8;
  11456. for (var i = 0; i < 8; i++) {
  11457. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  11458. --inCount;
  11459. }
  11460. else {
  11461. break;
  11462. }
  11463. }
  11464. if (inCount === 0)
  11465. return false;
  11466. }
  11467. return true;
  11468. };
  11469. return BoundingBox;
  11470. }());
  11471. BABYLON.BoundingBox = BoundingBox;
  11472. })(BABYLON || (BABYLON = {}));
  11473. //# sourceMappingURL=babylon.boundingBox.js.map
  11474. var BABYLON;
  11475. (function (BABYLON) {
  11476. var computeBoxExtents = function (axis, box) {
  11477. var p = BABYLON.Vector3.Dot(box.centerWorld, axis);
  11478. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  11479. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  11480. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  11481. var r = r0 + r1 + r2;
  11482. return {
  11483. min: p - r,
  11484. max: p + r
  11485. };
  11486. };
  11487. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  11488. var axisOverlap = function (axis, box0, box1) {
  11489. var result0 = computeBoxExtents(axis, box0);
  11490. var result1 = computeBoxExtents(axis, box1);
  11491. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  11492. };
  11493. var BoundingInfo = (function () {
  11494. function BoundingInfo(minimum, maximum) {
  11495. this.minimum = minimum;
  11496. this.maximum = maximum;
  11497. this._isLocked = false;
  11498. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  11499. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  11500. }
  11501. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  11502. get: function () {
  11503. return this._isLocked;
  11504. },
  11505. set: function (value) {
  11506. this._isLocked = value;
  11507. },
  11508. enumerable: true,
  11509. configurable: true
  11510. });
  11511. // Methods
  11512. BoundingInfo.prototype.update = function (world) {
  11513. if (this._isLocked) {
  11514. return;
  11515. }
  11516. this.boundingBox._update(world);
  11517. this.boundingSphere._update(world);
  11518. };
  11519. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  11520. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  11521. return false;
  11522. return this.boundingBox.isInFrustum(frustumPlanes);
  11523. };
  11524. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  11525. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  11526. };
  11527. BoundingInfo.prototype._checkCollision = function (collider) {
  11528. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  11529. };
  11530. BoundingInfo.prototype.intersectsPoint = function (point) {
  11531. if (!this.boundingSphere.centerWorld) {
  11532. return false;
  11533. }
  11534. if (!this.boundingSphere.intersectsPoint(point)) {
  11535. return false;
  11536. }
  11537. if (!this.boundingBox.intersectsPoint(point)) {
  11538. return false;
  11539. }
  11540. return true;
  11541. };
  11542. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  11543. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  11544. return false;
  11545. }
  11546. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  11547. return false;
  11548. }
  11549. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  11550. return false;
  11551. }
  11552. if (!precise) {
  11553. return true;
  11554. }
  11555. var box0 = this.boundingBox;
  11556. var box1 = boundingInfo.boundingBox;
  11557. if (!axisOverlap(box0.directions[0], box0, box1))
  11558. return false;
  11559. if (!axisOverlap(box0.directions[1], box0, box1))
  11560. return false;
  11561. if (!axisOverlap(box0.directions[2], box0, box1))
  11562. return false;
  11563. if (!axisOverlap(box1.directions[0], box0, box1))
  11564. return false;
  11565. if (!axisOverlap(box1.directions[1], box0, box1))
  11566. return false;
  11567. if (!axisOverlap(box1.directions[2], box0, box1))
  11568. return false;
  11569. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  11570. return false;
  11571. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  11572. return false;
  11573. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  11574. return false;
  11575. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  11576. return false;
  11577. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  11578. return false;
  11579. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  11580. return false;
  11581. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  11582. return false;
  11583. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  11584. return false;
  11585. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  11586. return false;
  11587. return true;
  11588. };
  11589. return BoundingInfo;
  11590. }());
  11591. BABYLON.BoundingInfo = BoundingInfo;
  11592. })(BABYLON || (BABYLON = {}));
  11593. //# sourceMappingURL=babylon.boundingInfo.js.map
  11594. var BABYLON;
  11595. (function (BABYLON) {
  11596. var Ray = (function () {
  11597. function Ray(origin, direction, length) {
  11598. if (length === void 0) { length = Number.MAX_VALUE; }
  11599. this.origin = origin;
  11600. this.direction = direction;
  11601. this.length = length;
  11602. }
  11603. // Methods
  11604. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  11605. var d = 0.0;
  11606. var maxValue = Number.MAX_VALUE;
  11607. var inv;
  11608. var min;
  11609. var max;
  11610. var temp;
  11611. if (Math.abs(this.direction.x) < 0.0000001) {
  11612. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  11613. return false;
  11614. }
  11615. }
  11616. else {
  11617. inv = 1.0 / this.direction.x;
  11618. min = (minimum.x - this.origin.x) * inv;
  11619. max = (maximum.x - this.origin.x) * inv;
  11620. if (max === -Infinity) {
  11621. max = Infinity;
  11622. }
  11623. if (min > max) {
  11624. temp = min;
  11625. min = max;
  11626. max = temp;
  11627. }
  11628. d = Math.max(min, d);
  11629. maxValue = Math.min(max, maxValue);
  11630. if (d > maxValue) {
  11631. return false;
  11632. }
  11633. }
  11634. if (Math.abs(this.direction.y) < 0.0000001) {
  11635. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  11636. return false;
  11637. }
  11638. }
  11639. else {
  11640. inv = 1.0 / this.direction.y;
  11641. min = (minimum.y - this.origin.y) * inv;
  11642. max = (maximum.y - this.origin.y) * inv;
  11643. if (max === -Infinity) {
  11644. max = Infinity;
  11645. }
  11646. if (min > max) {
  11647. temp = min;
  11648. min = max;
  11649. max = temp;
  11650. }
  11651. d = Math.max(min, d);
  11652. maxValue = Math.min(max, maxValue);
  11653. if (d > maxValue) {
  11654. return false;
  11655. }
  11656. }
  11657. if (Math.abs(this.direction.z) < 0.0000001) {
  11658. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  11659. return false;
  11660. }
  11661. }
  11662. else {
  11663. inv = 1.0 / this.direction.z;
  11664. min = (minimum.z - this.origin.z) * inv;
  11665. max = (maximum.z - this.origin.z) * inv;
  11666. if (max === -Infinity) {
  11667. max = Infinity;
  11668. }
  11669. if (min > max) {
  11670. temp = min;
  11671. min = max;
  11672. max = temp;
  11673. }
  11674. d = Math.max(min, d);
  11675. maxValue = Math.min(max, maxValue);
  11676. if (d > maxValue) {
  11677. return false;
  11678. }
  11679. }
  11680. return true;
  11681. };
  11682. Ray.prototype.intersectsBox = function (box) {
  11683. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  11684. };
  11685. Ray.prototype.intersectsSphere = function (sphere) {
  11686. var x = sphere.center.x - this.origin.x;
  11687. var y = sphere.center.y - this.origin.y;
  11688. var z = sphere.center.z - this.origin.z;
  11689. var pyth = (x * x) + (y * y) + (z * z);
  11690. var rr = sphere.radius * sphere.radius;
  11691. if (pyth <= rr) {
  11692. return true;
  11693. }
  11694. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  11695. if (dot < 0.0) {
  11696. return false;
  11697. }
  11698. var temp = pyth - (dot * dot);
  11699. return temp <= rr;
  11700. };
  11701. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  11702. if (!this._edge1) {
  11703. this._edge1 = BABYLON.Vector3.Zero();
  11704. this._edge2 = BABYLON.Vector3.Zero();
  11705. this._pvec = BABYLON.Vector3.Zero();
  11706. this._tvec = BABYLON.Vector3.Zero();
  11707. this._qvec = BABYLON.Vector3.Zero();
  11708. }
  11709. vertex1.subtractToRef(vertex0, this._edge1);
  11710. vertex2.subtractToRef(vertex0, this._edge2);
  11711. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  11712. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  11713. if (det === 0) {
  11714. return null;
  11715. }
  11716. var invdet = 1 / det;
  11717. this.origin.subtractToRef(vertex0, this._tvec);
  11718. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  11719. if (bu < 0 || bu > 1.0) {
  11720. return null;
  11721. }
  11722. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  11723. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  11724. if (bv < 0 || bu + bv > 1.0) {
  11725. return null;
  11726. }
  11727. //check if the distance is longer than the predefined length.
  11728. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  11729. if (distance > this.length) {
  11730. return null;
  11731. }
  11732. return new BABYLON.IntersectionInfo(bu, bv, distance);
  11733. };
  11734. Ray.prototype.intersectsPlane = function (plane) {
  11735. var distance;
  11736. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  11737. if (Math.abs(result1) < 9.99999997475243E-07) {
  11738. return null;
  11739. }
  11740. else {
  11741. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  11742. distance = (-plane.d - result2) / result1;
  11743. if (distance < 0.0) {
  11744. if (distance < -9.99999997475243E-07) {
  11745. return null;
  11746. }
  11747. else {
  11748. return 0;
  11749. }
  11750. }
  11751. return distance;
  11752. }
  11753. };
  11754. Ray.prototype.intersectsMesh = function (mesh, fastCheck) {
  11755. var tm = BABYLON.Tmp.Matrix[0];
  11756. mesh.getWorldMatrix().invertToRef(tm);
  11757. if (this._tmpRay) {
  11758. Ray.TransformToRef(this, tm, this._tmpRay);
  11759. }
  11760. else {
  11761. this._tmpRay = Ray.Transform(this, tm);
  11762. }
  11763. return mesh.intersects(this._tmpRay, fastCheck);
  11764. };
  11765. Ray.prototype.intersectsMeshes = function (meshes, fastCheck, results) {
  11766. if (results) {
  11767. results.length = 0;
  11768. }
  11769. else {
  11770. results = [];
  11771. }
  11772. for (var i = 0; i < meshes.length; i++) {
  11773. var pickInfo = this.intersectsMesh(meshes[i], fastCheck);
  11774. if (pickInfo.hit) {
  11775. results.push(pickInfo);
  11776. }
  11777. }
  11778. results.sort(this._comparePickingInfo);
  11779. return results;
  11780. };
  11781. Ray.prototype._comparePickingInfo = function (pickingInfoA, pickingInfoB) {
  11782. if (pickingInfoA.distance < pickingInfoB.distance) {
  11783. return -1;
  11784. }
  11785. else if (pickingInfoA.distance > pickingInfoB.distance) {
  11786. return 1;
  11787. }
  11788. else {
  11789. return 0;
  11790. }
  11791. };
  11792. /**
  11793. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  11794. * @param sega the first point of the segment to test the intersection against
  11795. * @param segb the second point of the segment to test the intersection against
  11796. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  11797. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  11798. */
  11799. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  11800. var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
  11801. var u = segb.subtract(sega);
  11802. var v = rsegb.subtract(this.origin);
  11803. var w = sega.subtract(this.origin);
  11804. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  11805. var b = BABYLON.Vector3.Dot(u, v);
  11806. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  11807. var d = BABYLON.Vector3.Dot(u, w);
  11808. var e = BABYLON.Vector3.Dot(v, w);
  11809. var D = a * c - b * b; // always >= 0
  11810. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  11811. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  11812. // compute the line parameters of the two closest points
  11813. if (D < Ray.smallnum) {
  11814. sN = 0.0; // force using point P0 on segment S1
  11815. sD = 1.0; // to prevent possible division by 0.0 later
  11816. tN = e;
  11817. tD = c;
  11818. }
  11819. else {
  11820. sN = (b * e - c * d);
  11821. tN = (a * e - b * d);
  11822. if (sN < 0.0) {
  11823. sN = 0.0;
  11824. tN = e;
  11825. tD = c;
  11826. }
  11827. else if (sN > sD) {
  11828. sN = sD;
  11829. tN = e + b;
  11830. tD = c;
  11831. }
  11832. }
  11833. if (tN < 0.0) {
  11834. tN = 0.0;
  11835. // recompute sc for this edge
  11836. if (-d < 0.0) {
  11837. sN = 0.0;
  11838. }
  11839. else if (-d > a)
  11840. sN = sD;
  11841. else {
  11842. sN = -d;
  11843. sD = a;
  11844. }
  11845. }
  11846. else if (tN > tD) {
  11847. tN = tD;
  11848. // recompute sc for this edge
  11849. if ((-d + b) < 0.0) {
  11850. sN = 0;
  11851. }
  11852. else if ((-d + b) > a) {
  11853. sN = sD;
  11854. }
  11855. else {
  11856. sN = (-d + b);
  11857. sD = a;
  11858. }
  11859. }
  11860. // finally do the division to get sc and tc
  11861. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  11862. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  11863. // get the difference of the two closest points
  11864. var qtc = v.multiplyByFloats(tc, tc, tc);
  11865. var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)
  11866. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  11867. if (isIntersected) {
  11868. return qtc.length();
  11869. }
  11870. return -1;
  11871. };
  11872. // Statics
  11873. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  11874. var start = BABYLON.Vector3.Unproject(new BABYLON.Vector3(x, y, 0), viewportWidth, viewportHeight, world, view, projection);
  11875. var end = BABYLON.Vector3.Unproject(new BABYLON.Vector3(x, y, 1), viewportWidth, viewportHeight, world, view, projection);
  11876. var direction = end.subtract(start);
  11877. direction.normalize();
  11878. return new Ray(start, direction);
  11879. };
  11880. /**
  11881. * 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
  11882. * transformed to the given world matrix.
  11883. * @param origin The origin point
  11884. * @param end The end point
  11885. * @param world a matrix to transform the ray to. Default is the identity matrix.
  11886. */
  11887. Ray.CreateNewFromTo = function (origin, end, world) {
  11888. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  11889. var direction = end.subtract(origin);
  11890. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  11891. direction.normalize();
  11892. return Ray.Transform(new Ray(origin, direction, length), world);
  11893. };
  11894. Ray.Transform = function (ray, matrix) {
  11895. var result = new Ray(new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, 0));
  11896. Ray.TransformToRef(ray, matrix, result);
  11897. return result;
  11898. };
  11899. Ray.TransformToRef = function (ray, matrix, result) {
  11900. BABYLON.Vector3.TransformCoordinatesToRef(ray.origin, matrix, result.origin);
  11901. BABYLON.Vector3.TransformNormalToRef(ray.direction, matrix, result.direction);
  11902. result.length = ray.length;
  11903. var dir = result.direction;
  11904. var len = dir.length();
  11905. if (!(len === 0 || len === 1)) {
  11906. var num = 1.0 / len;
  11907. dir.x *= num;
  11908. dir.y *= num;
  11909. dir.z *= num;
  11910. result.length *= len;
  11911. }
  11912. };
  11913. return Ray;
  11914. }());
  11915. Ray.smallnum = 0.00000001;
  11916. Ray.rayl = 10e8;
  11917. BABYLON.Ray = Ray;
  11918. })(BABYLON || (BABYLON = {}));
  11919. //# sourceMappingURL=babylon.ray.js.map
  11920. var BABYLON;
  11921. (function (BABYLON) {
  11922. var RayHelper = (function () {
  11923. function RayHelper(ray) {
  11924. this.ray = ray;
  11925. }
  11926. RayHelper.CreateAndShow = function (ray, scene, color) {
  11927. var helper = new RayHelper(ray);
  11928. helper.show(scene, color);
  11929. return helper;
  11930. };
  11931. RayHelper.prototype.show = function (scene, color) {
  11932. if (!this._renderFunction) {
  11933. var ray = this.ray;
  11934. this._renderFunction = this._render.bind(this);
  11935. this._scene = scene;
  11936. this._renderPoints = [ray.origin, ray.origin.add(ray.direction.scale(ray.length))];
  11937. this._renderLine = BABYLON.Mesh.CreateLines("ray", this._renderPoints, scene, true);
  11938. this._scene.registerBeforeRender(this._renderFunction);
  11939. }
  11940. if (color) {
  11941. this._renderLine.color.copyFrom(color);
  11942. }
  11943. };
  11944. RayHelper.prototype.hide = function () {
  11945. if (this._renderFunction) {
  11946. this._scene.unregisterBeforeRender(this._renderFunction);
  11947. this._scene = null;
  11948. this._renderFunction = null;
  11949. this._renderLine.dispose();
  11950. this._renderLine = null;
  11951. this._renderPoints = null;
  11952. }
  11953. };
  11954. RayHelper.prototype._render = function () {
  11955. var ray = this.ray;
  11956. var point = this._renderPoints[1];
  11957. var len = Math.min(ray.length, 1000000);
  11958. point.copyFrom(ray.direction);
  11959. point.scaleInPlace(len);
  11960. point.addInPlace(ray.origin);
  11961. BABYLON.Mesh.CreateLines("ray", this._renderPoints, this._scene, true, this._renderLine);
  11962. };
  11963. RayHelper.prototype.attachToMesh = function (mesh, meshSpaceDirection, meshSpaceOrigin, length) {
  11964. this._attachedToMesh = mesh;
  11965. var ray = this.ray;
  11966. if (!ray.direction) {
  11967. ray.direction = BABYLON.Vector3.Zero();
  11968. }
  11969. if (!ray.origin) {
  11970. ray.origin = BABYLON.Vector3.Zero();
  11971. }
  11972. if (length) {
  11973. ray.length = length;
  11974. }
  11975. if (!meshSpaceOrigin) {
  11976. meshSpaceOrigin = BABYLON.Vector3.Zero();
  11977. }
  11978. if (!meshSpaceDirection) {
  11979. // -1 so that this will work with Mesh.lookAt
  11980. meshSpaceDirection = new BABYLON.Vector3(0, 0, -1);
  11981. }
  11982. if (!this._meshSpaceDirection) {
  11983. this._meshSpaceDirection = meshSpaceDirection.clone();
  11984. this._meshSpaceOrigin = meshSpaceOrigin.clone();
  11985. }
  11986. else {
  11987. this._meshSpaceDirection.copyFrom(meshSpaceDirection);
  11988. this._meshSpaceOrigin.copyFrom(meshSpaceOrigin);
  11989. }
  11990. if (!this._updateToMeshFunction) {
  11991. this._updateToMeshFunction = this._updateToMesh.bind(this);
  11992. this._attachedToMesh.getScene().registerBeforeRender(this._updateToMeshFunction);
  11993. }
  11994. this._updateToMesh();
  11995. };
  11996. RayHelper.prototype.detachFromMesh = function () {
  11997. if (this._attachedToMesh) {
  11998. this._attachedToMesh.getScene().unregisterBeforeRender(this._updateToMeshFunction);
  11999. this._attachedToMesh = null;
  12000. this._updateToMeshFunction = null;
  12001. }
  12002. };
  12003. RayHelper.prototype._updateToMesh = function () {
  12004. var ray = this.ray;
  12005. if (this._attachedToMesh._isDisposed) {
  12006. this.detachFromMesh();
  12007. return;
  12008. }
  12009. this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection, ray.direction);
  12010. BABYLON.Vector3.TransformCoordinatesToRef(this._meshSpaceOrigin, this._attachedToMesh.getWorldMatrix(), ray.origin);
  12011. };
  12012. RayHelper.prototype.dispose = function () {
  12013. this.hide();
  12014. this.detachFromMesh();
  12015. this.ray = null;
  12016. };
  12017. return RayHelper;
  12018. }());
  12019. BABYLON.RayHelper = RayHelper;
  12020. })(BABYLON || (BABYLON = {}));
  12021. //# sourceMappingURL=babylon.rayHelper.js.map
  12022. var BABYLON;
  12023. (function (BABYLON) {
  12024. var AbstractMesh = (function (_super) {
  12025. __extends(AbstractMesh, _super);
  12026. // Constructor
  12027. function AbstractMesh(name, scene) {
  12028. var _this = _super.call(this, name, scene) || this;
  12029. _this._facetNb = 0; // facet number
  12030. _this._partitioningSubdivisions = 10; // number of subdivisions per axis in the partioning space
  12031. _this._partitioningBBoxRatio = 1.01; // the partioning array space is by default 1% bigger than the bounding box
  12032. _this._facetDataEnabled = false; // is the facet data feature enabled on this mesh ?
  12033. _this._facetParameters = {}; // keep a reference to the object parameters to avoid memory re-allocation
  12034. _this._bbSize = BABYLON.Vector3.Zero(); // bbox size approximated for facet data
  12035. _this._subDiv = {
  12036. max: 1,
  12037. X: 1,
  12038. Y: 1,
  12039. Z: 1
  12040. };
  12041. // Events
  12042. /**
  12043. * An event triggered when this mesh collides with another one
  12044. * @type {BABYLON.Observable}
  12045. */
  12046. _this.onCollideObservable = new BABYLON.Observable();
  12047. /**
  12048. * An event triggered when the collision's position changes
  12049. * @type {BABYLON.Observable}
  12050. */
  12051. _this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  12052. /**
  12053. * An event triggered after the world matrix is updated
  12054. * @type {BABYLON.Observable}
  12055. */
  12056. _this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  12057. // Properties
  12058. _this.definedFacingForward = true; // orientation for POV movement & rotation
  12059. _this.position = new BABYLON.Vector3(0.0, 0.0, 0.0);
  12060. _this._rotation = new BABYLON.Vector3(0.0, 0.0, 0.0);
  12061. _this._scaling = new BABYLON.Vector3(1.0, 1.0, 1.0);
  12062. _this.billboardMode = AbstractMesh.BILLBOARDMODE_NONE;
  12063. _this.visibility = 1.0;
  12064. _this.alphaIndex = Number.MAX_VALUE;
  12065. _this.infiniteDistance = false;
  12066. _this.isVisible = true;
  12067. _this.isPickable = true;
  12068. _this.showBoundingBox = false;
  12069. _this.showSubMeshesBoundingBox = false;
  12070. _this.isBlocker = false;
  12071. _this.renderingGroupId = 0;
  12072. _this.receiveShadows = false;
  12073. _this.renderOutline = false;
  12074. _this.outlineColor = BABYLON.Color3.Red();
  12075. _this.outlineWidth = 0.02;
  12076. _this.renderOverlay = false;
  12077. _this.overlayColor = BABYLON.Color3.Red();
  12078. _this.overlayAlpha = 0.5;
  12079. _this.hasVertexAlpha = false;
  12080. _this.useVertexColors = true;
  12081. _this.applyFog = true;
  12082. _this.computeBonesUsingShaders = true;
  12083. _this.scalingDeterminant = 1;
  12084. _this.numBoneInfluencers = 4;
  12085. _this.useOctreeForRenderingSelection = true;
  12086. _this.useOctreeForPicking = true;
  12087. _this.useOctreeForCollisions = true;
  12088. _this.layerMask = 0x0FFFFFFF;
  12089. /**
  12090. * True if the mesh must be rendered in any case.
  12091. */
  12092. _this.alwaysSelectAsActiveMesh = false;
  12093. // Collisions
  12094. _this._checkCollisions = false;
  12095. _this._collisionMask = -1;
  12096. _this._collisionGroup = -1;
  12097. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  12098. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  12099. _this._collider = new BABYLON.Collider();
  12100. _this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  12101. _this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  12102. _this._newPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  12103. // Edges
  12104. _this.edgesWidth = 1;
  12105. _this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  12106. // Cache
  12107. _this._localWorld = BABYLON.Matrix.Zero();
  12108. _this._worldMatrix = BABYLON.Matrix.Zero();
  12109. _this._absolutePosition = BABYLON.Vector3.Zero();
  12110. _this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  12111. _this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  12112. _this._isDirty = false;
  12113. _this._pivotMatrix = BABYLON.Matrix.Identity();
  12114. _this._isDisposed = false;
  12115. _this._renderId = 0;
  12116. _this._intersectionsInProgress = new Array();
  12117. _this._isWorldMatrixFrozen = false;
  12118. _this._unIndexed = false;
  12119. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  12120. if (collidedMesh === void 0) { collidedMesh = null; }
  12121. //TODO move this to the collision coordinator!
  12122. if (_this.getScene().workerCollisions)
  12123. newPosition.multiplyInPlace(_this._collider.radius);
  12124. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  12125. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  12126. _this.position.addInPlace(_this._diffPositionForCollisions);
  12127. }
  12128. if (collidedMesh) {
  12129. _this.onCollideObservable.notifyObservers(collidedMesh);
  12130. }
  12131. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  12132. };
  12133. _this.getScene().addMesh(_this);
  12134. return _this;
  12135. }
  12136. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  12137. get: function () {
  12138. return AbstractMesh._BILLBOARDMODE_NONE;
  12139. },
  12140. enumerable: true,
  12141. configurable: true
  12142. });
  12143. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  12144. get: function () {
  12145. return AbstractMesh._BILLBOARDMODE_X;
  12146. },
  12147. enumerable: true,
  12148. configurable: true
  12149. });
  12150. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  12151. get: function () {
  12152. return AbstractMesh._BILLBOARDMODE_Y;
  12153. },
  12154. enumerable: true,
  12155. configurable: true
  12156. });
  12157. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  12158. get: function () {
  12159. return AbstractMesh._BILLBOARDMODE_Z;
  12160. },
  12161. enumerable: true,
  12162. configurable: true
  12163. });
  12164. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  12165. get: function () {
  12166. return AbstractMesh._BILLBOARDMODE_ALL;
  12167. },
  12168. enumerable: true,
  12169. configurable: true
  12170. });
  12171. Object.defineProperty(AbstractMesh.prototype, "facetNb", {
  12172. /**
  12173. * Read-only : the number of facets in the mesh
  12174. */
  12175. get: function () {
  12176. return this._facetNb;
  12177. },
  12178. enumerable: true,
  12179. configurable: true
  12180. });
  12181. Object.defineProperty(AbstractMesh.prototype, "partitioningSubdivisions", {
  12182. /**
  12183. * The number (integer) of subdivisions per axis in the partioning space
  12184. */
  12185. get: function () {
  12186. return this._partitioningSubdivisions;
  12187. },
  12188. set: function (nb) {
  12189. this._partitioningSubdivisions = nb;
  12190. },
  12191. enumerable: true,
  12192. configurable: true
  12193. });
  12194. Object.defineProperty(AbstractMesh.prototype, "partitioningBBoxRatio", {
  12195. /**
  12196. * The ratio (float) to apply to the bouding box size to set to the partioning space.
  12197. * Ex : 1.01 (default) the partioning space is 1% bigger than the bounding box.
  12198. */
  12199. get: function () {
  12200. return this._partitioningBBoxRatio;
  12201. },
  12202. set: function (ratio) {
  12203. this._partitioningBBoxRatio = ratio;
  12204. },
  12205. enumerable: true,
  12206. configurable: true
  12207. });
  12208. Object.defineProperty(AbstractMesh.prototype, "isFacetDataEnabled", {
  12209. /**
  12210. * Read-only boolean : is the feature facetData enabled ?
  12211. */
  12212. get: function () {
  12213. return this._facetDataEnabled;
  12214. },
  12215. enumerable: true,
  12216. configurable: true
  12217. });
  12218. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  12219. set: function (callback) {
  12220. if (this._onCollideObserver) {
  12221. this.onCollideObservable.remove(this._onCollideObserver);
  12222. }
  12223. this._onCollideObserver = this.onCollideObservable.add(callback);
  12224. },
  12225. enumerable: true,
  12226. configurable: true
  12227. });
  12228. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  12229. set: function (callback) {
  12230. if (this._onCollisionPositionChangeObserver) {
  12231. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  12232. }
  12233. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  12234. },
  12235. enumerable: true,
  12236. configurable: true
  12237. });
  12238. Object.defineProperty(AbstractMesh.prototype, "collisionMask", {
  12239. get: function () {
  12240. return this._collisionMask;
  12241. },
  12242. set: function (mask) {
  12243. this._collisionMask = !isNaN(mask) ? mask : -1;
  12244. },
  12245. enumerable: true,
  12246. configurable: true
  12247. });
  12248. Object.defineProperty(AbstractMesh.prototype, "collisionGroup", {
  12249. get: function () {
  12250. return this._collisionGroup;
  12251. },
  12252. set: function (mask) {
  12253. this._collisionGroup = !isNaN(mask) ? mask : -1;
  12254. },
  12255. enumerable: true,
  12256. configurable: true
  12257. });
  12258. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  12259. get: function () {
  12260. return this._skeleton;
  12261. },
  12262. set: function (value) {
  12263. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  12264. this._skeleton._unregisterMeshWithPoseMatrix(this);
  12265. }
  12266. if (value && value.needInitialSkinMatrix) {
  12267. value._registerMeshWithPoseMatrix(this);
  12268. }
  12269. this._skeleton = value;
  12270. if (!this._skeleton) {
  12271. this._bonesTransformMatrices = null;
  12272. }
  12273. },
  12274. enumerable: true,
  12275. configurable: true
  12276. });
  12277. /**
  12278. * Returns the string "AbstractMesh"
  12279. */
  12280. AbstractMesh.prototype.getClassName = function () {
  12281. return "AbstractMesh";
  12282. };
  12283. /**
  12284. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  12285. */
  12286. AbstractMesh.prototype.toString = function (fullDetails) {
  12287. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  12288. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  12289. if (this._skeleton) {
  12290. ret += ", skeleton: " + this._skeleton.name;
  12291. }
  12292. if (fullDetails) {
  12293. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  12294. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  12295. }
  12296. return ret;
  12297. };
  12298. Object.defineProperty(AbstractMesh.prototype, "rotation", {
  12299. /**
  12300. * Rotation property : a Vector3 depicting the rotation value in radians around each local axis X, Y, Z.
  12301. * If rotation quaternion is set, this Vector3 will (almost always) be the Zero vector!
  12302. * Default : (0.0, 0.0, 0.0)
  12303. */
  12304. get: function () {
  12305. return this._rotation;
  12306. },
  12307. set: function (newRotation) {
  12308. this._rotation = newRotation;
  12309. },
  12310. enumerable: true,
  12311. configurable: true
  12312. });
  12313. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  12314. /**
  12315. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  12316. * Default : (1.0, 1.0, 1.0)
  12317. */
  12318. get: function () {
  12319. return this._scaling;
  12320. },
  12321. set: function (newScaling) {
  12322. this._scaling = newScaling;
  12323. if (this.physicsImpostor) {
  12324. this.physicsImpostor.forceUpdate();
  12325. }
  12326. },
  12327. enumerable: true,
  12328. configurable: true
  12329. });
  12330. Object.defineProperty(AbstractMesh.prototype, "rotationQuaternion", {
  12331. /**
  12332. * Rotation Quaternion property : this a Quaternion object depicting the mesh rotation by using a unit quaternion.
  12333. * It's null by default.
  12334. * If set, only the rotationQuaternion is then used to compute the mesh rotation and its property `.rotation\ is then ignored and set to (0.0, 0.0, 0.0)
  12335. */
  12336. get: function () {
  12337. return this._rotationQuaternion;
  12338. },
  12339. set: function (quaternion) {
  12340. this._rotationQuaternion = quaternion;
  12341. //reset the rotation vector.
  12342. if (quaternion && this.rotation.length()) {
  12343. this.rotation.copyFromFloats(0.0, 0.0, 0.0);
  12344. }
  12345. },
  12346. enumerable: true,
  12347. configurable: true
  12348. });
  12349. // Methods
  12350. /**
  12351. * Copies the paramater passed Matrix into the mesh Pose matrix.
  12352. * Returns the AbstractMesh.
  12353. */
  12354. AbstractMesh.prototype.updatePoseMatrix = function (matrix) {
  12355. this._poseMatrix.copyFrom(matrix);
  12356. return this;
  12357. };
  12358. /**
  12359. * Returns the mesh Pose matrix.
  12360. * Returned object : Matrix
  12361. */
  12362. AbstractMesh.prototype.getPoseMatrix = function () {
  12363. return this._poseMatrix;
  12364. };
  12365. /**
  12366. * Disables the mesh edger rendering mode.
  12367. * Returns the AbstractMesh.
  12368. */
  12369. AbstractMesh.prototype.disableEdgesRendering = function () {
  12370. if (this._edgesRenderer !== undefined) {
  12371. this._edgesRenderer.dispose();
  12372. this._edgesRenderer = undefined;
  12373. }
  12374. return this;
  12375. };
  12376. /**
  12377. * Enables the edge rendering mode on the mesh.
  12378. * This mode makes the mesh edges visible.
  12379. * Returns the AbstractMesh.
  12380. */
  12381. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  12382. if (epsilon === void 0) { epsilon = 0.95; }
  12383. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  12384. this.disableEdgesRendering();
  12385. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  12386. return this;
  12387. };
  12388. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  12389. /**
  12390. * Returns true if the mesh is blocked. Used by the class Mesh.
  12391. * Returns the boolean `false` by default.
  12392. */
  12393. get: function () {
  12394. return false;
  12395. },
  12396. enumerable: true,
  12397. configurable: true
  12398. });
  12399. /**
  12400. * Returns the mesh itself by default, used by the class Mesh.
  12401. * Returned type : AbstractMesh
  12402. */
  12403. AbstractMesh.prototype.getLOD = function (camera) {
  12404. return this;
  12405. };
  12406. /**
  12407. * Returns 0 by default, used by the class Mesh.
  12408. * Returns an integer.
  12409. */
  12410. AbstractMesh.prototype.getTotalVertices = function () {
  12411. return 0;
  12412. };
  12413. /**
  12414. * Returns null by default, used by the class Mesh.
  12415. * Returned type : integer array
  12416. */
  12417. AbstractMesh.prototype.getIndices = function () {
  12418. return null;
  12419. };
  12420. /**
  12421. * Returns the array of the requested vertex data kind. Used by the class Mesh. Returns null here.
  12422. * Returned type : float array or Float32Array
  12423. */
  12424. AbstractMesh.prototype.getVerticesData = function (kind) {
  12425. return null;
  12426. };
  12427. /** Returns false by default, used by the class Mesh.
  12428. * Returns a boolean
  12429. */
  12430. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  12431. return false;
  12432. };
  12433. /**
  12434. * Returns the mesh BoundingInfo object or creates a new one and returns it if undefined.
  12435. * Returns a BoundingInfo
  12436. */
  12437. AbstractMesh.prototype.getBoundingInfo = function () {
  12438. if (this._masterMesh) {
  12439. return this._masterMesh.getBoundingInfo();
  12440. }
  12441. if (!this._boundingInfo) {
  12442. this._updateBoundingInfo();
  12443. }
  12444. return this._boundingInfo;
  12445. };
  12446. /**
  12447. * Sets a mesh new object BoundingInfo.
  12448. * Returns the AbstractMesh.
  12449. */
  12450. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  12451. this._boundingInfo = boundingInfo;
  12452. return this;
  12453. };
  12454. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  12455. get: function () {
  12456. return this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind);
  12457. },
  12458. enumerable: true,
  12459. configurable: true
  12460. });
  12461. AbstractMesh.prototype._preActivate = function () {
  12462. };
  12463. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  12464. };
  12465. AbstractMesh.prototype._activate = function (renderId) {
  12466. this._renderId = renderId;
  12467. };
  12468. /**
  12469. * Returns the last update of the World matrix
  12470. * Returns a Matrix.
  12471. */
  12472. AbstractMesh.prototype.getWorldMatrix = function () {
  12473. if (this._masterMesh) {
  12474. return this._masterMesh.getWorldMatrix();
  12475. }
  12476. if (this._currentRenderId !== this.getScene().getRenderId() || !this.isSynchronized()) {
  12477. this.computeWorldMatrix();
  12478. }
  12479. return this._worldMatrix;
  12480. };
  12481. Object.defineProperty(AbstractMesh.prototype, "worldMatrixFromCache", {
  12482. /**
  12483. * Returns directly the last state of the mesh World matrix.
  12484. * A Matrix is returned.
  12485. */
  12486. get: function () {
  12487. return this._worldMatrix;
  12488. },
  12489. enumerable: true,
  12490. configurable: true
  12491. });
  12492. Object.defineProperty(AbstractMesh.prototype, "absolutePosition", {
  12493. /**
  12494. * Returns the current mesh absolute position.
  12495. * Retuns a Vector3.
  12496. */
  12497. get: function () {
  12498. return this._absolutePosition;
  12499. },
  12500. enumerable: true,
  12501. configurable: true
  12502. });
  12503. /**
  12504. * Prevents the World matrix to be computed any longer.
  12505. * Returns the AbstractMesh.
  12506. */
  12507. AbstractMesh.prototype.freezeWorldMatrix = function () {
  12508. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  12509. this.computeWorldMatrix(true);
  12510. this._isWorldMatrixFrozen = true;
  12511. return this;
  12512. };
  12513. /**
  12514. * Allows back the World matrix computation.
  12515. * Returns the AbstractMesh.
  12516. */
  12517. AbstractMesh.prototype.unfreezeWorldMatrix = function () {
  12518. this._isWorldMatrixFrozen = false;
  12519. this.computeWorldMatrix(true);
  12520. return this;
  12521. };
  12522. Object.defineProperty(AbstractMesh.prototype, "isWorldMatrixFrozen", {
  12523. /**
  12524. * True if the World matrix has been frozen.
  12525. * Returns a boolean.
  12526. */
  12527. get: function () {
  12528. return this._isWorldMatrixFrozen;
  12529. },
  12530. enumerable: true,
  12531. configurable: true
  12532. });
  12533. /**
  12534. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in the given space.
  12535. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  12536. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  12537. * The passed axis is also normalized.
  12538. * Returns the AbstractMesh.
  12539. */
  12540. AbstractMesh.prototype.rotate = function (axis, amount, space) {
  12541. axis.normalize();
  12542. if (!this.rotationQuaternion) {
  12543. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  12544. this.rotation = BABYLON.Vector3.Zero();
  12545. }
  12546. var rotationQuaternion;
  12547. if (!space || space === BABYLON.Space.LOCAL) {
  12548. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, AbstractMesh._rotationAxisCache);
  12549. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  12550. }
  12551. else {
  12552. if (this.parent) {
  12553. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  12554. invertParentWorldMatrix.invert();
  12555. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  12556. }
  12557. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, AbstractMesh._rotationAxisCache);
  12558. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  12559. }
  12560. return this;
  12561. };
  12562. /**
  12563. * Translates the mesh along the axis vector for the passed distance in the given space.
  12564. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  12565. * Returns the AbstractMesh.
  12566. */
  12567. AbstractMesh.prototype.translate = function (axis, distance, space) {
  12568. var displacementVector = axis.scale(distance);
  12569. if (!space || space === BABYLON.Space.LOCAL) {
  12570. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  12571. this.setPositionWithLocalVector(tempV3);
  12572. }
  12573. else {
  12574. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  12575. }
  12576. return this;
  12577. };
  12578. /**
  12579. * Adds a rotation step to the mesh current rotation.
  12580. * x, y, z are Euler angles expressed in radians.
  12581. * This methods updates the current mesh rotation, either mesh.rotation, either mesh.rotationQuaternion if it's set.
  12582. * This means this rotation is made in the mesh local space only.
  12583. * It's useful to set a custom rotation order different from the BJS standard one YXZ.
  12584. * Example : this rotates the mesh first around its local X axis, then around its local Z axis, finally around its local Y axis.
  12585. * ```javascript
  12586. * mesh.addRotation(x1, 0, 0).addRotation(0, 0, z2).addRotation(0, 0, y3);
  12587. * ```
  12588. * Note that `addRotation()` accumulates the passed rotation values to the current ones and computes the .rotation or .rotationQuaternion updated values.
  12589. * Under the hood, only quaternions are used. So it's a little faster is you use .rotationQuaternion because it doesn't need to translate them back to Euler angles.
  12590. * Returns the AbstractMesh.
  12591. */
  12592. AbstractMesh.prototype.addRotation = function (x, y, z) {
  12593. var rotationQuaternion;
  12594. if (this.rotationQuaternion) {
  12595. rotationQuaternion = this.rotationQuaternion;
  12596. }
  12597. else {
  12598. rotationQuaternion = BABYLON.Tmp.Quaternion[1];
  12599. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, rotationQuaternion);
  12600. }
  12601. var accumulation = BABYLON.Tmp.Quaternion[0];
  12602. BABYLON.Quaternion.RotationYawPitchRollToRef(y, x, z, accumulation);
  12603. rotationQuaternion.multiplyInPlace(accumulation);
  12604. if (!this.rotationQuaternion) {
  12605. rotationQuaternion.toEulerAnglesToRef(this.rotation);
  12606. }
  12607. return this;
  12608. };
  12609. /**
  12610. * Retuns the mesh absolute position in the World.
  12611. * Returns a Vector3.
  12612. */
  12613. AbstractMesh.prototype.getAbsolutePosition = function () {
  12614. this.computeWorldMatrix();
  12615. return this._absolutePosition;
  12616. };
  12617. /**
  12618. * Sets the mesh absolute position in the World from a Vector3 or an Array(3).
  12619. * Returns the AbstractMesh.
  12620. */
  12621. AbstractMesh.prototype.setAbsolutePosition = function (absolutePosition) {
  12622. if (!absolutePosition) {
  12623. return;
  12624. }
  12625. var absolutePositionX;
  12626. var absolutePositionY;
  12627. var absolutePositionZ;
  12628. if (absolutePosition.x === undefined) {
  12629. if (arguments.length < 3) {
  12630. return;
  12631. }
  12632. absolutePositionX = arguments[0];
  12633. absolutePositionY = arguments[1];
  12634. absolutePositionZ = arguments[2];
  12635. }
  12636. else {
  12637. absolutePositionX = absolutePosition.x;
  12638. absolutePositionY = absolutePosition.y;
  12639. absolutePositionZ = absolutePosition.z;
  12640. }
  12641. if (this.parent) {
  12642. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  12643. invertParentWorldMatrix.invert();
  12644. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  12645. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  12646. }
  12647. else {
  12648. this.position.x = absolutePositionX;
  12649. this.position.y = absolutePositionY;
  12650. this.position.z = absolutePositionZ;
  12651. }
  12652. return this;
  12653. };
  12654. // ================================== Point of View Movement =================================
  12655. /**
  12656. * Perform relative position change from the point of view of behind the front of the mesh.
  12657. * This is performed taking into account the meshes current rotation, so you do not have to care.
  12658. * Supports definition of mesh facing forward or backward.
  12659. * @param {number} amountRight
  12660. * @param {number} amountUp
  12661. * @param {number} amountForward
  12662. *
  12663. * Returns the AbstractMesh.
  12664. */
  12665. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  12666. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  12667. return this;
  12668. };
  12669. /**
  12670. * Calculate relative position change from the point of view of behind the front of the mesh.
  12671. * This is performed taking into account the meshes current rotation, so you do not have to care.
  12672. * Supports definition of mesh facing forward or backward.
  12673. * @param {number} amountRight
  12674. * @param {number} amountUp
  12675. * @param {number} amountForward
  12676. *
  12677. * Returns a new Vector3.
  12678. */
  12679. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  12680. var rotMatrix = new BABYLON.Matrix();
  12681. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  12682. rotQuaternion.toRotationMatrix(rotMatrix);
  12683. var translationDelta = BABYLON.Vector3.Zero();
  12684. var defForwardMult = this.definedFacingForward ? -1 : 1;
  12685. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  12686. return translationDelta;
  12687. };
  12688. // ================================== Point of View Rotation =================================
  12689. /**
  12690. * Perform relative rotation change from the point of view of behind the front of the mesh.
  12691. * Supports definition of mesh facing forward or backward.
  12692. * @param {number} flipBack
  12693. * @param {number} twirlClockwise
  12694. * @param {number} tiltRight
  12695. *
  12696. * Returns the AbstractMesh.
  12697. */
  12698. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  12699. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  12700. return this;
  12701. };
  12702. /**
  12703. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  12704. * Supports definition of mesh facing forward or backward.
  12705. * @param {number} flipBack
  12706. * @param {number} twirlClockwise
  12707. * @param {number} tiltRight
  12708. *
  12709. * Returns a new Vector3.
  12710. */
  12711. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  12712. var defForwardMult = this.definedFacingForward ? 1 : -1;
  12713. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  12714. };
  12715. /**
  12716. * Sets a new pivot matrix to the mesh.
  12717. * Returns the AbstractMesh.
  12718. */
  12719. AbstractMesh.prototype.setPivotMatrix = function (matrix) {
  12720. this._pivotMatrix = matrix;
  12721. this._cache.pivotMatrixUpdated = true;
  12722. return this;
  12723. };
  12724. /**
  12725. * Returns the mesh pivot matrix.
  12726. * Default : Identity.
  12727. * A Matrix is returned.
  12728. */
  12729. AbstractMesh.prototype.getPivotMatrix = function () {
  12730. return this._pivotMatrix;
  12731. };
  12732. AbstractMesh.prototype._isSynchronized = function () {
  12733. if (this._isDirty) {
  12734. return false;
  12735. }
  12736. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE)
  12737. return false;
  12738. if (this._cache.pivotMatrixUpdated) {
  12739. return false;
  12740. }
  12741. if (this.infiniteDistance) {
  12742. return false;
  12743. }
  12744. if (!this._cache.position.equals(this.position))
  12745. return false;
  12746. if (this.rotationQuaternion) {
  12747. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  12748. return false;
  12749. }
  12750. if (!this._cache.rotation.equals(this.rotation))
  12751. return false;
  12752. if (!this._cache.scaling.equals(this.scaling))
  12753. return false;
  12754. return true;
  12755. };
  12756. AbstractMesh.prototype._initCache = function () {
  12757. _super.prototype._initCache.call(this);
  12758. this._cache.localMatrixUpdated = false;
  12759. this._cache.position = BABYLON.Vector3.Zero();
  12760. this._cache.scaling = BABYLON.Vector3.Zero();
  12761. this._cache.rotation = BABYLON.Vector3.Zero();
  12762. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  12763. this._cache.billboardMode = -1;
  12764. };
  12765. AbstractMesh.prototype.markAsDirty = function (property) {
  12766. if (property === "rotation") {
  12767. this.rotationQuaternion = null;
  12768. }
  12769. this._currentRenderId = Number.MAX_VALUE;
  12770. this._isDirty = true;
  12771. return this;
  12772. };
  12773. /**
  12774. * Updates the mesh BoundingInfo object and all its children BoundingInfo objects also.
  12775. * Returns the AbstractMesh.
  12776. */
  12777. AbstractMesh.prototype._updateBoundingInfo = function () {
  12778. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  12779. this._boundingInfo.update(this.worldMatrixFromCache);
  12780. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  12781. return this;
  12782. };
  12783. /**
  12784. * Update a mesh's children BoundingInfo objects only.
  12785. * Returns the AbstractMesh.
  12786. */
  12787. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  12788. if (!this.subMeshes) {
  12789. return;
  12790. }
  12791. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  12792. var subMesh = this.subMeshes[subIndex];
  12793. if (!subMesh.IsGlobal) {
  12794. subMesh.updateBoundingInfo(matrix);
  12795. }
  12796. }
  12797. return this;
  12798. };
  12799. /**
  12800. * Computes the mesh World matrix and returns it.
  12801. * If the mesh world matrix is frozen, this computation does nothing more than returning the last frozen values.
  12802. * If the parameter `force` is let to `false` (default), the current cached World matrix is returned.
  12803. * If the parameter `force`is set to `true`, the actual computation is done.
  12804. * Returns the mesh World Matrix.
  12805. */
  12806. AbstractMesh.prototype.computeWorldMatrix = function (force) {
  12807. if (this._isWorldMatrixFrozen) {
  12808. return this._worldMatrix;
  12809. }
  12810. if (!force && ((this._currentRenderId === this.getScene().getRenderId() && this.isSynchronized(true)))) {
  12811. this._currentRenderId = this.getScene().getRenderId();
  12812. return this._worldMatrix;
  12813. }
  12814. this._cache.position.copyFrom(this.position);
  12815. this._cache.scaling.copyFrom(this.scaling);
  12816. this._cache.pivotMatrixUpdated = false;
  12817. this._cache.billboardMode = this.billboardMode;
  12818. this._currentRenderId = this.getScene().getRenderId();
  12819. this._isDirty = false;
  12820. // Scaling
  12821. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  12822. // Rotation
  12823. //rotate, if quaternion is set and rotation was used
  12824. if (this.rotationQuaternion) {
  12825. var len = this.rotation.length();
  12826. if (len) {
  12827. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  12828. this.rotation.copyFromFloats(0, 0, 0);
  12829. }
  12830. }
  12831. if (this.rotationQuaternion) {
  12832. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  12833. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  12834. }
  12835. else {
  12836. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  12837. this._cache.rotation.copyFrom(this.rotation);
  12838. }
  12839. // Translation
  12840. if (this.infiniteDistance && !this.parent) {
  12841. var camera = this.getScene().activeCamera;
  12842. if (camera) {
  12843. var cameraWorldMatrix = camera.getWorldMatrix();
  12844. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  12845. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  12846. }
  12847. }
  12848. else {
  12849. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  12850. }
  12851. // Composing transformations
  12852. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  12853. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  12854. // Billboarding (testing PG:http://www.babylonjs-playground.com/#UJEIL#13)
  12855. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE && this.getScene().activeCamera) {
  12856. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_ALL) !== AbstractMesh.BILLBOARDMODE_ALL) {
  12857. // Need to decompose each rotation here
  12858. var currentPosition = BABYLON.Tmp.Vector3[3];
  12859. if (this.parent && this.parent.getWorldMatrix) {
  12860. if (this._meshToBoneReferal) {
  12861. this.parent.getWorldMatrix().multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  12862. BABYLON.Vector3.TransformCoordinatesToRef(this.position, BABYLON.Tmp.Matrix[6], currentPosition);
  12863. }
  12864. else {
  12865. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), currentPosition);
  12866. }
  12867. }
  12868. else {
  12869. currentPosition.copyFrom(this.position);
  12870. }
  12871. currentPosition.subtractInPlace(this.getScene().activeCamera.globalPosition);
  12872. var finalEuler = BABYLON.Tmp.Vector3[4].copyFromFloats(0, 0, 0);
  12873. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_X) === AbstractMesh.BILLBOARDMODE_X) {
  12874. finalEuler.x = Math.atan2(-currentPosition.y, currentPosition.z);
  12875. }
  12876. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_Y) === AbstractMesh.BILLBOARDMODE_Y) {
  12877. finalEuler.y = Math.atan2(currentPosition.x, currentPosition.z);
  12878. }
  12879. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_Z) === AbstractMesh.BILLBOARDMODE_Z) {
  12880. finalEuler.z = Math.atan2(currentPosition.y, currentPosition.x);
  12881. }
  12882. BABYLON.Matrix.RotationYawPitchRollToRef(finalEuler.y, finalEuler.x, finalEuler.z, BABYLON.Tmp.Matrix[0]);
  12883. }
  12884. else {
  12885. BABYLON.Tmp.Matrix[1].copyFrom(this.getScene().activeCamera.getViewMatrix());
  12886. BABYLON.Tmp.Matrix[1].setTranslationFromFloats(0, 0, 0);
  12887. BABYLON.Tmp.Matrix[1].invertToRef(BABYLON.Tmp.Matrix[0]);
  12888. }
  12889. BABYLON.Tmp.Matrix[1].copyFrom(BABYLON.Tmp.Matrix[5]);
  12890. BABYLON.Tmp.Matrix[1].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  12891. }
  12892. // Local world
  12893. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  12894. // Parent
  12895. if (this.parent && this.parent.getWorldMatrix) {
  12896. this._markSyncedWithParent();
  12897. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE) {
  12898. if (this._meshToBoneReferal) {
  12899. this.parent.getWorldMatrix().multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  12900. BABYLON.Tmp.Matrix[5].copyFrom(BABYLON.Tmp.Matrix[6]);
  12901. }
  12902. else {
  12903. BABYLON.Tmp.Matrix[5].copyFrom(this.parent.getWorldMatrix());
  12904. }
  12905. this._localWorld.getTranslationToRef(BABYLON.Tmp.Vector3[5]);
  12906. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Tmp.Vector3[5], BABYLON.Tmp.Matrix[5], BABYLON.Tmp.Vector3[5]);
  12907. this._worldMatrix.copyFrom(this._localWorld);
  12908. this._worldMatrix.setTranslation(BABYLON.Tmp.Vector3[5]);
  12909. }
  12910. else {
  12911. if (this._meshToBoneReferal) {
  12912. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  12913. BABYLON.Tmp.Matrix[6].multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), this._worldMatrix);
  12914. }
  12915. else {
  12916. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  12917. }
  12918. }
  12919. }
  12920. else {
  12921. this._worldMatrix.copyFrom(this._localWorld);
  12922. }
  12923. // Bounding info
  12924. this._updateBoundingInfo();
  12925. // Absolute position
  12926. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  12927. // Callbacks
  12928. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  12929. if (!this._poseMatrix) {
  12930. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  12931. }
  12932. return this._worldMatrix;
  12933. };
  12934. /**
  12935. * If you'd like to be called back after the mesh position, rotation or scaling has been updated.
  12936. * @param func: callback function to add
  12937. *
  12938. * Returns the AbstractMesh.
  12939. */
  12940. AbstractMesh.prototype.registerAfterWorldMatrixUpdate = function (func) {
  12941. this.onAfterWorldMatrixUpdateObservable.add(func);
  12942. return this;
  12943. };
  12944. /**
  12945. * Removes a registered callback function.
  12946. * Returns the AbstractMesh.
  12947. */
  12948. AbstractMesh.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  12949. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  12950. return this;
  12951. };
  12952. /**
  12953. * Sets the mesh position in its local space.
  12954. * Returns the AbstractMesh.
  12955. */
  12956. AbstractMesh.prototype.setPositionWithLocalVector = function (vector3) {
  12957. this.computeWorldMatrix();
  12958. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  12959. return this;
  12960. };
  12961. /**
  12962. * Returns the mesh position in the local space from the current World matrix values.
  12963. * Returns a new Vector3.
  12964. */
  12965. AbstractMesh.prototype.getPositionExpressedInLocalSpace = function () {
  12966. this.computeWorldMatrix();
  12967. var invLocalWorldMatrix = this._localWorld.clone();
  12968. invLocalWorldMatrix.invert();
  12969. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  12970. };
  12971. /**
  12972. * Translates the mesh along the passed Vector3 in its local space.
  12973. * Returns the AbstractMesh.
  12974. */
  12975. AbstractMesh.prototype.locallyTranslate = function (vector3) {
  12976. this.computeWorldMatrix(true);
  12977. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  12978. return this;
  12979. };
  12980. AbstractMesh.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  12981. /// <summary>Orients a mesh towards a target point. Mesh must be drawn facing user.</summary>
  12982. /// <param name="targetPoint" type="Vector3">The position (must be in same space as current mesh) to look at</param>
  12983. /// <param name="yawCor" type="Number">optional yaw (y-axis) correction in radians</param>
  12984. /// <param name="pitchCor" type="Number">optional pitch (x-axis) correction in radians</param>
  12985. /// <param name="rollCor" type="Number">optional roll (z-axis) correction in radians</param>
  12986. /// <returns>Mesh oriented towards targetMesh</returns>
  12987. if (yawCor === void 0) { yawCor = 0; }
  12988. if (pitchCor === void 0) { pitchCor = 0; }
  12989. if (rollCor === void 0) { rollCor = 0; }
  12990. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  12991. var dv = AbstractMesh._lookAtVectorCache;
  12992. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  12993. targetPoint.subtractToRef(pos, dv);
  12994. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  12995. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  12996. var pitch = Math.atan2(dv.y, len);
  12997. this.rotationQuaternion = this.rotationQuaternion || new BABYLON.Quaternion();
  12998. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  12999. return this;
  13000. };
  13001. AbstractMesh.prototype.attachToBone = function (bone, affectedMesh) {
  13002. this._meshToBoneReferal = affectedMesh;
  13003. this.parent = bone;
  13004. if (bone.getWorldMatrix().determinant() < 0) {
  13005. this.scalingDeterminant *= -1;
  13006. }
  13007. return this;
  13008. };
  13009. AbstractMesh.prototype.detachFromBone = function () {
  13010. if (this.parent.getWorldMatrix().determinant() < 0) {
  13011. this.scalingDeterminant *= -1;
  13012. }
  13013. this._meshToBoneReferal = null;
  13014. this.parent = null;
  13015. return this;
  13016. };
  13017. /**
  13018. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  13019. * A mesh is in the frustum if its bounding box intersects the frustum.
  13020. * Boolean returned.
  13021. */
  13022. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  13023. return this._boundingInfo.isInFrustum(frustumPlanes);
  13024. };
  13025. /**
  13026. * Returns `true` if the mesh is completely in the frustum defined be the passed array of planes.
  13027. * A mesh is completely in the frustum if its bounding box it completely inside the frustum.
  13028. * Boolean returned.
  13029. */
  13030. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  13031. return this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  13032. ;
  13033. };
  13034. /**
  13035. * True if the mesh intersects another mesh or a SolidParticle object.
  13036. * Unless the parameter `precise` is set to `true` the intersection is computed according to Axis Aligned Bounding Boxes (AABB), else according to OBB (Oriented BBoxes)
  13037. * Returns a boolean.
  13038. */
  13039. AbstractMesh.prototype.intersectsMesh = function (mesh, precise) {
  13040. if (!this._boundingInfo || !mesh._boundingInfo) {
  13041. return false;
  13042. }
  13043. return this._boundingInfo.intersects(mesh._boundingInfo, precise);
  13044. };
  13045. /**
  13046. * Returns true if the passed point (Vector3) is inside the mesh bounding box.
  13047. * Returns a boolean.
  13048. */
  13049. AbstractMesh.prototype.intersectsPoint = function (point) {
  13050. if (!this._boundingInfo) {
  13051. return false;
  13052. }
  13053. return this._boundingInfo.intersectsPoint(point);
  13054. };
  13055. AbstractMesh.prototype.getPhysicsImpostor = function () {
  13056. return this.physicsImpostor;
  13057. };
  13058. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  13059. if (!camera) {
  13060. camera = this.getScene().activeCamera;
  13061. }
  13062. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  13063. };
  13064. /**
  13065. * Returns the distance from the mesh to the active camera.
  13066. * Returns a float.
  13067. */
  13068. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  13069. if (!camera) {
  13070. camera = this.getScene().activeCamera;
  13071. }
  13072. return this.absolutePosition.subtract(camera.position).length();
  13073. };
  13074. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  13075. if (!this.physicsImpostor) {
  13076. return;
  13077. }
  13078. this.physicsImpostor.applyImpulse(force, contactPoint);
  13079. return this;
  13080. };
  13081. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  13082. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  13083. return;
  13084. }
  13085. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  13086. mainPivot: pivot1,
  13087. connectedPivot: pivot2,
  13088. nativeParams: options
  13089. });
  13090. return this;
  13091. };
  13092. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  13093. // Collisions
  13094. /**
  13095. * Property checkCollisions : Boolean, whether the camera should check the collisions against the mesh.
  13096. * Default `false`.
  13097. */
  13098. get: function () {
  13099. return this._checkCollisions;
  13100. },
  13101. set: function (collisionEnabled) {
  13102. this._checkCollisions = collisionEnabled;
  13103. if (this.getScene().workerCollisions) {
  13104. this.getScene().collisionCoordinator.onMeshUpdated(this);
  13105. }
  13106. },
  13107. enumerable: true,
  13108. configurable: true
  13109. });
  13110. AbstractMesh.prototype.moveWithCollisions = function (velocity) {
  13111. var globalPosition = this.getAbsolutePosition();
  13112. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPositionForCollisions);
  13113. this._oldPositionForCollisions.addInPlace(this.ellipsoidOffset);
  13114. this._collider.radius = this.ellipsoid;
  13115. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, velocity, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  13116. return this;
  13117. };
  13118. // Submeshes octree
  13119. /**
  13120. * This function will create an octree to help to select the right submeshes for rendering, picking and collision computations.
  13121. * Please note that you must have a decent number of submeshes to get performance improvements when using an octree.
  13122. * Returns an Octree of submeshes.
  13123. */
  13124. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  13125. if (maxCapacity === void 0) { maxCapacity = 64; }
  13126. if (maxDepth === void 0) { maxDepth = 2; }
  13127. if (!this._submeshesOctree) {
  13128. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  13129. }
  13130. this.computeWorldMatrix(true);
  13131. // Update octree
  13132. var bbox = this.getBoundingInfo().boundingBox;
  13133. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  13134. return this._submeshesOctree;
  13135. };
  13136. // Collisions
  13137. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  13138. this._generatePointsArray();
  13139. // Transformation
  13140. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  13141. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  13142. subMesh._lastColliderWorldVertices = [];
  13143. subMesh._trianglePlanes = [];
  13144. var start = subMesh.verticesStart;
  13145. var end = (subMesh.verticesStart + subMesh.verticesCount);
  13146. for (var i = start; i < end; i++) {
  13147. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  13148. }
  13149. }
  13150. // Collide
  13151. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  13152. if (collider.collisionFound) {
  13153. collider.collidedMesh = this;
  13154. }
  13155. return this;
  13156. };
  13157. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  13158. var subMeshes;
  13159. var len;
  13160. // Octrees
  13161. if (this._submeshesOctree && this.useOctreeForCollisions) {
  13162. var radius = collider.velocityWorldLength + Math.max(collider.radius.x, collider.radius.y, collider.radius.z);
  13163. var intersections = this._submeshesOctree.intersects(collider.basePointWorld, radius);
  13164. len = intersections.length;
  13165. subMeshes = intersections.data;
  13166. }
  13167. else {
  13168. subMeshes = this.subMeshes;
  13169. len = subMeshes.length;
  13170. }
  13171. for (var index = 0; index < len; index++) {
  13172. var subMesh = subMeshes[index];
  13173. // Bounding test
  13174. if (len > 1 && !subMesh._checkCollision(collider))
  13175. continue;
  13176. this._collideForSubMesh(subMesh, transformMatrix, collider);
  13177. }
  13178. return this;
  13179. };
  13180. AbstractMesh.prototype._checkCollision = function (collider) {
  13181. // Bounding box test
  13182. if (!this._boundingInfo._checkCollision(collider))
  13183. return this;
  13184. // Transformation matrix
  13185. BABYLON.Matrix.ScalingToRef(1.0 / collider.radius.x, 1.0 / collider.radius.y, 1.0 / collider.radius.z, this._collisionsScalingMatrix);
  13186. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  13187. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  13188. return this;
  13189. };
  13190. // Picking
  13191. AbstractMesh.prototype._generatePointsArray = function () {
  13192. return false;
  13193. };
  13194. /**
  13195. * Checks if the passed Ray intersects with the mesh.
  13196. * Returns an object PickingInfo.
  13197. */
  13198. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  13199. var pickingInfo = new BABYLON.PickingInfo();
  13200. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  13201. return pickingInfo;
  13202. }
  13203. if (!this._generatePointsArray()) {
  13204. return pickingInfo;
  13205. }
  13206. var intersectInfo = null;
  13207. // Octrees
  13208. var subMeshes;
  13209. var len;
  13210. if (this._submeshesOctree && this.useOctreeForPicking) {
  13211. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  13212. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  13213. len = intersections.length;
  13214. subMeshes = intersections.data;
  13215. }
  13216. else {
  13217. subMeshes = this.subMeshes;
  13218. len = subMeshes.length;
  13219. }
  13220. for (var index = 0; index < len; index++) {
  13221. var subMesh = subMeshes[index];
  13222. // Bounding test
  13223. if (len > 1 && !subMesh.canIntersects(ray))
  13224. continue;
  13225. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  13226. if (currentIntersectInfo) {
  13227. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  13228. intersectInfo = currentIntersectInfo;
  13229. intersectInfo.subMeshId = index;
  13230. if (fastCheck) {
  13231. break;
  13232. }
  13233. }
  13234. }
  13235. }
  13236. if (intersectInfo) {
  13237. // Get picked point
  13238. var world = this.getWorldMatrix();
  13239. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  13240. var direction = ray.direction.clone();
  13241. direction = direction.scale(intersectInfo.distance);
  13242. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  13243. var pickedPoint = worldOrigin.add(worldDirection);
  13244. // Return result
  13245. pickingInfo.hit = true;
  13246. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  13247. pickingInfo.pickedPoint = pickedPoint;
  13248. pickingInfo.pickedMesh = this;
  13249. pickingInfo.bu = intersectInfo.bu;
  13250. pickingInfo.bv = intersectInfo.bv;
  13251. pickingInfo.faceId = intersectInfo.faceId;
  13252. pickingInfo.subMeshId = intersectInfo.subMeshId;
  13253. return pickingInfo;
  13254. }
  13255. return pickingInfo;
  13256. };
  13257. /**
  13258. * Clones the mesh, used by the class Mesh.
  13259. * Just returns `null` for an AbstractMesh.
  13260. */
  13261. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  13262. return null;
  13263. };
  13264. /**
  13265. * Disposes all the mesh submeshes.
  13266. * Returns the AbstractMesh.
  13267. */
  13268. AbstractMesh.prototype.releaseSubMeshes = function () {
  13269. if (this.subMeshes) {
  13270. while (this.subMeshes.length) {
  13271. this.subMeshes[0].dispose();
  13272. }
  13273. }
  13274. else {
  13275. this.subMeshes = new Array();
  13276. }
  13277. return this;
  13278. };
  13279. /**
  13280. * Disposes the AbstractMesh.
  13281. * Some internal references are kept for further use.
  13282. * By default, all the mesh children are also disposed unless the parameter `doNotRecurse` is set to `true`.
  13283. * Returns nothing.
  13284. */
  13285. AbstractMesh.prototype.dispose = function (doNotRecurse) {
  13286. var _this = this;
  13287. var index;
  13288. // Action manager
  13289. if (this.actionManager) {
  13290. this.actionManager.dispose();
  13291. this.actionManager = null;
  13292. }
  13293. // Skeleton
  13294. this.skeleton = null;
  13295. // Animations
  13296. this.getScene().stopAnimation(this);
  13297. // Physics
  13298. if (this.physicsImpostor) {
  13299. this.physicsImpostor.dispose();
  13300. }
  13301. // Intersections in progress
  13302. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  13303. var other = this._intersectionsInProgress[index];
  13304. var pos = other._intersectionsInProgress.indexOf(this);
  13305. other._intersectionsInProgress.splice(pos, 1);
  13306. }
  13307. this._intersectionsInProgress = [];
  13308. // Lights
  13309. var lights = this.getScene().lights;
  13310. lights.forEach(function (light) {
  13311. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  13312. if (meshIndex !== -1) {
  13313. light.includedOnlyMeshes.splice(meshIndex, 1);
  13314. }
  13315. meshIndex = light.excludedMeshes.indexOf(_this);
  13316. if (meshIndex !== -1) {
  13317. light.excludedMeshes.splice(meshIndex, 1);
  13318. }
  13319. // Shadow generators
  13320. var generator = light.getShadowGenerator();
  13321. if (generator) {
  13322. meshIndex = generator.getShadowMap().renderList.indexOf(_this);
  13323. if (meshIndex !== -1) {
  13324. generator.getShadowMap().renderList.splice(meshIndex, 1);
  13325. }
  13326. }
  13327. });
  13328. // Edges
  13329. if (this._edgesRenderer) {
  13330. this._edgesRenderer.dispose();
  13331. this._edgesRenderer = null;
  13332. }
  13333. // SubMeshes
  13334. if (this.getClassName() !== "InstancedMesh") {
  13335. this.releaseSubMeshes();
  13336. }
  13337. // Engine
  13338. this.getScene().getEngine().wipeCaches();
  13339. // Remove from scene
  13340. this.getScene().removeMesh(this);
  13341. if (!doNotRecurse) {
  13342. // Particles
  13343. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  13344. if (this.getScene().particleSystems[index].emitter === this) {
  13345. this.getScene().particleSystems[index].dispose();
  13346. index--;
  13347. }
  13348. }
  13349. // Children
  13350. var objects = this.getDescendants(true);
  13351. for (index = 0; index < objects.length; index++) {
  13352. objects[index].dispose();
  13353. }
  13354. }
  13355. else {
  13356. var childMeshes = this.getChildMeshes(true);
  13357. for (index = 0; index < childMeshes.length; index++) {
  13358. var child = childMeshes[index];
  13359. child.parent = null;
  13360. child.computeWorldMatrix(true);
  13361. }
  13362. }
  13363. // facet data
  13364. if (this._facetDataEnabled) {
  13365. this.disableFacetData();
  13366. }
  13367. this.onAfterWorldMatrixUpdateObservable.clear();
  13368. this.onCollideObservable.clear();
  13369. this.onCollisionPositionChangeObservable.clear();
  13370. this._isDisposed = true;
  13371. _super.prototype.dispose.call(this);
  13372. };
  13373. /**
  13374. * Returns a new Vector3 what is the localAxis, expressed in the mesh local space, rotated like the mesh.
  13375. * This Vector3 is expressed in the World space.
  13376. */
  13377. AbstractMesh.prototype.getDirection = function (localAxis) {
  13378. var result = BABYLON.Vector3.Zero();
  13379. this.getDirectionToRef(localAxis, result);
  13380. return result;
  13381. };
  13382. /**
  13383. * Sets the Vector3 "result" as the rotated Vector3 "localAxis" in the same rotation than the mesh.
  13384. * localAxis is expressed in the mesh local space.
  13385. * result is computed in the Wordl space from the mesh World matrix.
  13386. * Returns the AbstractMesh.
  13387. */
  13388. AbstractMesh.prototype.getDirectionToRef = function (localAxis, result) {
  13389. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  13390. return this;
  13391. };
  13392. AbstractMesh.prototype.setPivotPoint = function (point, space) {
  13393. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  13394. if (this.getScene().getRenderId() == 0) {
  13395. this.computeWorldMatrix(true);
  13396. }
  13397. var wm = this.getWorldMatrix();
  13398. if (space == BABYLON.Space.WORLD) {
  13399. var tmat = BABYLON.Tmp.Matrix[0];
  13400. wm.invertToRef(tmat);
  13401. point = BABYLON.Vector3.TransformCoordinates(point, tmat);
  13402. }
  13403. BABYLON.Vector3.TransformCoordinatesToRef(point, wm, this.position);
  13404. this._pivotMatrix.m[12] = -point.x;
  13405. this._pivotMatrix.m[13] = -point.y;
  13406. this._pivotMatrix.m[14] = -point.z;
  13407. this._cache.pivotMatrixUpdated = true;
  13408. return this;
  13409. };
  13410. /**
  13411. * Returns a new Vector3 set with the mesh pivot point coordinates in the local space.
  13412. */
  13413. AbstractMesh.prototype.getPivotPoint = function () {
  13414. var point = BABYLON.Vector3.Zero();
  13415. this.getPivotPointToRef(point);
  13416. return point;
  13417. };
  13418. /**
  13419. * Sets the passed Vector3 "result" with the coordinates of the mesh pivot point in the local space.
  13420. * Returns the AbstractMesh.
  13421. */
  13422. AbstractMesh.prototype.getPivotPointToRef = function (result) {
  13423. result.x = -this._pivotMatrix.m[12];
  13424. result.y = -this._pivotMatrix.m[13];
  13425. result.z = -this._pivotMatrix.m[14];
  13426. return this;
  13427. };
  13428. /**
  13429. * Returns a new Vector3 set with the mesh pivot point World coordinates.
  13430. */
  13431. AbstractMesh.prototype.getAbsolutePivotPoint = function () {
  13432. var point = BABYLON.Vector3.Zero();
  13433. this.getAbsolutePivotPointToRef(point);
  13434. return point;
  13435. };
  13436. /**
  13437. * Defines the passed mesh as the parent of the current mesh.
  13438. * If keepWorldPositionRotation is set to `true` (default `false`), the current mesh position and rotation are kept.
  13439. * Returns the AbstractMesh.
  13440. */
  13441. AbstractMesh.prototype.setParent = function (mesh, keepWorldPositionRotation) {
  13442. if (keepWorldPositionRotation === void 0) { keepWorldPositionRotation = false; }
  13443. var child = this;
  13444. var parent = mesh;
  13445. if (mesh == null) {
  13446. if (child.parent && keepWorldPositionRotation) {
  13447. var rotation = BABYLON.Tmp.Quaternion[0];
  13448. var position = BABYLON.Tmp.Vector3[0];
  13449. var scale = BABYLON.Tmp.Vector3[1];
  13450. child.getWorldMatrix().decompose(scale, rotation, position);
  13451. if (child.rotationQuaternion) {
  13452. child.rotationQuaternion.copyFrom(rotation);
  13453. }
  13454. else {
  13455. rotation.toEulerAnglesToRef(child.rotation);
  13456. }
  13457. child.position.x = position.x;
  13458. child.position.y = position.y;
  13459. child.position.z = position.z;
  13460. }
  13461. }
  13462. else {
  13463. if (keepWorldPositionRotation) {
  13464. var rotation = BABYLON.Tmp.Quaternion[0];
  13465. var position = BABYLON.Tmp.Vector3[0];
  13466. var scale = BABYLON.Tmp.Vector3[1];
  13467. var m1 = BABYLON.Tmp.Matrix[0];
  13468. var m2 = BABYLON.Tmp.Matrix[1];
  13469. parent.getWorldMatrix().decompose(scale, rotation, position);
  13470. rotation.toRotationMatrix(m1);
  13471. m2.setTranslation(position);
  13472. m2.multiplyToRef(m1, m1);
  13473. var invParentMatrix = BABYLON.Matrix.Invert(m1);
  13474. var m = child.getWorldMatrix().multiply(invParentMatrix);
  13475. m.decompose(scale, rotation, position);
  13476. if (child.rotationQuaternion) {
  13477. child.rotationQuaternion.copyFrom(rotation);
  13478. }
  13479. else {
  13480. rotation.toEulerAnglesToRef(child.rotation);
  13481. }
  13482. invParentMatrix = BABYLON.Matrix.Invert(parent.getWorldMatrix());
  13483. var m = child.getWorldMatrix().multiply(invParentMatrix);
  13484. m.decompose(scale, rotation, position);
  13485. child.position.x = position.x;
  13486. child.position.y = position.y;
  13487. child.position.z = position.z;
  13488. }
  13489. }
  13490. child.parent = parent;
  13491. return this;
  13492. };
  13493. /**
  13494. * Adds the passed mesh as a child to the current mesh.
  13495. * If keepWorldPositionRotation is set to `true` (default `false`), the child world position and rotation are kept.
  13496. * Returns the AbstractMesh.
  13497. */
  13498. AbstractMesh.prototype.addChild = function (mesh, keepWorldPositionRotation) {
  13499. if (keepWorldPositionRotation === void 0) { keepWorldPositionRotation = false; }
  13500. mesh.setParent(this, keepWorldPositionRotation);
  13501. return this;
  13502. };
  13503. /**
  13504. * Removes the passed mesh from the current mesh children list.
  13505. * Returns the AbstractMesh.
  13506. */
  13507. AbstractMesh.prototype.removeChild = function (mesh, keepWorldPositionRotation) {
  13508. if (keepWorldPositionRotation === void 0) { keepWorldPositionRotation = false; }
  13509. mesh.setParent(null, keepWorldPositionRotation);
  13510. return this;
  13511. };
  13512. /**
  13513. * Sets the Vector3 "result" coordinates with the mesh pivot point World coordinates.
  13514. * Returns the AbstractMesh.
  13515. */
  13516. AbstractMesh.prototype.getAbsolutePivotPointToRef = function (result) {
  13517. result.x = this._pivotMatrix.m[12];
  13518. result.y = this._pivotMatrix.m[13];
  13519. result.z = this._pivotMatrix.m[14];
  13520. this.getPivotPointToRef(result);
  13521. BABYLON.Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
  13522. return this;
  13523. };
  13524. // Facet data
  13525. /**
  13526. * Initialize the facet data arrays : facetNormals, facetPositions and facetPartitioning.
  13527. * Returns the AbstractMesh.
  13528. */
  13529. AbstractMesh.prototype._initFacetData = function () {
  13530. if (!this._facetNormals) {
  13531. this._facetNormals = new Array();
  13532. }
  13533. if (!this._facetPositions) {
  13534. this._facetPositions = new Array();
  13535. }
  13536. if (!this._facetPartitioning) {
  13537. this._facetPartitioning = new Array();
  13538. }
  13539. this._facetNb = this.getIndices().length / 3;
  13540. this._partitioningSubdivisions = (this._partitioningSubdivisions) ? this._partitioningSubdivisions : 10; // default nb of partitioning subdivisions = 10
  13541. this._partitioningBBoxRatio = (this._partitioningBBoxRatio) ? this._partitioningBBoxRatio : 1.01; // default ratio 1.01 = the partitioning is 1% bigger than the bounding box
  13542. for (var f = 0; f < this._facetNb; f++) {
  13543. this._facetNormals[f] = BABYLON.Vector3.Zero();
  13544. this._facetPositions[f] = BABYLON.Vector3.Zero();
  13545. }
  13546. this._facetDataEnabled = true;
  13547. return this;
  13548. };
  13549. /**
  13550. * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated.
  13551. * This method can be called within the render loop.
  13552. * 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.
  13553. * Returns the AbstractMesh.
  13554. */
  13555. AbstractMesh.prototype.updateFacetData = function () {
  13556. if (!this._facetDataEnabled) {
  13557. this._initFacetData();
  13558. }
  13559. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  13560. var indices = this.getIndices();
  13561. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  13562. var bInfo = this.getBoundingInfo();
  13563. this._bbSize.x = (bInfo.maximum.x - bInfo.minimum.x > BABYLON.Epsilon) ? bInfo.maximum.x - bInfo.minimum.x : BABYLON.Epsilon;
  13564. this._bbSize.y = (bInfo.maximum.y - bInfo.minimum.y > BABYLON.Epsilon) ? bInfo.maximum.y - bInfo.minimum.y : BABYLON.Epsilon;
  13565. this._bbSize.z = (bInfo.maximum.z - bInfo.minimum.z > BABYLON.Epsilon) ? bInfo.maximum.z - bInfo.minimum.z : BABYLON.Epsilon;
  13566. var bbSizeMax = (this._bbSize.x > this._bbSize.y) ? this._bbSize.x : this._bbSize.y;
  13567. bbSizeMax = (bbSizeMax > this._bbSize.z) ? bbSizeMax : this._bbSize.z;
  13568. this._subDiv.max = this._partitioningSubdivisions;
  13569. this._subDiv.X = Math.floor(this._subDiv.max * this._bbSize.x / bbSizeMax); // adjust the number of subdivisions per axis
  13570. this._subDiv.Y = Math.floor(this._subDiv.max * this._bbSize.y / bbSizeMax); // according to each bbox size per axis
  13571. this._subDiv.Z = Math.floor(this._subDiv.max * this._bbSize.z / bbSizeMax);
  13572. this._subDiv.X = this._subDiv.X < 1 ? 1 : this._subDiv.X; // at least one subdivision
  13573. this._subDiv.Y = this._subDiv.Y < 1 ? 1 : this._subDiv.Y;
  13574. this._subDiv.Z = this._subDiv.Z < 1 ? 1 : this._subDiv.Z;
  13575. // set the parameters for ComputeNormals()
  13576. this._facetParameters.facetNormals = this.getFacetLocalNormals();
  13577. this._facetParameters.facetPositions = this.getFacetLocalPositions();
  13578. this._facetParameters.facetPartitioning = this.getFacetLocalPartitioning();
  13579. this._facetParameters.bInfo = bInfo;
  13580. this._facetParameters.bbSize = this._bbSize;
  13581. this._facetParameters.subDiv = this._subDiv;
  13582. this._facetParameters.ratio = this.partitioningBBoxRatio;
  13583. BABYLON.VertexData.ComputeNormals(positions, indices, normals, this._facetParameters);
  13584. return this;
  13585. };
  13586. /**
  13587. * Returns the facetLocalNormals array.
  13588. * The normals are expressed in the mesh local space.
  13589. */
  13590. AbstractMesh.prototype.getFacetLocalNormals = function () {
  13591. if (!this._facetNormals) {
  13592. this.updateFacetData();
  13593. }
  13594. return this._facetNormals;
  13595. };
  13596. /**
  13597. * Returns the facetLocalPositions array.
  13598. * The facet positions are expressed in the mesh local space.
  13599. */
  13600. AbstractMesh.prototype.getFacetLocalPositions = function () {
  13601. if (!this._facetPositions) {
  13602. this.updateFacetData();
  13603. }
  13604. return this._facetPositions;
  13605. };
  13606. /**
  13607. * Returns the facetLocalPartioning array.
  13608. */
  13609. AbstractMesh.prototype.getFacetLocalPartitioning = function () {
  13610. if (!this._facetPartitioning) {
  13611. this.updateFacetData();
  13612. }
  13613. return this._facetPartitioning;
  13614. };
  13615. /**
  13616. * Returns the i-th facet position in the world system.
  13617. * This method allocates a new Vector3 per call.
  13618. */
  13619. AbstractMesh.prototype.getFacetPosition = function (i) {
  13620. var pos = BABYLON.Vector3.Zero();
  13621. this.getFacetPositionToRef(i, pos);
  13622. return pos;
  13623. };
  13624. /**
  13625. * Sets the reference Vector3 with the i-th facet position in the world system.
  13626. * Returns the AbstractMesh.
  13627. */
  13628. AbstractMesh.prototype.getFacetPositionToRef = function (i, ref) {
  13629. var localPos = (this.getFacetLocalPositions())[i];
  13630. var world = this.getWorldMatrix();
  13631. BABYLON.Vector3.TransformCoordinatesToRef(localPos, world, ref);
  13632. return this;
  13633. };
  13634. /**
  13635. * Returns the i-th facet normal in the world system.
  13636. * This method allocates a new Vector3 per call.
  13637. */
  13638. AbstractMesh.prototype.getFacetNormal = function (i) {
  13639. var norm = BABYLON.Vector3.Zero();
  13640. this.getFacetNormalToRef(i, norm);
  13641. return norm;
  13642. };
  13643. /**
  13644. * Sets the reference Vector3 with the i-th facet normal in the world system.
  13645. * Returns the AbstractMesh.
  13646. */
  13647. AbstractMesh.prototype.getFacetNormalToRef = function (i, ref) {
  13648. var localNorm = (this.getFacetLocalNormals())[i];
  13649. BABYLON.Vector3.TransformNormalToRef(localNorm, this.getWorldMatrix(), ref);
  13650. return this;
  13651. };
  13652. /**
  13653. * 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).
  13654. */
  13655. AbstractMesh.prototype.getFacetsAtLocalCoordinates = function (x, y, z) {
  13656. var bInfo = this.getBoundingInfo();
  13657. var ox = Math.floor((x - bInfo.minimum.x * this._partitioningBBoxRatio) * this._subDiv.X * this._partitioningBBoxRatio / this._bbSize.x);
  13658. var oy = Math.floor((y - bInfo.minimum.y * this._partitioningBBoxRatio) * this._subDiv.Y * this._partitioningBBoxRatio / this._bbSize.y);
  13659. var oz = Math.floor((z - bInfo.minimum.z * this._partitioningBBoxRatio) * this._subDiv.Z * this._partitioningBBoxRatio / this._bbSize.z);
  13660. if (ox < 0 || ox > this._subDiv.max || oy < 0 || oy > this._subDiv.max || oz < 0 || oz > this._subDiv.max) {
  13661. return null;
  13662. }
  13663. return this._facetPartitioning[ox + this._subDiv.max * oy + this._subDiv.max * this._subDiv.max * oz];
  13664. };
  13665. /**
  13666. * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found.
  13667. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) World projection on the facet.
  13668. * 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.
  13669. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  13670. * 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.
  13671. */
  13672. AbstractMesh.prototype.getClosestFacetAtCoordinates = function (x, y, z, projected, checkFace, facing) {
  13673. if (checkFace === void 0) { checkFace = false; }
  13674. if (facing === void 0) { facing = true; }
  13675. var world = this.getWorldMatrix();
  13676. var invMat = BABYLON.Tmp.Matrix[5];
  13677. world.invertToRef(invMat);
  13678. var invVect = BABYLON.Tmp.Vector3[8];
  13679. var closest = null;
  13680. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, invMat, invVect); // transform (x,y,z) to coordinates in the mesh local space
  13681. closest = this.getClosestFacetAtLocalCoordinates(invVect.x, invVect.y, invVect.z, projected, checkFace, facing);
  13682. if (projected) {
  13683. // tranform the local computed projected vector to world coordinates
  13684. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(projected.x, projected.y, projected.z, world, projected);
  13685. }
  13686. return closest;
  13687. };
  13688. /**
  13689. * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found.
  13690. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) local projection on the facet.
  13691. * 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.
  13692. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  13693. * 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.
  13694. */
  13695. AbstractMesh.prototype.getClosestFacetAtLocalCoordinates = function (x, y, z, projected, checkFace, facing) {
  13696. if (checkFace === void 0) { checkFace = false; }
  13697. if (facing === void 0) { facing = true; }
  13698. var closest = null;
  13699. var tmpx = 0.0;
  13700. var tmpy = 0.0;
  13701. var tmpz = 0.0;
  13702. var d = 0.0; // tmp dot facet normal * facet position
  13703. var t0 = 0.0;
  13704. var projx = 0.0;
  13705. var projy = 0.0;
  13706. var projz = 0.0;
  13707. // Get all the facets in the same partitioning block than (x, y, z)
  13708. var facetPositions = this.getFacetLocalPositions();
  13709. var facetNormals = this.getFacetLocalNormals();
  13710. var facetsInBlock = this.getFacetsAtLocalCoordinates(x, y, z);
  13711. if (!facetsInBlock) {
  13712. return null;
  13713. }
  13714. // Get the closest facet to (x, y, z)
  13715. var shortest = Number.MAX_VALUE; // init distance vars
  13716. var tmpDistance = shortest;
  13717. var fib; // current facet in the block
  13718. var norm; // current facet normal
  13719. var p0; // current facet barycenter position
  13720. // loop on all the facets in the current partitioning block
  13721. for (var idx = 0; idx < facetsInBlock.length; idx++) {
  13722. fib = facetsInBlock[idx];
  13723. norm = facetNormals[fib];
  13724. p0 = facetPositions[fib];
  13725. d = (x - p0.x) * norm.x + (y - p0.y) * norm.y + (z - p0.z) * norm.z;
  13726. if (!checkFace || (checkFace && facing && d >= 0.0) || (checkFace && !facing && d <= 0.0)) {
  13727. // compute (x,y,z) projection on the facet = (projx, projy, projz)
  13728. d = norm.x * p0.x + norm.y * p0.y + norm.z * p0.z;
  13729. t0 = -(norm.x * x + norm.y * y + norm.z * z - d) / (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);
  13730. projx = x + norm.x * t0;
  13731. projy = y + norm.y * t0;
  13732. projz = z + norm.z * t0;
  13733. tmpx = projx - x;
  13734. tmpy = projy - y;
  13735. tmpz = projz - z;
  13736. tmpDistance = tmpx * tmpx + tmpy * tmpy + tmpz * tmpz; // compute length between (x, y, z) and its projection on the facet
  13737. if (tmpDistance < shortest) {
  13738. shortest = tmpDistance;
  13739. closest = fib;
  13740. if (projected) {
  13741. projected.x = projx;
  13742. projected.y = projy;
  13743. projected.z = projz;
  13744. }
  13745. }
  13746. }
  13747. }
  13748. return closest;
  13749. };
  13750. /**
  13751. * Returns the object "parameter" set with all the expected parameters for facetData computation by ComputeNormals()
  13752. */
  13753. AbstractMesh.prototype.getFacetDataParameters = function () {
  13754. return this._facetParameters;
  13755. };
  13756. /**
  13757. * Disables the feature FacetData and frees the related memory.
  13758. * Returns the AbstractMesh.
  13759. */
  13760. AbstractMesh.prototype.disableFacetData = function () {
  13761. if (this._facetDataEnabled) {
  13762. this._facetDataEnabled = false;
  13763. this._facetPositions = null;
  13764. this._facetNormals = null;
  13765. this._facetPartitioning = null;
  13766. this._facetParameters = null;
  13767. }
  13768. return this;
  13769. };
  13770. return AbstractMesh;
  13771. }(BABYLON.Node));
  13772. // Statics
  13773. AbstractMesh._BILLBOARDMODE_NONE = 0;
  13774. AbstractMesh._BILLBOARDMODE_X = 1;
  13775. AbstractMesh._BILLBOARDMODE_Y = 2;
  13776. AbstractMesh._BILLBOARDMODE_Z = 4;
  13777. AbstractMesh._BILLBOARDMODE_ALL = 7;
  13778. AbstractMesh._rotationAxisCache = new BABYLON.Quaternion();
  13779. AbstractMesh._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  13780. BABYLON.AbstractMesh = AbstractMesh;
  13781. })(BABYLON || (BABYLON = {}));
  13782. //# sourceMappingURL=babylon.abstractMesh.js.map
  13783. var BABYLON;
  13784. (function (BABYLON) {
  13785. var Light = (function (_super) {
  13786. __extends(Light, _super);
  13787. /**
  13788. * Creates a Light object in the scene.
  13789. * Documentation : http://doc.babylonjs.com/tutorials/lights
  13790. */
  13791. function Light(name, scene) {
  13792. var _this = _super.call(this, name, scene) || this;
  13793. _this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  13794. _this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  13795. _this.intensity = 1.0;
  13796. _this.range = Number.MAX_VALUE;
  13797. _this.includeOnlyWithLayerMask = 0;
  13798. _this.includedOnlyMeshes = new Array();
  13799. _this.excludedMeshes = new Array();
  13800. _this.excludeWithLayerMask = 0;
  13801. _this.lightmapMode = 0;
  13802. // PBR Properties.
  13803. _this.radius = 0.00001;
  13804. _this._excludedMeshesIds = new Array();
  13805. _this._includedOnlyMeshesIds = new Array();
  13806. _this.getScene().addLight(_this);
  13807. return _this;
  13808. }
  13809. Object.defineProperty(Light, "LIGHTMAP_DEFAULT", {
  13810. /**
  13811. * If every light affecting the material is in this lightmapMode,
  13812. * material.lightmapTexture adds or multiplies
  13813. * (depends on material.useLightmapAsShadowmap)
  13814. * after every other light calculations.
  13815. */
  13816. get: function () {
  13817. return Light._LIGHTMAP_DEFAULT;
  13818. },
  13819. enumerable: true,
  13820. configurable: true
  13821. });
  13822. Object.defineProperty(Light, "LIGHTMAP_SPECULAR", {
  13823. /**
  13824. * material.lightmapTexture as only diffuse lighting from this light
  13825. * adds pnly specular lighting from this light
  13826. * adds dynamic shadows
  13827. */
  13828. get: function () {
  13829. return Light._LIGHTMAP_SPECULAR;
  13830. },
  13831. enumerable: true,
  13832. configurable: true
  13833. });
  13834. Object.defineProperty(Light, "LIGHTMAP_SHADOWSONLY", {
  13835. /**
  13836. * material.lightmapTexture as only lighting
  13837. * no light calculation from this light
  13838. * only adds dynamic shadows from this light
  13839. */
  13840. get: function () {
  13841. return Light._LIGHTMAP_SHADOWSONLY;
  13842. },
  13843. enumerable: true,
  13844. configurable: true
  13845. });
  13846. /**
  13847. * Returns the string "Light".
  13848. */
  13849. Light.prototype.getClassName = function () {
  13850. return "Light";
  13851. };
  13852. /**
  13853. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  13854. */
  13855. Light.prototype.toString = function (fullDetails) {
  13856. var ret = "Name: " + this.name;
  13857. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  13858. if (this.animations) {
  13859. for (var i = 0; i < this.animations.length; i++) {
  13860. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  13861. }
  13862. }
  13863. if (fullDetails) {
  13864. }
  13865. return ret;
  13866. };
  13867. /**
  13868. * Returns the Light associated shadow generator.
  13869. */
  13870. Light.prototype.getShadowGenerator = function () {
  13871. return this._shadowGenerator;
  13872. };
  13873. /**
  13874. * Returns a Vector3, the absolute light position in the World.
  13875. */
  13876. Light.prototype.getAbsolutePosition = function () {
  13877. return BABYLON.Vector3.Zero();
  13878. };
  13879. Light.prototype.transferToEffect = function (effect, uniformName0, uniformName1) {
  13880. };
  13881. Light.prototype._getWorldMatrix = function () {
  13882. return BABYLON.Matrix.Identity();
  13883. };
  13884. /**
  13885. * Boolean : True if the light will affect the passed mesh.
  13886. */
  13887. Light.prototype.canAffectMesh = function (mesh) {
  13888. if (!mesh) {
  13889. return true;
  13890. }
  13891. if (this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  13892. return false;
  13893. }
  13894. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  13895. return false;
  13896. }
  13897. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  13898. return false;
  13899. }
  13900. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  13901. return false;
  13902. }
  13903. return true;
  13904. };
  13905. /**
  13906. * Returns the light World matrix.
  13907. */
  13908. Light.prototype.getWorldMatrix = function () {
  13909. this._currentRenderId = this.getScene().getRenderId();
  13910. var worldMatrix = this._getWorldMatrix();
  13911. if (this.parent && this.parent.getWorldMatrix) {
  13912. if (!this._parentedWorldMatrix) {
  13913. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  13914. }
  13915. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  13916. this._markSyncedWithParent();
  13917. return this._parentedWorldMatrix;
  13918. }
  13919. return worldMatrix;
  13920. };
  13921. /**
  13922. * Disposes the light.
  13923. */
  13924. Light.prototype.dispose = function () {
  13925. if (this._shadowGenerator) {
  13926. this._shadowGenerator.dispose();
  13927. this._shadowGenerator = null;
  13928. }
  13929. // Animations
  13930. this.getScene().stopAnimation(this);
  13931. // Remove from scene
  13932. this.getScene().removeLight(this);
  13933. _super.prototype.dispose.call(this);
  13934. };
  13935. /**
  13936. * Returns the light type ID (integer).
  13937. */
  13938. Light.prototype.getTypeID = function () {
  13939. return 0;
  13940. };
  13941. /**
  13942. * Returns a new Light object, named "name", from the current one.
  13943. */
  13944. Light.prototype.clone = function (name) {
  13945. return BABYLON.SerializationHelper.Clone(Light.GetConstructorFromName(this.getTypeID(), name, this.getScene()), this);
  13946. };
  13947. /**
  13948. * Serializes the current light into a Serialization object.
  13949. * Returns the serialized object.
  13950. */
  13951. Light.prototype.serialize = function () {
  13952. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  13953. // Type
  13954. serializationObject.type = this.getTypeID();
  13955. // Parent
  13956. if (this.parent) {
  13957. serializationObject.parentId = this.parent.id;
  13958. }
  13959. // Inclusion / exclusions
  13960. if (this.excludedMeshes.length > 0) {
  13961. serializationObject.excludedMeshesIds = [];
  13962. this.excludedMeshes.forEach(function (mesh) {
  13963. serializationObject.excludedMeshesIds.push(mesh.id);
  13964. });
  13965. }
  13966. if (this.includedOnlyMeshes.length > 0) {
  13967. serializationObject.includedOnlyMeshesIds = [];
  13968. this.includedOnlyMeshes.forEach(function (mesh) {
  13969. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  13970. });
  13971. }
  13972. // Animations
  13973. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  13974. serializationObject.ranges = this.serializeAnimationRanges();
  13975. return serializationObject;
  13976. };
  13977. /**
  13978. * Creates a new typed light from the passed type (integer) : point light = 0, directional light = 1, spot light = 2, hemispheric light = 3.
  13979. * This new light is named "name" and added to the passed scene.
  13980. */
  13981. Light.GetConstructorFromName = function (type, name, scene) {
  13982. switch (type) {
  13983. case 0:
  13984. return function () { return new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), scene); };
  13985. case 1:
  13986. return function () { return new BABYLON.DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  13987. case 2:
  13988. return function () { return new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  13989. case 3:
  13990. return function () { return new BABYLON.HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  13991. }
  13992. };
  13993. /**
  13994. * Parses the passed "parsedLight" and returns a new instanced Light from this parsing.
  13995. */
  13996. Light.Parse = function (parsedLight, scene) {
  13997. var light = BABYLON.SerializationHelper.Parse(Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene), parsedLight, scene);
  13998. // Inclusion / exclusions
  13999. if (parsedLight.excludedMeshesIds) {
  14000. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  14001. }
  14002. if (parsedLight.includedOnlyMeshesIds) {
  14003. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  14004. }
  14005. // Parent
  14006. if (parsedLight.parentId) {
  14007. light._waitingParentId = parsedLight.parentId;
  14008. }
  14009. // Animations
  14010. if (parsedLight.animations) {
  14011. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  14012. var parsedAnimation = parsedLight.animations[animationIndex];
  14013. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  14014. }
  14015. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  14016. }
  14017. if (parsedLight.autoAnimate) {
  14018. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  14019. }
  14020. return light;
  14021. };
  14022. return Light;
  14023. }(BABYLON.Node));
  14024. //lightmapMode Consts
  14025. Light._LIGHTMAP_DEFAULT = 0;
  14026. Light._LIGHTMAP_SPECULAR = 1;
  14027. Light._LIGHTMAP_SHADOWSONLY = 2;
  14028. __decorate([
  14029. BABYLON.serializeAsColor3()
  14030. ], Light.prototype, "diffuse", void 0);
  14031. __decorate([
  14032. BABYLON.serializeAsColor3()
  14033. ], Light.prototype, "specular", void 0);
  14034. __decorate([
  14035. BABYLON.serialize()
  14036. ], Light.prototype, "intensity", void 0);
  14037. __decorate([
  14038. BABYLON.serialize()
  14039. ], Light.prototype, "range", void 0);
  14040. __decorate([
  14041. BABYLON.serialize()
  14042. ], Light.prototype, "includeOnlyWithLayerMask", void 0);
  14043. __decorate([
  14044. BABYLON.serialize()
  14045. ], Light.prototype, "excludeWithLayerMask", void 0);
  14046. __decorate([
  14047. BABYLON.serialize()
  14048. ], Light.prototype, "lightmapMode", void 0);
  14049. __decorate([
  14050. BABYLON.serialize()
  14051. ], Light.prototype, "radius", void 0);
  14052. BABYLON.Light = Light;
  14053. })(BABYLON || (BABYLON = {}));
  14054. //# sourceMappingURL=babylon.light.js.map
  14055. var BABYLON;
  14056. (function (BABYLON) {
  14057. var PointLight = (function (_super) {
  14058. __extends(PointLight, _super);
  14059. /**
  14060. * Creates a PointLight object from the passed name and position (Vector3) and adds it in the scene.
  14061. * A PointLight emits the light in every direction.
  14062. * It can cast shadows.
  14063. * If the scene camera is already defined and you want to set your PointLight at the camera position, just set it :
  14064. * ```javascript
  14065. * var pointLight = new BABYLON.PointLight("pl", camera.position, scene);
  14066. * ```
  14067. * Documentation : http://doc.babylonjs.com/tutorials/lights
  14068. */
  14069. function PointLight(name, position, scene) {
  14070. var _this = _super.call(this, name, scene) || this;
  14071. _this.position = position;
  14072. return _this;
  14073. }
  14074. /**
  14075. * Returns the string "PointLight"
  14076. */
  14077. PointLight.prototype.getClassName = function () {
  14078. return "PointLight";
  14079. };
  14080. /**
  14081. * Returns a Vector3, the PointLight absolute position in the World.
  14082. */
  14083. PointLight.prototype.getAbsolutePosition = function () {
  14084. return this.transformedPosition ? this.transformedPosition : this.position;
  14085. };
  14086. /**
  14087. * Computes the PointLight transformed position if parented. Returns true if ok, false if not parented.
  14088. */
  14089. PointLight.prototype.computeTransformedPosition = function () {
  14090. if (this.parent && this.parent.getWorldMatrix) {
  14091. if (!this.transformedPosition) {
  14092. this.transformedPosition = BABYLON.Vector3.Zero();
  14093. }
  14094. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  14095. return true;
  14096. }
  14097. return false;
  14098. };
  14099. /**
  14100. * Sets the passed Effect "effect" with the PointLight transformed position (or position, if none) and passed name (string).
  14101. * Returns the PointLight.
  14102. */
  14103. PointLight.prototype.transferToEffect = function (effect, positionUniformName) {
  14104. if (this.parent && this.parent.getWorldMatrix) {
  14105. this.computeTransformedPosition();
  14106. effect.setFloat4(positionUniformName, this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0.0);
  14107. return this;
  14108. }
  14109. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, 0);
  14110. return this;
  14111. };
  14112. /**
  14113. * Boolean : returns true by default.
  14114. */
  14115. PointLight.prototype.needCube = function () {
  14116. return true;
  14117. };
  14118. /**
  14119. * Boolean : returns false by default.
  14120. */
  14121. PointLight.prototype.supportsVSM = function () {
  14122. return false;
  14123. };
  14124. /**
  14125. * Boolean : returns false by default.
  14126. */
  14127. PointLight.prototype.needRefreshPerFrame = function () {
  14128. return false;
  14129. };
  14130. /**
  14131. * Returns a new Vector3 aligned with the PointLight cube system according to the passed cube face index (integer).
  14132. */
  14133. PointLight.prototype.getShadowDirection = function (faceIndex) {
  14134. switch (faceIndex) {
  14135. case 0:
  14136. return new BABYLON.Vector3(1.0, 0.0, 0.0);
  14137. case 1:
  14138. return new BABYLON.Vector3(-1.0, 0.0, 0.0);
  14139. case 2:
  14140. return new BABYLON.Vector3(0.0, -1.0, 0.0);
  14141. case 3:
  14142. return new BABYLON.Vector3(0.0, 1.0, 0.0);
  14143. case 4:
  14144. return new BABYLON.Vector3(0.0, 0.0, 1.0);
  14145. case 5:
  14146. return new BABYLON.Vector3(0.0, 0.0, -1.0);
  14147. }
  14148. return BABYLON.Vector3.Zero();
  14149. };
  14150. /**
  14151. * Sets the passed matrix "matrix" as a left-handed perspective projection matrix with the following settings :
  14152. * - fov = PI / 2
  14153. * - aspect ratio : 1.0
  14154. * - z-near and far equal to the active camera minZ and maxZ.
  14155. * Returns the PointLight.
  14156. */
  14157. PointLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  14158. if (this.customProjectionMatrixBuilder) {
  14159. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  14160. }
  14161. else {
  14162. var activeCamera = this.getScene().activeCamera;
  14163. BABYLON.Matrix.PerspectiveFovLHToRef(Math.PI / 2, 1.0, activeCamera.minZ, activeCamera.maxZ, matrix);
  14164. }
  14165. return this;
  14166. };
  14167. PointLight.prototype._getWorldMatrix = function () {
  14168. if (!this._worldMatrix) {
  14169. this._worldMatrix = BABYLON.Matrix.Identity();
  14170. }
  14171. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  14172. return this._worldMatrix;
  14173. };
  14174. /**
  14175. * Returns the integer 0.
  14176. */
  14177. PointLight.prototype.getTypeID = function () {
  14178. return 0;
  14179. };
  14180. return PointLight;
  14181. }(BABYLON.Light));
  14182. __decorate([
  14183. BABYLON.serializeAsVector3()
  14184. ], PointLight.prototype, "position", void 0);
  14185. BABYLON.PointLight = PointLight;
  14186. })(BABYLON || (BABYLON = {}));
  14187. //# sourceMappingURL=babylon.pointLight.js.map
  14188. var BABYLON;
  14189. (function (BABYLON) {
  14190. var SpotLight = (function (_super) {
  14191. __extends(SpotLight, _super);
  14192. /**
  14193. * Creates a SpotLight object in the scene with the passed parameters :
  14194. * - `position` (Vector3) is the initial SpotLight position,
  14195. * - `direction` (Vector3) is the initial SpotLight direction,
  14196. * - `angle` (float, in radians) is the spot light cone angle,
  14197. * - `exponent` (float) is the light decay speed with the distance from the emission spot.
  14198. * A spot light is a simply light oriented cone.
  14199. * It can cast shadows.
  14200. * Documentation : http://doc.babylonjs.com/tutorials/lights
  14201. */
  14202. function SpotLight(name, position, direction, angle, exponent, scene) {
  14203. var _this = _super.call(this, name, scene) || this;
  14204. _this.position = position;
  14205. _this.direction = direction;
  14206. _this.angle = angle;
  14207. _this.exponent = exponent;
  14208. return _this;
  14209. }
  14210. /**
  14211. * Returns the string "SpotLight".
  14212. */
  14213. SpotLight.prototype.getClassName = function () {
  14214. return "SpotLight";
  14215. };
  14216. /**
  14217. * Returns the SpotLight absolute position in the World (Vector3).
  14218. */
  14219. SpotLight.prototype.getAbsolutePosition = function () {
  14220. return this.transformedPosition ? this.transformedPosition : this.position;
  14221. };
  14222. /**
  14223. * Sets the passed matrix "matrix" as perspective projection matrix for the shadows and the passed view matrix with the fov equal to the SpotLight angle and and aspect ratio of 1.0.
  14224. * Returns the SpotLight.
  14225. */
  14226. SpotLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  14227. if (this.customProjectionMatrixBuilder) {
  14228. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  14229. }
  14230. else {
  14231. var activeCamera = this.getScene().activeCamera;
  14232. BABYLON.Matrix.PerspectiveFovLHToRef(this.angle, 1.0, activeCamera.minZ, activeCamera.maxZ, matrix);
  14233. }
  14234. return this;
  14235. };
  14236. /**
  14237. * Boolean : false by default.
  14238. */
  14239. SpotLight.prototype.needCube = function () {
  14240. return false;
  14241. };
  14242. /**
  14243. * Boolean : true by default.
  14244. */
  14245. SpotLight.prototype.supportsVSM = function () {
  14246. return true;
  14247. };
  14248. /**
  14249. * Boolean : false by default.
  14250. */
  14251. SpotLight.prototype.needRefreshPerFrame = function () {
  14252. return false;
  14253. };
  14254. /**
  14255. * Returns the SpotLight direction (Vector3) for any passed face index.
  14256. */
  14257. SpotLight.prototype.getShadowDirection = function (faceIndex) {
  14258. return this.direction;
  14259. };
  14260. /**
  14261. * Updates the SpotLight direction towards the passed target (Vector3).
  14262. * Returns the updated direction.
  14263. */
  14264. SpotLight.prototype.setDirectionToTarget = function (target) {
  14265. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  14266. return this.direction;
  14267. };
  14268. /**
  14269. * Computes the SpotLight transformed position if parented. Returns true if parented, else false.
  14270. */
  14271. SpotLight.prototype.computeTransformedPosition = function () {
  14272. if (this.parent && this.parent.getWorldMatrix) {
  14273. if (!this.transformedPosition) {
  14274. this.transformedPosition = BABYLON.Vector3.Zero();
  14275. }
  14276. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  14277. return true;
  14278. }
  14279. return false;
  14280. };
  14281. /**
  14282. * Sets the passed Effect object with the SpotLight transfomed position (or position if not parented) and normalized direction.
  14283. * Return the SpotLight.
  14284. */
  14285. SpotLight.prototype.transferToEffect = function (effect, positionUniformName, directionUniformName) {
  14286. var normalizeDirection;
  14287. if (this.parent && this.parent.getWorldMatrix) {
  14288. if (!this._transformedDirection) {
  14289. this._transformedDirection = BABYLON.Vector3.Zero();
  14290. }
  14291. this.computeTransformedPosition();
  14292. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  14293. effect.setFloat4(positionUniformName, this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent);
  14294. normalizeDirection = BABYLON.Vector3.Normalize(this._transformedDirection);
  14295. }
  14296. else {
  14297. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, this.exponent);
  14298. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  14299. }
  14300. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5));
  14301. return this;
  14302. };
  14303. SpotLight.prototype._getWorldMatrix = function () {
  14304. if (!this._worldMatrix) {
  14305. this._worldMatrix = BABYLON.Matrix.Identity();
  14306. }
  14307. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  14308. return this._worldMatrix;
  14309. };
  14310. /**
  14311. * Returns the integer 2.
  14312. */
  14313. SpotLight.prototype.getTypeID = function () {
  14314. return 2;
  14315. };
  14316. /**
  14317. * Returns the SpotLight rotation (Vector3).
  14318. */
  14319. SpotLight.prototype.getRotation = function () {
  14320. this.direction.normalize();
  14321. var xaxis = BABYLON.Vector3.Cross(this.direction, BABYLON.Axis.Y);
  14322. var yaxis = BABYLON.Vector3.Cross(xaxis, this.direction);
  14323. return BABYLON.Vector3.RotationFromAxis(xaxis, yaxis, this.direction);
  14324. };
  14325. return SpotLight;
  14326. }(BABYLON.Light));
  14327. __decorate([
  14328. BABYLON.serializeAsVector3()
  14329. ], SpotLight.prototype, "position", void 0);
  14330. __decorate([
  14331. BABYLON.serializeAsVector3()
  14332. ], SpotLight.prototype, "direction", void 0);
  14333. __decorate([
  14334. BABYLON.serialize()
  14335. ], SpotLight.prototype, "angle", void 0);
  14336. __decorate([
  14337. BABYLON.serialize()
  14338. ], SpotLight.prototype, "exponent", void 0);
  14339. BABYLON.SpotLight = SpotLight;
  14340. })(BABYLON || (BABYLON = {}));
  14341. //# sourceMappingURL=babylon.spotLight.js.map
  14342. var BABYLON;
  14343. (function (BABYLON) {
  14344. var HemisphericLight = (function (_super) {
  14345. __extends(HemisphericLight, _super);
  14346. /**
  14347. * Creates a HemisphericLight object in the scene according to the passed direction (Vector3).
  14348. * The HemisphericLight simulates the ambient environment light, so the passed direction is the light reflection direction, not the incoming direction.
  14349. * The HemisphericLight can't cast shadows.
  14350. * Documentation : http://doc.babylonjs.com/tutorials/lights
  14351. */
  14352. function HemisphericLight(name, direction, scene) {
  14353. var _this = _super.call(this, name, scene) || this;
  14354. _this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  14355. _this.direction = direction;
  14356. return _this;
  14357. }
  14358. /**
  14359. * Returns the string "HemisphericLight".
  14360. */
  14361. HemisphericLight.prototype.getClassName = function () {
  14362. return "HemisphericLight";
  14363. };
  14364. /**
  14365. * Sets the HemisphericLight direction towards the passed target (Vector3).
  14366. * Returns the updated direction.
  14367. */
  14368. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  14369. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  14370. return this.direction;
  14371. };
  14372. HemisphericLight.prototype.getShadowGenerator = function () {
  14373. return null;
  14374. };
  14375. /**
  14376. * Sets the passed Effect object with the HemisphericLight normalized direction and color and the passed name (string).
  14377. * Returns the HemisphericLight.
  14378. */
  14379. HemisphericLight.prototype.transferToEffect = function (effect, directionUniformName, groundColorUniformName) {
  14380. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  14381. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0.0);
  14382. effect.setColor3(groundColorUniformName, this.groundColor.scale(this.intensity));
  14383. return this;
  14384. };
  14385. HemisphericLight.prototype._getWorldMatrix = function () {
  14386. if (!this._worldMatrix) {
  14387. this._worldMatrix = BABYLON.Matrix.Identity();
  14388. }
  14389. return this._worldMatrix;
  14390. };
  14391. /**
  14392. * Returns the integer 3.
  14393. */
  14394. HemisphericLight.prototype.getTypeID = function () {
  14395. return 3;
  14396. };
  14397. return HemisphericLight;
  14398. }(BABYLON.Light));
  14399. __decorate([
  14400. BABYLON.serializeAsColor3()
  14401. ], HemisphericLight.prototype, "groundColor", void 0);
  14402. __decorate([
  14403. BABYLON.serializeAsVector3()
  14404. ], HemisphericLight.prototype, "direction", void 0);
  14405. BABYLON.HemisphericLight = HemisphericLight;
  14406. })(BABYLON || (BABYLON = {}));
  14407. //# sourceMappingURL=babylon.hemisphericLight.js.map
  14408. /// <reference path="babylon.light.ts" />
  14409. var BABYLON;
  14410. (function (BABYLON) {
  14411. var DirectionalLight = (function (_super) {
  14412. __extends(DirectionalLight, _super);
  14413. /**
  14414. * Creates a DirectionalLight object in the scene, oriented towards the passed direction (Vector3).
  14415. * The directional light is emitted from everywhere in the given direction.
  14416. * It can cast shawdows.
  14417. * Documentation : http://doc.babylonjs.com/tutorials/lights
  14418. */
  14419. function DirectionalLight(name, direction, scene) {
  14420. var _this = _super.call(this, name, scene) || this;
  14421. _this.shadowOrthoScale = 0.5;
  14422. _this.autoUpdateExtends = true;
  14423. // Cache
  14424. _this._orthoLeft = Number.MAX_VALUE;
  14425. _this._orthoRight = Number.MIN_VALUE;
  14426. _this._orthoTop = Number.MIN_VALUE;
  14427. _this._orthoBottom = Number.MAX_VALUE;
  14428. _this.position = direction.scale(-1.0);
  14429. _this.direction = direction;
  14430. return _this;
  14431. }
  14432. /**
  14433. * Returns the string "DirectionalLight".
  14434. */
  14435. DirectionalLight.prototype.getClassName = function () {
  14436. return "DirectionalLight";
  14437. };
  14438. /**
  14439. * Returns the DirectionalLight absolute position in the World.
  14440. */
  14441. DirectionalLight.prototype.getAbsolutePosition = function () {
  14442. return this.transformedPosition ? this.transformedPosition : this.position;
  14443. };
  14444. /**
  14445. * Sets the DirectionalLight direction toward the passed target (Vector3).
  14446. * Returns the updated DirectionalLight direction (Vector3).
  14447. */
  14448. DirectionalLight.prototype.setDirectionToTarget = function (target) {
  14449. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  14450. return this.direction;
  14451. };
  14452. /**
  14453. * Sets the passed matrix "matrix" as projection matrix for the shadows cast by the light according to the passed view matrix.
  14454. * Returns the DirectionalLight.
  14455. */
  14456. DirectionalLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  14457. if (this.customProjectionMatrixBuilder) {
  14458. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  14459. }
  14460. else {
  14461. var activeCamera = this.getScene().activeCamera;
  14462. // Check extends
  14463. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  14464. var tempVector3 = BABYLON.Vector3.Zero();
  14465. this._orthoLeft = Number.MAX_VALUE;
  14466. this._orthoRight = Number.MIN_VALUE;
  14467. this._orthoTop = Number.MIN_VALUE;
  14468. this._orthoBottom = Number.MAX_VALUE;
  14469. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  14470. var mesh = renderList[meshIndex];
  14471. if (!mesh) {
  14472. continue;
  14473. }
  14474. var boundingInfo = mesh.getBoundingInfo();
  14475. if (!boundingInfo) {
  14476. continue;
  14477. }
  14478. var boundingBox = boundingInfo.boundingBox;
  14479. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  14480. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  14481. if (tempVector3.x < this._orthoLeft)
  14482. this._orthoLeft = tempVector3.x;
  14483. if (tempVector3.y < this._orthoBottom)
  14484. this._orthoBottom = tempVector3.y;
  14485. if (tempVector3.x > this._orthoRight)
  14486. this._orthoRight = tempVector3.x;
  14487. if (tempVector3.y > this._orthoTop)
  14488. this._orthoTop = tempVector3.y;
  14489. }
  14490. }
  14491. }
  14492. var xOffset = this._orthoRight - this._orthoLeft;
  14493. var yOffset = this._orthoTop - this._orthoBottom;
  14494. 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);
  14495. }
  14496. return this;
  14497. };
  14498. /**
  14499. * Boolean : true by default.
  14500. */
  14501. DirectionalLight.prototype.supportsVSM = function () {
  14502. return true;
  14503. };
  14504. /**
  14505. * Boolean : true by default.
  14506. */
  14507. DirectionalLight.prototype.needRefreshPerFrame = function () {
  14508. return true;
  14509. };
  14510. /**
  14511. * Boolean : false by default.
  14512. */
  14513. DirectionalLight.prototype.needCube = function () {
  14514. return false;
  14515. };
  14516. /**
  14517. * Returns the light direction (Vector3) for any passed face index.
  14518. */
  14519. DirectionalLight.prototype.getShadowDirection = function (faceIndex) {
  14520. return this.direction;
  14521. };
  14522. /**
  14523. * Computes the light transformed position in case the light is parented. Returns true if parented, else false.
  14524. */
  14525. DirectionalLight.prototype.computeTransformedPosition = function () {
  14526. if (this.parent && this.parent.getWorldMatrix) {
  14527. if (!this.transformedPosition) {
  14528. this.transformedPosition = BABYLON.Vector3.Zero();
  14529. }
  14530. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  14531. return true;
  14532. }
  14533. return false;
  14534. };
  14535. /**
  14536. * Sets the passed Effect object with the DirectionalLight transformed position (or position if not parented) and the passed name.
  14537. * Returns the DirectionalLight.
  14538. */
  14539. DirectionalLight.prototype.transferToEffect = function (effect, directionUniformName) {
  14540. if (this.parent && this.parent.getWorldMatrix) {
  14541. if (!this._transformedDirection) {
  14542. this._transformedDirection = BABYLON.Vector3.Zero();
  14543. }
  14544. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  14545. effect.setFloat4(directionUniformName, this._transformedDirection.x, this._transformedDirection.y, this._transformedDirection.z, 1);
  14546. return this;
  14547. }
  14548. effect.setFloat4(directionUniformName, this.direction.x, this.direction.y, this.direction.z, 1);
  14549. return this;
  14550. };
  14551. DirectionalLight.prototype._getWorldMatrix = function () {
  14552. if (!this._worldMatrix) {
  14553. this._worldMatrix = BABYLON.Matrix.Identity();
  14554. }
  14555. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  14556. return this._worldMatrix;
  14557. };
  14558. /**
  14559. * Returns the integer 1.
  14560. */
  14561. DirectionalLight.prototype.getTypeID = function () {
  14562. return 1;
  14563. };
  14564. return DirectionalLight;
  14565. }(BABYLON.Light));
  14566. __decorate([
  14567. BABYLON.serializeAsVector3()
  14568. ], DirectionalLight.prototype, "position", void 0);
  14569. __decorate([
  14570. BABYLON.serializeAsVector3()
  14571. ], DirectionalLight.prototype, "direction", void 0);
  14572. __decorate([
  14573. BABYLON.serialize()
  14574. ], DirectionalLight.prototype, "shadowOrthoScale", void 0);
  14575. __decorate([
  14576. BABYLON.serialize()
  14577. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  14578. BABYLON.DirectionalLight = DirectionalLight;
  14579. })(BABYLON || (BABYLON = {}));
  14580. //# sourceMappingURL=babylon.directionalLight.js.map
  14581. var BABYLON;
  14582. (function (BABYLON) {
  14583. var ShadowGenerator = (function () {
  14584. /**
  14585. * Creates a ShadowGenerator object.
  14586. * A ShadowGenerator is the required tool to use the shadows.
  14587. * Each light casting shadows needs to use its own ShadowGenerator.
  14588. * Required parameters :
  14589. * - `mapSize` (integer), the size of the texture what stores the shadows. Example : 1024.
  14590. * - `light` : the light object generating the shadows.
  14591. * Documentation : http://doc.babylonjs.com/tutorials/shadows
  14592. */
  14593. function ShadowGenerator(mapSize, light) {
  14594. var _this = this;
  14595. // Members
  14596. this._filter = ShadowGenerator.FILTER_NONE;
  14597. this.blurScale = 2;
  14598. this._blurBoxOffset = 0;
  14599. this._bias = 0.00005;
  14600. this._lightDirection = BABYLON.Vector3.Zero();
  14601. this.forceBackFacesOnly = false;
  14602. this._darkness = 0;
  14603. this._transparencyShadow = false;
  14604. this._viewMatrix = BABYLON.Matrix.Zero();
  14605. this._projectionMatrix = BABYLON.Matrix.Zero();
  14606. this._transformMatrix = BABYLON.Matrix.Zero();
  14607. this._worldViewProjection = BABYLON.Matrix.Zero();
  14608. this._currentFaceIndex = 0;
  14609. this._currentFaceIndexCache = 0;
  14610. this._useFullFloat = true;
  14611. this._light = light;
  14612. this._scene = light.getScene();
  14613. this._mapSize = mapSize;
  14614. light._shadowGenerator = this;
  14615. // Texture type fallback from float to int if not supported.
  14616. var textureType;
  14617. var caps = this._scene.getEngine().getCaps();
  14618. if (caps.textureFloat && caps.textureFloatLinearFiltering && caps.textureFloatRender) {
  14619. this._useFullFloat = true;
  14620. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  14621. }
  14622. else {
  14623. this._useFullFloat = false;
  14624. textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  14625. }
  14626. // Render target
  14627. this._shadowMap = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, this._scene, false, true, textureType, light.needCube());
  14628. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  14629. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  14630. this._shadowMap.anisotropicFilteringLevel = 1;
  14631. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  14632. this._shadowMap.renderParticles = false;
  14633. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  14634. _this._currentFaceIndex = faceIndex;
  14635. });
  14636. this._shadowMap.onAfterUnbindObservable.add(function () {
  14637. if (!_this.useBlurVarianceShadowMap) {
  14638. return;
  14639. }
  14640. if (!_this._shadowMap2) {
  14641. _this._shadowMap2 = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, _this._scene, false, true, textureType);
  14642. _this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  14643. _this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  14644. _this._shadowMap2.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  14645. _this._downSamplePostprocess = new BABYLON.PassPostProcess("downScale", 1.0 / _this.blurScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, _this._scene.getEngine());
  14646. _this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  14647. effect.setTexture("textureSampler", _this._shadowMap);
  14648. });
  14649. _this.blurBoxOffset = 1;
  14650. }
  14651. _this._scene.postProcessManager.directRender([_this._downSamplePostprocess, _this._boxBlurPostprocess], _this._shadowMap2.getInternalTexture());
  14652. });
  14653. // Custom render function
  14654. var renderSubMesh = function (subMesh) {
  14655. var mesh = subMesh.getRenderingMesh();
  14656. var scene = _this._scene;
  14657. var engine = scene.getEngine();
  14658. // Culling
  14659. engine.setState(subMesh.getMaterial().backFaceCulling);
  14660. // Managing instances
  14661. var batch = mesh._getInstancesRenderList(subMesh._id);
  14662. if (batch.mustReturn) {
  14663. return;
  14664. }
  14665. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  14666. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  14667. engine.enableEffect(_this._effect);
  14668. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  14669. var material = subMesh.getMaterial();
  14670. _this._effect.setMatrix("viewProjection", _this.getTransformMatrix());
  14671. _this._effect.setVector3("lightPosition", _this.getLight().position);
  14672. if (_this.getLight().needCube()) {
  14673. _this._effect.setFloat2("depthValues", scene.activeCamera.minZ, scene.activeCamera.maxZ);
  14674. }
  14675. // Alpha test
  14676. if (material && material.needAlphaTesting()) {
  14677. var alphaTexture = material.getAlphaTestTexture();
  14678. _this._effect.setTexture("diffuseSampler", alphaTexture);
  14679. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  14680. }
  14681. // Bones
  14682. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  14683. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  14684. }
  14685. if (_this.forceBackFacesOnly) {
  14686. engine.setState(true, 0, false, true);
  14687. }
  14688. // Draw
  14689. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  14690. if (_this.forceBackFacesOnly) {
  14691. engine.setState(true, 0, false, false);
  14692. }
  14693. }
  14694. else {
  14695. // Need to reset refresh rate of the shadowMap
  14696. _this._shadowMap.resetRefreshCounter();
  14697. }
  14698. };
  14699. this._shadowMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  14700. var index;
  14701. for (index = 0; index < opaqueSubMeshes.length; index++) {
  14702. renderSubMesh(opaqueSubMeshes.data[index]);
  14703. }
  14704. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  14705. renderSubMesh(alphaTestSubMeshes.data[index]);
  14706. }
  14707. if (_this._transparencyShadow) {
  14708. for (index = 0; index < transparentSubMeshes.length; index++) {
  14709. renderSubMesh(transparentSubMeshes.data[index]);
  14710. }
  14711. }
  14712. };
  14713. this._shadowMap.onClearObservable.add(function (engine) {
  14714. if (_this.useBlurVarianceShadowMap || _this.useVarianceShadowMap) {
  14715. engine.clear(new BABYLON.Color4(0, 0, 0, 0), true, true, true);
  14716. }
  14717. else {
  14718. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  14719. }
  14720. });
  14721. }
  14722. Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
  14723. // Static
  14724. get: function () {
  14725. return ShadowGenerator._FILTER_NONE;
  14726. },
  14727. enumerable: true,
  14728. configurable: true
  14729. });
  14730. Object.defineProperty(ShadowGenerator, "FILTER_VARIANCESHADOWMAP", {
  14731. get: function () {
  14732. return ShadowGenerator._FILTER_VARIANCESHADOWMAP;
  14733. },
  14734. enumerable: true,
  14735. configurable: true
  14736. });
  14737. Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
  14738. get: function () {
  14739. return ShadowGenerator._FILTER_POISSONSAMPLING;
  14740. },
  14741. enumerable: true,
  14742. configurable: true
  14743. });
  14744. Object.defineProperty(ShadowGenerator, "FILTER_BLURVARIANCESHADOWMAP", {
  14745. get: function () {
  14746. return ShadowGenerator._FILTER_BLURVARIANCESHADOWMAP;
  14747. },
  14748. enumerable: true,
  14749. configurable: true
  14750. });
  14751. Object.defineProperty(ShadowGenerator, "FILTER_EXPONENTIALSHADOWMAP", {
  14752. get: function () {
  14753. return ShadowGenerator._FILTER_EXPONENTIALSHADOWMAP;
  14754. },
  14755. enumerable: true,
  14756. configurable: true
  14757. });
  14758. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  14759. get: function () {
  14760. return this._bias;
  14761. },
  14762. set: function (bias) {
  14763. this._bias = bias;
  14764. },
  14765. enumerable: true,
  14766. configurable: true
  14767. });
  14768. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  14769. get: function () {
  14770. return this._blurBoxOffset;
  14771. },
  14772. set: function (value) {
  14773. var _this = this;
  14774. if (this._blurBoxOffset === value) {
  14775. return;
  14776. }
  14777. this._blurBoxOffset = value;
  14778. if (this._boxBlurPostprocess) {
  14779. this._boxBlurPostprocess.dispose();
  14780. }
  14781. 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);
  14782. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  14783. effect.setFloat2("screenSize", _this._mapSize / _this.blurScale, _this._mapSize / _this.blurScale);
  14784. });
  14785. },
  14786. enumerable: true,
  14787. configurable: true
  14788. });
  14789. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  14790. get: function () {
  14791. return this._filter;
  14792. },
  14793. set: function (value) {
  14794. if (this._filter === value) {
  14795. return;
  14796. }
  14797. this._filter = value;
  14798. if (this.useVarianceShadowMap || this.useBlurVarianceShadowMap || this.usePoissonSampling) {
  14799. this._shadowMap.anisotropicFilteringLevel = 16;
  14800. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  14801. }
  14802. else {
  14803. this._shadowMap.anisotropicFilteringLevel = 1;
  14804. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  14805. }
  14806. },
  14807. enumerable: true,
  14808. configurable: true
  14809. });
  14810. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  14811. get: function () {
  14812. return this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP && this._light.supportsVSM();
  14813. },
  14814. set: function (value) {
  14815. this.filter = (value ? ShadowGenerator.FILTER_VARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  14816. },
  14817. enumerable: true,
  14818. configurable: true
  14819. });
  14820. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  14821. get: function () {
  14822. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING ||
  14823. (!this._light.supportsVSM() && (this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP ||
  14824. this.filter === ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP));
  14825. },
  14826. set: function (value) {
  14827. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  14828. },
  14829. enumerable: true,
  14830. configurable: true
  14831. });
  14832. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  14833. get: function () {
  14834. return this.filter === ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP && this._light.supportsVSM();
  14835. },
  14836. set: function (value) {
  14837. this.filter = (value ? ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  14838. },
  14839. enumerable: true,
  14840. configurable: true
  14841. });
  14842. Object.defineProperty(ShadowGenerator.prototype, "useExponentialShadowMap", {
  14843. get: function () {
  14844. return this.filter === ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP;
  14845. },
  14846. set: function (value) {
  14847. this.filter = (value ? ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  14848. },
  14849. enumerable: true,
  14850. configurable: true
  14851. });
  14852. /**
  14853. * Boolean : true when the ShadowGenerator is finally computed.
  14854. */
  14855. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  14856. var defines = [];
  14857. if (this._useFullFloat) {
  14858. defines.push("#define FULLFLOAT");
  14859. }
  14860. if (this.useVarianceShadowMap || this.useBlurVarianceShadowMap) {
  14861. defines.push("#define VSM");
  14862. }
  14863. if (this.getLight().needCube()) {
  14864. defines.push("#define CUBEMAP");
  14865. }
  14866. var attribs = [BABYLON.VertexBuffer.PositionKind];
  14867. var mesh = subMesh.getMesh();
  14868. var material = subMesh.getMaterial();
  14869. // Alpha test
  14870. if (material && material.needAlphaTesting()) {
  14871. defines.push("#define ALPHATEST");
  14872. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  14873. attribs.push(BABYLON.VertexBuffer.UVKind);
  14874. defines.push("#define UV1");
  14875. }
  14876. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  14877. var alphaTexture = material.getAlphaTestTexture();
  14878. if (alphaTexture.coordinatesIndex === 1) {
  14879. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  14880. defines.push("#define UV2");
  14881. }
  14882. }
  14883. }
  14884. // Bones
  14885. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  14886. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  14887. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  14888. if (mesh.numBoneInfluencers > 4) {
  14889. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  14890. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  14891. }
  14892. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  14893. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  14894. }
  14895. else {
  14896. defines.push("#define NUM_BONE_INFLUENCERS 0");
  14897. }
  14898. // Instances
  14899. if (useInstances) {
  14900. defines.push("#define INSTANCES");
  14901. attribs.push("world0");
  14902. attribs.push("world1");
  14903. attribs.push("world2");
  14904. attribs.push("world3");
  14905. }
  14906. // Get correct effect
  14907. var join = defines.join("\n");
  14908. if (this._cachedDefines !== join) {
  14909. this._cachedDefines = join;
  14910. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightPosition", "depthValues"], ["diffuseSampler"], join);
  14911. }
  14912. return this._effect.isReady();
  14913. };
  14914. /**
  14915. * Returns a RenderTargetTexture object : the shadow map texture.
  14916. */
  14917. ShadowGenerator.prototype.getShadowMap = function () {
  14918. return this._shadowMap;
  14919. };
  14920. /**
  14921. * Returns the most ready computed shadow map as a RenderTargetTexture object.
  14922. */
  14923. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  14924. if (this._shadowMap2) {
  14925. return this._shadowMap2;
  14926. }
  14927. return this._shadowMap;
  14928. };
  14929. /**
  14930. * Returns the associated light object.
  14931. */
  14932. ShadowGenerator.prototype.getLight = function () {
  14933. return this._light;
  14934. };
  14935. // Methods
  14936. /**
  14937. * Returns a Matrix object : the updated transformation matrix.
  14938. */
  14939. ShadowGenerator.prototype.getTransformMatrix = function () {
  14940. var scene = this._scene;
  14941. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  14942. return this._transformMatrix;
  14943. }
  14944. this._currentRenderID = scene.getRenderId();
  14945. this._currentFaceIndexCache = this._currentFaceIndex;
  14946. var lightPosition = this._light.position;
  14947. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  14948. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  14949. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  14950. }
  14951. if (this._light.computeTransformedPosition()) {
  14952. lightPosition = this._light.transformedPosition;
  14953. }
  14954. if (this._light.needRefreshPerFrame() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  14955. this._cachedPosition = lightPosition.clone();
  14956. this._cachedDirection = this._lightDirection.clone();
  14957. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  14958. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, this.getShadowMap().renderList);
  14959. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  14960. }
  14961. return this._transformMatrix;
  14962. };
  14963. /**
  14964. * Returns the darkness value (float).
  14965. */
  14966. ShadowGenerator.prototype.getDarkness = function () {
  14967. return this._darkness;
  14968. };
  14969. /**
  14970. * Sets the ShadowGenerator darkness value (float <= 1.0).
  14971. * Returns the ShadowGenerator.
  14972. */
  14973. ShadowGenerator.prototype.setDarkness = function (darkness) {
  14974. if (darkness >= 1.0)
  14975. this._darkness = 1.0;
  14976. else if (darkness <= 0.0)
  14977. this._darkness = 0.0;
  14978. else
  14979. this._darkness = darkness;
  14980. return this;
  14981. };
  14982. /**
  14983. * Sets the ability to have transparent shadow (boolean).
  14984. * Returns the ShadowGenerator.
  14985. */
  14986. ShadowGenerator.prototype.setTransparencyShadow = function (hasShadow) {
  14987. this._transparencyShadow = hasShadow;
  14988. return this;
  14989. };
  14990. ShadowGenerator.prototype._packHalf = function (depth) {
  14991. var scale = depth * 255.0;
  14992. var fract = scale - Math.floor(scale);
  14993. return new BABYLON.Vector2(depth - fract / 255.0, fract);
  14994. };
  14995. /**
  14996. * Disposes the ShadowGenerator.
  14997. * Returns nothing.
  14998. */
  14999. ShadowGenerator.prototype.dispose = function () {
  15000. this._shadowMap.dispose();
  15001. if (this._shadowMap2) {
  15002. this._shadowMap2.dispose();
  15003. }
  15004. if (this._downSamplePostprocess) {
  15005. this._downSamplePostprocess.dispose();
  15006. }
  15007. if (this._boxBlurPostprocess) {
  15008. this._boxBlurPostprocess.dispose();
  15009. }
  15010. this._light._shadowGenerator = null;
  15011. };
  15012. /**
  15013. * Serializes the ShadowGenerator and returns a serializationObject.
  15014. */
  15015. ShadowGenerator.prototype.serialize = function () {
  15016. var serializationObject = {};
  15017. serializationObject.lightId = this._light.id;
  15018. serializationObject.mapSize = this.getShadowMap().getRenderSize();
  15019. serializationObject.useVarianceShadowMap = this.useVarianceShadowMap;
  15020. serializationObject.usePoissonSampling = this.usePoissonSampling;
  15021. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  15022. serializationObject.darkness = this.getDarkness();
  15023. serializationObject.renderList = [];
  15024. for (var meshIndex = 0; meshIndex < this.getShadowMap().renderList.length; meshIndex++) {
  15025. var mesh = this.getShadowMap().renderList[meshIndex];
  15026. serializationObject.renderList.push(mesh.id);
  15027. }
  15028. return serializationObject;
  15029. };
  15030. /**
  15031. * Parses a serialized ShadowGenerator and returns a new ShadowGenerator.
  15032. */
  15033. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  15034. //casting to point light, as light is missing the position attr and typescript complains.
  15035. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  15036. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  15037. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  15038. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  15039. meshes.forEach(function (mesh) {
  15040. shadowGenerator.getShadowMap().renderList.push(mesh);
  15041. });
  15042. }
  15043. if (parsedShadowGenerator.usePoissonSampling) {
  15044. shadowGenerator.usePoissonSampling = true;
  15045. }
  15046. else if (parsedShadowGenerator.useVarianceShadowMap) {
  15047. shadowGenerator.useVarianceShadowMap = true;
  15048. }
  15049. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  15050. shadowGenerator.useBlurVarianceShadowMap = true;
  15051. if (parsedShadowGenerator.blurScale) {
  15052. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  15053. }
  15054. if (parsedShadowGenerator.blurBoxOffset) {
  15055. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  15056. }
  15057. }
  15058. if (parsedShadowGenerator.bias !== undefined) {
  15059. shadowGenerator.bias = parsedShadowGenerator.bias;
  15060. }
  15061. if (parsedShadowGenerator.darkness) {
  15062. shadowGenerator.setDarkness(parsedShadowGenerator.darkness);
  15063. }
  15064. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  15065. return shadowGenerator;
  15066. };
  15067. return ShadowGenerator;
  15068. }());
  15069. ShadowGenerator._FILTER_NONE = 0;
  15070. ShadowGenerator._FILTER_VARIANCESHADOWMAP = 1;
  15071. ShadowGenerator._FILTER_POISSONSAMPLING = 2;
  15072. ShadowGenerator._FILTER_BLURVARIANCESHADOWMAP = 3;
  15073. ShadowGenerator._FILTER_EXPONENTIALSHADOWMAP = 4;
  15074. BABYLON.ShadowGenerator = ShadowGenerator;
  15075. })(BABYLON || (BABYLON = {}));
  15076. //# sourceMappingURL=babylon.shadowGenerator.js.map
  15077. var BABYLON;
  15078. (function (BABYLON) {
  15079. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  15080. if (boxMin.x > sphereCenter.x + sphereRadius)
  15081. return false;
  15082. if (sphereCenter.x - sphereRadius > boxMax.x)
  15083. return false;
  15084. if (boxMin.y > sphereCenter.y + sphereRadius)
  15085. return false;
  15086. if (sphereCenter.y - sphereRadius > boxMax.y)
  15087. return false;
  15088. if (boxMin.z > sphereCenter.z + sphereRadius)
  15089. return false;
  15090. if (sphereCenter.z - sphereRadius > boxMax.z)
  15091. return false;
  15092. return true;
  15093. };
  15094. var getLowestRoot = (function () {
  15095. var result = { root: 0, found: false };
  15096. return function (a, b, c, maxR) {
  15097. result.root = 0;
  15098. result.found = false;
  15099. var determinant = b * b - 4.0 * a * c;
  15100. if (determinant < 0)
  15101. return result;
  15102. var sqrtD = Math.sqrt(determinant);
  15103. var r1 = (-b - sqrtD) / (2.0 * a);
  15104. var r2 = (-b + sqrtD) / (2.0 * a);
  15105. if (r1 > r2) {
  15106. var temp = r2;
  15107. r2 = r1;
  15108. r1 = temp;
  15109. }
  15110. if (r1 > 0 && r1 < maxR) {
  15111. result.root = r1;
  15112. result.found = true;
  15113. return result;
  15114. }
  15115. if (r2 > 0 && r2 < maxR) {
  15116. result.root = r2;
  15117. result.found = true;
  15118. return result;
  15119. }
  15120. return result;
  15121. };
  15122. })();
  15123. var Collider = (function () {
  15124. function Collider() {
  15125. this.radius = new BABYLON.Vector3(1, 1, 1);
  15126. this.retry = 0;
  15127. this.basePointWorld = BABYLON.Vector3.Zero();
  15128. this.velocityWorld = BABYLON.Vector3.Zero();
  15129. this.normalizedVelocity = BABYLON.Vector3.Zero();
  15130. this._collisionPoint = BABYLON.Vector3.Zero();
  15131. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  15132. this._tempVector = BABYLON.Vector3.Zero();
  15133. this._tempVector2 = BABYLON.Vector3.Zero();
  15134. this._tempVector3 = BABYLON.Vector3.Zero();
  15135. this._tempVector4 = BABYLON.Vector3.Zero();
  15136. this._edge = BABYLON.Vector3.Zero();
  15137. this._baseToVertex = BABYLON.Vector3.Zero();
  15138. this._destinationPoint = BABYLON.Vector3.Zero();
  15139. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  15140. this._displacementVector = BABYLON.Vector3.Zero();
  15141. this._collisionMask = -1;
  15142. }
  15143. Object.defineProperty(Collider.prototype, "collisionMask", {
  15144. get: function () {
  15145. return this._collisionMask;
  15146. },
  15147. set: function (mask) {
  15148. this._collisionMask = !isNaN(mask) ? mask : -1;
  15149. },
  15150. enumerable: true,
  15151. configurable: true
  15152. });
  15153. // Methods
  15154. Collider.prototype._initialize = function (source, dir, e) {
  15155. this.velocity = dir;
  15156. BABYLON.Vector3.NormalizeToRef(dir, this.normalizedVelocity);
  15157. this.basePoint = source;
  15158. source.multiplyToRef(this.radius, this.basePointWorld);
  15159. dir.multiplyToRef(this.radius, this.velocityWorld);
  15160. this.velocityWorldLength = this.velocityWorld.length();
  15161. this.epsilon = e;
  15162. this.collisionFound = false;
  15163. };
  15164. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  15165. pa.subtractToRef(point, this._tempVector);
  15166. pb.subtractToRef(point, this._tempVector2);
  15167. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  15168. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  15169. if (d < 0)
  15170. return false;
  15171. pc.subtractToRef(point, this._tempVector3);
  15172. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  15173. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  15174. if (d < 0)
  15175. return false;
  15176. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  15177. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  15178. return d >= 0;
  15179. };
  15180. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  15181. var distance = BABYLON.Vector3.Distance(this.basePointWorld, sphereCenter);
  15182. var max = Math.max(this.radius.x, this.radius.y, this.radius.z);
  15183. if (distance > this.velocityWorldLength + max + sphereRadius) {
  15184. return false;
  15185. }
  15186. if (!intersectBoxAASphere(vecMin, vecMax, this.basePointWorld, this.velocityWorldLength + max))
  15187. return false;
  15188. return true;
  15189. };
  15190. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  15191. var t0;
  15192. var embeddedInPlane = false;
  15193. //defensive programming, actually not needed.
  15194. if (!trianglePlaneArray) {
  15195. trianglePlaneArray = [];
  15196. }
  15197. if (!trianglePlaneArray[faceIndex]) {
  15198. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  15199. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  15200. }
  15201. var trianglePlane = trianglePlaneArray[faceIndex];
  15202. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this.normalizedVelocity, 0))
  15203. return;
  15204. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this.basePoint);
  15205. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this.velocity);
  15206. if (normalDotVelocity == 0) {
  15207. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  15208. return;
  15209. embeddedInPlane = true;
  15210. t0 = 0;
  15211. }
  15212. else {
  15213. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  15214. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  15215. if (t0 > t1) {
  15216. var temp = t1;
  15217. t1 = t0;
  15218. t0 = temp;
  15219. }
  15220. if (t0 > 1.0 || t1 < 0.0)
  15221. return;
  15222. if (t0 < 0)
  15223. t0 = 0;
  15224. if (t0 > 1.0)
  15225. t0 = 1.0;
  15226. }
  15227. this._collisionPoint.copyFromFloats(0, 0, 0);
  15228. var found = false;
  15229. var t = 1.0;
  15230. if (!embeddedInPlane) {
  15231. this.basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  15232. this.velocity.scaleToRef(t0, this._tempVector);
  15233. this._planeIntersectionPoint.addInPlace(this._tempVector);
  15234. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  15235. found = true;
  15236. t = t0;
  15237. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  15238. }
  15239. }
  15240. if (!found) {
  15241. var velocitySquaredLength = this.velocity.lengthSquared();
  15242. var a = velocitySquaredLength;
  15243. this.basePoint.subtractToRef(p1, this._tempVector);
  15244. var b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  15245. var c = this._tempVector.lengthSquared() - 1.0;
  15246. var lowestRoot = getLowestRoot(a, b, c, t);
  15247. if (lowestRoot.found) {
  15248. t = lowestRoot.root;
  15249. found = true;
  15250. this._collisionPoint.copyFrom(p1);
  15251. }
  15252. this.basePoint.subtractToRef(p2, this._tempVector);
  15253. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  15254. c = this._tempVector.lengthSquared() - 1.0;
  15255. lowestRoot = getLowestRoot(a, b, c, t);
  15256. if (lowestRoot.found) {
  15257. t = lowestRoot.root;
  15258. found = true;
  15259. this._collisionPoint.copyFrom(p2);
  15260. }
  15261. this.basePoint.subtractToRef(p3, this._tempVector);
  15262. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  15263. c = this._tempVector.lengthSquared() - 1.0;
  15264. lowestRoot = getLowestRoot(a, b, c, t);
  15265. if (lowestRoot.found) {
  15266. t = lowestRoot.root;
  15267. found = true;
  15268. this._collisionPoint.copyFrom(p3);
  15269. }
  15270. p2.subtractToRef(p1, this._edge);
  15271. p1.subtractToRef(this.basePoint, this._baseToVertex);
  15272. var edgeSquaredLength = this._edge.lengthSquared();
  15273. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  15274. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  15275. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  15276. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  15277. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  15278. lowestRoot = getLowestRoot(a, b, c, t);
  15279. if (lowestRoot.found) {
  15280. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  15281. if (f >= 0.0 && f <= 1.0) {
  15282. t = lowestRoot.root;
  15283. found = true;
  15284. this._edge.scaleInPlace(f);
  15285. p1.addToRef(this._edge, this._collisionPoint);
  15286. }
  15287. }
  15288. p3.subtractToRef(p2, this._edge);
  15289. p2.subtractToRef(this.basePoint, this._baseToVertex);
  15290. edgeSquaredLength = this._edge.lengthSquared();
  15291. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  15292. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  15293. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  15294. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  15295. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  15296. lowestRoot = getLowestRoot(a, b, c, t);
  15297. if (lowestRoot.found) {
  15298. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  15299. if (f >= 0.0 && f <= 1.0) {
  15300. t = lowestRoot.root;
  15301. found = true;
  15302. this._edge.scaleInPlace(f);
  15303. p2.addToRef(this._edge, this._collisionPoint);
  15304. }
  15305. }
  15306. p1.subtractToRef(p3, this._edge);
  15307. p3.subtractToRef(this.basePoint, this._baseToVertex);
  15308. edgeSquaredLength = this._edge.lengthSquared();
  15309. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  15310. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  15311. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  15312. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  15313. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  15314. lowestRoot = getLowestRoot(a, b, c, t);
  15315. if (lowestRoot.found) {
  15316. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  15317. if (f >= 0.0 && f <= 1.0) {
  15318. t = lowestRoot.root;
  15319. found = true;
  15320. this._edge.scaleInPlace(f);
  15321. p3.addToRef(this._edge, this._collisionPoint);
  15322. }
  15323. }
  15324. }
  15325. if (found) {
  15326. var distToCollision = t * this.velocity.length();
  15327. if (!this.collisionFound || distToCollision < this.nearestDistance) {
  15328. if (!this.intersectionPoint) {
  15329. this.intersectionPoint = this._collisionPoint.clone();
  15330. }
  15331. else {
  15332. this.intersectionPoint.copyFrom(this._collisionPoint);
  15333. }
  15334. this.nearestDistance = distToCollision;
  15335. this.collisionFound = true;
  15336. }
  15337. }
  15338. };
  15339. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  15340. for (var i = indexStart; i < indexEnd; i += 3) {
  15341. var p1 = pts[indices[i] - decal];
  15342. var p2 = pts[indices[i + 1] - decal];
  15343. var p3 = pts[indices[i + 2] - decal];
  15344. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  15345. }
  15346. };
  15347. Collider.prototype._getResponse = function (pos, vel) {
  15348. pos.addToRef(vel, this._destinationPoint);
  15349. vel.scaleInPlace((this.nearestDistance / vel.length()));
  15350. this.basePoint.addToRef(vel, pos);
  15351. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  15352. this._slidePlaneNormal.normalize();
  15353. this._slidePlaneNormal.scaleToRef(this.epsilon, this._displacementVector);
  15354. pos.addInPlace(this._displacementVector);
  15355. this.intersectionPoint.addInPlace(this._displacementVector);
  15356. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  15357. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  15358. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  15359. };
  15360. return Collider;
  15361. }());
  15362. BABYLON.Collider = Collider;
  15363. })(BABYLON || (BABYLON = {}));
  15364. //# sourceMappingURL=babylon.collider.js.map
  15365. var BABYLON;
  15366. (function (BABYLON) {
  15367. //WebWorker code will be inserted to this variable.
  15368. BABYLON.CollisionWorker = "";
  15369. var WorkerTaskType;
  15370. (function (WorkerTaskType) {
  15371. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  15372. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  15373. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  15374. })(WorkerTaskType = BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  15375. var WorkerReplyType;
  15376. (function (WorkerReplyType) {
  15377. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  15378. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  15379. })(WorkerReplyType = BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  15380. var CollisionCoordinatorWorker = (function () {
  15381. function CollisionCoordinatorWorker() {
  15382. var _this = this;
  15383. this._scaledPosition = BABYLON.Vector3.Zero();
  15384. this._scaledVelocity = BABYLON.Vector3.Zero();
  15385. this.onMeshUpdated = function (mesh) {
  15386. _this._addUpdateMeshesList[mesh.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(mesh);
  15387. };
  15388. this.onGeometryUpdated = function (geometry) {
  15389. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  15390. };
  15391. this._afterRender = function () {
  15392. if (!_this._init)
  15393. return;
  15394. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  15395. return;
  15396. }
  15397. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  15398. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  15399. if (_this._runningUpdated > 4) {
  15400. return;
  15401. }
  15402. ++_this._runningUpdated;
  15403. var payload = {
  15404. updatedMeshes: _this._addUpdateMeshesList,
  15405. updatedGeometries: _this._addUpdateGeometriesList,
  15406. removedGeometries: _this._toRemoveGeometryArray,
  15407. removedMeshes: _this._toRemoveMeshesArray
  15408. };
  15409. var message = {
  15410. payload: payload,
  15411. taskType: WorkerTaskType.UPDATE
  15412. };
  15413. var serializable = [];
  15414. for (var id in payload.updatedGeometries) {
  15415. if (payload.updatedGeometries.hasOwnProperty(id)) {
  15416. //prepare transferables
  15417. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  15418. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  15419. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  15420. }
  15421. }
  15422. _this._worker.postMessage(message, serializable);
  15423. _this._addUpdateMeshesList = {};
  15424. _this._addUpdateGeometriesList = {};
  15425. _this._toRemoveGeometryArray = [];
  15426. _this._toRemoveMeshesArray = [];
  15427. };
  15428. this._onMessageFromWorker = function (e) {
  15429. var returnData = e.data;
  15430. if (returnData.error != WorkerReplyType.SUCCESS) {
  15431. //TODO what errors can be returned from the worker?
  15432. BABYLON.Tools.Warn("error returned from worker!");
  15433. return;
  15434. }
  15435. switch (returnData.taskType) {
  15436. case WorkerTaskType.INIT:
  15437. _this._init = true;
  15438. //Update the worked with ALL of the scene's current state
  15439. _this._scene.meshes.forEach(function (mesh) {
  15440. _this.onMeshAdded(mesh);
  15441. });
  15442. _this._scene.getGeometries().forEach(function (geometry) {
  15443. _this.onGeometryAdded(geometry);
  15444. });
  15445. break;
  15446. case WorkerTaskType.UPDATE:
  15447. _this._runningUpdated--;
  15448. break;
  15449. case WorkerTaskType.COLLIDE:
  15450. _this._runningCollisionTask = false;
  15451. var returnPayload = returnData.payload;
  15452. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  15453. return;
  15454. _this._collisionsCallbackArray[returnPayload.collisionId](returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId));
  15455. //cleanup
  15456. _this._collisionsCallbackArray[returnPayload.collisionId] = undefined;
  15457. break;
  15458. }
  15459. };
  15460. this._collisionsCallbackArray = [];
  15461. this._init = false;
  15462. this._runningUpdated = 0;
  15463. this._runningCollisionTask = false;
  15464. this._addUpdateMeshesList = {};
  15465. this._addUpdateGeometriesList = {};
  15466. this._toRemoveGeometryArray = [];
  15467. this._toRemoveMeshesArray = [];
  15468. }
  15469. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, velocity, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  15470. if (!this._init)
  15471. return;
  15472. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  15473. return;
  15474. position.divideToRef(collider.radius, this._scaledPosition);
  15475. velocity.divideToRef(collider.radius, this._scaledVelocity);
  15476. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  15477. var payload = {
  15478. collider: {
  15479. position: this._scaledPosition.asArray(),
  15480. velocity: this._scaledVelocity.asArray(),
  15481. radius: collider.radius.asArray()
  15482. },
  15483. collisionId: collisionIndex,
  15484. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  15485. maximumRetry: maximumRetry
  15486. };
  15487. var message = {
  15488. payload: payload,
  15489. taskType: WorkerTaskType.COLLIDE
  15490. };
  15491. this._worker.postMessage(message);
  15492. };
  15493. CollisionCoordinatorWorker.prototype.init = function (scene) {
  15494. this._scene = scene;
  15495. this._scene.registerAfterRender(this._afterRender);
  15496. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  15497. this._worker = new Worker(workerUrl);
  15498. this._worker.onmessage = this._onMessageFromWorker;
  15499. var message = {
  15500. payload: {},
  15501. taskType: WorkerTaskType.INIT
  15502. };
  15503. this._worker.postMessage(message);
  15504. };
  15505. CollisionCoordinatorWorker.prototype.destroy = function () {
  15506. this._scene.unregisterAfterRender(this._afterRender);
  15507. this._worker.terminate();
  15508. };
  15509. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  15510. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  15511. this.onMeshUpdated(mesh);
  15512. };
  15513. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  15514. this._toRemoveMeshesArray.push(mesh.uniqueId);
  15515. };
  15516. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  15517. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  15518. geometry.onGeometryUpdated = this.onGeometryUpdated;
  15519. this.onGeometryUpdated(geometry);
  15520. };
  15521. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  15522. this._toRemoveGeometryArray.push(geometry.id);
  15523. };
  15524. return CollisionCoordinatorWorker;
  15525. }());
  15526. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  15527. var submeshes = [];
  15528. if (mesh.subMeshes) {
  15529. submeshes = mesh.subMeshes.map(function (sm, idx) {
  15530. return {
  15531. position: idx,
  15532. verticesStart: sm.verticesStart,
  15533. verticesCount: sm.verticesCount,
  15534. indexStart: sm.indexStart,
  15535. indexCount: sm.indexCount,
  15536. hasMaterial: !!sm.getMaterial(),
  15537. sphereCenter: sm.getBoundingInfo().boundingSphere.centerWorld.asArray(),
  15538. sphereRadius: sm.getBoundingInfo().boundingSphere.radiusWorld,
  15539. boxMinimum: sm.getBoundingInfo().boundingBox.minimumWorld.asArray(),
  15540. boxMaximum: sm.getBoundingInfo().boundingBox.maximumWorld.asArray()
  15541. };
  15542. });
  15543. }
  15544. var geometryId = null;
  15545. if (mesh instanceof BABYLON.Mesh) {
  15546. geometryId = mesh.geometry ? mesh.geometry.id : null;
  15547. }
  15548. else if (mesh instanceof BABYLON.InstancedMesh) {
  15549. geometryId = (mesh.sourceMesh && mesh.sourceMesh.geometry) ? mesh.sourceMesh.geometry.id : null;
  15550. }
  15551. return {
  15552. uniqueId: mesh.uniqueId,
  15553. id: mesh.id,
  15554. name: mesh.name,
  15555. geometryId: geometryId,
  15556. sphereCenter: mesh.getBoundingInfo().boundingSphere.centerWorld.asArray(),
  15557. sphereRadius: mesh.getBoundingInfo().boundingSphere.radiusWorld,
  15558. boxMinimum: mesh.getBoundingInfo().boundingBox.minimumWorld.asArray(),
  15559. boxMaximum: mesh.getBoundingInfo().boundingBox.maximumWorld.asArray(),
  15560. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  15561. subMeshes: submeshes,
  15562. checkCollisions: mesh.checkCollisions
  15563. };
  15564. };
  15565. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  15566. return {
  15567. id: geometry.id,
  15568. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  15569. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  15570. indices: new Uint32Array(geometry.getIndices() || []),
  15571. };
  15572. };
  15573. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  15574. var CollisionCoordinatorLegacy = (function () {
  15575. function CollisionCoordinatorLegacy() {
  15576. this._scaledPosition = BABYLON.Vector3.Zero();
  15577. this._scaledVelocity = BABYLON.Vector3.Zero();
  15578. this._finalPosition = BABYLON.Vector3.Zero();
  15579. }
  15580. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, velocity, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  15581. position.divideToRef(collider.radius, this._scaledPosition);
  15582. velocity.divideToRef(collider.radius, this._scaledVelocity);
  15583. collider.collidedMesh = null;
  15584. collider.retry = 0;
  15585. collider.initialVelocity = this._scaledVelocity;
  15586. collider.initialPosition = this._scaledPosition;
  15587. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  15588. this._finalPosition.multiplyInPlace(collider.radius);
  15589. //run the callback
  15590. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  15591. };
  15592. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  15593. this._scene = scene;
  15594. };
  15595. CollisionCoordinatorLegacy.prototype.destroy = function () {
  15596. //Legacy need no destruction method.
  15597. };
  15598. //No update in legacy mode
  15599. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  15600. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  15601. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  15602. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  15603. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  15604. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  15605. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  15606. if (excludedMesh === void 0) { excludedMesh = null; }
  15607. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  15608. if (collider.retry >= maximumRetry) {
  15609. finalPosition.copyFrom(position);
  15610. return;
  15611. }
  15612. // Check if this is a mesh else camera or -1
  15613. var collisionMask = (excludedMesh ? excludedMesh.collisionMask : collider.collisionMask);
  15614. collider._initialize(position, velocity, closeDistance);
  15615. // Check all meshes
  15616. for (var index = 0; index < this._scene.meshes.length; index++) {
  15617. var mesh = this._scene.meshes[index];
  15618. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh && ((collisionMask & mesh.collisionGroup) !== 0)) {
  15619. mesh._checkCollision(collider);
  15620. }
  15621. }
  15622. if (!collider.collisionFound) {
  15623. position.addToRef(velocity, finalPosition);
  15624. return;
  15625. }
  15626. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  15627. collider._getResponse(position, velocity);
  15628. }
  15629. if (velocity.length() <= closeDistance) {
  15630. finalPosition.copyFrom(position);
  15631. return;
  15632. }
  15633. collider.retry++;
  15634. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  15635. };
  15636. return CollisionCoordinatorLegacy;
  15637. }());
  15638. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  15639. })(BABYLON || (BABYLON = {}));
  15640. //# sourceMappingURL=babylon.collisionCoordinator.js.map
  15641. var BABYLON;
  15642. (function (BABYLON) {
  15643. var Camera = (function (_super) {
  15644. __extends(Camera, _super);
  15645. function Camera(name, position, scene) {
  15646. var _this = _super.call(this, name, scene) || this;
  15647. _this.upVector = BABYLON.Vector3.Up();
  15648. _this.orthoLeft = null;
  15649. _this.orthoRight = null;
  15650. _this.orthoBottom = null;
  15651. _this.orthoTop = null;
  15652. _this.fov = 0.8;
  15653. _this.minZ = 1.0;
  15654. _this.maxZ = 10000.0;
  15655. _this.inertia = 0.9;
  15656. _this.mode = Camera.PERSPECTIVE_CAMERA;
  15657. _this.isIntermediate = false;
  15658. _this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  15659. _this.layerMask = 0x0FFFFFFF;
  15660. _this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  15661. // Camera rig members
  15662. _this.cameraRigMode = Camera.RIG_MODE_NONE;
  15663. _this._rigCameras = new Array();
  15664. _this._webvrViewMatrix = BABYLON.Matrix.Identity();
  15665. // Cache
  15666. _this._computedViewMatrix = BABYLON.Matrix.Identity();
  15667. _this._projectionMatrix = new BABYLON.Matrix();
  15668. _this._doNotComputeProjectionMatrix = false;
  15669. _this._postProcesses = new Array();
  15670. _this._transformMatrix = BABYLON.Matrix.Zero();
  15671. _this._activeMeshes = new BABYLON.SmartArray(256);
  15672. _this._globalPosition = BABYLON.Vector3.Zero();
  15673. _this._refreshFrustumPlanes = true;
  15674. _this.getScene().addCamera(_this);
  15675. if (!_this.getScene().activeCamera) {
  15676. _this.getScene().activeCamera = _this;
  15677. }
  15678. _this.position = position;
  15679. return _this;
  15680. }
  15681. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  15682. get: function () {
  15683. return Camera._PERSPECTIVE_CAMERA;
  15684. },
  15685. enumerable: true,
  15686. configurable: true
  15687. });
  15688. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  15689. get: function () {
  15690. return Camera._ORTHOGRAPHIC_CAMERA;
  15691. },
  15692. enumerable: true,
  15693. configurable: true
  15694. });
  15695. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  15696. get: function () {
  15697. return Camera._FOVMODE_VERTICAL_FIXED;
  15698. },
  15699. enumerable: true,
  15700. configurable: true
  15701. });
  15702. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  15703. get: function () {
  15704. return Camera._FOVMODE_HORIZONTAL_FIXED;
  15705. },
  15706. enumerable: true,
  15707. configurable: true
  15708. });
  15709. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  15710. get: function () {
  15711. return Camera._RIG_MODE_NONE;
  15712. },
  15713. enumerable: true,
  15714. configurable: true
  15715. });
  15716. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  15717. get: function () {
  15718. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  15719. },
  15720. enumerable: true,
  15721. configurable: true
  15722. });
  15723. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  15724. get: function () {
  15725. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  15726. },
  15727. enumerable: true,
  15728. configurable: true
  15729. });
  15730. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  15731. get: function () {
  15732. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  15733. },
  15734. enumerable: true,
  15735. configurable: true
  15736. });
  15737. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  15738. get: function () {
  15739. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  15740. },
  15741. enumerable: true,
  15742. configurable: true
  15743. });
  15744. Object.defineProperty(Camera, "RIG_MODE_VR", {
  15745. get: function () {
  15746. return Camera._RIG_MODE_VR;
  15747. },
  15748. enumerable: true,
  15749. configurable: true
  15750. });
  15751. Object.defineProperty(Camera, "RIG_MODE_WEBVR", {
  15752. get: function () {
  15753. return Camera._RIG_MODE_WEBVR;
  15754. },
  15755. enumerable: true,
  15756. configurable: true
  15757. });
  15758. Camera.prototype.getClassName = function () {
  15759. return "Camera";
  15760. };
  15761. /**
  15762. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  15763. */
  15764. Camera.prototype.toString = function (fullDetails) {
  15765. var ret = "Name: " + this.name;
  15766. ret += ", type: " + this.getClassName();
  15767. if (this.animations) {
  15768. for (var i = 0; i < this.animations.length; i++) {
  15769. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  15770. }
  15771. }
  15772. if (fullDetails) {
  15773. }
  15774. return ret;
  15775. };
  15776. Object.defineProperty(Camera.prototype, "globalPosition", {
  15777. get: function () {
  15778. return this._globalPosition;
  15779. },
  15780. enumerable: true,
  15781. configurable: true
  15782. });
  15783. Camera.prototype.getActiveMeshes = function () {
  15784. return this._activeMeshes;
  15785. };
  15786. Camera.prototype.isActiveMesh = function (mesh) {
  15787. return (this._activeMeshes.indexOf(mesh) !== -1);
  15788. };
  15789. //Cache
  15790. Camera.prototype._initCache = function () {
  15791. _super.prototype._initCache.call(this);
  15792. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  15793. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  15794. this._cache.mode = undefined;
  15795. this._cache.minZ = undefined;
  15796. this._cache.maxZ = undefined;
  15797. this._cache.fov = undefined;
  15798. this._cache.fovMode = undefined;
  15799. this._cache.aspectRatio = undefined;
  15800. this._cache.orthoLeft = undefined;
  15801. this._cache.orthoRight = undefined;
  15802. this._cache.orthoBottom = undefined;
  15803. this._cache.orthoTop = undefined;
  15804. this._cache.renderWidth = undefined;
  15805. this._cache.renderHeight = undefined;
  15806. };
  15807. Camera.prototype._updateCache = function (ignoreParentClass) {
  15808. if (!ignoreParentClass) {
  15809. _super.prototype._updateCache.call(this);
  15810. }
  15811. var engine = this.getEngine();
  15812. this._cache.position.copyFrom(this.position);
  15813. this._cache.upVector.copyFrom(this.upVector);
  15814. this._cache.mode = this.mode;
  15815. this._cache.minZ = this.minZ;
  15816. this._cache.maxZ = this.maxZ;
  15817. this._cache.fov = this.fov;
  15818. this._cache.fovMode = this.fovMode;
  15819. this._cache.aspectRatio = engine.getAspectRatio(this);
  15820. this._cache.orthoLeft = this.orthoLeft;
  15821. this._cache.orthoRight = this.orthoRight;
  15822. this._cache.orthoBottom = this.orthoBottom;
  15823. this._cache.orthoTop = this.orthoTop;
  15824. this._cache.renderWidth = engine.getRenderWidth();
  15825. this._cache.renderHeight = engine.getRenderHeight();
  15826. };
  15827. Camera.prototype._updateFromScene = function () {
  15828. this.updateCache();
  15829. this.update();
  15830. };
  15831. // Synchronized
  15832. Camera.prototype._isSynchronized = function () {
  15833. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  15834. };
  15835. Camera.prototype._isSynchronizedViewMatrix = function () {
  15836. if (!_super.prototype._isSynchronized.call(this))
  15837. return false;
  15838. return this._cache.position.equals(this.position)
  15839. && this._cache.upVector.equals(this.upVector)
  15840. && this.isSynchronizedWithParent();
  15841. };
  15842. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  15843. var check = this._cache.mode === this.mode
  15844. && this._cache.minZ === this.minZ
  15845. && this._cache.maxZ === this.maxZ;
  15846. if (!check) {
  15847. return false;
  15848. }
  15849. var engine = this.getEngine();
  15850. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  15851. check = this._cache.fov === this.fov
  15852. && this._cache.fovMode === this.fovMode
  15853. && this._cache.aspectRatio === engine.getAspectRatio(this);
  15854. }
  15855. else {
  15856. check = this._cache.orthoLeft === this.orthoLeft
  15857. && this._cache.orthoRight === this.orthoRight
  15858. && this._cache.orthoBottom === this.orthoBottom
  15859. && this._cache.orthoTop === this.orthoTop
  15860. && this._cache.renderWidth === engine.getRenderWidth()
  15861. && this._cache.renderHeight === engine.getRenderHeight();
  15862. }
  15863. return check;
  15864. };
  15865. // Controls
  15866. Camera.prototype.attachControl = function (element, noPreventDefault) {
  15867. };
  15868. Camera.prototype.detachControl = function (element) {
  15869. };
  15870. Camera.prototype.update = function () {
  15871. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  15872. this._updateRigCameras();
  15873. }
  15874. this._checkInputs();
  15875. };
  15876. Camera.prototype._checkInputs = function () {
  15877. };
  15878. Object.defineProperty(Camera.prototype, "rigCameras", {
  15879. get: function () {
  15880. return this._rigCameras;
  15881. },
  15882. enumerable: true,
  15883. configurable: true
  15884. });
  15885. Object.defineProperty(Camera.prototype, "rigPostProcess", {
  15886. get: function () {
  15887. return this._rigPostProcess;
  15888. },
  15889. enumerable: true,
  15890. configurable: true
  15891. });
  15892. Camera.prototype._cascadePostProcessesToRigCams = function () {
  15893. // invalidate framebuffer
  15894. if (this._postProcesses.length > 0) {
  15895. this._postProcesses[0].markTextureDirty();
  15896. }
  15897. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  15898. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  15899. var cam = this._rigCameras[i];
  15900. var rigPostProcess = cam._rigPostProcess;
  15901. // for VR rig, there does not have to be a post process
  15902. if (rigPostProcess) {
  15903. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  15904. if (isPass) {
  15905. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  15906. cam.isIntermediate = this._postProcesses.length === 0;
  15907. }
  15908. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  15909. rigPostProcess.markTextureDirty();
  15910. }
  15911. else {
  15912. cam._postProcesses = this._postProcesses.slice(0);
  15913. }
  15914. }
  15915. };
  15916. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  15917. if (insertAt === void 0) { insertAt = null; }
  15918. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  15919. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  15920. return 0;
  15921. }
  15922. if (insertAt == null || insertAt < 0) {
  15923. this._postProcesses.push(postProcess);
  15924. }
  15925. else {
  15926. this._postProcesses.splice(insertAt, 0, postProcess);
  15927. }
  15928. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  15929. return this._postProcesses.indexOf(postProcess);
  15930. };
  15931. Camera.prototype.detachPostProcess = function (postProcess, atIndices) {
  15932. if (atIndices === void 0) { atIndices = null; }
  15933. var result = [];
  15934. var i;
  15935. var index;
  15936. if (!atIndices) {
  15937. var idx = this._postProcesses.indexOf(postProcess);
  15938. if (idx !== -1) {
  15939. this._postProcesses.splice(idx, 1);
  15940. }
  15941. }
  15942. else {
  15943. atIndices = (atIndices instanceof Array) ? atIndices : [atIndices];
  15944. // iterate descending, so can just splice as we go
  15945. for (i = atIndices.length - 1; i >= 0; i--) {
  15946. if (this._postProcesses[atIndices[i]] !== postProcess) {
  15947. result.push(i);
  15948. continue;
  15949. }
  15950. index = atIndices[i];
  15951. this._postProcesses.splice(index, 1);
  15952. }
  15953. }
  15954. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  15955. return result;
  15956. };
  15957. Camera.prototype.getWorldMatrix = function () {
  15958. if (!this._worldMatrix) {
  15959. this._worldMatrix = BABYLON.Matrix.Identity();
  15960. }
  15961. var viewMatrix = this.getViewMatrix();
  15962. viewMatrix.invertToRef(this._worldMatrix);
  15963. return this._worldMatrix;
  15964. };
  15965. Camera.prototype._getViewMatrix = function () {
  15966. return BABYLON.Matrix.Identity();
  15967. };
  15968. Camera.prototype.getViewMatrix = function (force) {
  15969. this._computedViewMatrix = this._computeViewMatrix(force);
  15970. if (!force && this._isSynchronizedViewMatrix()) {
  15971. return this._computedViewMatrix;
  15972. }
  15973. this._refreshFrustumPlanes = true;
  15974. if (!this.parent || !this.parent.getWorldMatrix) {
  15975. this._globalPosition.copyFrom(this.position);
  15976. }
  15977. else {
  15978. if (!this._worldMatrix) {
  15979. this._worldMatrix = BABYLON.Matrix.Identity();
  15980. }
  15981. this._computedViewMatrix.invertToRef(this._worldMatrix);
  15982. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  15983. this._globalPosition.copyFromFloats(this._computedViewMatrix.m[12], this._computedViewMatrix.m[13], this._computedViewMatrix.m[14]);
  15984. this._computedViewMatrix.invert();
  15985. this._markSyncedWithParent();
  15986. }
  15987. if (this._cameraRigParams && this._cameraRigParams.vrPreViewMatrix) {
  15988. this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._computedViewMatrix);
  15989. }
  15990. this._currentRenderId = this.getScene().getRenderId();
  15991. return this._computedViewMatrix;
  15992. };
  15993. Camera.prototype._computeViewMatrix = function (force) {
  15994. if (!force && this._isSynchronizedViewMatrix()) {
  15995. return this._computedViewMatrix;
  15996. }
  15997. this._computedViewMatrix = this._getViewMatrix();
  15998. this._currentRenderId = this.getScene().getRenderId();
  15999. return this._computedViewMatrix;
  16000. };
  16001. Camera.prototype.freezeProjectionMatrix = function (projection) {
  16002. this._doNotComputeProjectionMatrix = true;
  16003. if (projection !== undefined) {
  16004. this._projectionMatrix = projection;
  16005. }
  16006. };
  16007. ;
  16008. Camera.prototype.unfreezeProjectionMatrix = function () {
  16009. this._doNotComputeProjectionMatrix = false;
  16010. };
  16011. ;
  16012. Camera.prototype.getProjectionMatrix = function (force) {
  16013. if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {
  16014. return this._projectionMatrix;
  16015. }
  16016. this._refreshFrustumPlanes = true;
  16017. var engine = this.getEngine();
  16018. var scene = this.getScene();
  16019. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  16020. if (this.minZ <= 0) {
  16021. this.minZ = 0.1;
  16022. }
  16023. if (scene.useRightHandedSystem) {
  16024. BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  16025. }
  16026. else {
  16027. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  16028. }
  16029. return this._projectionMatrix;
  16030. }
  16031. var halfWidth = engine.getRenderWidth() / 2.0;
  16032. var halfHeight = engine.getRenderHeight() / 2.0;
  16033. if (scene.useRightHandedSystem) {
  16034. BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  16035. }
  16036. else {
  16037. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  16038. }
  16039. return this._projectionMatrix;
  16040. };
  16041. Camera.prototype.getTranformationMatrix = function () {
  16042. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  16043. return this._transformMatrix;
  16044. };
  16045. Camera.prototype.updateFrustumPlanes = function () {
  16046. if (!this._refreshFrustumPlanes) {
  16047. return;
  16048. }
  16049. this.getTranformationMatrix();
  16050. if (!this._frustumPlanes) {
  16051. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  16052. }
  16053. else {
  16054. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  16055. }
  16056. this._refreshFrustumPlanes = false;
  16057. };
  16058. Camera.prototype.isInFrustum = function (target) {
  16059. this.updateFrustumPlanes();
  16060. return target.isInFrustum(this._frustumPlanes);
  16061. };
  16062. Camera.prototype.isCompletelyInFrustum = function (target) {
  16063. this.updateFrustumPlanes();
  16064. return target.isCompletelyInFrustum(this._frustumPlanes);
  16065. };
  16066. Camera.prototype.dispose = function () {
  16067. // Animations
  16068. this.getScene().stopAnimation(this);
  16069. // Remove from scene
  16070. this.getScene().removeCamera(this);
  16071. while (this._rigCameras.length > 0) {
  16072. this._rigCameras.pop().dispose();
  16073. }
  16074. // Postprocesses
  16075. var i = this._postProcesses.length;
  16076. while (--i >= 0) {
  16077. this._postProcesses[i].dispose(this);
  16078. }
  16079. _super.prototype.dispose.call(this);
  16080. };
  16081. // ---- Camera rigs section ----
  16082. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  16083. while (this._rigCameras.length > 0) {
  16084. this._rigCameras.pop().dispose();
  16085. }
  16086. this.cameraRigMode = mode;
  16087. this._cameraRigParams = {};
  16088. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  16089. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  16090. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  16091. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  16092. // create the rig cameras, unless none
  16093. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  16094. this._rigCameras.push(this.createRigCamera(this.name + "_L", 0));
  16095. this._rigCameras.push(this.createRigCamera(this.name + "_R", 1));
  16096. }
  16097. switch (this.cameraRigMode) {
  16098. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  16099. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  16100. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  16101. break;
  16102. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  16103. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  16104. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  16105. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  16106. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  16107. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  16108. break;
  16109. case Camera.RIG_MODE_VR:
  16110. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  16111. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  16112. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  16113. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  16114. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  16115. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  16116. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  16117. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  16118. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  16119. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  16120. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  16121. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  16122. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  16123. if (metrics.compensateDistortion) {
  16124. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  16125. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  16126. }
  16127. break;
  16128. case Camera.RIG_MODE_WEBVR:
  16129. if (rigParams.vrDisplay) {
  16130. var leftEye = rigParams.vrDisplay.getEyeParameters('left');
  16131. var rightEye = rigParams.vrDisplay.getEyeParameters('right');
  16132. //Left eye
  16133. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  16134. this._rigCameras[0].setCameraRigParameter("left", true);
  16135. this._rigCameras[0].setCameraRigParameter("eyeParameters", leftEye);
  16136. this._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData);
  16137. this._rigCameras[0].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  16138. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  16139. this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
  16140. this._rigCameras[0].parent = this;
  16141. this._rigCameras[0]._getViewMatrix = this._getWebVRViewMatrix;
  16142. //Right eye
  16143. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  16144. this._rigCameras[0].setCameraRigParameter("left", false);
  16145. this._rigCameras[1].setCameraRigParameter('eyeParameters', rightEye);
  16146. this._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData);
  16147. this._rigCameras[1].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  16148. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  16149. this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
  16150. this._rigCameras[1].parent = this;
  16151. this._rigCameras[1]._getViewMatrix = this._getWebVRViewMatrix;
  16152. }
  16153. break;
  16154. }
  16155. this._cascadePostProcessesToRigCams();
  16156. this.
  16157. update();
  16158. };
  16159. Camera.prototype._getVRProjectionMatrix = function () {
  16160. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  16161. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  16162. return this._projectionMatrix;
  16163. };
  16164. Camera.prototype._updateCameraRotationMatrix = function () {
  16165. //Here for WebVR
  16166. };
  16167. Camera.prototype._updateWebVRCameraRotationMatrix = function () {
  16168. //Here for WebVR
  16169. };
  16170. /**
  16171. * This function MUST be overwritten by the different WebVR cameras available.
  16172. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  16173. */
  16174. Camera.prototype._getWebVRProjectionMatrix = function () {
  16175. return BABYLON.Matrix.Identity();
  16176. };
  16177. /**
  16178. * This function MUST be overwritten by the different WebVR cameras available.
  16179. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  16180. */
  16181. Camera.prototype._getWebVRViewMatrix = function () {
  16182. return BABYLON.Matrix.Identity();
  16183. };
  16184. Camera.prototype.setCameraRigParameter = function (name, value) {
  16185. if (!this._cameraRigParams) {
  16186. this._cameraRigParams = {};
  16187. }
  16188. this._cameraRigParams[name] = value;
  16189. //provisionnally:
  16190. if (name === "interaxialDistance") {
  16191. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  16192. }
  16193. };
  16194. /**
  16195. * needs to be overridden by children so sub has required properties to be copied
  16196. */
  16197. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  16198. return null;
  16199. };
  16200. /**
  16201. * May need to be overridden by children
  16202. */
  16203. Camera.prototype._updateRigCameras = function () {
  16204. for (var i = 0; i < this._rigCameras.length; i++) {
  16205. this._rigCameras[i].minZ = this.minZ;
  16206. this._rigCameras[i].maxZ = this.maxZ;
  16207. this._rigCameras[i].fov = this.fov;
  16208. }
  16209. // only update viewport when ANAGLYPH
  16210. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  16211. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  16212. }
  16213. };
  16214. Camera.prototype._setupInputs = function () {
  16215. };
  16216. Camera.prototype.serialize = function () {
  16217. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  16218. // Type
  16219. serializationObject.type = this.getClassName();
  16220. // Parent
  16221. if (this.parent) {
  16222. serializationObject.parentId = this.parent.id;
  16223. }
  16224. if (this.inputs) {
  16225. this.inputs.serialize(serializationObject);
  16226. }
  16227. // Animations
  16228. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  16229. serializationObject.ranges = this.serializeAnimationRanges();
  16230. return serializationObject;
  16231. };
  16232. Camera.prototype.clone = function (name) {
  16233. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  16234. };
  16235. Camera.prototype.getDirection = function (localAxis) {
  16236. var result = BABYLON.Vector3.Zero();
  16237. this.getDirectionToRef(localAxis, result);
  16238. return result;
  16239. };
  16240. Camera.prototype.getDirectionToRef = function (localAxis, result) {
  16241. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  16242. };
  16243. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  16244. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  16245. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  16246. switch (type) {
  16247. case "ArcRotateCamera":
  16248. return function () { return new BABYLON.ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  16249. case "DeviceOrientationCamera":
  16250. return function () { return new BABYLON.DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  16251. case "FollowCamera":
  16252. return function () { return new BABYLON.FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  16253. case "ArcFollowCamera":
  16254. return function () { return new BABYLON.ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  16255. case "GamepadCamera":
  16256. return function () { return new BABYLON.GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  16257. case "TouchCamera":
  16258. return function () { return new BABYLON.TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  16259. case "VirtualJoysticksCamera":
  16260. return function () { return new BABYLON.VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  16261. case "WebVRFreeCamera":
  16262. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  16263. case "WebVRGamepadCamera":
  16264. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  16265. case "VRDeviceOrientationFreeCamera":
  16266. return function () { return new BABYLON.VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  16267. case "VRDeviceOrientationGamepadCamera":
  16268. return function () { return new BABYLON.VRDeviceOrientationGamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  16269. case "AnaglyphArcRotateCamera":
  16270. return function () { return new BABYLON.AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  16271. case "AnaglyphFreeCamera":
  16272. return function () { return new BABYLON.AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  16273. case "AnaglyphGamepadCamera":
  16274. return function () { return new BABYLON.AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  16275. case "AnaglyphUniversalCamera":
  16276. return function () { return new BABYLON.AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  16277. case "StereoscopicArcRotateCamera":
  16278. return function () { return new BABYLON.StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  16279. case "StereoscopicFreeCamera":
  16280. return function () { return new BABYLON.StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  16281. case "StereoscopicGamepadCamera":
  16282. return function () { return new BABYLON.StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  16283. case "StereoscopicUniversalCamera":
  16284. return function () { return new BABYLON.StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  16285. case "FreeCamera":
  16286. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  16287. default:
  16288. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  16289. }
  16290. };
  16291. Camera.Parse = function (parsedCamera, scene) {
  16292. var type = parsedCamera.type;
  16293. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  16294. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  16295. // Parent
  16296. if (parsedCamera.parentId) {
  16297. camera._waitingParentId = parsedCamera.parentId;
  16298. }
  16299. //If camera has an input manager, let it parse inputs settings
  16300. if (camera.inputs) {
  16301. camera.inputs.parse(parsedCamera);
  16302. camera._setupInputs();
  16303. }
  16304. // Target
  16305. if (parsedCamera.target) {
  16306. if (camera.setTarget) {
  16307. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  16308. }
  16309. }
  16310. // Apply 3d rig, when found
  16311. if (parsedCamera.cameraRigMode) {
  16312. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  16313. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  16314. }
  16315. // Animations
  16316. if (parsedCamera.animations) {
  16317. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  16318. var parsedAnimation = parsedCamera.animations[animationIndex];
  16319. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  16320. }
  16321. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  16322. }
  16323. if (parsedCamera.autoAnimate) {
  16324. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  16325. }
  16326. return camera;
  16327. };
  16328. return Camera;
  16329. }(BABYLON.Node));
  16330. // Statics
  16331. Camera._PERSPECTIVE_CAMERA = 0;
  16332. Camera._ORTHOGRAPHIC_CAMERA = 1;
  16333. Camera._FOVMODE_VERTICAL_FIXED = 0;
  16334. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  16335. Camera._RIG_MODE_NONE = 0;
  16336. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  16337. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  16338. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  16339. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  16340. Camera._RIG_MODE_VR = 20;
  16341. Camera._RIG_MODE_WEBVR = 21;
  16342. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  16343. __decorate([
  16344. BABYLON.serializeAsVector3()
  16345. ], Camera.prototype, "position", void 0);
  16346. __decorate([
  16347. BABYLON.serializeAsVector3()
  16348. ], Camera.prototype, "upVector", void 0);
  16349. __decorate([
  16350. BABYLON.serialize()
  16351. ], Camera.prototype, "orthoLeft", void 0);
  16352. __decorate([
  16353. BABYLON.serialize()
  16354. ], Camera.prototype, "orthoRight", void 0);
  16355. __decorate([
  16356. BABYLON.serialize()
  16357. ], Camera.prototype, "orthoBottom", void 0);
  16358. __decorate([
  16359. BABYLON.serialize()
  16360. ], Camera.prototype, "orthoTop", void 0);
  16361. __decorate([
  16362. BABYLON.serialize()
  16363. ], Camera.prototype, "fov", void 0);
  16364. __decorate([
  16365. BABYLON.serialize()
  16366. ], Camera.prototype, "minZ", void 0);
  16367. __decorate([
  16368. BABYLON.serialize()
  16369. ], Camera.prototype, "maxZ", void 0);
  16370. __decorate([
  16371. BABYLON.serialize()
  16372. ], Camera.prototype, "inertia", void 0);
  16373. __decorate([
  16374. BABYLON.serialize()
  16375. ], Camera.prototype, "mode", void 0);
  16376. __decorate([
  16377. BABYLON.serialize()
  16378. ], Camera.prototype, "layerMask", void 0);
  16379. __decorate([
  16380. BABYLON.serialize()
  16381. ], Camera.prototype, "fovMode", void 0);
  16382. __decorate([
  16383. BABYLON.serialize()
  16384. ], Camera.prototype, "cameraRigMode", void 0);
  16385. __decorate([
  16386. BABYLON.serialize()
  16387. ], Camera.prototype, "interaxialDistance", void 0);
  16388. __decorate([
  16389. BABYLON.serialize()
  16390. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  16391. BABYLON.Camera = Camera;
  16392. })(BABYLON || (BABYLON = {}));
  16393. //# sourceMappingURL=babylon.camera.js.map
  16394. var BABYLON;
  16395. (function (BABYLON) {
  16396. BABYLON.CameraInputTypes = {};
  16397. var CameraInputsManager = (function () {
  16398. function CameraInputsManager(camera) {
  16399. this.attached = {};
  16400. this.camera = camera;
  16401. this.checkInputs = function () { };
  16402. }
  16403. CameraInputsManager.prototype.add = function (input) {
  16404. var type = input.getSimpleName();
  16405. if (this.attached[type]) {
  16406. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  16407. return;
  16408. }
  16409. this.attached[type] = input;
  16410. input.camera = this.camera;
  16411. //for checkInputs, we are dynamically creating a function
  16412. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  16413. if (input.checkInputs) {
  16414. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  16415. }
  16416. if (this.attachedElement) {
  16417. input.attachControl(this.attachedElement);
  16418. }
  16419. };
  16420. CameraInputsManager.prototype.remove = function (inputToRemove) {
  16421. for (var cam in this.attached) {
  16422. var input = this.attached[cam];
  16423. if (input === inputToRemove) {
  16424. input.detachControl(this.attachedElement);
  16425. delete this.attached[cam];
  16426. this.rebuildInputCheck();
  16427. }
  16428. }
  16429. };
  16430. CameraInputsManager.prototype.removeByType = function (inputType) {
  16431. for (var cam in this.attached) {
  16432. var input = this.attached[cam];
  16433. if (input.getTypeName() === inputType) {
  16434. input.detachControl(this.attachedElement);
  16435. delete this.attached[cam];
  16436. this.rebuildInputCheck();
  16437. }
  16438. }
  16439. };
  16440. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  16441. var current = this.checkInputs;
  16442. return function () {
  16443. current();
  16444. fn();
  16445. };
  16446. };
  16447. CameraInputsManager.prototype.attachInput = function (input) {
  16448. input.attachControl(this.attachedElement, this.noPreventDefault);
  16449. };
  16450. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  16451. if (this.attachedElement) {
  16452. return;
  16453. }
  16454. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  16455. this.attachedElement = element;
  16456. this.noPreventDefault = noPreventDefault;
  16457. for (var cam in this.attached) {
  16458. var input = this.attached[cam];
  16459. this.attached[cam].attachControl(element, noPreventDefault);
  16460. }
  16461. };
  16462. CameraInputsManager.prototype.detachElement = function (element) {
  16463. if (this.attachedElement !== element) {
  16464. return;
  16465. }
  16466. for (var cam in this.attached) {
  16467. var input = this.attached[cam];
  16468. this.attached[cam].detachControl(element);
  16469. }
  16470. this.attachedElement = null;
  16471. };
  16472. CameraInputsManager.prototype.rebuildInputCheck = function () {
  16473. this.checkInputs = function () { };
  16474. for (var cam in this.attached) {
  16475. var input = this.attached[cam];
  16476. if (input.checkInputs) {
  16477. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  16478. }
  16479. }
  16480. };
  16481. CameraInputsManager.prototype.clear = function () {
  16482. if (this.attachedElement) {
  16483. this.detachElement(this.attachedElement);
  16484. }
  16485. this.attached = {};
  16486. this.attachedElement = null;
  16487. this.checkInputs = function () { };
  16488. };
  16489. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  16490. var inputs = {};
  16491. for (var cam in this.attached) {
  16492. var input = this.attached[cam];
  16493. var res = BABYLON.SerializationHelper.Serialize(input);
  16494. inputs[input.getTypeName()] = res;
  16495. }
  16496. serializedCamera.inputsmgr = inputs;
  16497. };
  16498. CameraInputsManager.prototype.parse = function (parsedCamera) {
  16499. var parsedInputs = parsedCamera.inputsmgr;
  16500. if (parsedInputs) {
  16501. this.clear();
  16502. for (var n in parsedInputs) {
  16503. var construct = BABYLON.CameraInputTypes[n];
  16504. if (construct) {
  16505. var parsedinput = parsedInputs[n];
  16506. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  16507. this.add(input);
  16508. }
  16509. }
  16510. }
  16511. else {
  16512. //2016-03-08 this part is for managing backward compatibility
  16513. for (var n in this.attached) {
  16514. var construct = BABYLON.CameraInputTypes[this.attached[n].getTypeName()];
  16515. if (construct) {
  16516. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  16517. this.remove(this.attached[n]);
  16518. this.add(input);
  16519. }
  16520. }
  16521. }
  16522. };
  16523. return CameraInputsManager;
  16524. }());
  16525. BABYLON.CameraInputsManager = CameraInputsManager;
  16526. })(BABYLON || (BABYLON = {}));
  16527. //# sourceMappingURL=babylon.cameraInputsManager.js.map
  16528. var BABYLON;
  16529. (function (BABYLON) {
  16530. var FreeCameraMouseInput = (function () {
  16531. function FreeCameraMouseInput(touchEnabled) {
  16532. if (touchEnabled === void 0) { touchEnabled = true; }
  16533. this.touchEnabled = touchEnabled;
  16534. this.buttons = [0, 1, 2];
  16535. this.angularSensibility = 2000.0;
  16536. }
  16537. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  16538. var _this = this;
  16539. var engine = this.camera.getEngine();
  16540. if (!this._pointerInput) {
  16541. this._pointerInput = function (p, s) {
  16542. var evt = p.event;
  16543. if (!_this.touchEnabled && evt.pointerType === "touch") {
  16544. return;
  16545. }
  16546. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  16547. return;
  16548. }
  16549. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  16550. try {
  16551. evt.srcElement.setPointerCapture(evt.pointerId);
  16552. }
  16553. catch (e) {
  16554. }
  16555. _this.previousPosition = {
  16556. x: evt.clientX,
  16557. y: evt.clientY
  16558. };
  16559. if (!noPreventDefault) {
  16560. evt.preventDefault();
  16561. element.focus();
  16562. }
  16563. }
  16564. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  16565. try {
  16566. evt.srcElement.releasePointerCapture(evt.pointerId);
  16567. }
  16568. catch (e) {
  16569. }
  16570. _this.previousPosition = null;
  16571. if (!noPreventDefault) {
  16572. evt.preventDefault();
  16573. }
  16574. }
  16575. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  16576. if (!_this.previousPosition || engine.isPointerLock) {
  16577. return;
  16578. }
  16579. var offsetX = evt.clientX - _this.previousPosition.x;
  16580. var offsetY = evt.clientY - _this.previousPosition.y;
  16581. if (_this.camera.getScene().useRightHandedSystem) {
  16582. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  16583. }
  16584. else {
  16585. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  16586. }
  16587. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  16588. _this.previousPosition = {
  16589. x: evt.clientX,
  16590. y: evt.clientY
  16591. };
  16592. if (!noPreventDefault) {
  16593. evt.preventDefault();
  16594. }
  16595. }
  16596. };
  16597. }
  16598. this._onMouseMove = function (evt) {
  16599. if (!engine.isPointerLock) {
  16600. return;
  16601. }
  16602. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  16603. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  16604. if (_this.camera.getScene().useRightHandedSystem) {
  16605. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  16606. }
  16607. else {
  16608. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  16609. }
  16610. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  16611. _this.previousPosition = null;
  16612. if (!noPreventDefault) {
  16613. evt.preventDefault();
  16614. }
  16615. };
  16616. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  16617. element.addEventListener("mousemove", this._onMouseMove, false);
  16618. };
  16619. FreeCameraMouseInput.prototype.detachControl = function (element) {
  16620. if (this._observer && element) {
  16621. this.camera.getScene().onPointerObservable.remove(this._observer);
  16622. element.removeEventListener("mousemove", this._onMouseMove);
  16623. this._observer = null;
  16624. this._onMouseMove = null;
  16625. this.previousPosition = null;
  16626. }
  16627. };
  16628. FreeCameraMouseInput.prototype.getTypeName = function () {
  16629. return "FreeCameraMouseInput";
  16630. };
  16631. FreeCameraMouseInput.prototype.getSimpleName = function () {
  16632. return "mouse";
  16633. };
  16634. return FreeCameraMouseInput;
  16635. }());
  16636. __decorate([
  16637. BABYLON.serialize()
  16638. ], FreeCameraMouseInput.prototype, "buttons", void 0);
  16639. __decorate([
  16640. BABYLON.serialize()
  16641. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  16642. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  16643. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  16644. })(BABYLON || (BABYLON = {}));
  16645. //# sourceMappingURL=babylon.freecamera.input.mouse.js.map
  16646. var BABYLON;
  16647. (function (BABYLON) {
  16648. var FreeCameraKeyboardMoveInput = (function () {
  16649. function FreeCameraKeyboardMoveInput() {
  16650. this._keys = [];
  16651. this.keysUp = [38];
  16652. this.keysDown = [40];
  16653. this.keysLeft = [37];
  16654. this.keysRight = [39];
  16655. }
  16656. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  16657. var _this = this;
  16658. if (!this._onKeyDown) {
  16659. element.tabIndex = 1;
  16660. this._onKeyDown = function (evt) {
  16661. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  16662. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  16663. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  16664. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  16665. var index = _this._keys.indexOf(evt.keyCode);
  16666. if (index === -1) {
  16667. _this._keys.push(evt.keyCode);
  16668. }
  16669. if (!noPreventDefault) {
  16670. evt.preventDefault();
  16671. }
  16672. }
  16673. };
  16674. this._onKeyUp = function (evt) {
  16675. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  16676. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  16677. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  16678. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  16679. var index = _this._keys.indexOf(evt.keyCode);
  16680. if (index >= 0) {
  16681. _this._keys.splice(index, 1);
  16682. }
  16683. if (!noPreventDefault) {
  16684. evt.preventDefault();
  16685. }
  16686. }
  16687. };
  16688. element.addEventListener("keydown", this._onKeyDown, false);
  16689. element.addEventListener("keyup", this._onKeyUp, false);
  16690. BABYLON.Tools.RegisterTopRootEvents([
  16691. { name: "blur", handler: this._onLostFocus }
  16692. ]);
  16693. }
  16694. };
  16695. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  16696. if (this._onKeyDown) {
  16697. element.removeEventListener("keydown", this._onKeyDown);
  16698. element.removeEventListener("keyup", this._onKeyUp);
  16699. BABYLON.Tools.UnregisterTopRootEvents([
  16700. { name: "blur", handler: this._onLostFocus }
  16701. ]);
  16702. this._keys = [];
  16703. this._onKeyDown = null;
  16704. this._onKeyUp = null;
  16705. }
  16706. };
  16707. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  16708. if (this._onKeyDown) {
  16709. var camera = this.camera;
  16710. // Keyboard
  16711. for (var index = 0; index < this._keys.length; index++) {
  16712. var keyCode = this._keys[index];
  16713. var speed = camera._computeLocalCameraSpeed();
  16714. if (this.keysLeft.indexOf(keyCode) !== -1) {
  16715. camera._localDirection.copyFromFloats(-speed, 0, 0);
  16716. }
  16717. else if (this.keysUp.indexOf(keyCode) !== -1) {
  16718. camera._localDirection.copyFromFloats(0, 0, speed);
  16719. }
  16720. else if (this.keysRight.indexOf(keyCode) !== -1) {
  16721. camera._localDirection.copyFromFloats(speed, 0, 0);
  16722. }
  16723. else if (this.keysDown.indexOf(keyCode) !== -1) {
  16724. camera._localDirection.copyFromFloats(0, 0, -speed);
  16725. }
  16726. if (camera.getScene().useRightHandedSystem) {
  16727. camera._localDirection.z *= -1;
  16728. }
  16729. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  16730. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  16731. camera.cameraDirection.addInPlace(camera._transformedDirection);
  16732. }
  16733. }
  16734. };
  16735. FreeCameraKeyboardMoveInput.prototype.getTypeName = function () {
  16736. return "FreeCameraKeyboardMoveInput";
  16737. };
  16738. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  16739. this._keys = [];
  16740. };
  16741. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  16742. return "keyboard";
  16743. };
  16744. return FreeCameraKeyboardMoveInput;
  16745. }());
  16746. __decorate([
  16747. BABYLON.serialize()
  16748. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  16749. __decorate([
  16750. BABYLON.serialize()
  16751. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  16752. __decorate([
  16753. BABYLON.serialize()
  16754. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  16755. __decorate([
  16756. BABYLON.serialize()
  16757. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  16758. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  16759. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  16760. })(BABYLON || (BABYLON = {}));
  16761. //# sourceMappingURL=babylon.freecamera.input.keyboard.js.map
  16762. var BABYLON;
  16763. (function (BABYLON) {
  16764. var FreeCameraTouchInput = (function () {
  16765. function FreeCameraTouchInput() {
  16766. this._offsetX = null;
  16767. this._offsetY = null;
  16768. this._pointerCount = 0;
  16769. this._pointerPressed = [];
  16770. this.touchAngularSensibility = 200000.0;
  16771. this.touchMoveSensibility = 250.0;
  16772. }
  16773. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  16774. var _this = this;
  16775. var previousPosition;
  16776. if (this._pointerInput === undefined) {
  16777. this._onLostFocus = function (evt) {
  16778. _this._offsetX = null;
  16779. _this._offsetY = null;
  16780. };
  16781. this._pointerInput = function (p, s) {
  16782. var evt = p.event;
  16783. if (evt.pointerType === "mouse") {
  16784. return;
  16785. }
  16786. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  16787. if (!noPreventDefault) {
  16788. evt.preventDefault();
  16789. }
  16790. _this._pointerPressed.push(evt.pointerId);
  16791. if (_this._pointerPressed.length !== 1) {
  16792. return;
  16793. }
  16794. previousPosition = {
  16795. x: evt.clientX,
  16796. y: evt.clientY
  16797. };
  16798. }
  16799. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  16800. if (!noPreventDefault) {
  16801. evt.preventDefault();
  16802. }
  16803. var index = _this._pointerPressed.indexOf(evt.pointerId);
  16804. if (index === -1) {
  16805. return;
  16806. }
  16807. _this._pointerPressed.splice(index, 1);
  16808. if (index != 0) {
  16809. return;
  16810. }
  16811. previousPosition = null;
  16812. _this._offsetX = null;
  16813. _this._offsetY = null;
  16814. }
  16815. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  16816. if (!noPreventDefault) {
  16817. evt.preventDefault();
  16818. }
  16819. if (!previousPosition) {
  16820. return;
  16821. }
  16822. var index = _this._pointerPressed.indexOf(evt.pointerId);
  16823. if (index != 0) {
  16824. return;
  16825. }
  16826. _this._offsetX = evt.clientX - previousPosition.x;
  16827. _this._offsetY = -(evt.clientY - previousPosition.y);
  16828. }
  16829. };
  16830. }
  16831. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  16832. element.addEventListener("blur", this._onLostFocus);
  16833. };
  16834. FreeCameraTouchInput.prototype.detachControl = function (element) {
  16835. if (this._pointerInput && element) {
  16836. this.camera.getScene().onPointerObservable.remove(this._observer);
  16837. this._observer = null;
  16838. element.removeEventListener("blur", this._onLostFocus);
  16839. this._onLostFocus = null;
  16840. this._pointerPressed = [];
  16841. this._offsetX = null;
  16842. this._offsetY = null;
  16843. this._pointerCount = 0;
  16844. }
  16845. };
  16846. FreeCameraTouchInput.prototype.checkInputs = function () {
  16847. if (this._offsetX) {
  16848. var camera = this.camera;
  16849. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  16850. if (this._pointerPressed.length > 1) {
  16851. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  16852. }
  16853. else {
  16854. var speed = camera._computeLocalCameraSpeed();
  16855. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  16856. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  16857. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  16858. }
  16859. }
  16860. };
  16861. FreeCameraTouchInput.prototype.getTypeName = function () {
  16862. return "FreeCameraTouchInput";
  16863. };
  16864. FreeCameraTouchInput.prototype.getSimpleName = function () {
  16865. return "touch";
  16866. };
  16867. return FreeCameraTouchInput;
  16868. }());
  16869. __decorate([
  16870. BABYLON.serialize()
  16871. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  16872. __decorate([
  16873. BABYLON.serialize()
  16874. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  16875. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  16876. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  16877. })(BABYLON || (BABYLON = {}));
  16878. //# sourceMappingURL=babylon.freecamera.input.touch.js.map
  16879. var BABYLON;
  16880. (function (BABYLON) {
  16881. var FreeCameraDeviceOrientationInput = (function () {
  16882. function FreeCameraDeviceOrientationInput() {
  16883. var _this = this;
  16884. this._screenOrientationAngle = 0;
  16885. this._screenQuaternion = new BABYLON.Quaternion();
  16886. this._alpha = 0;
  16887. this._beta = 0;
  16888. this._gamma = 0;
  16889. this._orientationChanged = function () {
  16890. _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && window.screen.orientation['angle'] ? window.screen.orientation.angle : 0));
  16891. _this._screenOrientationAngle = -BABYLON.Tools.ToRadians(_this._screenOrientationAngle / 2);
  16892. _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle));
  16893. };
  16894. this._deviceOrientation = function (evt) {
  16895. _this._alpha = evt.alpha;
  16896. _this._beta = evt.beta;
  16897. _this._gamma = evt.gamma;
  16898. };
  16899. this._constantTranform = new BABYLON.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));
  16900. this._orientationChanged();
  16901. }
  16902. Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", {
  16903. get: function () {
  16904. return this._camera;
  16905. },
  16906. set: function (camera) {
  16907. this._camera = camera;
  16908. if (!this._camera.rotationQuaternion)
  16909. this._camera.rotationQuaternion = new BABYLON.Quaternion();
  16910. },
  16911. enumerable: true,
  16912. configurable: true
  16913. });
  16914. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  16915. window.addEventListener("orientationchange", this._orientationChanged);
  16916. window.addEventListener("deviceorientation", this._deviceOrientation);
  16917. //In certain cases, the attach control is called AFTER orientation was changed,
  16918. //So this is needed.
  16919. this._orientationChanged();
  16920. };
  16921. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  16922. window.removeEventListener("orientationchange", this._orientationChanged);
  16923. window.removeEventListener("deviceorientation", this._deviceOrientation);
  16924. };
  16925. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  16926. //if no device orientation provided, don't update the rotation.
  16927. //Only testing against alpha under the assumption thatnorientation will never be so exact when set.
  16928. if (!this._alpha)
  16929. return;
  16930. BABYLON.Quaternion.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(this._alpha), BABYLON.Tools.ToRadians(this._beta), -BABYLON.Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);
  16931. this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);
  16932. this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);
  16933. //Mirror on XY Plane
  16934. this._camera.rotationQuaternion.z *= -1;
  16935. this._camera.rotationQuaternion.w *= -1;
  16936. };
  16937. FreeCameraDeviceOrientationInput.prototype.getTypeName = function () {
  16938. return "FreeCameraDeviceOrientationInput";
  16939. };
  16940. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  16941. return "deviceOrientation";
  16942. };
  16943. return FreeCameraDeviceOrientationInput;
  16944. }());
  16945. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  16946. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  16947. })(BABYLON || (BABYLON = {}));
  16948. //# sourceMappingURL=babylon.freecamera.input.deviceorientation.js.map
  16949. var BABYLON;
  16950. (function (BABYLON) {
  16951. var FreeCameraGamepadInput = (function () {
  16952. function FreeCameraGamepadInput() {
  16953. this.gamepadAngularSensibility = 200;
  16954. this.gamepadMoveSensibility = 40;
  16955. // private members
  16956. this._cameraTransform = BABYLON.Matrix.Identity();
  16957. this._deltaTransform = BABYLON.Vector3.Zero();
  16958. this._vector3 = BABYLON.Vector3.Zero();
  16959. this._vector2 = BABYLON.Vector2.Zero();
  16960. }
  16961. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  16962. var _this = this;
  16963. this._gamepads = new BABYLON.Gamepads(function (gamepad) { _this._onNewGameConnected(gamepad); });
  16964. };
  16965. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  16966. if (this._gamepads) {
  16967. this._gamepads.dispose();
  16968. }
  16969. this.gamepad = null;
  16970. };
  16971. FreeCameraGamepadInput.prototype.checkInputs = function () {
  16972. if (this.gamepad && this.gamepad.leftStick) {
  16973. var camera = this.camera;
  16974. var LSValues = this.gamepad.leftStick;
  16975. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  16976. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  16977. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  16978. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  16979. var RSValues = this.gamepad.rightStick;
  16980. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  16981. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  16982. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  16983. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  16984. if (!camera.rotationQuaternion) {
  16985. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, this._cameraTransform);
  16986. }
  16987. else {
  16988. camera.rotationQuaternion.toRotationMatrix(this._cameraTransform);
  16989. }
  16990. var speed = camera._computeLocalCameraSpeed() * 50.0;
  16991. this._vector3.copyFromFloats(LSValues.x * speed, 0, -LSValues.y * speed);
  16992. BABYLON.Vector3.TransformCoordinatesToRef(this._vector3, this._cameraTransform, this._deltaTransform);
  16993. camera.cameraDirection.addInPlace(this._deltaTransform);
  16994. this._vector2.copyFromFloats(RSValues.y, RSValues.x);
  16995. camera.cameraRotation.addInPlace(this._vector2);
  16996. }
  16997. };
  16998. FreeCameraGamepadInput.prototype._onNewGameConnected = function (gamepad) {
  16999. // Only the first gamepad found can control the camera
  17000. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  17001. // prioritize XBOX gamepads.
  17002. if (!this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  17003. this.gamepad = gamepad;
  17004. }
  17005. }
  17006. };
  17007. FreeCameraGamepadInput.prototype.getTypeName = function () {
  17008. return "FreeCameraGamepadInput";
  17009. };
  17010. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  17011. return "gamepad";
  17012. };
  17013. return FreeCameraGamepadInput;
  17014. }());
  17015. __decorate([
  17016. BABYLON.serialize()
  17017. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  17018. __decorate([
  17019. BABYLON.serialize()
  17020. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  17021. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  17022. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  17023. })(BABYLON || (BABYLON = {}));
  17024. //# sourceMappingURL=babylon.freecamera.input.gamepad.js.map
  17025. var BABYLON;
  17026. (function (BABYLON) {
  17027. var ArcRotateCameraKeyboardMoveInput = (function () {
  17028. function ArcRotateCameraKeyboardMoveInput() {
  17029. this._keys = [];
  17030. this.keysUp = [38];
  17031. this.keysDown = [40];
  17032. this.keysLeft = [37];
  17033. this.keysRight = [39];
  17034. }
  17035. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  17036. var _this = this;
  17037. element.tabIndex = 1;
  17038. this._onKeyDown = function (evt) {
  17039. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  17040. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  17041. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  17042. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  17043. var index = _this._keys.indexOf(evt.keyCode);
  17044. if (index === -1) {
  17045. _this._keys.push(evt.keyCode);
  17046. }
  17047. if (evt.preventDefault) {
  17048. if (!noPreventDefault) {
  17049. evt.preventDefault();
  17050. }
  17051. }
  17052. }
  17053. };
  17054. this._onKeyUp = function (evt) {
  17055. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  17056. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  17057. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  17058. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  17059. var index = _this._keys.indexOf(evt.keyCode);
  17060. if (index >= 0) {
  17061. _this._keys.splice(index, 1);
  17062. }
  17063. if (evt.preventDefault) {
  17064. if (!noPreventDefault) {
  17065. evt.preventDefault();
  17066. }
  17067. }
  17068. }
  17069. };
  17070. this._onLostFocus = function () {
  17071. _this._keys = [];
  17072. };
  17073. element.addEventListener("keydown", this._onKeyDown, false);
  17074. element.addEventListener("keyup", this._onKeyUp, false);
  17075. BABYLON.Tools.RegisterTopRootEvents([
  17076. { name: "blur", handler: this._onLostFocus }
  17077. ]);
  17078. };
  17079. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  17080. if (element) {
  17081. element.removeEventListener("keydown", this._onKeyDown);
  17082. element.removeEventListener("keyup", this._onKeyUp);
  17083. }
  17084. BABYLON.Tools.UnregisterTopRootEvents([
  17085. { name: "blur", handler: this._onLostFocus }
  17086. ]);
  17087. this._keys = [];
  17088. this._onKeyDown = null;
  17089. this._onKeyUp = null;
  17090. this._onLostFocus = null;
  17091. };
  17092. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  17093. if (this._onKeyDown) {
  17094. var camera = this.camera;
  17095. for (var index = 0; index < this._keys.length; index++) {
  17096. var keyCode = this._keys[index];
  17097. if (this.keysLeft.indexOf(keyCode) !== -1) {
  17098. camera.inertialAlphaOffset -= 0.01;
  17099. }
  17100. else if (this.keysUp.indexOf(keyCode) !== -1) {
  17101. camera.inertialBetaOffset -= 0.01;
  17102. }
  17103. else if (this.keysRight.indexOf(keyCode) !== -1) {
  17104. camera.inertialAlphaOffset += 0.01;
  17105. }
  17106. else if (this.keysDown.indexOf(keyCode) !== -1) {
  17107. camera.inertialBetaOffset += 0.01;
  17108. }
  17109. }
  17110. }
  17111. };
  17112. ArcRotateCameraKeyboardMoveInput.prototype.getTypeName = function () {
  17113. return "ArcRotateCameraKeyboardMoveInput";
  17114. };
  17115. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  17116. return "keyboard";
  17117. };
  17118. return ArcRotateCameraKeyboardMoveInput;
  17119. }());
  17120. __decorate([
  17121. BABYLON.serialize()
  17122. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  17123. __decorate([
  17124. BABYLON.serialize()
  17125. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  17126. __decorate([
  17127. BABYLON.serialize()
  17128. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  17129. __decorate([
  17130. BABYLON.serialize()
  17131. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  17132. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  17133. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  17134. })(BABYLON || (BABYLON = {}));
  17135. //# sourceMappingURL=babylon.arcrotatecamera.input.keyboard.js.map
  17136. var BABYLON;
  17137. (function (BABYLON) {
  17138. var ArcRotateCameraMouseWheelInput = (function () {
  17139. function ArcRotateCameraMouseWheelInput() {
  17140. this.wheelPrecision = 3.0;
  17141. }
  17142. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  17143. var _this = this;
  17144. this._wheel = function (p, s) {
  17145. //sanity check - this should be a PointerWheel event.
  17146. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  17147. return;
  17148. var event = p.event;
  17149. var delta = 0;
  17150. if (event.wheelDelta) {
  17151. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  17152. }
  17153. else if (event.detail) {
  17154. delta = -event.detail / _this.wheelPrecision;
  17155. }
  17156. if (delta)
  17157. _this.camera.inertialRadiusOffset += delta;
  17158. if (event.preventDefault) {
  17159. if (!noPreventDefault) {
  17160. event.preventDefault();
  17161. }
  17162. }
  17163. };
  17164. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  17165. };
  17166. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  17167. if (this._observer && element) {
  17168. this.camera.getScene().onPointerObservable.remove(this._observer);
  17169. this._observer = null;
  17170. this._wheel = null;
  17171. }
  17172. };
  17173. ArcRotateCameraMouseWheelInput.prototype.getTypeName = function () {
  17174. return "ArcRotateCameraMouseWheelInput";
  17175. };
  17176. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  17177. return "mousewheel";
  17178. };
  17179. return ArcRotateCameraMouseWheelInput;
  17180. }());
  17181. __decorate([
  17182. BABYLON.serialize()
  17183. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  17184. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  17185. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  17186. })(BABYLON || (BABYLON = {}));
  17187. //# sourceMappingURL=babylon.arcrotatecamera.input.mousewheel.js.map
  17188. var BABYLON;
  17189. (function (BABYLON) {
  17190. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  17191. var ArcRotateCameraPointersInput = (function () {
  17192. function ArcRotateCameraPointersInput() {
  17193. this.buttons = [0, 1, 2];
  17194. this.angularSensibilityX = 1000.0;
  17195. this.angularSensibilityY = 1000.0;
  17196. this.pinchPrecision = 6.0;
  17197. this.panningSensibility = 50.0;
  17198. this._isPanClick = false;
  17199. this.pinchInwards = true;
  17200. }
  17201. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  17202. var _this = this;
  17203. var engine = this.camera.getEngine();
  17204. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  17205. var pointA, pointB;
  17206. var previousPinchDistance = 0;
  17207. this._pointerInput = function (p, s) {
  17208. var evt = p.event;
  17209. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  17210. return;
  17211. }
  17212. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  17213. try {
  17214. evt.srcElement.setPointerCapture(evt.pointerId);
  17215. }
  17216. catch (e) {
  17217. }
  17218. // Manage panning with pan button click
  17219. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  17220. // manage pointers
  17221. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  17222. if (pointA === undefined) {
  17223. pointA = cacheSoloPointer;
  17224. }
  17225. else if (pointB === undefined) {
  17226. pointB = cacheSoloPointer;
  17227. }
  17228. if (!noPreventDefault) {
  17229. evt.preventDefault();
  17230. element.focus();
  17231. }
  17232. }
  17233. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  17234. try {
  17235. evt.srcElement.releasePointerCapture(evt.pointerId);
  17236. }
  17237. catch (e) {
  17238. }
  17239. cacheSoloPointer = null;
  17240. previousPinchDistance = 0;
  17241. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  17242. //but emptying completly pointers collection is required to fix a bug on iPhone :
  17243. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  17244. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  17245. pointA = pointB = undefined;
  17246. if (!noPreventDefault) {
  17247. evt.preventDefault();
  17248. }
  17249. }
  17250. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  17251. if (!noPreventDefault) {
  17252. evt.preventDefault();
  17253. }
  17254. // One button down
  17255. if (pointA && pointB === undefined) {
  17256. if (_this.panningSensibility !== 0 &&
  17257. ((evt.ctrlKey && _this.camera._useCtrlForPanning) ||
  17258. (!_this.camera._useCtrlForPanning && _this._isPanClick))) {
  17259. _this.camera
  17260. .inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  17261. _this.camera
  17262. .inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  17263. }
  17264. else {
  17265. var offsetX = evt.clientX - cacheSoloPointer.x;
  17266. var offsetY = evt.clientY - cacheSoloPointer.y;
  17267. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  17268. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  17269. }
  17270. cacheSoloPointer.x = evt.clientX;
  17271. cacheSoloPointer.y = evt.clientY;
  17272. }
  17273. else if (pointA && pointB) {
  17274. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  17275. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  17276. ed.x = evt.clientX;
  17277. ed.y = evt.clientY;
  17278. var direction = _this.pinchInwards ? 1 : -1;
  17279. var distX = pointA.x - pointB.x;
  17280. var distY = pointA.y - pointB.y;
  17281. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  17282. if (previousPinchDistance === 0) {
  17283. previousPinchDistance = pinchSquaredDistance;
  17284. return;
  17285. }
  17286. if (pinchSquaredDistance !== previousPinchDistance) {
  17287. _this.camera
  17288. .inertialRadiusOffset += (pinchSquaredDistance - previousPinchDistance) /
  17289. (_this.pinchPrecision *
  17290. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  17291. direction);
  17292. previousPinchDistance = pinchSquaredDistance;
  17293. }
  17294. }
  17295. }
  17296. };
  17297. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  17298. this._onContextMenu = function (evt) {
  17299. evt.preventDefault();
  17300. };
  17301. if (!this.camera._useCtrlForPanning) {
  17302. element.addEventListener("contextmenu", this._onContextMenu, false);
  17303. }
  17304. this._onLostFocus = function () {
  17305. //this._keys = [];
  17306. pointA = pointB = undefined;
  17307. previousPinchDistance = 0;
  17308. cacheSoloPointer = null;
  17309. };
  17310. this._onMouseMove = function (evt) {
  17311. if (!engine.isPointerLock) {
  17312. return;
  17313. }
  17314. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  17315. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  17316. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  17317. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  17318. if (!noPreventDefault) {
  17319. evt.preventDefault();
  17320. }
  17321. };
  17322. this._onGestureStart = function (e) {
  17323. if (window.MSGesture === undefined) {
  17324. return;
  17325. }
  17326. if (!_this._MSGestureHandler) {
  17327. _this._MSGestureHandler = new MSGesture();
  17328. _this._MSGestureHandler.target = element;
  17329. }
  17330. _this._MSGestureHandler.addPointer(e.pointerId);
  17331. };
  17332. this._onGesture = function (e) {
  17333. _this.camera.radius *= e.scale;
  17334. if (e.preventDefault) {
  17335. if (!noPreventDefault) {
  17336. e.stopPropagation();
  17337. e.preventDefault();
  17338. }
  17339. }
  17340. };
  17341. element.addEventListener("mousemove", this._onMouseMove, false);
  17342. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  17343. element.addEventListener("MSGestureChange", this._onGesture, false);
  17344. element.addEventListener("keydown", this._onKeyDown, false);
  17345. element.addEventListener("keyup", this._onKeyUp, false);
  17346. BABYLON.Tools.RegisterTopRootEvents([
  17347. { name: "blur", handler: this._onLostFocus }
  17348. ]);
  17349. };
  17350. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  17351. if (element && this._observer) {
  17352. this.camera.getScene().onPointerObservable.remove(this._observer);
  17353. this._observer = null;
  17354. element.removeEventListener("contextmenu", this._onContextMenu);
  17355. element.removeEventListener("mousemove", this._onMouseMove);
  17356. element.removeEventListener("MSPointerDown", this._onGestureStart);
  17357. element.removeEventListener("MSGestureChange", this._onGesture);
  17358. element.removeEventListener("keydown", this._onKeyDown);
  17359. element.removeEventListener("keyup", this._onKeyUp);
  17360. this._isPanClick = false;
  17361. this.pinchInwards = true;
  17362. this._onKeyDown = null;
  17363. this._onKeyUp = null;
  17364. this._onMouseMove = null;
  17365. this._onGestureStart = null;
  17366. this._onGesture = null;
  17367. this._MSGestureHandler = null;
  17368. this._onLostFocus = null;
  17369. this._onContextMenu = null;
  17370. }
  17371. BABYLON.Tools.UnregisterTopRootEvents([
  17372. { name: "blur", handler: this._onLostFocus }
  17373. ]);
  17374. };
  17375. ArcRotateCameraPointersInput.prototype.getTypeName = function () {
  17376. return "ArcRotateCameraPointersInput";
  17377. };
  17378. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  17379. return "pointers";
  17380. };
  17381. return ArcRotateCameraPointersInput;
  17382. }());
  17383. __decorate([
  17384. BABYLON.serialize()
  17385. ], ArcRotateCameraPointersInput.prototype, "buttons", void 0);
  17386. __decorate([
  17387. BABYLON.serialize()
  17388. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  17389. __decorate([
  17390. BABYLON.serialize()
  17391. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  17392. __decorate([
  17393. BABYLON.serialize()
  17394. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  17395. __decorate([
  17396. BABYLON.serialize()
  17397. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  17398. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  17399. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  17400. })(BABYLON || (BABYLON = {}));
  17401. //# sourceMappingURL=babylon.arcrotatecamera.input.pointers.js.map
  17402. var BABYLON;
  17403. (function (BABYLON) {
  17404. var ArcRotateCameraGamepadInput = (function () {
  17405. function ArcRotateCameraGamepadInput() {
  17406. this.gamepadRotationSensibility = 80;
  17407. this.gamepadMoveSensibility = 40;
  17408. }
  17409. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  17410. var _this = this;
  17411. this._gamepads = new BABYLON.Gamepads(function (gamepad) { _this._onNewGameConnected(gamepad); });
  17412. };
  17413. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  17414. if (this._gamepads) {
  17415. this._gamepads.dispose();
  17416. }
  17417. this.gamepad = null;
  17418. };
  17419. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  17420. if (this.gamepad) {
  17421. var camera = this.camera;
  17422. var RSValues = this.gamepad.rightStick;
  17423. if (RSValues.x != 0) {
  17424. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  17425. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  17426. camera.inertialAlphaOffset += normalizedRX;
  17427. }
  17428. }
  17429. if (RSValues.y != 0) {
  17430. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  17431. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  17432. camera.inertialBetaOffset += normalizedRY;
  17433. }
  17434. }
  17435. var LSValues = this.gamepad.leftStick;
  17436. if (LSValues.y != 0) {
  17437. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  17438. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  17439. this.camera.inertialRadiusOffset -= normalizedLY;
  17440. }
  17441. }
  17442. }
  17443. };
  17444. ArcRotateCameraGamepadInput.prototype._onNewGameConnected = function (gamepad) {
  17445. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  17446. // prioritize XBOX gamepads.
  17447. if (!this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  17448. this.gamepad = gamepad;
  17449. }
  17450. }
  17451. };
  17452. ArcRotateCameraGamepadInput.prototype.getTypeName = function () {
  17453. return "ArcRotateCameraGamepadInput";
  17454. };
  17455. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  17456. return "gamepad";
  17457. };
  17458. return ArcRotateCameraGamepadInput;
  17459. }());
  17460. __decorate([
  17461. BABYLON.serialize()
  17462. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  17463. __decorate([
  17464. BABYLON.serialize()
  17465. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  17466. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  17467. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  17468. })(BABYLON || (BABYLON = {}));
  17469. //# sourceMappingURL=babylon.arcrotatecamera.input.gamepad.js.map
  17470. var BABYLON;
  17471. (function (BABYLON) {
  17472. var ArcRotateCameraVRDeviceOrientationInput = (function () {
  17473. function ArcRotateCameraVRDeviceOrientationInput() {
  17474. this.alphaCorrection = 1;
  17475. this.betaCorrection = 1;
  17476. this.gammaCorrection = 1;
  17477. this._alpha = 0;
  17478. this._beta = 0;
  17479. this._gamma = 0;
  17480. this._dirty = false;
  17481. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  17482. }
  17483. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  17484. this.camera.attachControl(element, noPreventDefault);
  17485. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  17486. };
  17487. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  17488. var camera = this.camera;
  17489. this._alpha = +evt.alpha | 0;
  17490. this._beta = +evt.beta | 0;
  17491. this._gamma = +evt.gamma | 0;
  17492. this._dirty = true;
  17493. };
  17494. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  17495. if (this._dirty) {
  17496. this._dirty = false;
  17497. if (this._gamma < 0) {
  17498. this._gamma = 180 + this._gamma;
  17499. }
  17500. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  17501. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  17502. }
  17503. };
  17504. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  17505. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  17506. };
  17507. ArcRotateCameraVRDeviceOrientationInput.prototype.getTypeName = function () {
  17508. return "ArcRotateCameraVRDeviceOrientationInput";
  17509. };
  17510. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  17511. return "VRDeviceOrientation";
  17512. };
  17513. return ArcRotateCameraVRDeviceOrientationInput;
  17514. }());
  17515. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  17516. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  17517. })(BABYLON || (BABYLON = {}));
  17518. //# sourceMappingURL=babylon.arcrotatecamera.input.vrdeviceorientation.js.map
  17519. /// <reference path="babylon.camera.ts" />
  17520. var BABYLON;
  17521. (function (BABYLON) {
  17522. var TargetCamera = (function (_super) {
  17523. __extends(TargetCamera, _super);
  17524. function TargetCamera(name, position, scene) {
  17525. var _this = _super.call(this, name, position, scene) || this;
  17526. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  17527. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  17528. _this.rotation = new BABYLON.Vector3(0, 0, 0);
  17529. _this.speed = 2.0;
  17530. _this.noRotationConstraint = false;
  17531. _this.lockedTarget = null;
  17532. _this._currentTarget = BABYLON.Vector3.Zero();
  17533. _this._viewMatrix = BABYLON.Matrix.Zero();
  17534. _this._camMatrix = BABYLON.Matrix.Zero();
  17535. _this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  17536. _this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  17537. _this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  17538. _this._defaultUpVector = new BABYLON.Vector3(0, 1, 0);
  17539. _this._transformedReferencePoint = BABYLON.Vector3.Zero();
  17540. _this._lookAtTemp = BABYLON.Matrix.Zero();
  17541. _this._tempMatrix = BABYLON.Matrix.Zero();
  17542. return _this;
  17543. }
  17544. TargetCamera.prototype.getFrontPosition = function (distance) {
  17545. var direction = this.getTarget().subtract(this.position);
  17546. direction.normalize();
  17547. direction.scaleInPlace(distance);
  17548. return this.globalPosition.add(direction);
  17549. };
  17550. TargetCamera.prototype._getLockedTargetPosition = function () {
  17551. if (!this.lockedTarget) {
  17552. return null;
  17553. }
  17554. if (this.lockedTarget.absolutePosition) {
  17555. this.lockedTarget.computeWorldMatrix();
  17556. }
  17557. return this.lockedTarget.absolutePosition || this.lockedTarget;
  17558. };
  17559. // Cache
  17560. TargetCamera.prototype._initCache = function () {
  17561. _super.prototype._initCache.call(this);
  17562. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  17563. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  17564. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  17565. };
  17566. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  17567. if (!ignoreParentClass) {
  17568. _super.prototype._updateCache.call(this);
  17569. }
  17570. var lockedTargetPosition = this._getLockedTargetPosition();
  17571. if (!lockedTargetPosition) {
  17572. this._cache.lockedTarget = null;
  17573. }
  17574. else {
  17575. if (!this._cache.lockedTarget) {
  17576. this._cache.lockedTarget = lockedTargetPosition.clone();
  17577. }
  17578. else {
  17579. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  17580. }
  17581. }
  17582. this._cache.rotation.copyFrom(this.rotation);
  17583. if (this.rotationQuaternion)
  17584. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  17585. };
  17586. // Synchronized
  17587. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  17588. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  17589. return false;
  17590. }
  17591. var lockedTargetPosition = this._getLockedTargetPosition();
  17592. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  17593. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  17594. };
  17595. // Methods
  17596. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  17597. var engine = this.getEngine();
  17598. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  17599. };
  17600. // Target
  17601. TargetCamera.prototype.setTarget = function (target) {
  17602. this.upVector.normalize();
  17603. BABYLON.Matrix.LookAtLHToRef(this.position, target, this._defaultUpVector, this._camMatrix);
  17604. this._camMatrix.invert();
  17605. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  17606. var vDir = target.subtract(this.position);
  17607. if (vDir.x >= 0.0) {
  17608. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  17609. }
  17610. else {
  17611. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  17612. }
  17613. this.rotation.z = 0;
  17614. if (isNaN(this.rotation.x)) {
  17615. this.rotation.x = 0;
  17616. }
  17617. if (isNaN(this.rotation.y)) {
  17618. this.rotation.y = 0;
  17619. }
  17620. if (isNaN(this.rotation.z)) {
  17621. this.rotation.z = 0;
  17622. }
  17623. if (this.rotationQuaternion) {
  17624. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  17625. }
  17626. };
  17627. /**
  17628. * Return the current target position of the camera. This value is expressed in local space.
  17629. */
  17630. TargetCamera.prototype.getTarget = function () {
  17631. return this._currentTarget;
  17632. };
  17633. TargetCamera.prototype._decideIfNeedsToMove = function () {
  17634. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  17635. };
  17636. TargetCamera.prototype._updatePosition = function () {
  17637. if (this.parent) {
  17638. this.parent.getWorldMatrix().invertToRef(BABYLON.Tmp.Matrix[0]);
  17639. BABYLON.Vector3.TransformNormalToRef(this.cameraDirection, BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Vector3[0]);
  17640. this.position.addInPlace(BABYLON.Tmp.Vector3[0]);
  17641. return;
  17642. }
  17643. this.position.addInPlace(this.cameraDirection);
  17644. };
  17645. TargetCamera.prototype._checkInputs = function () {
  17646. var needToMove = this._decideIfNeedsToMove();
  17647. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  17648. // Move
  17649. if (needToMove) {
  17650. this._updatePosition();
  17651. }
  17652. // Rotate
  17653. if (needToRotate) {
  17654. this.rotation.x += this.cameraRotation.x;
  17655. this.rotation.y += this.cameraRotation.y;
  17656. //rotate, if quaternion is set and rotation was used
  17657. if (this.rotationQuaternion) {
  17658. var len = this.rotation.lengthSquared();
  17659. if (len) {
  17660. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  17661. }
  17662. }
  17663. if (!this.noRotationConstraint) {
  17664. var limit = (Math.PI / 2) * 0.95;
  17665. if (this.rotation.x > limit)
  17666. this.rotation.x = limit;
  17667. if (this.rotation.x < -limit)
  17668. this.rotation.x = -limit;
  17669. }
  17670. }
  17671. // Inertia
  17672. if (needToMove) {
  17673. if (Math.abs(this.cameraDirection.x) < BABYLON.Epsilon) {
  17674. this.cameraDirection.x = 0;
  17675. }
  17676. if (Math.abs(this.cameraDirection.y) < BABYLON.Epsilon) {
  17677. this.cameraDirection.y = 0;
  17678. }
  17679. if (Math.abs(this.cameraDirection.z) < BABYLON.Epsilon) {
  17680. this.cameraDirection.z = 0;
  17681. }
  17682. this.cameraDirection.scaleInPlace(this.inertia);
  17683. }
  17684. if (needToRotate) {
  17685. if (Math.abs(this.cameraRotation.x) < BABYLON.Epsilon) {
  17686. this.cameraRotation.x = 0;
  17687. }
  17688. if (Math.abs(this.cameraRotation.y) < BABYLON.Epsilon) {
  17689. this.cameraRotation.y = 0;
  17690. }
  17691. this.cameraRotation.scaleInPlace(this.inertia);
  17692. }
  17693. _super.prototype._checkInputs.call(this);
  17694. };
  17695. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  17696. if (this.rotationQuaternion) {
  17697. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  17698. //update the up vector!
  17699. BABYLON.Vector3.TransformNormalToRef(this._defaultUpVector, this._cameraRotationMatrix, this.upVector);
  17700. }
  17701. else {
  17702. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  17703. }
  17704. };
  17705. TargetCamera.prototype._getViewMatrix = function () {
  17706. if (!this.lockedTarget) {
  17707. // Compute
  17708. this._updateCameraRotationMatrix();
  17709. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  17710. // Computing target and final matrix
  17711. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  17712. }
  17713. else {
  17714. this._currentTarget.copyFrom(this._getLockedTargetPosition());
  17715. }
  17716. if (this.getScene().useRightHandedSystem) {
  17717. BABYLON.Matrix.LookAtRHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  17718. }
  17719. else {
  17720. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  17721. }
  17722. return this._viewMatrix;
  17723. };
  17724. /**
  17725. * @override
  17726. * Override Camera.createRigCamera
  17727. */
  17728. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  17729. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  17730. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  17731. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
  17732. if (!this.rotationQuaternion) {
  17733. this.rotationQuaternion = new BABYLON.Quaternion();
  17734. }
  17735. rigCamera._cameraRigParams = {};
  17736. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  17737. }
  17738. return rigCamera;
  17739. }
  17740. return null;
  17741. };
  17742. /**
  17743. * @override
  17744. * Override Camera._updateRigCameras
  17745. */
  17746. TargetCamera.prototype._updateRigCameras = function () {
  17747. var camLeft = this._rigCameras[0];
  17748. var camRight = this._rigCameras[1];
  17749. switch (this.cameraRigMode) {
  17750. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  17751. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  17752. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  17753. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  17754. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  17755. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  17756. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  17757. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  17758. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  17759. camLeft.setTarget(this.getTarget());
  17760. camRight.setTarget(this.getTarget());
  17761. break;
  17762. case BABYLON.Camera.RIG_MODE_VR:
  17763. if (camLeft.rotationQuaternion) {
  17764. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  17765. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  17766. }
  17767. else {
  17768. camLeft.rotation.copyFrom(this.rotation);
  17769. camRight.rotation.copyFrom(this.rotation);
  17770. }
  17771. camLeft.position.copyFrom(this.position);
  17772. camRight.position.copyFrom(this.position);
  17773. break;
  17774. }
  17775. _super.prototype._updateRigCameras.call(this);
  17776. };
  17777. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  17778. if (!this._rigCamTransformMatrix) {
  17779. this._rigCamTransformMatrix = new BABYLON.Matrix();
  17780. }
  17781. var target = this.getTarget();
  17782. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  17783. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  17784. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  17785. };
  17786. TargetCamera.prototype.getClassName = function () {
  17787. return "TargetCamera";
  17788. };
  17789. return TargetCamera;
  17790. }(BABYLON.Camera));
  17791. __decorate([
  17792. BABYLON.serializeAsVector3()
  17793. ], TargetCamera.prototype, "rotation", void 0);
  17794. __decorate([
  17795. BABYLON.serialize()
  17796. ], TargetCamera.prototype, "speed", void 0);
  17797. __decorate([
  17798. BABYLON.serializeAsMeshReference("lockedTargetId")
  17799. ], TargetCamera.prototype, "lockedTarget", void 0);
  17800. BABYLON.TargetCamera = TargetCamera;
  17801. })(BABYLON || (BABYLON = {}));
  17802. //# sourceMappingURL=babylon.targetCamera.js.map
  17803. var BABYLON;
  17804. (function (BABYLON) {
  17805. var FreeCamera = (function (_super) {
  17806. __extends(FreeCamera, _super);
  17807. function FreeCamera(name, position, scene) {
  17808. var _this = _super.call(this, name, position, scene) || this;
  17809. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  17810. _this.checkCollisions = false;
  17811. _this.applyGravity = false;
  17812. _this._collider = new BABYLON.Collider();
  17813. _this._needMoveForGravity = false;
  17814. _this._oldPosition = BABYLON.Vector3.Zero();
  17815. _this._diffPosition = BABYLON.Vector3.Zero();
  17816. _this._newPosition = BABYLON.Vector3.Zero();
  17817. // Collisions
  17818. _this._collisionMask = -1;
  17819. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  17820. if (collidedMesh === void 0) { collidedMesh = null; }
  17821. //TODO move this to the collision coordinator!
  17822. if (_this.getScene().workerCollisions)
  17823. newPosition.multiplyInPlace(_this._collider.radius);
  17824. var updatePosition = function (newPos) {
  17825. _this._newPosition.copyFrom(newPos);
  17826. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  17827. var oldPosition = _this.position.clone();
  17828. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  17829. _this.position.addInPlace(_this._diffPosition);
  17830. if (_this.onCollide && collidedMesh) {
  17831. _this.onCollide(collidedMesh);
  17832. }
  17833. }
  17834. };
  17835. updatePosition(newPosition);
  17836. };
  17837. _this.inputs = new BABYLON.FreeCameraInputsManager(_this);
  17838. _this.inputs.addKeyboard().addMouse();
  17839. return _this;
  17840. }
  17841. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  17842. //-- begin properties for backward compatibility for inputs
  17843. get: function () {
  17844. var mouse = this.inputs.attached["mouse"];
  17845. if (mouse)
  17846. return mouse.angularSensibility;
  17847. },
  17848. set: function (value) {
  17849. var mouse = this.inputs.attached["mouse"];
  17850. if (mouse)
  17851. mouse.angularSensibility = value;
  17852. },
  17853. enumerable: true,
  17854. configurable: true
  17855. });
  17856. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  17857. get: function () {
  17858. var keyboard = this.inputs.attached["keyboard"];
  17859. if (keyboard)
  17860. return keyboard.keysUp;
  17861. },
  17862. set: function (value) {
  17863. var keyboard = this.inputs.attached["keyboard"];
  17864. if (keyboard)
  17865. keyboard.keysUp = value;
  17866. },
  17867. enumerable: true,
  17868. configurable: true
  17869. });
  17870. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  17871. get: function () {
  17872. var keyboard = this.inputs.attached["keyboard"];
  17873. if (keyboard)
  17874. return keyboard.keysDown;
  17875. },
  17876. set: function (value) {
  17877. var keyboard = this.inputs.attached["keyboard"];
  17878. if (keyboard)
  17879. keyboard.keysDown = value;
  17880. },
  17881. enumerable: true,
  17882. configurable: true
  17883. });
  17884. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  17885. get: function () {
  17886. var keyboard = this.inputs.attached["keyboard"];
  17887. if (keyboard)
  17888. return keyboard.keysLeft;
  17889. },
  17890. set: function (value) {
  17891. var keyboard = this.inputs.attached["keyboard"];
  17892. if (keyboard)
  17893. keyboard.keysLeft = value;
  17894. },
  17895. enumerable: true,
  17896. configurable: true
  17897. });
  17898. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  17899. get: function () {
  17900. var keyboard = this.inputs.attached["keyboard"];
  17901. if (keyboard)
  17902. return keyboard.keysRight;
  17903. },
  17904. set: function (value) {
  17905. var keyboard = this.inputs.attached["keyboard"];
  17906. if (keyboard)
  17907. keyboard.keysRight = value;
  17908. },
  17909. enumerable: true,
  17910. configurable: true
  17911. });
  17912. // Controls
  17913. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  17914. this.inputs.attachElement(element, noPreventDefault);
  17915. };
  17916. FreeCamera.prototype.detachControl = function (element) {
  17917. this.inputs.detachElement(element);
  17918. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  17919. this.cameraRotation = new BABYLON.Vector2(0, 0);
  17920. };
  17921. Object.defineProperty(FreeCamera.prototype, "collisionMask", {
  17922. get: function () {
  17923. return this._collisionMask;
  17924. },
  17925. set: function (mask) {
  17926. this._collisionMask = !isNaN(mask) ? mask : -1;
  17927. },
  17928. enumerable: true,
  17929. configurable: true
  17930. });
  17931. FreeCamera.prototype._collideWithWorld = function (velocity) {
  17932. var globalPosition;
  17933. if (this.parent) {
  17934. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  17935. }
  17936. else {
  17937. globalPosition = this.position;
  17938. }
  17939. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  17940. this._collider.radius = this.ellipsoid;
  17941. this._collider.collisionMask = this._collisionMask;
  17942. //no need for clone, as long as gravity is not on.
  17943. var actualVelocity = velocity;
  17944. //add gravity to the velocity to prevent the dual-collision checking
  17945. if (this.applyGravity) {
  17946. //this prevents mending with cameraDirection, a global variable of the free camera class.
  17947. actualVelocity = velocity.add(this.getScene().gravity);
  17948. }
  17949. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  17950. };
  17951. FreeCamera.prototype._checkInputs = function () {
  17952. if (!this._localDirection) {
  17953. this._localDirection = BABYLON.Vector3.Zero();
  17954. this._transformedDirection = BABYLON.Vector3.Zero();
  17955. }
  17956. this.inputs.checkInputs();
  17957. _super.prototype._checkInputs.call(this);
  17958. };
  17959. FreeCamera.prototype._decideIfNeedsToMove = function () {
  17960. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  17961. };
  17962. FreeCamera.prototype._updatePosition = function () {
  17963. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  17964. this._collideWithWorld(this.cameraDirection);
  17965. }
  17966. else {
  17967. _super.prototype._updatePosition.call(this);
  17968. }
  17969. };
  17970. FreeCamera.prototype.dispose = function () {
  17971. this.inputs.clear();
  17972. _super.prototype.dispose.call(this);
  17973. };
  17974. FreeCamera.prototype.getClassName = function () {
  17975. return "FreeCamera";
  17976. };
  17977. return FreeCamera;
  17978. }(BABYLON.TargetCamera));
  17979. __decorate([
  17980. BABYLON.serializeAsVector3()
  17981. ], FreeCamera.prototype, "ellipsoid", void 0);
  17982. __decorate([
  17983. BABYLON.serialize()
  17984. ], FreeCamera.prototype, "checkCollisions", void 0);
  17985. __decorate([
  17986. BABYLON.serialize()
  17987. ], FreeCamera.prototype, "applyGravity", void 0);
  17988. BABYLON.FreeCamera = FreeCamera;
  17989. })(BABYLON || (BABYLON = {}));
  17990. //# sourceMappingURL=babylon.freeCamera.js.map
  17991. var BABYLON;
  17992. (function (BABYLON) {
  17993. var FreeCameraInputsManager = (function (_super) {
  17994. __extends(FreeCameraInputsManager, _super);
  17995. function FreeCameraInputsManager(camera) {
  17996. return _super.call(this, camera) || this;
  17997. }
  17998. FreeCameraInputsManager.prototype.addKeyboard = function () {
  17999. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  18000. return this;
  18001. };
  18002. FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  18003. if (touchEnabled === void 0) { touchEnabled = true; }
  18004. this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
  18005. return this;
  18006. };
  18007. FreeCameraInputsManager.prototype.addGamepad = function () {
  18008. this.add(new BABYLON.FreeCameraGamepadInput());
  18009. return this;
  18010. };
  18011. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  18012. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  18013. return this;
  18014. };
  18015. FreeCameraInputsManager.prototype.addTouch = function () {
  18016. this.add(new BABYLON.FreeCameraTouchInput());
  18017. return this;
  18018. };
  18019. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  18020. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  18021. return this;
  18022. };
  18023. return FreeCameraInputsManager;
  18024. }(BABYLON.CameraInputsManager));
  18025. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  18026. })(BABYLON || (BABYLON = {}));
  18027. //# sourceMappingURL=babylon.freeCameraInputsManager.js.map
  18028. /// <reference path="babylon.targetCamera.ts" />
  18029. var BABYLON;
  18030. (function (BABYLON) {
  18031. var FollowCamera = (function (_super) {
  18032. __extends(FollowCamera, _super);
  18033. function FollowCamera(name, position, scene, lockedTarget) {
  18034. var _this = _super.call(this, name, position, scene) || this;
  18035. _this.radius = 12;
  18036. _this.rotationOffset = 0;
  18037. _this.heightOffset = 4;
  18038. _this.cameraAcceleration = 0.05;
  18039. _this.maxCameraSpeed = 20;
  18040. _this.lockedTarget = lockedTarget;
  18041. return _this;
  18042. }
  18043. FollowCamera.prototype.getRadians = function (degrees) {
  18044. return degrees * Math.PI / 180;
  18045. };
  18046. FollowCamera.prototype.follow = function (cameraTarget) {
  18047. if (!cameraTarget)
  18048. return;
  18049. var yRotation;
  18050. if (cameraTarget.rotationQuaternion) {
  18051. var rotMatrix = new BABYLON.Matrix();
  18052. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  18053. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  18054. }
  18055. else {
  18056. yRotation = cameraTarget.rotation.y;
  18057. }
  18058. var radians = this.getRadians(this.rotationOffset) + yRotation;
  18059. var targetPosition = cameraTarget.getAbsolutePosition();
  18060. var targetX = targetPosition.x + Math.sin(radians) * this.radius;
  18061. var targetZ = targetPosition.z + Math.cos(radians) * this.radius;
  18062. var dx = targetX - this.position.x;
  18063. var dy = (targetPosition.y + this.heightOffset) - this.position.y;
  18064. var dz = (targetZ) - this.position.z;
  18065. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  18066. var vy = dy * this.cameraAcceleration;
  18067. var vz = dz * this.cameraAcceleration * 2;
  18068. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  18069. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  18070. }
  18071. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  18072. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  18073. }
  18074. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  18075. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  18076. }
  18077. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  18078. this.setTarget(targetPosition);
  18079. };
  18080. FollowCamera.prototype._checkInputs = function () {
  18081. _super.prototype._checkInputs.call(this);
  18082. this.follow(this.lockedTarget);
  18083. };
  18084. FollowCamera.prototype.getClassName = function () {
  18085. return "FollowCamera";
  18086. };
  18087. return FollowCamera;
  18088. }(BABYLON.TargetCamera));
  18089. __decorate([
  18090. BABYLON.serialize()
  18091. ], FollowCamera.prototype, "radius", void 0);
  18092. __decorate([
  18093. BABYLON.serialize()
  18094. ], FollowCamera.prototype, "rotationOffset", void 0);
  18095. __decorate([
  18096. BABYLON.serialize()
  18097. ], FollowCamera.prototype, "heightOffset", void 0);
  18098. __decorate([
  18099. BABYLON.serialize()
  18100. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  18101. __decorate([
  18102. BABYLON.serialize()
  18103. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  18104. __decorate([
  18105. BABYLON.serializeAsMeshReference("lockedTargetId")
  18106. ], FollowCamera.prototype, "lockedTarget", void 0);
  18107. BABYLON.FollowCamera = FollowCamera;
  18108. var ArcFollowCamera = (function (_super) {
  18109. __extends(ArcFollowCamera, _super);
  18110. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  18111. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  18112. _this.alpha = alpha;
  18113. _this.beta = beta;
  18114. _this.radius = radius;
  18115. _this.target = target;
  18116. _this._cartesianCoordinates = BABYLON.Vector3.Zero();
  18117. _this.follow();
  18118. return _this;
  18119. }
  18120. ArcFollowCamera.prototype.follow = function () {
  18121. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  18122. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  18123. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  18124. var targetPosition = this.target.getAbsolutePosition();
  18125. this.position = targetPosition.add(this._cartesianCoordinates);
  18126. this.setTarget(targetPosition);
  18127. };
  18128. ArcFollowCamera.prototype._checkInputs = function () {
  18129. _super.prototype._checkInputs.call(this);
  18130. this.follow();
  18131. };
  18132. ArcFollowCamera.prototype.getClassName = function () {
  18133. return "ArcFollowCamera";
  18134. };
  18135. return ArcFollowCamera;
  18136. }(BABYLON.TargetCamera));
  18137. BABYLON.ArcFollowCamera = ArcFollowCamera;
  18138. })(BABYLON || (BABYLON = {}));
  18139. //# sourceMappingURL=babylon.followCamera.js.map
  18140. /// <reference path="babylon.freeCamera.ts" />
  18141. var BABYLON;
  18142. (function (BABYLON) {
  18143. // We're mainly based on the logic defined into the FreeCamera code
  18144. var TouchCamera = (function (_super) {
  18145. __extends(TouchCamera, _super);
  18146. //-- end properties for backward compatibility for inputs
  18147. function TouchCamera(name, position, scene) {
  18148. var _this = _super.call(this, name, position, scene) || this;
  18149. _this.inputs.addTouch();
  18150. _this._setupInputs();
  18151. return _this;
  18152. }
  18153. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  18154. //-- Begin properties for backward compatibility for inputs
  18155. get: function () {
  18156. var touch = this.inputs.attached["touch"];
  18157. if (touch)
  18158. return touch.touchAngularSensibility;
  18159. },
  18160. set: function (value) {
  18161. var touch = this.inputs.attached["touch"];
  18162. if (touch)
  18163. touch.touchAngularSensibility = value;
  18164. },
  18165. enumerable: true,
  18166. configurable: true
  18167. });
  18168. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  18169. get: function () {
  18170. var touch = this.inputs.attached["touch"];
  18171. if (touch)
  18172. return touch.touchMoveSensibility;
  18173. },
  18174. set: function (value) {
  18175. var touch = this.inputs.attached["touch"];
  18176. if (touch)
  18177. touch.touchMoveSensibility = value;
  18178. },
  18179. enumerable: true,
  18180. configurable: true
  18181. });
  18182. TouchCamera.prototype.getClassName = function () {
  18183. return "TouchCamera";
  18184. };
  18185. TouchCamera.prototype._setupInputs = function () {
  18186. var mouse = this.inputs.attached["mouse"];
  18187. if (mouse) {
  18188. mouse.touchEnabled = false;
  18189. }
  18190. };
  18191. return TouchCamera;
  18192. }(BABYLON.FreeCamera));
  18193. BABYLON.TouchCamera = TouchCamera;
  18194. })(BABYLON || (BABYLON = {}));
  18195. //# sourceMappingURL=babylon.touchCamera.js.map
  18196. /// <reference path="babylon.targetCamera.ts" />
  18197. /// <reference path="..\Tools\babylon.tools.ts" />
  18198. var BABYLON;
  18199. (function (BABYLON) {
  18200. var ArcRotateCamera = (function (_super) {
  18201. __extends(ArcRotateCamera, _super);
  18202. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  18203. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  18204. _this.inertialAlphaOffset = 0;
  18205. _this.inertialBetaOffset = 0;
  18206. _this.inertialRadiusOffset = 0;
  18207. _this.lowerAlphaLimit = null;
  18208. _this.upperAlphaLimit = null;
  18209. _this.lowerBetaLimit = 0.01;
  18210. _this.upperBetaLimit = Math.PI;
  18211. _this.lowerRadiusLimit = null;
  18212. _this.upperRadiusLimit = null;
  18213. _this.inertialPanningX = 0;
  18214. _this.inertialPanningY = 0;
  18215. //-- end properties for backward compatibility for inputs
  18216. _this.zoomOnFactor = 1;
  18217. _this.targetScreenOffset = BABYLON.Vector2.Zero();
  18218. _this.allowUpsideDown = true;
  18219. _this._viewMatrix = new BABYLON.Matrix();
  18220. // Panning
  18221. _this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  18222. _this.checkCollisions = false;
  18223. _this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  18224. _this._collider = new BABYLON.Collider();
  18225. _this._previousPosition = BABYLON.Vector3.Zero();
  18226. _this._collisionVelocity = BABYLON.Vector3.Zero();
  18227. _this._newPosition = BABYLON.Vector3.Zero();
  18228. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  18229. if (collidedMesh === void 0) { collidedMesh = null; }
  18230. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  18231. newPosition.multiplyInPlace(_this._collider.radius);
  18232. }
  18233. if (!collidedMesh) {
  18234. _this._previousPosition.copyFrom(_this.position);
  18235. }
  18236. else {
  18237. _this.setPosition(newPosition);
  18238. if (_this.onCollide) {
  18239. _this.onCollide(collidedMesh);
  18240. }
  18241. }
  18242. // Recompute because of constraints
  18243. var cosa = Math.cos(_this.alpha);
  18244. var sina = Math.sin(_this.alpha);
  18245. var cosb = Math.cos(_this.beta);
  18246. var sinb = Math.sin(_this.beta);
  18247. if (sinb === 0) {
  18248. sinb = 0.0001;
  18249. }
  18250. var target = _this._getTargetPosition();
  18251. target.addToRef(new BABYLON.Vector3(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb), _this._newPosition);
  18252. _this.position.copyFrom(_this._newPosition);
  18253. var up = _this.upVector;
  18254. if (_this.allowUpsideDown && _this.beta < 0) {
  18255. up = up.clone();
  18256. up = up.negate();
  18257. }
  18258. BABYLON.Matrix.LookAtLHToRef(_this.position, target, up, _this._viewMatrix);
  18259. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  18260. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  18261. _this._collisionTriggered = false;
  18262. };
  18263. if (!target) {
  18264. _this.target = BABYLON.Vector3.Zero();
  18265. }
  18266. else {
  18267. _this.target = target;
  18268. }
  18269. _this.alpha = alpha;
  18270. _this.beta = beta;
  18271. _this.radius = radius;
  18272. _this.getViewMatrix();
  18273. _this.inputs = new BABYLON.ArcRotateCameraInputsManager(_this);
  18274. _this.inputs.addKeyboard().addMouseWheel().addPointers().addGamepad();
  18275. return _this;
  18276. }
  18277. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  18278. //-- begin properties for backward compatibility for inputs
  18279. get: function () {
  18280. var pointers = this.inputs.attached["pointers"];
  18281. if (pointers)
  18282. return pointers.angularSensibilityX;
  18283. },
  18284. set: function (value) {
  18285. var pointers = this.inputs.attached["pointers"];
  18286. if (pointers) {
  18287. pointers.angularSensibilityX = value;
  18288. }
  18289. },
  18290. enumerable: true,
  18291. configurable: true
  18292. });
  18293. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  18294. get: function () {
  18295. var pointers = this.inputs.attached["pointers"];
  18296. if (pointers)
  18297. return pointers.angularSensibilityY;
  18298. },
  18299. set: function (value) {
  18300. var pointers = this.inputs.attached["pointers"];
  18301. if (pointers) {
  18302. pointers.angularSensibilityY = value;
  18303. }
  18304. },
  18305. enumerable: true,
  18306. configurable: true
  18307. });
  18308. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  18309. get: function () {
  18310. var pointers = this.inputs.attached["pointers"];
  18311. if (pointers)
  18312. return pointers.pinchPrecision;
  18313. },
  18314. set: function (value) {
  18315. var pointers = this.inputs.attached["pointers"];
  18316. if (pointers) {
  18317. pointers.pinchPrecision = value;
  18318. }
  18319. },
  18320. enumerable: true,
  18321. configurable: true
  18322. });
  18323. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  18324. get: function () {
  18325. var pointers = this.inputs.attached["pointers"];
  18326. if (pointers)
  18327. return pointers.panningSensibility;
  18328. },
  18329. set: function (value) {
  18330. var pointers = this.inputs.attached["pointers"];
  18331. if (pointers) {
  18332. pointers.panningSensibility = value;
  18333. }
  18334. },
  18335. enumerable: true,
  18336. configurable: true
  18337. });
  18338. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  18339. get: function () {
  18340. var keyboard = this.inputs.attached["keyboard"];
  18341. if (keyboard)
  18342. return keyboard.keysUp;
  18343. },
  18344. set: function (value) {
  18345. var keyboard = this.inputs.attached["keyboard"];
  18346. if (keyboard)
  18347. keyboard.keysUp = value;
  18348. },
  18349. enumerable: true,
  18350. configurable: true
  18351. });
  18352. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  18353. get: function () {
  18354. var keyboard = this.inputs.attached["keyboard"];
  18355. if (keyboard)
  18356. return keyboard.keysDown;
  18357. },
  18358. set: function (value) {
  18359. var keyboard = this.inputs.attached["keyboard"];
  18360. if (keyboard)
  18361. keyboard.keysDown = value;
  18362. },
  18363. enumerable: true,
  18364. configurable: true
  18365. });
  18366. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  18367. get: function () {
  18368. var keyboard = this.inputs.attached["keyboard"];
  18369. if (keyboard)
  18370. return keyboard.keysLeft;
  18371. },
  18372. set: function (value) {
  18373. var keyboard = this.inputs.attached["keyboard"];
  18374. if (keyboard)
  18375. keyboard.keysLeft = value;
  18376. },
  18377. enumerable: true,
  18378. configurable: true
  18379. });
  18380. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  18381. get: function () {
  18382. var keyboard = this.inputs.attached["keyboard"];
  18383. if (keyboard)
  18384. return keyboard.keysRight;
  18385. },
  18386. set: function (value) {
  18387. var keyboard = this.inputs.attached["keyboard"];
  18388. if (keyboard)
  18389. keyboard.keysRight = value;
  18390. },
  18391. enumerable: true,
  18392. configurable: true
  18393. });
  18394. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  18395. get: function () {
  18396. var mousewheel = this.inputs.attached["mousewheel"];
  18397. if (mousewheel)
  18398. return mousewheel.wheelPrecision;
  18399. },
  18400. set: function (value) {
  18401. var mousewheel = this.inputs.attached["mousewheel"];
  18402. if (mousewheel)
  18403. mousewheel.wheelPrecision = value;
  18404. },
  18405. enumerable: true,
  18406. configurable: true
  18407. });
  18408. // Cache
  18409. ArcRotateCamera.prototype._initCache = function () {
  18410. _super.prototype._initCache.call(this);
  18411. this._cache.target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  18412. this._cache.alpha = undefined;
  18413. this._cache.beta = undefined;
  18414. this._cache.radius = undefined;
  18415. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  18416. };
  18417. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  18418. if (!ignoreParentClass) {
  18419. _super.prototype._updateCache.call(this);
  18420. }
  18421. this._cache.target.copyFrom(this._getTargetPosition());
  18422. this._cache.alpha = this.alpha;
  18423. this._cache.beta = this.beta;
  18424. this._cache.radius = this.radius;
  18425. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  18426. };
  18427. ArcRotateCamera.prototype._getTargetPosition = function () {
  18428. if (this.target.getAbsolutePosition) {
  18429. var pos = this.target.getAbsolutePosition();
  18430. return this._targetBoundingCenter ? pos.add(this._targetBoundingCenter) : pos;
  18431. }
  18432. return this.target;
  18433. };
  18434. // Synchronized
  18435. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  18436. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  18437. return false;
  18438. return this._cache.target.equals(this.target)
  18439. && this._cache.alpha === this.alpha
  18440. && this._cache.beta === this.beta
  18441. && this._cache.radius === this.radius
  18442. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  18443. };
  18444. // Methods
  18445. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  18446. var _this = this;
  18447. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  18448. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  18449. this._useCtrlForPanning = useCtrlForPanning;
  18450. this._panningMouseButton = panningMouseButton;
  18451. this.inputs.attachElement(element, noPreventDefault);
  18452. this._reset = function () {
  18453. _this.inertialAlphaOffset = 0;
  18454. _this.inertialBetaOffset = 0;
  18455. _this.inertialRadiusOffset = 0;
  18456. };
  18457. };
  18458. ArcRotateCamera.prototype.detachControl = function (element) {
  18459. this.inputs.detachElement(element);
  18460. if (this._reset) {
  18461. this._reset();
  18462. }
  18463. };
  18464. ArcRotateCamera.prototype._checkInputs = function () {
  18465. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  18466. if (this._collisionTriggered) {
  18467. return;
  18468. }
  18469. this.inputs.checkInputs();
  18470. // Inertia
  18471. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  18472. if (this.getScene().useRightHandedSystem) {
  18473. this.alpha -= this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  18474. }
  18475. else {
  18476. this.alpha += this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  18477. }
  18478. this.beta += this.inertialBetaOffset;
  18479. this.radius -= this.inertialRadiusOffset;
  18480. this.inertialAlphaOffset *= this.inertia;
  18481. this.inertialBetaOffset *= this.inertia;
  18482. this.inertialRadiusOffset *= this.inertia;
  18483. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)
  18484. this.inertialAlphaOffset = 0;
  18485. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)
  18486. this.inertialBetaOffset = 0;
  18487. if (Math.abs(this.inertialRadiusOffset) < BABYLON.Epsilon)
  18488. this.inertialRadiusOffset = 0;
  18489. }
  18490. // Panning inertia
  18491. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  18492. if (!this._localDirection) {
  18493. this._localDirection = BABYLON.Vector3.Zero();
  18494. this._transformedDirection = BABYLON.Vector3.Zero();
  18495. }
  18496. this.inertialPanningX *= this.inertia;
  18497. this.inertialPanningY *= this.inertia;
  18498. if (Math.abs(this.inertialPanningX) < BABYLON.Epsilon)
  18499. this.inertialPanningX = 0;
  18500. if (Math.abs(this.inertialPanningY) < BABYLON.Epsilon)
  18501. this.inertialPanningY = 0;
  18502. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  18503. this._localDirection.multiplyInPlace(this.panningAxis);
  18504. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  18505. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  18506. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  18507. if (!this.panningAxis.y) {
  18508. this._transformedDirection.y = 0;
  18509. }
  18510. if (!this.target.getAbsolutePosition) {
  18511. this.target.addInPlace(this._transformedDirection);
  18512. }
  18513. }
  18514. // Limits
  18515. this._checkLimits();
  18516. _super.prototype._checkInputs.call(this);
  18517. };
  18518. ArcRotateCamera.prototype._checkLimits = function () {
  18519. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  18520. if (this.allowUpsideDown && this.beta > Math.PI) {
  18521. this.beta = this.beta - (2 * Math.PI);
  18522. }
  18523. }
  18524. else {
  18525. if (this.beta < this.lowerBetaLimit) {
  18526. this.beta = this.lowerBetaLimit;
  18527. }
  18528. }
  18529. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  18530. if (this.allowUpsideDown && this.beta < -Math.PI) {
  18531. this.beta = this.beta + (2 * Math.PI);
  18532. }
  18533. }
  18534. else {
  18535. if (this.beta > this.upperBetaLimit) {
  18536. this.beta = this.upperBetaLimit;
  18537. }
  18538. }
  18539. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  18540. this.alpha = this.lowerAlphaLimit;
  18541. }
  18542. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  18543. this.alpha = this.upperAlphaLimit;
  18544. }
  18545. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  18546. this.radius = this.lowerRadiusLimit;
  18547. }
  18548. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  18549. this.radius = this.upperRadiusLimit;
  18550. }
  18551. };
  18552. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  18553. var radiusv3 = this.position.subtract(this._getTargetPosition());
  18554. this.radius = radiusv3.length();
  18555. // Alpha
  18556. this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
  18557. if (radiusv3.z < 0) {
  18558. this.alpha = 2 * Math.PI - this.alpha;
  18559. }
  18560. // Beta
  18561. this.beta = Math.acos(radiusv3.y / this.radius);
  18562. this._checkLimits();
  18563. };
  18564. ArcRotateCamera.prototype.setPosition = function (position) {
  18565. if (this.position.equals(position)) {
  18566. return;
  18567. }
  18568. this.position.copyFrom(position);
  18569. this.rebuildAnglesAndRadius();
  18570. };
  18571. ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter, allowSamePosition) {
  18572. if (toBoundingCenter === void 0) { toBoundingCenter = false; }
  18573. if (allowSamePosition === void 0) { allowSamePosition = false; }
  18574. if (!allowSamePosition && this._getTargetPosition().equals(target)) {
  18575. return;
  18576. }
  18577. if (toBoundingCenter && target.getBoundingInfo) {
  18578. this._targetBoundingCenter = target.getBoundingInfo().boundingBox.centerWorld.clone();
  18579. }
  18580. else {
  18581. this._targetBoundingCenter = null;
  18582. }
  18583. this.target = target;
  18584. this.rebuildAnglesAndRadius();
  18585. };
  18586. ArcRotateCamera.prototype._getViewMatrix = function () {
  18587. // Compute
  18588. var cosa = Math.cos(this.alpha);
  18589. var sina = Math.sin(this.alpha);
  18590. var cosb = Math.cos(this.beta);
  18591. var sinb = Math.sin(this.beta);
  18592. if (sinb === 0) {
  18593. sinb = 0.0001;
  18594. }
  18595. var target = this._getTargetPosition();
  18596. target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this._newPosition);
  18597. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  18598. this._collider.radius = this.collisionRadius;
  18599. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  18600. this._collisionTriggered = true;
  18601. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  18602. }
  18603. else {
  18604. this.position.copyFrom(this._newPosition);
  18605. var up = this.upVector;
  18606. if (this.allowUpsideDown && sinb < 0) {
  18607. up = up.clone();
  18608. up = up.negate();
  18609. }
  18610. if (this.getScene().useRightHandedSystem) {
  18611. BABYLON.Matrix.LookAtRHToRef(this.position, target, up, this._viewMatrix);
  18612. }
  18613. else {
  18614. BABYLON.Matrix.LookAtLHToRef(this.position, target, up, this._viewMatrix);
  18615. }
  18616. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  18617. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  18618. }
  18619. this._currentTarget = target;
  18620. return this._viewMatrix;
  18621. };
  18622. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  18623. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  18624. meshes = meshes || this.getScene().meshes;
  18625. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  18626. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  18627. this.radius = distance * this.zoomOnFactor;
  18628. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  18629. };
  18630. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  18631. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  18632. var meshesOrMinMaxVector;
  18633. var distance;
  18634. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  18635. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  18636. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshesOrMinMaxVector);
  18637. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  18638. }
  18639. else {
  18640. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance;
  18641. distance = meshesOrMinMaxVectorAndDistance.distance;
  18642. }
  18643. this.target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  18644. if (!doNotUpdateMaxZ) {
  18645. this.maxZ = distance * 2;
  18646. }
  18647. };
  18648. /**
  18649. * @override
  18650. * Override Camera.createRigCamera
  18651. */
  18652. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  18653. var alphaShift;
  18654. switch (this.cameraRigMode) {
  18655. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  18656. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  18657. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  18658. case BABYLON.Camera.RIG_MODE_VR:
  18659. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  18660. break;
  18661. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  18662. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  18663. break;
  18664. }
  18665. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this.target, this.getScene());
  18666. rigCam._cameraRigParams = {};
  18667. return rigCam;
  18668. };
  18669. /**
  18670. * @override
  18671. * Override Camera._updateRigCameras
  18672. */
  18673. ArcRotateCamera.prototype._updateRigCameras = function () {
  18674. var camLeft = this._rigCameras[0];
  18675. var camRight = this._rigCameras[1];
  18676. camLeft.beta = camRight.beta = this.beta;
  18677. camLeft.radius = camRight.radius = this.radius;
  18678. switch (this.cameraRigMode) {
  18679. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  18680. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  18681. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  18682. case BABYLON.Camera.RIG_MODE_VR:
  18683. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  18684. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  18685. break;
  18686. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  18687. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  18688. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  18689. break;
  18690. }
  18691. _super.prototype._updateRigCameras.call(this);
  18692. };
  18693. ArcRotateCamera.prototype.dispose = function () {
  18694. this.inputs.clear();
  18695. _super.prototype.dispose.call(this);
  18696. };
  18697. ArcRotateCamera.prototype.getClassName = function () {
  18698. return "ArcRotateCamera";
  18699. };
  18700. return ArcRotateCamera;
  18701. }(BABYLON.TargetCamera));
  18702. __decorate([
  18703. BABYLON.serialize()
  18704. ], ArcRotateCamera.prototype, "alpha", void 0);
  18705. __decorate([
  18706. BABYLON.serialize()
  18707. ], ArcRotateCamera.prototype, "beta", void 0);
  18708. __decorate([
  18709. BABYLON.serialize()
  18710. ], ArcRotateCamera.prototype, "radius", void 0);
  18711. __decorate([
  18712. BABYLON.serializeAsVector3()
  18713. ], ArcRotateCamera.prototype, "target", void 0);
  18714. __decorate([
  18715. BABYLON.serialize()
  18716. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  18717. __decorate([
  18718. BABYLON.serialize()
  18719. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  18720. __decorate([
  18721. BABYLON.serialize()
  18722. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  18723. __decorate([
  18724. BABYLON.serialize()
  18725. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  18726. __decorate([
  18727. BABYLON.serialize()
  18728. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  18729. __decorate([
  18730. BABYLON.serialize()
  18731. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  18732. __decorate([
  18733. BABYLON.serialize()
  18734. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  18735. __decorate([
  18736. BABYLON.serialize()
  18737. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  18738. __decorate([
  18739. BABYLON.serialize()
  18740. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  18741. __decorate([
  18742. BABYLON.serialize()
  18743. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  18744. __decorate([
  18745. BABYLON.serialize()
  18746. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  18747. __decorate([
  18748. BABYLON.serialize()
  18749. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  18750. __decorate([
  18751. BABYLON.serialize()
  18752. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  18753. BABYLON.ArcRotateCamera = ArcRotateCamera;
  18754. })(BABYLON || (BABYLON = {}));
  18755. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  18756. /// <reference path="..\Cameras\babylon.cameraInputsManager.ts" />
  18757. var BABYLON;
  18758. (function (BABYLON) {
  18759. var ArcRotateCameraInputsManager = (function (_super) {
  18760. __extends(ArcRotateCameraInputsManager, _super);
  18761. function ArcRotateCameraInputsManager(camera) {
  18762. return _super.call(this, camera) || this;
  18763. }
  18764. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  18765. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  18766. return this;
  18767. };
  18768. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  18769. this.add(new BABYLON.ArcRotateCameraPointersInput());
  18770. return this;
  18771. };
  18772. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  18773. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  18774. return this;
  18775. };
  18776. ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  18777. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  18778. return this;
  18779. };
  18780. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  18781. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  18782. return this;
  18783. };
  18784. return ArcRotateCameraInputsManager;
  18785. }(BABYLON.CameraInputsManager));
  18786. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  18787. })(BABYLON || (BABYLON = {}));
  18788. //# sourceMappingURL=babylon.arcRotateCameraInputsManager.js.map
  18789. var BABYLON;
  18790. (function (BABYLON) {
  18791. var RenderingManager = (function () {
  18792. function RenderingManager(scene) {
  18793. this._renderingGroups = new Array();
  18794. this._autoClearDepthStencil = {};
  18795. this._customOpaqueSortCompareFn = {};
  18796. this._customAlphaTestSortCompareFn = {};
  18797. this._customTransparentSortCompareFn = {};
  18798. this._renderinGroupInfo = null;
  18799. this._scene = scene;
  18800. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  18801. this._autoClearDepthStencil[i] = { autoClear: true, depth: true, stencil: true };
  18802. }
  18803. }
  18804. RenderingManager.prototype._clearDepthStencilBuffer = function (depth, stencil) {
  18805. if (depth === void 0) { depth = true; }
  18806. if (stencil === void 0) { stencil = true; }
  18807. if (this._depthStencilBufferAlreadyCleaned) {
  18808. return;
  18809. }
  18810. this._scene.getEngine().clear(null, false, depth, stencil);
  18811. this._depthStencilBufferAlreadyCleaned = true;
  18812. };
  18813. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  18814. // Check if there's at least on observer on the onRenderingGroupObservable and initialize things to fire it
  18815. var observable = this._scene.onRenderingGroupObservable.hasObservers() ? this._scene.onRenderingGroupObservable : null;
  18816. var info = null;
  18817. if (observable) {
  18818. if (!this._renderinGroupInfo) {
  18819. this._renderinGroupInfo = new BABYLON.RenderingGroupInfo();
  18820. }
  18821. info = this._renderinGroupInfo;
  18822. info.scene = this._scene;
  18823. info.camera = this._scene.activeCamera;
  18824. }
  18825. // Dispatch sprites
  18826. if (renderSprites) {
  18827. for (var index = 0; index < this._scene.spriteManagers.length; index++) {
  18828. var manager = this._scene.spriteManagers[index];
  18829. this.dispatchSprites(manager);
  18830. }
  18831. }
  18832. // Render
  18833. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  18834. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  18835. var renderingGroup = this._renderingGroups[index];
  18836. if (!renderingGroup && !observable)
  18837. continue;
  18838. this._currentIndex = index;
  18839. var renderingGroupMask = 0;
  18840. // Fire PRECLEAR stage
  18841. if (observable) {
  18842. renderingGroupMask = Math.pow(2, index);
  18843. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRECLEAR;
  18844. info.renderingGroupId = index;
  18845. observable.notifyObservers(info, renderingGroupMask);
  18846. }
  18847. // Clear depth/stencil if needed
  18848. var autoClear = this._autoClearDepthStencil[index];
  18849. if (autoClear && autoClear.autoClear) {
  18850. this._clearDepthStencilBuffer(autoClear.depth, autoClear.stencil);
  18851. }
  18852. if (observable) {
  18853. // Fire PREOPAQUE stage
  18854. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PREOPAQUE;
  18855. observable.notifyObservers(info, renderingGroupMask);
  18856. // Fire PRETRANSPARENT stage
  18857. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRETRANSPARENT;
  18858. observable.notifyObservers(info, renderingGroupMask);
  18859. }
  18860. if (renderingGroup)
  18861. renderingGroup.render(customRenderFunction, renderSprites, renderParticles, activeMeshes);
  18862. // Fire POSTTRANSPARENT stage
  18863. if (observable) {
  18864. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_POSTTRANSPARENT;
  18865. observable.notifyObservers(info, renderingGroupMask);
  18866. }
  18867. }
  18868. };
  18869. RenderingManager.prototype.reset = function () {
  18870. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  18871. var renderingGroup = this._renderingGroups[index];
  18872. if (renderingGroup) {
  18873. renderingGroup.prepare();
  18874. }
  18875. }
  18876. };
  18877. RenderingManager.prototype.dispose = function () {
  18878. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  18879. var renderingGroup = this._renderingGroups[index];
  18880. if (renderingGroup) {
  18881. renderingGroup.dispose();
  18882. }
  18883. }
  18884. this._renderingGroups.length = 0;
  18885. };
  18886. RenderingManager.prototype._prepareRenderingGroup = function (renderingGroupId) {
  18887. if (!this._renderingGroups[renderingGroupId]) {
  18888. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  18889. }
  18890. };
  18891. RenderingManager.prototype.dispatchSprites = function (spriteManager) {
  18892. var renderingGroupId = spriteManager.renderingGroupId || 0;
  18893. this._prepareRenderingGroup(renderingGroupId);
  18894. this._renderingGroups[renderingGroupId].dispatchSprites(spriteManager);
  18895. };
  18896. RenderingManager.prototype.dispatchParticles = function (particleSystem) {
  18897. var renderingGroupId = particleSystem.renderingGroupId || 0;
  18898. this._prepareRenderingGroup(renderingGroupId);
  18899. this._renderingGroups[renderingGroupId].dispatchParticles(particleSystem);
  18900. };
  18901. RenderingManager.prototype.dispatch = function (subMesh) {
  18902. var mesh = subMesh.getMesh();
  18903. var renderingGroupId = mesh.renderingGroupId || 0;
  18904. this._prepareRenderingGroup(renderingGroupId);
  18905. this._renderingGroups[renderingGroupId].dispatch(subMesh);
  18906. };
  18907. /**
  18908. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  18909. * This allowed control for front to back rendering or reversly depending of the special needs.
  18910. *
  18911. * @param renderingGroupId The rendering group id corresponding to its index
  18912. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  18913. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  18914. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  18915. */
  18916. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  18917. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  18918. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  18919. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  18920. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  18921. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  18922. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  18923. if (this._renderingGroups[renderingGroupId]) {
  18924. var group = this._renderingGroups[renderingGroupId];
  18925. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  18926. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  18927. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  18928. }
  18929. };
  18930. /**
  18931. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  18932. *
  18933. * @param renderingGroupId The rendering group id corresponding to its index
  18934. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  18935. * @param depth Automatically clears depth between groups if true and autoClear is true.
  18936. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  18937. */
  18938. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  18939. if (depth === void 0) { depth = true; }
  18940. if (stencil === void 0) { stencil = true; }
  18941. this._autoClearDepthStencil[renderingGroupId] = {
  18942. autoClear: autoClearDepthStencil,
  18943. depth: depth,
  18944. stencil: stencil
  18945. };
  18946. };
  18947. return RenderingManager;
  18948. }());
  18949. /**
  18950. * The max id used for rendering groups (not included)
  18951. */
  18952. RenderingManager.MAX_RENDERINGGROUPS = 4;
  18953. /**
  18954. * The min id used for rendering groups (included)
  18955. */
  18956. RenderingManager.MIN_RENDERINGGROUPS = 0;
  18957. BABYLON.RenderingManager = RenderingManager;
  18958. })(BABYLON || (BABYLON = {}));
  18959. //# sourceMappingURL=babylon.renderingManager.js.map
  18960. var BABYLON;
  18961. (function (BABYLON) {
  18962. var RenderingGroup = (function () {
  18963. /**
  18964. * Creates a new rendering group.
  18965. * @param index The rendering group index
  18966. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  18967. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  18968. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  18969. */
  18970. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  18971. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  18972. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  18973. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  18974. this.index = index;
  18975. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  18976. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  18977. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  18978. this._particleSystems = new BABYLON.SmartArray(256);
  18979. this._spriteManagers = new BABYLON.SmartArray(256);
  18980. this._scene = scene;
  18981. this.opaqueSortCompareFn = opaqueSortCompareFn;
  18982. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  18983. this.transparentSortCompareFn = transparentSortCompareFn;
  18984. }
  18985. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  18986. /**
  18987. * Set the opaque sort comparison function.
  18988. * If null the sub meshes will be render in the order they were created
  18989. */
  18990. set: function (value) {
  18991. this._opaqueSortCompareFn = value;
  18992. if (value) {
  18993. this._renderOpaque = this.renderOpaqueSorted;
  18994. }
  18995. else {
  18996. this._renderOpaque = RenderingGroup.renderUnsorted;
  18997. }
  18998. },
  18999. enumerable: true,
  19000. configurable: true
  19001. });
  19002. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  19003. /**
  19004. * Set the alpha test sort comparison function.
  19005. * If null the sub meshes will be render in the order they were created
  19006. */
  19007. set: function (value) {
  19008. this._alphaTestSortCompareFn = value;
  19009. if (value) {
  19010. this._renderAlphaTest = this.renderAlphaTestSorted;
  19011. }
  19012. else {
  19013. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  19014. }
  19015. },
  19016. enumerable: true,
  19017. configurable: true
  19018. });
  19019. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  19020. /**
  19021. * Set the transparent sort comparison function.
  19022. * If null the sub meshes will be render in the order they were created
  19023. */
  19024. set: function (value) {
  19025. if (value) {
  19026. this._transparentSortCompareFn = value;
  19027. }
  19028. else {
  19029. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  19030. }
  19031. this._renderTransparent = this.renderTransparentSorted;
  19032. },
  19033. enumerable: true,
  19034. configurable: true
  19035. });
  19036. /**
  19037. * Render all the sub meshes contained in the group.
  19038. * @param customRenderFunction Used to override the default render behaviour of the group.
  19039. * @returns true if rendered some submeshes.
  19040. */
  19041. RenderingGroup.prototype.render = function (customRenderFunction, renderSprites, renderParticles, activeMeshes) {
  19042. if (customRenderFunction) {
  19043. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes);
  19044. return;
  19045. }
  19046. var engine = this._scene.getEngine();
  19047. // Opaque
  19048. if (this._opaqueSubMeshes.length !== 0) {
  19049. this._renderOpaque(this._opaqueSubMeshes);
  19050. }
  19051. // Alpha test
  19052. if (this._alphaTestSubMeshes.length !== 0) {
  19053. engine.setAlphaTesting(true);
  19054. this._renderAlphaTest(this._alphaTestSubMeshes);
  19055. engine.setAlphaTesting(false);
  19056. }
  19057. // Sprites
  19058. if (renderSprites) {
  19059. this._renderSprites();
  19060. }
  19061. // Particles
  19062. if (renderParticles) {
  19063. this._renderParticles(activeMeshes);
  19064. }
  19065. if (this.onBeforeTransparentRendering) {
  19066. this.onBeforeTransparentRendering();
  19067. }
  19068. // Transparent
  19069. if (this._transparentSubMeshes.length !== 0) {
  19070. this._renderTransparent(this._transparentSubMeshes);
  19071. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  19072. }
  19073. };
  19074. /**
  19075. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  19076. * @param subMeshes The submeshes to render
  19077. */
  19078. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  19079. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera.globalPosition, false);
  19080. };
  19081. /**
  19082. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  19083. * @param subMeshes The submeshes to render
  19084. */
  19085. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  19086. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera.globalPosition, false);
  19087. };
  19088. /**
  19089. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  19090. * @param subMeshes The submeshes to render
  19091. */
  19092. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  19093. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera.globalPosition, true);
  19094. };
  19095. /**
  19096. * Renders the submeshes in a specified order.
  19097. * @param subMeshes The submeshes to sort before render
  19098. * @param sortCompareFn The comparison function use to sort
  19099. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  19100. * @param transparent Specifies to activate blending if true
  19101. */
  19102. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, cameraPosition, transparent) {
  19103. var subIndex = 0;
  19104. var subMesh;
  19105. for (; subIndex < subMeshes.length; subIndex++) {
  19106. subMesh = subMeshes.data[subIndex];
  19107. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  19108. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  19109. }
  19110. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  19111. sortedArray.sort(sortCompareFn);
  19112. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  19113. subMesh = sortedArray[subIndex];
  19114. subMesh.render(transparent);
  19115. }
  19116. };
  19117. /**
  19118. * Renders the submeshes in the order they were dispatched (no sort applied).
  19119. * @param subMeshes The submeshes to render
  19120. */
  19121. RenderingGroup.renderUnsorted = function (subMeshes) {
  19122. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  19123. var submesh = subMeshes.data[subIndex];
  19124. submesh.render(false);
  19125. }
  19126. };
  19127. /**
  19128. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  19129. * are rendered back to front if in the same alpha index.
  19130. *
  19131. * @param a The first submesh
  19132. * @param b The second submesh
  19133. * @returns The result of the comparison
  19134. */
  19135. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  19136. // Alpha index first
  19137. if (a._alphaIndex > b._alphaIndex) {
  19138. return 1;
  19139. }
  19140. if (a._alphaIndex < b._alphaIndex) {
  19141. return -1;
  19142. }
  19143. // Then distance to camera
  19144. return RenderingGroup.backToFrontSortCompare(a, b);
  19145. };
  19146. /**
  19147. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  19148. * are rendered back to front.
  19149. *
  19150. * @param a The first submesh
  19151. * @param b The second submesh
  19152. * @returns The result of the comparison
  19153. */
  19154. RenderingGroup.backToFrontSortCompare = function (a, b) {
  19155. // Then distance to camera
  19156. if (a._distanceToCamera < b._distanceToCamera) {
  19157. return 1;
  19158. }
  19159. if (a._distanceToCamera > b._distanceToCamera) {
  19160. return -1;
  19161. }
  19162. return 0;
  19163. };
  19164. /**
  19165. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  19166. * are rendered front to back (prevent overdraw).
  19167. *
  19168. * @param a The first submesh
  19169. * @param b The second submesh
  19170. * @returns The result of the comparison
  19171. */
  19172. RenderingGroup.frontToBackSortCompare = function (a, b) {
  19173. // Then distance to camera
  19174. if (a._distanceToCamera < b._distanceToCamera) {
  19175. return -1;
  19176. }
  19177. if (a._distanceToCamera > b._distanceToCamera) {
  19178. return 1;
  19179. }
  19180. return 0;
  19181. };
  19182. /**
  19183. * Resets the different lists of submeshes to prepare a new frame.
  19184. */
  19185. RenderingGroup.prototype.prepare = function () {
  19186. this._opaqueSubMeshes.reset();
  19187. this._transparentSubMeshes.reset();
  19188. this._alphaTestSubMeshes.reset();
  19189. this._particleSystems.reset();
  19190. this._spriteManagers.reset();
  19191. };
  19192. RenderingGroup.prototype.dispose = function () {
  19193. this._opaqueSubMeshes.dispose();
  19194. this._transparentSubMeshes.dispose();
  19195. this._alphaTestSubMeshes.dispose();
  19196. this._particleSystems.dispose();
  19197. this._spriteManagers.dispose();
  19198. };
  19199. /**
  19200. * Inserts the submesh in its correct queue depending on its material.
  19201. * @param subMesh The submesh to dispatch
  19202. */
  19203. RenderingGroup.prototype.dispatch = function (subMesh) {
  19204. var material = subMesh.getMaterial();
  19205. var mesh = subMesh.getMesh();
  19206. if (material.needAlphaBlending() || mesh.visibility < 1.0 || mesh.hasVertexAlpha) {
  19207. this._transparentSubMeshes.push(subMesh);
  19208. }
  19209. else if (material.needAlphaTesting()) {
  19210. this._alphaTestSubMeshes.push(subMesh);
  19211. }
  19212. else {
  19213. this._opaqueSubMeshes.push(subMesh); // Opaque
  19214. }
  19215. };
  19216. RenderingGroup.prototype.dispatchSprites = function (spriteManager) {
  19217. this._spriteManagers.push(spriteManager);
  19218. };
  19219. RenderingGroup.prototype.dispatchParticles = function (particleSystem) {
  19220. this._particleSystems.push(particleSystem);
  19221. };
  19222. RenderingGroup.prototype._renderParticles = function (activeMeshes) {
  19223. if (this._particleSystems.length === 0) {
  19224. return;
  19225. }
  19226. // Particles
  19227. var activeCamera = this._scene.activeCamera;
  19228. this._scene._particlesDuration.beginMonitoring();
  19229. for (var particleIndex = 0; particleIndex < this._scene._activeParticleSystems.length; particleIndex++) {
  19230. var particleSystem = this._scene._activeParticleSystems.data[particleIndex];
  19231. if ((activeCamera.layerMask & particleSystem.layerMask) === 0) {
  19232. continue;
  19233. }
  19234. if (!particleSystem.emitter.position || !activeMeshes || activeMeshes.indexOf(particleSystem.emitter) !== -1) {
  19235. this._scene._activeParticles.addCount(particleSystem.render(), false);
  19236. }
  19237. }
  19238. this._scene._particlesDuration.endMonitoring(false);
  19239. };
  19240. RenderingGroup.prototype._renderSprites = function () {
  19241. if (!this._scene.spritesEnabled || this._spriteManagers.length === 0) {
  19242. return;
  19243. }
  19244. // Sprites
  19245. var activeCamera = this._scene.activeCamera;
  19246. this._scene._spritesDuration.beginMonitoring();
  19247. for (var id = 0; id < this._spriteManagers.length; id++) {
  19248. var spriteManager = this._spriteManagers.data[id];
  19249. if (((activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  19250. spriteManager.render();
  19251. }
  19252. }
  19253. this._scene._spritesDuration.endMonitoring(false);
  19254. };
  19255. return RenderingGroup;
  19256. }());
  19257. BABYLON.RenderingGroup = RenderingGroup;
  19258. })(BABYLON || (BABYLON = {}));
  19259. //# sourceMappingURL=babylon.renderingGroup.js.map
  19260. var BABYLON;
  19261. (function (BABYLON) {
  19262. var ClickInfo = (function () {
  19263. function ClickInfo() {
  19264. this._singleClick = false;
  19265. this._doubleClick = false;
  19266. this._hasSwiped = false;
  19267. this._ignore = false;
  19268. }
  19269. Object.defineProperty(ClickInfo.prototype, "singleClick", {
  19270. get: function () {
  19271. return this._singleClick;
  19272. },
  19273. set: function (b) {
  19274. this._singleClick = b;
  19275. },
  19276. enumerable: true,
  19277. configurable: true
  19278. });
  19279. Object.defineProperty(ClickInfo.prototype, "doubleClick", {
  19280. get: function () {
  19281. return this._doubleClick;
  19282. },
  19283. set: function (b) {
  19284. this._doubleClick = b;
  19285. },
  19286. enumerable: true,
  19287. configurable: true
  19288. });
  19289. Object.defineProperty(ClickInfo.prototype, "hasSwiped", {
  19290. get: function () {
  19291. return this._hasSwiped;
  19292. },
  19293. set: function (b) {
  19294. this._hasSwiped = b;
  19295. },
  19296. enumerable: true,
  19297. configurable: true
  19298. });
  19299. Object.defineProperty(ClickInfo.prototype, "ignore", {
  19300. get: function () {
  19301. return this._ignore;
  19302. },
  19303. set: function (b) {
  19304. this._ignore = b;
  19305. },
  19306. enumerable: true,
  19307. configurable: true
  19308. });
  19309. return ClickInfo;
  19310. }());
  19311. var PointerEventTypes = (function () {
  19312. function PointerEventTypes() {
  19313. }
  19314. Object.defineProperty(PointerEventTypes, "POINTERDOWN", {
  19315. get: function () {
  19316. return PointerEventTypes._POINTERDOWN;
  19317. },
  19318. enumerable: true,
  19319. configurable: true
  19320. });
  19321. Object.defineProperty(PointerEventTypes, "POINTERUP", {
  19322. get: function () {
  19323. return PointerEventTypes._POINTERUP;
  19324. },
  19325. enumerable: true,
  19326. configurable: true
  19327. });
  19328. Object.defineProperty(PointerEventTypes, "POINTERMOVE", {
  19329. get: function () {
  19330. return PointerEventTypes._POINTERMOVE;
  19331. },
  19332. enumerable: true,
  19333. configurable: true
  19334. });
  19335. Object.defineProperty(PointerEventTypes, "POINTERWHEEL", {
  19336. get: function () {
  19337. return PointerEventTypes._POINTERWHEEL;
  19338. },
  19339. enumerable: true,
  19340. configurable: true
  19341. });
  19342. Object.defineProperty(PointerEventTypes, "POINTERPICK", {
  19343. get: function () {
  19344. return PointerEventTypes._POINTERPICK;
  19345. },
  19346. enumerable: true,
  19347. configurable: true
  19348. });
  19349. Object.defineProperty(PointerEventTypes, "POINTERTAP", {
  19350. get: function () {
  19351. return PointerEventTypes._POINTERTAP;
  19352. },
  19353. enumerable: true,
  19354. configurable: true
  19355. });
  19356. Object.defineProperty(PointerEventTypes, "POINTERDOUBLETAP", {
  19357. get: function () {
  19358. return PointerEventTypes._POINTERDOUBLETAP;
  19359. },
  19360. enumerable: true,
  19361. configurable: true
  19362. });
  19363. return PointerEventTypes;
  19364. }());
  19365. PointerEventTypes._POINTERDOWN = 0x01;
  19366. PointerEventTypes._POINTERUP = 0x02;
  19367. PointerEventTypes._POINTERMOVE = 0x04;
  19368. PointerEventTypes._POINTERWHEEL = 0x08;
  19369. PointerEventTypes._POINTERPICK = 0x10;
  19370. PointerEventTypes._POINTERTAP = 0x20;
  19371. PointerEventTypes._POINTERDOUBLETAP = 0x40;
  19372. BABYLON.PointerEventTypes = PointerEventTypes;
  19373. var PointerInfoBase = (function () {
  19374. function PointerInfoBase(type, event) {
  19375. this.type = type;
  19376. this.event = event;
  19377. }
  19378. return PointerInfoBase;
  19379. }());
  19380. BABYLON.PointerInfoBase = PointerInfoBase;
  19381. /**
  19382. * This class is used to store pointer related info for the onPrePointerObservable event.
  19383. * Set the skipOnPointerObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onPointerObservable
  19384. */
  19385. var PointerInfoPre = (function (_super) {
  19386. __extends(PointerInfoPre, _super);
  19387. function PointerInfoPre(type, event, localX, localY) {
  19388. var _this = _super.call(this, type, event) || this;
  19389. _this.skipOnPointerObservable = false;
  19390. _this.localPosition = new BABYLON.Vector2(localX, localY);
  19391. return _this;
  19392. }
  19393. return PointerInfoPre;
  19394. }(PointerInfoBase));
  19395. BABYLON.PointerInfoPre = PointerInfoPre;
  19396. /**
  19397. * This type contains all the data related to a pointer event in Babylon.js.
  19398. * 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.
  19399. */
  19400. var PointerInfo = (function (_super) {
  19401. __extends(PointerInfo, _super);
  19402. function PointerInfo(type, event, pickInfo) {
  19403. var _this = _super.call(this, type, event) || this;
  19404. _this.pickInfo = pickInfo;
  19405. return _this;
  19406. }
  19407. return PointerInfo;
  19408. }(PointerInfoBase));
  19409. BABYLON.PointerInfo = PointerInfo;
  19410. /**
  19411. * This class is used by the onRenderingGroupObservable
  19412. */
  19413. var RenderingGroupInfo = (function () {
  19414. function RenderingGroupInfo() {
  19415. }
  19416. return RenderingGroupInfo;
  19417. }());
  19418. /**
  19419. * Stage corresponding to the very first hook in the renderingGroup phase: before the render buffer may be cleared
  19420. * This stage will be fired no matter what
  19421. */
  19422. RenderingGroupInfo.STAGE_PRECLEAR = 1;
  19423. /**
  19424. * Called before opaque object are rendered.
  19425. * This stage will be fired only if there's 3D Opaque content to render
  19426. */
  19427. RenderingGroupInfo.STAGE_PREOPAQUE = 2;
  19428. /**
  19429. * Called after the opaque objects are rendered and before the transparent ones
  19430. * This stage will be fired only if there's 3D transparent content to render
  19431. */
  19432. RenderingGroupInfo.STAGE_PRETRANSPARENT = 3;
  19433. /**
  19434. * Called after the transparent object are rendered, last hook of the renderingGroup phase
  19435. * This stage will be fired no matter what
  19436. */
  19437. RenderingGroupInfo.STAGE_POSTTRANSPARENT = 4;
  19438. BABYLON.RenderingGroupInfo = RenderingGroupInfo;
  19439. /**
  19440. * Represents a scene to be rendered by the engine.
  19441. * @see http://doc.babylonjs.com/page.php?p=21911
  19442. */
  19443. var Scene = (function () {
  19444. /**
  19445. * @constructor
  19446. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  19447. */
  19448. function Scene(engine) {
  19449. // Members
  19450. this.autoClear = true;
  19451. this.clearColor = new BABYLON.Color4(0.2, 0.2, 0.3, 1.0);
  19452. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  19453. this.forceWireframe = false;
  19454. this.forcePointsCloud = false;
  19455. this.forceShowBoundingBoxes = false;
  19456. this.animationsEnabled = true;
  19457. this.constantlyUpdateMeshUnderPointer = false;
  19458. this.useRightHandedSystem = false;
  19459. this.hoverCursor = "pointer";
  19460. // Metadata
  19461. this.metadata = null;
  19462. // Events
  19463. /**
  19464. * An event triggered when the scene is disposed.
  19465. * @type {BABYLON.Observable}
  19466. */
  19467. this.onDisposeObservable = new BABYLON.Observable();
  19468. /**
  19469. * An event triggered before rendering the scene
  19470. * @type {BABYLON.Observable}
  19471. */
  19472. this.onBeforeRenderObservable = new BABYLON.Observable();
  19473. /**
  19474. * An event triggered after rendering the scene
  19475. * @type {BABYLON.Observable}
  19476. */
  19477. this.onAfterRenderObservable = new BABYLON.Observable();
  19478. /**
  19479. * An event triggered when the scene is ready
  19480. * @type {BABYLON.Observable}
  19481. */
  19482. this.onReadyObservable = new BABYLON.Observable();
  19483. /**
  19484. * An event triggered before rendering a camera
  19485. * @type {BABYLON.Observable}
  19486. */
  19487. this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  19488. /**
  19489. * An event triggered after rendering a camera
  19490. * @type {BABYLON.Observable}
  19491. */
  19492. this.onAfterCameraRenderObservable = new BABYLON.Observable();
  19493. /**
  19494. * An event triggered when a camera is created
  19495. * @type {BABYLON.Observable}
  19496. */
  19497. this.onNewCameraAddedObservable = new BABYLON.Observable();
  19498. /**
  19499. * An event triggered when a camera is removed
  19500. * @type {BABYLON.Observable}
  19501. */
  19502. this.onCameraRemovedObservable = new BABYLON.Observable();
  19503. /**
  19504. * An event triggered when a light is created
  19505. * @type {BABYLON.Observable}
  19506. */
  19507. this.onNewLightAddedObservable = new BABYLON.Observable();
  19508. /**
  19509. * An event triggered when a light is removed
  19510. * @type {BABYLON.Observable}
  19511. */
  19512. this.onLightRemovedObservable = new BABYLON.Observable();
  19513. /**
  19514. * An event triggered when a geometry is created
  19515. * @type {BABYLON.Observable}
  19516. */
  19517. this.onNewGeometryAddedObservable = new BABYLON.Observable();
  19518. /**
  19519. * An event triggered when a geometry is removed
  19520. * @type {BABYLON.Observable}
  19521. */
  19522. this.onGeometryRemovedObservable = new BABYLON.Observable();
  19523. /**
  19524. * An event triggered when a mesh is created
  19525. * @type {BABYLON.Observable}
  19526. */
  19527. this.onNewMeshAddedObservable = new BABYLON.Observable();
  19528. /**
  19529. * An event triggered when a mesh is removed
  19530. * @type {BABYLON.Observable}
  19531. */
  19532. this.onMeshRemovedObservable = new BABYLON.Observable();
  19533. /**
  19534. * This Observable will be triggered for each stage of each renderingGroup of each rendered camera.
  19535. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  19536. * 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)
  19537. */
  19538. this.onRenderingGroupObservable = new BABYLON.Observable();
  19539. // Animations
  19540. this.animations = [];
  19541. /**
  19542. * 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).
  19543. * You have the possibility to skip the 3D Engine process and the call to onPointerObservable by setting PointerInfoBase.skipOnPointerObservable to true
  19544. */
  19545. this.onPrePointerObservable = new BABYLON.Observable();
  19546. /**
  19547. * Observable event triggered each time an input event is received from the rendering canvas
  19548. */
  19549. this.onPointerObservable = new BABYLON.Observable();
  19550. this._meshPickProceed = false;
  19551. this._previousHasSwiped = false;
  19552. this._currentPickResult = null;
  19553. this._previousPickResult = null;
  19554. this._isButtonPressed = false;
  19555. this._doubleClickOccured = false;
  19556. 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
  19557. this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  19558. this._previousStartingPointerPosition = new BABYLON.Vector2(0, 0);
  19559. this._startingPointerTime = 0;
  19560. this._previousStartingPointerTime = 0;
  19561. // Fog
  19562. /**
  19563. * is fog enabled on this scene.
  19564. * @type {boolean}
  19565. */
  19566. this.fogEnabled = true;
  19567. this.fogMode = Scene.FOGMODE_NONE;
  19568. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  19569. this.fogDensity = 0.1;
  19570. this.fogStart = 0;
  19571. this.fogEnd = 1000.0;
  19572. // Lights
  19573. /**
  19574. * is shadow enabled on this scene.
  19575. * @type {boolean}
  19576. */
  19577. this.shadowsEnabled = true;
  19578. /**
  19579. * is light enabled on this scene.
  19580. * @type {boolean}
  19581. */
  19582. this.lightsEnabled = true;
  19583. /**
  19584. * All of the lights added to this scene.
  19585. * @see BABYLON.Light
  19586. * @type {BABYLON.Light[]}
  19587. */
  19588. this.lights = new Array();
  19589. // Cameras
  19590. /**
  19591. * All of the cameras added to this scene.
  19592. * @see BABYLON.Camera
  19593. * @type {BABYLON.Camera[]}
  19594. */
  19595. this.cameras = new Array();
  19596. this.activeCameras = new Array();
  19597. // Meshes
  19598. /**
  19599. * All of the (abstract) meshes added to this scene.
  19600. * @see BABYLON.AbstractMesh
  19601. * @type {BABYLON.AbstractMesh[]}
  19602. */
  19603. this.meshes = new Array();
  19604. // Geometries
  19605. this._geometries = new Array();
  19606. this.materials = new Array();
  19607. this.multiMaterials = new Array();
  19608. // Textures
  19609. this.texturesEnabled = true;
  19610. this.textures = new Array();
  19611. // Particles
  19612. this.particlesEnabled = true;
  19613. this.particleSystems = new Array();
  19614. // Sprites
  19615. this.spritesEnabled = true;
  19616. this.spriteManagers = new Array();
  19617. // Layers
  19618. this.layers = new Array();
  19619. this.highlightLayers = new Array();
  19620. // Skeletons
  19621. this.skeletonsEnabled = true;
  19622. this.skeletons = new Array();
  19623. // Lens flares
  19624. this.lensFlaresEnabled = true;
  19625. this.lensFlareSystems = new Array();
  19626. // Collisions
  19627. this.collisionsEnabled = true;
  19628. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  19629. // Postprocesses
  19630. this.postProcessesEnabled = true;
  19631. // Customs render targets
  19632. this.renderTargetsEnabled = true;
  19633. this.dumpNextRenderTargets = false;
  19634. this.customRenderTargets = new Array();
  19635. // Imported meshes
  19636. this.importedMeshesFiles = new Array();
  19637. // Probes
  19638. this.probesEnabled = true;
  19639. this.reflectionProbes = new Array();
  19640. this._actionManagers = new Array();
  19641. this._meshesForIntersections = new BABYLON.SmartArray(256);
  19642. // Procedural textures
  19643. this.proceduralTexturesEnabled = true;
  19644. this._proceduralTextures = new Array();
  19645. this.soundTracks = new Array();
  19646. this._audioEnabled = true;
  19647. this._headphone = false;
  19648. // Performance counters
  19649. this._totalMeshesCounter = new BABYLON.PerfCounter();
  19650. this._totalLightsCounter = new BABYLON.PerfCounter();
  19651. this._totalMaterialsCounter = new BABYLON.PerfCounter();
  19652. this._totalTexturesCounter = new BABYLON.PerfCounter();
  19653. this._totalVertices = new BABYLON.PerfCounter();
  19654. this._activeIndices = new BABYLON.PerfCounter();
  19655. this._activeParticles = new BABYLON.PerfCounter();
  19656. this._lastFrameDuration = new BABYLON.PerfCounter();
  19657. this._evaluateActiveMeshesDuration = new BABYLON.PerfCounter();
  19658. this._renderTargetsDuration = new BABYLON.PerfCounter();
  19659. this._particlesDuration = new BABYLON.PerfCounter();
  19660. this._renderDuration = new BABYLON.PerfCounter();
  19661. this._spritesDuration = new BABYLON.PerfCounter();
  19662. this._activeBones = new BABYLON.PerfCounter();
  19663. this._animationTime = 0;
  19664. this.animationTimeScale = 1;
  19665. this._renderId = 0;
  19666. this._executeWhenReadyTimeoutId = -1;
  19667. this._intermediateRendering = false;
  19668. this._toBeDisposed = new BABYLON.SmartArray(256);
  19669. this._pendingData = []; //ANY
  19670. this._activeMeshes = new BABYLON.SmartArray(256);
  19671. this._processedMaterials = new BABYLON.SmartArray(256);
  19672. this._renderTargets = new BABYLON.SmartArray(256);
  19673. this._activeParticleSystems = new BABYLON.SmartArray(256);
  19674. this._activeSkeletons = new BABYLON.SmartArray(32);
  19675. this._softwareSkinnedMeshes = new BABYLON.SmartArray(32);
  19676. this._activeAnimatables = new Array();
  19677. this._transformMatrix = BABYLON.Matrix.Zero();
  19678. this._edgesRenderers = new BABYLON.SmartArray(16);
  19679. this._uniqueIdCounter = 0;
  19680. this._engine = engine || BABYLON.Engine.LastCreatedEngine;
  19681. this._engine.scenes.push(this);
  19682. this._externalData = new BABYLON.StringDictionary();
  19683. this._uid = null;
  19684. this._renderingManager = new BABYLON.RenderingManager(this);
  19685. this.postProcessManager = new BABYLON.PostProcessManager(this);
  19686. this.postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  19687. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  19688. if (BABYLON.OutlineRenderer) {
  19689. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  19690. }
  19691. this.attachControl();
  19692. if (BABYLON.SoundTrack) {
  19693. this.mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  19694. }
  19695. //simplification queue
  19696. if (BABYLON.SimplificationQueue) {
  19697. this.simplificationQueue = new BABYLON.SimplificationQueue();
  19698. }
  19699. //collision coordinator initialization. For now legacy per default.
  19700. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  19701. }
  19702. Object.defineProperty(Scene, "FOGMODE_NONE", {
  19703. get: function () {
  19704. return Scene._FOGMODE_NONE;
  19705. },
  19706. enumerable: true,
  19707. configurable: true
  19708. });
  19709. Object.defineProperty(Scene, "FOGMODE_EXP", {
  19710. get: function () {
  19711. return Scene._FOGMODE_EXP;
  19712. },
  19713. enumerable: true,
  19714. configurable: true
  19715. });
  19716. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  19717. get: function () {
  19718. return Scene._FOGMODE_EXP2;
  19719. },
  19720. enumerable: true,
  19721. configurable: true
  19722. });
  19723. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  19724. get: function () {
  19725. return Scene._FOGMODE_LINEAR;
  19726. },
  19727. enumerable: true,
  19728. configurable: true
  19729. });
  19730. Object.defineProperty(Scene.prototype, "onDispose", {
  19731. set: function (callback) {
  19732. if (this._onDisposeObserver) {
  19733. this.onDisposeObservable.remove(this._onDisposeObserver);
  19734. }
  19735. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  19736. },
  19737. enumerable: true,
  19738. configurable: true
  19739. });
  19740. Object.defineProperty(Scene.prototype, "beforeRender", {
  19741. set: function (callback) {
  19742. if (this._onBeforeRenderObserver) {
  19743. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  19744. }
  19745. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  19746. },
  19747. enumerable: true,
  19748. configurable: true
  19749. });
  19750. Object.defineProperty(Scene.prototype, "afterRender", {
  19751. set: function (callback) {
  19752. if (this._onAfterRenderObserver) {
  19753. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  19754. }
  19755. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  19756. },
  19757. enumerable: true,
  19758. configurable: true
  19759. });
  19760. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  19761. set: function (callback) {
  19762. if (this._onBeforeCameraRenderObserver) {
  19763. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  19764. }
  19765. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  19766. },
  19767. enumerable: true,
  19768. configurable: true
  19769. });
  19770. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  19771. set: function (callback) {
  19772. if (this._onAfterCameraRenderObserver) {
  19773. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  19774. }
  19775. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  19776. },
  19777. enumerable: true,
  19778. configurable: true
  19779. });
  19780. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  19781. get: function () {
  19782. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  19783. },
  19784. enumerable: true,
  19785. configurable: true
  19786. });
  19787. Object.defineProperty(Scene.prototype, "defaultMaterial", {
  19788. get: function () {
  19789. if (!this._defaultMaterial) {
  19790. this._defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  19791. }
  19792. return this._defaultMaterial;
  19793. },
  19794. enumerable: true,
  19795. configurable: true
  19796. });
  19797. Object.defineProperty(Scene.prototype, "frustumPlanes", {
  19798. get: function () {
  19799. return this._frustumPlanes;
  19800. },
  19801. enumerable: true,
  19802. configurable: true
  19803. });
  19804. Object.defineProperty(Scene.prototype, "debugLayer", {
  19805. // Properties
  19806. get: function () {
  19807. if (!this._debugLayer) {
  19808. this._debugLayer = new BABYLON.DebugLayer(this);
  19809. }
  19810. return this._debugLayer;
  19811. },
  19812. enumerable: true,
  19813. configurable: true
  19814. });
  19815. Object.defineProperty(Scene.prototype, "workerCollisions", {
  19816. get: function () {
  19817. return this._workerCollisions;
  19818. },
  19819. set: function (enabled) {
  19820. enabled = (enabled && !!Worker);
  19821. this._workerCollisions = enabled;
  19822. if (this.collisionCoordinator) {
  19823. this.collisionCoordinator.destroy();
  19824. }
  19825. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  19826. this.collisionCoordinator.init(this);
  19827. },
  19828. enumerable: true,
  19829. configurable: true
  19830. });
  19831. Object.defineProperty(Scene.prototype, "SelectionOctree", {
  19832. get: function () {
  19833. return this._selectionOctree;
  19834. },
  19835. enumerable: true,
  19836. configurable: true
  19837. });
  19838. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  19839. /**
  19840. * The mesh that is currently under the pointer.
  19841. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  19842. */
  19843. get: function () {
  19844. return this._pointerOverMesh;
  19845. },
  19846. enumerable: true,
  19847. configurable: true
  19848. });
  19849. Object.defineProperty(Scene.prototype, "pointerX", {
  19850. /**
  19851. * Current on-screen X position of the pointer
  19852. * @return {number} X position of the pointer
  19853. */
  19854. get: function () {
  19855. return this._pointerX;
  19856. },
  19857. enumerable: true,
  19858. configurable: true
  19859. });
  19860. Object.defineProperty(Scene.prototype, "pointerY", {
  19861. /**
  19862. * Current on-screen Y position of the pointer
  19863. * @return {number} Y position of the pointer
  19864. */
  19865. get: function () {
  19866. return this._pointerY;
  19867. },
  19868. enumerable: true,
  19869. configurable: true
  19870. });
  19871. Scene.prototype.getCachedMaterial = function () {
  19872. return this._cachedMaterial;
  19873. };
  19874. Scene.prototype.getBoundingBoxRenderer = function () {
  19875. return this._boundingBoxRenderer;
  19876. };
  19877. Scene.prototype.getOutlineRenderer = function () {
  19878. return this._outlineRenderer;
  19879. };
  19880. Scene.prototype.getEngine = function () {
  19881. return this._engine;
  19882. };
  19883. Scene.prototype.getTotalVertices = function () {
  19884. return this._totalVertices.current;
  19885. };
  19886. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  19887. get: function () {
  19888. return this._totalVertices;
  19889. },
  19890. enumerable: true,
  19891. configurable: true
  19892. });
  19893. Scene.prototype.getActiveIndices = function () {
  19894. return this._activeIndices.current;
  19895. };
  19896. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  19897. get: function () {
  19898. return this._activeIndices;
  19899. },
  19900. enumerable: true,
  19901. configurable: true
  19902. });
  19903. Scene.prototype.getActiveParticles = function () {
  19904. return this._activeParticles.current;
  19905. };
  19906. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  19907. get: function () {
  19908. return this._activeParticles;
  19909. },
  19910. enumerable: true,
  19911. configurable: true
  19912. });
  19913. Scene.prototype.getActiveBones = function () {
  19914. return this._activeBones.current;
  19915. };
  19916. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  19917. get: function () {
  19918. return this._activeBones;
  19919. },
  19920. enumerable: true,
  19921. configurable: true
  19922. });
  19923. // Stats
  19924. Scene.prototype.getLastFrameDuration = function () {
  19925. return this._lastFrameDuration.current;
  19926. };
  19927. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  19928. get: function () {
  19929. return this._lastFrameDuration;
  19930. },
  19931. enumerable: true,
  19932. configurable: true
  19933. });
  19934. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  19935. return this._evaluateActiveMeshesDuration.current;
  19936. };
  19937. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  19938. get: function () {
  19939. return this._evaluateActiveMeshesDuration;
  19940. },
  19941. enumerable: true,
  19942. configurable: true
  19943. });
  19944. Scene.prototype.getActiveMeshes = function () {
  19945. return this._activeMeshes;
  19946. };
  19947. Scene.prototype.getRenderTargetsDuration = function () {
  19948. return this._renderTargetsDuration.current;
  19949. };
  19950. Scene.prototype.getRenderDuration = function () {
  19951. return this._renderDuration.current;
  19952. };
  19953. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  19954. get: function () {
  19955. return this._renderDuration;
  19956. },
  19957. enumerable: true,
  19958. configurable: true
  19959. });
  19960. Scene.prototype.getParticlesDuration = function () {
  19961. return this._particlesDuration.current;
  19962. };
  19963. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  19964. get: function () {
  19965. return this._particlesDuration;
  19966. },
  19967. enumerable: true,
  19968. configurable: true
  19969. });
  19970. Scene.prototype.getSpritesDuration = function () {
  19971. return this._spritesDuration.current;
  19972. };
  19973. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  19974. get: function () {
  19975. return this._spritesDuration;
  19976. },
  19977. enumerable: true,
  19978. configurable: true
  19979. });
  19980. Scene.prototype.getAnimationRatio = function () {
  19981. return this._animationRatio;
  19982. };
  19983. Scene.prototype.getRenderId = function () {
  19984. return this._renderId;
  19985. };
  19986. Scene.prototype.incrementRenderId = function () {
  19987. this._renderId++;
  19988. };
  19989. Scene.prototype._updatePointerPosition = function (evt) {
  19990. var canvasRect = this._engine.getRenderingCanvasClientRect();
  19991. this._pointerX = evt.clientX - canvasRect.left;
  19992. this._pointerY = evt.clientY - canvasRect.top;
  19993. this._unTranslatedPointerX = this._pointerX;
  19994. this._unTranslatedPointerY = this._pointerY;
  19995. if (this.cameraToUseForPointers) {
  19996. this._pointerX = this._pointerX - this.cameraToUseForPointers.viewport.x * this._engine.getRenderWidth();
  19997. this._pointerY = this._pointerY - this.cameraToUseForPointers.viewport.y * this._engine.getRenderHeight();
  19998. }
  19999. };
  20000. // Pointers handling
  20001. /**
  20002. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  20003. * @param attachUp defines if you want to attach events to pointerup
  20004. * @param attachDown defines if you want to attach events to pointerdown
  20005. * @param attachMove defines if you want to attach events to pointermove
  20006. */
  20007. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  20008. var _this = this;
  20009. if (attachUp === void 0) { attachUp = true; }
  20010. if (attachDown === void 0) { attachDown = true; }
  20011. if (attachMove === void 0) { attachMove = true; }
  20012. this._initActionManager = function (act, clickInfo) {
  20013. if (!_this._meshPickProceed) {
  20014. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  20015. _this._currentPickResult = pickResult;
  20016. act = (pickResult.hit && pickResult.pickedMesh) ? pickResult.pickedMesh.actionManager : null;
  20017. _this._meshPickProceed = true;
  20018. }
  20019. return act;
  20020. };
  20021. this._delayedSimpleClick = function (btn, clickInfo, cb) {
  20022. // double click delay is over and that no double click has been raised since, or the 2 consecutive keys pressed are different
  20023. if ((new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay && !_this._doubleClickOccured) ||
  20024. btn !== _this._previousButtonPressed) {
  20025. _this._doubleClickOccured = false;
  20026. clickInfo.singleClick = true;
  20027. clickInfo.ignore = false;
  20028. cb(clickInfo, _this._currentPickResult);
  20029. }
  20030. };
  20031. this._initClickEvent = function (obs1, obs2, evt, cb) {
  20032. var clickInfo = new ClickInfo();
  20033. _this._currentPickResult = null;
  20034. var act;
  20035. var checkPicking = obs1.hasSpecificMask(PointerEventTypes.POINTERPICK) || obs2.hasSpecificMask(PointerEventTypes.POINTERPICK)
  20036. || obs1.hasSpecificMask(PointerEventTypes.POINTERTAP) || obs2.hasSpecificMask(PointerEventTypes.POINTERTAP)
  20037. || obs1.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP) || obs2.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP);
  20038. if (!checkPicking && BABYLON.ActionManager.HasPickTriggers) {
  20039. act = _this._initActionManager(act, clickInfo);
  20040. if (act)
  20041. checkPicking = act.hasPickTriggers;
  20042. }
  20043. if (checkPicking) {
  20044. var btn = evt.button;
  20045. clickInfo.hasSwiped = Math.abs(_this._startingPointerPosition.x - _this._pointerX) > Scene.DragMovementThreshold ||
  20046. Math.abs(_this._startingPointerPosition.y - _this._pointerY) > Scene.DragMovementThreshold;
  20047. if (!clickInfo.hasSwiped) {
  20048. var checkSingleClickImmediately = !Scene.ExclusiveDoubleClickMode;
  20049. if (!checkSingleClickImmediately) {
  20050. checkSingleClickImmediately = !obs1.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP) &&
  20051. !obs2.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP);
  20052. if (checkSingleClickImmediately && !BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  20053. act = _this._initActionManager(act, clickInfo);
  20054. if (act)
  20055. checkSingleClickImmediately = !act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  20056. }
  20057. }
  20058. if (checkSingleClickImmediately) {
  20059. // single click detected if double click delay is over or two different successive keys pressed without exclusive double click or no double click required
  20060. if (new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay ||
  20061. btn !== _this._previousButtonPressed) {
  20062. clickInfo.singleClick = true;
  20063. cb(clickInfo, _this._currentPickResult);
  20064. }
  20065. }
  20066. else {
  20067. // wait that no double click has been raised during the double click delay
  20068. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  20069. _this._delayedSimpleClickTimeout = window.setTimeout(_this._delayedSimpleClick.bind(_this, btn, clickInfo, cb), Scene.DoubleClickDelay);
  20070. }
  20071. var checkDoubleClick = obs1.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP) ||
  20072. obs2.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP);
  20073. if (!checkDoubleClick && BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  20074. act = _this._initActionManager(act, clickInfo);
  20075. if (act)
  20076. checkDoubleClick = act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  20077. }
  20078. if (checkDoubleClick) {
  20079. // two successive keys pressed are equal, double click delay is not over and double click has not just occurred
  20080. if (btn === _this._previousButtonPressed &&
  20081. new Date().getTime() - _this._previousStartingPointerTime < Scene.DoubleClickDelay &&
  20082. !_this._doubleClickOccured) {
  20083. // pointer has not moved for 2 clicks, it's a double click
  20084. if (!clickInfo.hasSwiped &&
  20085. Math.abs(_this._previousStartingPointerPosition.x - _this._startingPointerPosition.x) < Scene.DragMovementThreshold &&
  20086. Math.abs(_this._previousStartingPointerPosition.y - _this._startingPointerPosition.y) < Scene.DragMovementThreshold) {
  20087. _this._previousStartingPointerTime = 0;
  20088. _this._doubleClickOccured = true;
  20089. clickInfo.doubleClick = true;
  20090. clickInfo.ignore = false;
  20091. if (Scene.ExclusiveDoubleClickMode && _this._previousDelayedSimpleClickTimeout && _this._previousDelayedSimpleClickTimeout.clearTimeout)
  20092. _this._previousDelayedSimpleClickTimeout.clearTimeout();
  20093. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  20094. cb(clickInfo, _this._currentPickResult);
  20095. }
  20096. else {
  20097. _this._doubleClickOccured = false;
  20098. _this._previousStartingPointerTime = _this._startingPointerTime;
  20099. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  20100. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  20101. _this._previousButtonPressed = btn;
  20102. _this._previousHasSwiped = clickInfo.hasSwiped;
  20103. if (Scene.ExclusiveDoubleClickMode) {
  20104. if (_this._previousDelayedSimpleClickTimeout && _this._previousDelayedSimpleClickTimeout.clearTimeout) {
  20105. _this._previousDelayedSimpleClickTimeout.clearTimeout();
  20106. }
  20107. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  20108. cb(clickInfo, _this._previousPickResult);
  20109. }
  20110. else {
  20111. cb(clickInfo, _this._currentPickResult);
  20112. }
  20113. }
  20114. }
  20115. else {
  20116. _this._doubleClickOccured = false;
  20117. _this._previousStartingPointerTime = _this._startingPointerTime;
  20118. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  20119. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  20120. _this._previousButtonPressed = btn;
  20121. _this._previousHasSwiped = clickInfo.hasSwiped;
  20122. }
  20123. }
  20124. }
  20125. }
  20126. clickInfo.ignore = true;
  20127. cb(clickInfo, _this._currentPickResult);
  20128. };
  20129. var spritePredicate = function (sprite) {
  20130. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  20131. };
  20132. this._onPointerMove = function (evt) {
  20133. _this._updatePointerPosition(evt);
  20134. // PreObservable support
  20135. if (_this.onPrePointerObservable.hasObservers()) {
  20136. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? PointerEventTypes.POINTERWHEEL : PointerEventTypes.POINTERMOVE;
  20137. var pi = new PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  20138. _this.onPrePointerObservable.notifyObservers(pi, type);
  20139. if (pi.skipOnPointerObservable) {
  20140. return;
  20141. }
  20142. }
  20143. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  20144. return;
  20145. }
  20146. var canvas = _this._engine.getRenderingCanvas();
  20147. if (!_this.pointerMovePredicate) {
  20148. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && (_this.constantlyUpdateMeshUnderPointer || (mesh.actionManager !== null && mesh.actionManager !== undefined)); };
  20149. }
  20150. // Meshes
  20151. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  20152. if (pickResult.hit && pickResult.pickedMesh) {
  20153. _this.setPointerOverSprite(null);
  20154. _this.setPointerOverMesh(pickResult.pickedMesh);
  20155. if (_this._pointerOverMesh.actionManager && _this._pointerOverMesh.actionManager.hasPointerTriggers) {
  20156. if (_this._pointerOverMesh.actionManager.hoverCursor) {
  20157. canvas.style.cursor = _this._pointerOverMesh.actionManager.hoverCursor;
  20158. }
  20159. else {
  20160. canvas.style.cursor = _this.hoverCursor;
  20161. }
  20162. }
  20163. else {
  20164. canvas.style.cursor = "";
  20165. }
  20166. }
  20167. else {
  20168. _this.setPointerOverMesh(null);
  20169. // Sprites
  20170. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, spritePredicate, false, _this.cameraToUseForPointers);
  20171. if (pickResult.hit && pickResult.pickedSprite) {
  20172. _this.setPointerOverSprite(pickResult.pickedSprite);
  20173. if (_this._pointerOverSprite.actionManager && _this._pointerOverSprite.actionManager.hoverCursor) {
  20174. canvas.style.cursor = _this._pointerOverSprite.actionManager.hoverCursor;
  20175. }
  20176. else {
  20177. canvas.style.cursor = _this.hoverCursor;
  20178. }
  20179. }
  20180. else {
  20181. _this.setPointerOverSprite(null);
  20182. // Restore pointer
  20183. canvas.style.cursor = "";
  20184. }
  20185. }
  20186. if (_this.onPointerMove) {
  20187. _this.onPointerMove(evt, pickResult);
  20188. }
  20189. if (_this.onPointerObservable.hasObservers()) {
  20190. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? PointerEventTypes.POINTERWHEEL : PointerEventTypes.POINTERMOVE;
  20191. var pi = new PointerInfo(type, evt, pickResult);
  20192. _this.onPointerObservable.notifyObservers(pi, type);
  20193. }
  20194. };
  20195. this._onPointerDown = function (evt) {
  20196. _this._isButtonPressed = true;
  20197. _this._pickedDownMesh = null;
  20198. _this._meshPickProceed = false;
  20199. _this._updatePointerPosition(evt);
  20200. // PreObservable support
  20201. if (_this.onPrePointerObservable.hasObservers()) {
  20202. var type = PointerEventTypes.POINTERDOWN;
  20203. var pi = new PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  20204. _this.onPrePointerObservable.notifyObservers(pi, type);
  20205. if (pi.skipOnPointerObservable) {
  20206. return;
  20207. }
  20208. }
  20209. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  20210. return;
  20211. }
  20212. _this._startingPointerPosition.x = _this._pointerX;
  20213. _this._startingPointerPosition.y = _this._pointerY;
  20214. _this._startingPointerTime = new Date().getTime();
  20215. if (!_this.pointerDownPredicate) {
  20216. _this.pointerDownPredicate = function (mesh) {
  20217. return mesh.isPickable && mesh.isVisible && mesh.isReady();
  20218. };
  20219. }
  20220. // Meshes
  20221. _this._pickedDownMesh = null;
  20222. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  20223. if (pickResult.hit && pickResult.pickedMesh) {
  20224. _this._pickedDownMesh = pickResult.pickedMesh;
  20225. var actionManager = pickResult.pickedMesh.actionManager;
  20226. if (actionManager) {
  20227. if (actionManager.hasPickTriggers) {
  20228. actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  20229. switch (evt.button) {
  20230. case 0:
  20231. actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  20232. break;
  20233. case 1:
  20234. actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  20235. break;
  20236. case 2:
  20237. actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  20238. break;
  20239. }
  20240. }
  20241. if (actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  20242. window.setTimeout((function () {
  20243. var _this = this;
  20244. var pickResult = this.pick(this._unTranslatedPointerX, this._unTranslatedPointerY, function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.actionManager && mesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger) && mesh == _this._pickedDownMesh; }, false, this.cameraToUseForPointers);
  20245. if (pickResult.hit && pickResult.pickedMesh) {
  20246. if (this._isButtonPressed &&
  20247. ((new Date().getTime() - this._startingPointerTime) > Scene.LongPressDelay) &&
  20248. (Math.abs(this._startingPointerPosition.x - this._pointerX) < Scene.DragMovementThreshold &&
  20249. Math.abs(this._startingPointerPosition.y - this._pointerY) < Scene.DragMovementThreshold)) {
  20250. this._startingPointerTime = 0;
  20251. actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  20252. }
  20253. }
  20254. }).bind(_this), Scene.LongPressDelay);
  20255. }
  20256. }
  20257. }
  20258. if (_this.onPointerDown) {
  20259. _this.onPointerDown(evt, pickResult);
  20260. }
  20261. if (_this.onPointerObservable.hasObservers()) {
  20262. var type = PointerEventTypes.POINTERDOWN;
  20263. var pi = new PointerInfo(type, evt, pickResult);
  20264. _this.onPointerObservable.notifyObservers(pi, type);
  20265. }
  20266. // Sprites
  20267. _this._pickedDownSprite = null;
  20268. if (_this.spriteManagers.length > 0) {
  20269. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, spritePredicate, false, _this.cameraToUseForPointers);
  20270. if (pickResult.hit && pickResult.pickedSprite) {
  20271. if (pickResult.pickedSprite.actionManager) {
  20272. _this._pickedDownSprite = pickResult.pickedSprite;
  20273. switch (evt.button) {
  20274. case 0:
  20275. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  20276. break;
  20277. case 1:
  20278. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  20279. break;
  20280. case 2:
  20281. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  20282. break;
  20283. }
  20284. if (pickResult.pickedSprite.actionManager) {
  20285. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  20286. }
  20287. }
  20288. }
  20289. }
  20290. };
  20291. this._onPointerUp = function (evt) {
  20292. _this._isButtonPressed = false;
  20293. _this._pickedUpMesh = null;
  20294. _this._meshPickProceed = false;
  20295. _this._updatePointerPosition(evt);
  20296. _this._initClickEvent(_this.onPrePointerObservable, _this.onPointerObservable, evt, (function (clickInfo, pickResult) {
  20297. // PreObservable support
  20298. if (this.onPrePointerObservable.hasObservers()) {
  20299. if (!clickInfo.ignore) {
  20300. if (!clickInfo.hasSwiped) {
  20301. if (clickInfo.singleClick && this.onPrePointerObservable.hasSpecificMask(PointerEventTypes.POINTERTAP)) {
  20302. var type = PointerEventTypes.POINTERTAP;
  20303. var pi = new PointerInfoPre(type, evt, this._unTranslatedPointerX, this._unTranslatedPointerY);
  20304. this.onPrePointerObservable.notifyObservers(pi, type);
  20305. if (pi.skipOnPointerObservable) {
  20306. return;
  20307. }
  20308. }
  20309. if (clickInfo.doubleClick && this.onPrePointerObservable.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP)) {
  20310. var type = PointerEventTypes.POINTERDOUBLETAP;
  20311. var pi = new PointerInfoPre(type, evt, this._unTranslatedPointerX, this._unTranslatedPointerY);
  20312. this.onPrePointerObservable.notifyObservers(pi, type);
  20313. if (pi.skipOnPointerObservable) {
  20314. return;
  20315. }
  20316. }
  20317. }
  20318. }
  20319. else {
  20320. var type = PointerEventTypes.POINTERUP;
  20321. var pi = new PointerInfoPre(type, evt, this._unTranslatedPointerX, this._unTranslatedPointerY);
  20322. this.onPrePointerObservable.notifyObservers(pi, type);
  20323. if (pi.skipOnPointerObservable) {
  20324. return;
  20325. }
  20326. }
  20327. }
  20328. if (!this.cameraToUseForPointers && !this.activeCamera) {
  20329. return;
  20330. }
  20331. if (!this.pointerUpPredicate) {
  20332. this.pointerUpPredicate = function (mesh) {
  20333. return mesh.isPickable && mesh.isVisible && mesh.isReady();
  20334. };
  20335. }
  20336. // Meshes
  20337. if (!this._meshPickProceed && BABYLON.ActionManager.HasTriggers) {
  20338. this._initActionManager(null, clickInfo);
  20339. }
  20340. if (!pickResult) {
  20341. pickResult = this._currentPickResult;
  20342. }
  20343. if (pickResult && pickResult.pickedMesh) {
  20344. this._pickedUpMesh = pickResult.pickedMesh;
  20345. if (this._pickedDownMesh === this._pickedUpMesh) {
  20346. if (this.onPointerPick) {
  20347. this.onPointerPick(evt, pickResult);
  20348. }
  20349. if (clickInfo.singleClick && !clickInfo.ignore && this.onPointerObservable.hasObservers()) {
  20350. var type = PointerEventTypes.POINTERPICK;
  20351. var pi = new PointerInfo(type, evt, pickResult);
  20352. this.onPointerObservable.notifyObservers(pi, type);
  20353. }
  20354. }
  20355. if (pickResult.pickedMesh.actionManager) {
  20356. if (clickInfo.ignore) {
  20357. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  20358. }
  20359. if (!clickInfo.hasSwiped && !clickInfo.ignore && clickInfo.singleClick) {
  20360. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  20361. }
  20362. if (clickInfo.doubleClick && !clickInfo.ignore && pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  20363. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnDoublePickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  20364. }
  20365. }
  20366. }
  20367. if (this._pickedDownMesh &&
  20368. this._pickedDownMesh.actionManager &&
  20369. this._pickedDownMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickOutTrigger) &&
  20370. this._pickedDownMesh !== this._pickedUpMesh) {
  20371. this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(this._pickedDownMesh, evt));
  20372. }
  20373. if (this.onPointerUp) {
  20374. this.onPointerUp(evt, pickResult);
  20375. }
  20376. if (this.onPointerObservable.hasObservers()) {
  20377. if (!clickInfo.ignore) {
  20378. if (!clickInfo.hasSwiped) {
  20379. if (clickInfo.singleClick && this.onPointerObservable.hasSpecificMask(PointerEventTypes.POINTERTAP)) {
  20380. var type = PointerEventTypes.POINTERTAP;
  20381. var pi = new PointerInfo(type, evt, pickResult);
  20382. this.onPointerObservable.notifyObservers(pi, type);
  20383. }
  20384. if (clickInfo.doubleClick && this.onPointerObservable.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP)) {
  20385. var type = PointerEventTypes.POINTERDOUBLETAP;
  20386. var pi = new PointerInfo(type, evt, pickResult);
  20387. this.onPointerObservable.notifyObservers(pi, type);
  20388. }
  20389. }
  20390. }
  20391. else {
  20392. var type = PointerEventTypes.POINTERUP;
  20393. var pi = new PointerInfo(type, evt, pickResult);
  20394. this.onPointerObservable.notifyObservers(pi, type);
  20395. }
  20396. }
  20397. // Sprites
  20398. if (this.spriteManagers.length > 0) {
  20399. pickResult = this.pickSprite(this._unTranslatedPointerX, this._unTranslatedPointerY, spritePredicate, false, this.cameraToUseForPointers);
  20400. if (pickResult.hit && pickResult.pickedSprite) {
  20401. if (pickResult.pickedSprite.actionManager) {
  20402. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, this, evt));
  20403. if (pickResult.pickedSprite.actionManager) {
  20404. if (Math.abs(this._startingPointerPosition.x - this._pointerX) < Scene.DragMovementThreshold && Math.abs(this._startingPointerPosition.y - this._pointerY) < Scene.DragMovementThreshold) {
  20405. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, this, evt));
  20406. }
  20407. }
  20408. }
  20409. }
  20410. if (this._pickedDownSprite && this._pickedDownSprite.actionManager && this._pickedDownSprite !== pickResult.pickedSprite) {
  20411. this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pickedDownSprite, this, evt));
  20412. }
  20413. }
  20414. this._previousPickResult = this._currentPickResult;
  20415. }).bind(_this));
  20416. };
  20417. this._onKeyDown = function (evt) {
  20418. if (_this.actionManager) {
  20419. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  20420. }
  20421. };
  20422. this._onKeyUp = function (evt) {
  20423. if (_this.actionManager) {
  20424. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  20425. }
  20426. };
  20427. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  20428. var canvas = this._engine.getRenderingCanvas();
  20429. if (attachMove) {
  20430. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  20431. // Wheel
  20432. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  20433. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  20434. }
  20435. if (attachDown) {
  20436. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  20437. }
  20438. if (attachUp) {
  20439. canvas.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  20440. }
  20441. canvas.tabIndex = 1;
  20442. canvas.addEventListener("keydown", this._onKeyDown, false);
  20443. canvas.addEventListener("keyup", this._onKeyUp, false);
  20444. };
  20445. Scene.prototype.detachControl = function () {
  20446. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  20447. var canvas = this._engine.getRenderingCanvas();
  20448. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  20449. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  20450. canvas.removeEventListener(eventPrefix + "up", this._onPointerUp);
  20451. // Wheel
  20452. canvas.removeEventListener('mousewheel', this._onPointerMove);
  20453. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  20454. canvas.removeEventListener("keydown", this._onKeyDown);
  20455. canvas.removeEventListener("keyup", this._onKeyUp);
  20456. };
  20457. // Ready
  20458. Scene.prototype.isReady = function () {
  20459. if (this._pendingData.length > 0) {
  20460. return false;
  20461. }
  20462. var index;
  20463. for (index = 0; index < this._geometries.length; index++) {
  20464. var geometry = this._geometries[index];
  20465. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  20466. return false;
  20467. }
  20468. }
  20469. for (index = 0; index < this.meshes.length; index++) {
  20470. var mesh = this.meshes[index];
  20471. if (!mesh.isEnabled()) {
  20472. continue;
  20473. }
  20474. if (!mesh.isReady()) {
  20475. return false;
  20476. }
  20477. var mat = mesh.material;
  20478. if (mat) {
  20479. if (!mat.isReady(mesh)) {
  20480. return false;
  20481. }
  20482. }
  20483. }
  20484. return true;
  20485. };
  20486. Scene.prototype.resetCachedMaterial = function () {
  20487. this._cachedMaterial = null;
  20488. };
  20489. Scene.prototype.registerBeforeRender = function (func) {
  20490. this.onBeforeRenderObservable.add(func);
  20491. };
  20492. Scene.prototype.unregisterBeforeRender = function (func) {
  20493. this.onBeforeRenderObservable.removeCallback(func);
  20494. };
  20495. Scene.prototype.registerAfterRender = function (func) {
  20496. this.onAfterRenderObservable.add(func);
  20497. };
  20498. Scene.prototype.unregisterAfterRender = function (func) {
  20499. this.onAfterRenderObservable.removeCallback(func);
  20500. };
  20501. Scene.prototype._addPendingData = function (data) {
  20502. this._pendingData.push(data);
  20503. };
  20504. Scene.prototype._removePendingData = function (data) {
  20505. var index = this._pendingData.indexOf(data);
  20506. if (index !== -1) {
  20507. this._pendingData.splice(index, 1);
  20508. }
  20509. };
  20510. Scene.prototype.getWaitingItemsCount = function () {
  20511. return this._pendingData.length;
  20512. };
  20513. /**
  20514. * Registers a function to be executed when the scene is ready.
  20515. * @param {Function} func - the function to be executed.
  20516. */
  20517. Scene.prototype.executeWhenReady = function (func) {
  20518. var _this = this;
  20519. this.onReadyObservable.add(func);
  20520. if (this._executeWhenReadyTimeoutId !== -1) {
  20521. return;
  20522. }
  20523. this._executeWhenReadyTimeoutId = setTimeout(function () {
  20524. _this._checkIsReady();
  20525. }, 150);
  20526. };
  20527. Scene.prototype._checkIsReady = function () {
  20528. var _this = this;
  20529. if (this.isReady()) {
  20530. this.onReadyObservable.notifyObservers(this);
  20531. this.onReadyObservable.clear();
  20532. this._executeWhenReadyTimeoutId = -1;
  20533. return;
  20534. }
  20535. this._executeWhenReadyTimeoutId = setTimeout(function () {
  20536. _this._checkIsReady();
  20537. }, 150);
  20538. };
  20539. // Animations
  20540. /**
  20541. * Will start the animation sequence of a given target
  20542. * @param target - the target
  20543. * @param {number} from - from which frame should animation start
  20544. * @param {number} to - till which frame should animation run.
  20545. * @param {boolean} [loop] - should the animation loop
  20546. * @param {number} [speedRatio] - the speed in which to run the animation
  20547. * @param {Function} [onAnimationEnd] function to be executed when the animation ended.
  20548. * @param {BABYLON.Animatable} [animatable] an animatable object. If not provided a new one will be created from the given params.
  20549. * @return {BABYLON.Animatable} the animatable object created for this animation
  20550. * @see BABYLON.Animatable
  20551. * @see http://doc.babylonjs.com/page.php?p=22081
  20552. */
  20553. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  20554. if (speedRatio === void 0) { speedRatio = 1.0; }
  20555. this.stopAnimation(target);
  20556. if (!animatable) {
  20557. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  20558. }
  20559. // Local animations
  20560. if (target.animations) {
  20561. animatable.appendAnimations(target, target.animations);
  20562. }
  20563. // Children animations
  20564. if (target.getAnimatables) {
  20565. var animatables = target.getAnimatables();
  20566. for (var index = 0; index < animatables.length; index++) {
  20567. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  20568. }
  20569. }
  20570. animatable.reset();
  20571. return animatable;
  20572. };
  20573. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  20574. if (speedRatio === undefined) {
  20575. speedRatio = 1.0;
  20576. }
  20577. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  20578. return animatable;
  20579. };
  20580. Scene.prototype.getAnimatableByTarget = function (target) {
  20581. for (var index = 0; index < this._activeAnimatables.length; index++) {
  20582. if (this._activeAnimatables[index].target === target) {
  20583. return this._activeAnimatables[index];
  20584. }
  20585. }
  20586. return null;
  20587. };
  20588. Object.defineProperty(Scene.prototype, "Animatables", {
  20589. get: function () {
  20590. return this._activeAnimatables;
  20591. },
  20592. enumerable: true,
  20593. configurable: true
  20594. });
  20595. /**
  20596. * Will stop the animation of the given target
  20597. * @param target - the target
  20598. * @param animationName - the name of the animation to stop (all animations will be stopped is empty)
  20599. * @see beginAnimation
  20600. */
  20601. Scene.prototype.stopAnimation = function (target, animationName) {
  20602. var animatable = this.getAnimatableByTarget(target);
  20603. if (animatable) {
  20604. animatable.stop(animationName);
  20605. }
  20606. };
  20607. Scene.prototype._animate = function () {
  20608. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  20609. return;
  20610. }
  20611. // Getting time
  20612. var now = BABYLON.Tools.Now;
  20613. if (!this._animationTimeLast) {
  20614. if (this._pendingData.length > 0) {
  20615. return;
  20616. }
  20617. this._animationTimeLast = now;
  20618. }
  20619. var deltaTime = (now - this._animationTimeLast) * this.animationTimeScale;
  20620. this._animationTime += deltaTime;
  20621. this._animationTimeLast = now;
  20622. for (var index = 0; index < this._activeAnimatables.length; index++) {
  20623. this._activeAnimatables[index]._animate(this._animationTime);
  20624. }
  20625. };
  20626. // Matrix
  20627. Scene.prototype.getViewMatrix = function () {
  20628. return this._viewMatrix;
  20629. };
  20630. Scene.prototype.getProjectionMatrix = function () {
  20631. return this._projectionMatrix;
  20632. };
  20633. Scene.prototype.getTransformMatrix = function () {
  20634. return this._transformMatrix;
  20635. };
  20636. Scene.prototype.setTransformMatrix = function (view, projection) {
  20637. this._viewMatrix = view;
  20638. this._projectionMatrix = projection;
  20639. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  20640. // Update frustum
  20641. if (!this._frustumPlanes) {
  20642. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  20643. }
  20644. else {
  20645. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  20646. }
  20647. };
  20648. // Methods
  20649. Scene.prototype.addMesh = function (newMesh) {
  20650. newMesh.uniqueId = this._uniqueIdCounter++;
  20651. var position = this.meshes.push(newMesh);
  20652. //notify the collision coordinator
  20653. this.collisionCoordinator.onMeshAdded(newMesh);
  20654. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  20655. };
  20656. Scene.prototype.removeMesh = function (toRemove) {
  20657. var index = this.meshes.indexOf(toRemove);
  20658. if (index !== -1) {
  20659. // Remove from the scene if mesh found
  20660. this.meshes.splice(index, 1);
  20661. }
  20662. //notify the collision coordinator
  20663. this.collisionCoordinator.onMeshRemoved(toRemove);
  20664. this.onMeshRemovedObservable.notifyObservers(toRemove);
  20665. return index;
  20666. };
  20667. Scene.prototype.removeSkeleton = function (toRemove) {
  20668. var index = this.skeletons.indexOf(toRemove);
  20669. if (index !== -1) {
  20670. // Remove from the scene if mesh found
  20671. this.skeletons.splice(index, 1);
  20672. }
  20673. return index;
  20674. };
  20675. Scene.prototype.removeLight = function (toRemove) {
  20676. var index = this.lights.indexOf(toRemove);
  20677. if (index !== -1) {
  20678. // Remove from the scene if mesh found
  20679. this.lights.splice(index, 1);
  20680. }
  20681. this.onLightRemovedObservable.notifyObservers(toRemove);
  20682. return index;
  20683. };
  20684. Scene.prototype.removeCamera = function (toRemove) {
  20685. var index = this.cameras.indexOf(toRemove);
  20686. if (index !== -1) {
  20687. // Remove from the scene if mesh found
  20688. this.cameras.splice(index, 1);
  20689. }
  20690. // Remove from activeCameras
  20691. var index2 = this.activeCameras.indexOf(toRemove);
  20692. if (index2 !== -1) {
  20693. // Remove from the scene if mesh found
  20694. this.activeCameras.splice(index2, 1);
  20695. }
  20696. // Reset the activeCamera
  20697. if (this.activeCamera === toRemove) {
  20698. if (this.cameras.length > 0) {
  20699. this.activeCamera = this.cameras[0];
  20700. }
  20701. else {
  20702. this.activeCamera = null;
  20703. }
  20704. }
  20705. this.onCameraRemovedObservable.notifyObservers(toRemove);
  20706. return index;
  20707. };
  20708. Scene.prototype.addLight = function (newLight) {
  20709. newLight.uniqueId = this._uniqueIdCounter++;
  20710. var position = this.lights.push(newLight);
  20711. this.onNewLightAddedObservable.notifyObservers(newLight);
  20712. };
  20713. Scene.prototype.addCamera = function (newCamera) {
  20714. newCamera.uniqueId = this._uniqueIdCounter++;
  20715. var position = this.cameras.push(newCamera);
  20716. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  20717. };
  20718. /**
  20719. * Switch active camera
  20720. * @param {Camera} newCamera - new active camera
  20721. * @param {boolean} attachControl - call attachControl for the new active camera (default: true)
  20722. */
  20723. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  20724. if (attachControl === void 0) { attachControl = true; }
  20725. var canvas = this._engine.getRenderingCanvas();
  20726. this.activeCamera.detachControl(canvas);
  20727. this.activeCamera = newCamera;
  20728. if (attachControl) {
  20729. newCamera.attachControl(canvas);
  20730. }
  20731. };
  20732. /**
  20733. * sets the active camera of the scene using its ID
  20734. * @param {string} id - the camera's ID
  20735. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  20736. * @see activeCamera
  20737. */
  20738. Scene.prototype.setActiveCameraByID = function (id) {
  20739. var camera = this.getCameraByID(id);
  20740. if (camera) {
  20741. this.activeCamera = camera;
  20742. return camera;
  20743. }
  20744. return null;
  20745. };
  20746. /**
  20747. * sets the active camera of the scene using its name
  20748. * @param {string} name - the camera's name
  20749. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  20750. * @see activeCamera
  20751. */
  20752. Scene.prototype.setActiveCameraByName = function (name) {
  20753. var camera = this.getCameraByName(name);
  20754. if (camera) {
  20755. this.activeCamera = camera;
  20756. return camera;
  20757. }
  20758. return null;
  20759. };
  20760. /**
  20761. * get a material using its id
  20762. * @param {string} the material's ID
  20763. * @return {BABYLON.Material|null} the material or null if none found.
  20764. */
  20765. Scene.prototype.getMaterialByID = function (id) {
  20766. for (var index = 0; index < this.materials.length; index++) {
  20767. if (this.materials[index].id === id) {
  20768. return this.materials[index];
  20769. }
  20770. }
  20771. return null;
  20772. };
  20773. /**
  20774. * get a material using its name
  20775. * @param {string} the material's name
  20776. * @return {BABYLON.Material|null} the material or null if none found.
  20777. */
  20778. Scene.prototype.getMaterialByName = function (name) {
  20779. for (var index = 0; index < this.materials.length; index++) {
  20780. if (this.materials[index].name === name) {
  20781. return this.materials[index];
  20782. }
  20783. }
  20784. return null;
  20785. };
  20786. Scene.prototype.getLensFlareSystemByName = function (name) {
  20787. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  20788. if (this.lensFlareSystems[index].name === name) {
  20789. return this.lensFlareSystems[index];
  20790. }
  20791. }
  20792. return null;
  20793. };
  20794. Scene.prototype.getLensFlareSystemByID = function (id) {
  20795. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  20796. if (this.lensFlareSystems[index].id === id) {
  20797. return this.lensFlareSystems[index];
  20798. }
  20799. }
  20800. return null;
  20801. };
  20802. Scene.prototype.getCameraByID = function (id) {
  20803. for (var index = 0; index < this.cameras.length; index++) {
  20804. if (this.cameras[index].id === id) {
  20805. return this.cameras[index];
  20806. }
  20807. }
  20808. return null;
  20809. };
  20810. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  20811. for (var index = 0; index < this.cameras.length; index++) {
  20812. if (this.cameras[index].uniqueId === uniqueId) {
  20813. return this.cameras[index];
  20814. }
  20815. }
  20816. return null;
  20817. };
  20818. /**
  20819. * get a camera using its name
  20820. * @param {string} the camera's name
  20821. * @return {BABYLON.Camera|null} the camera or null if none found.
  20822. */
  20823. Scene.prototype.getCameraByName = function (name) {
  20824. for (var index = 0; index < this.cameras.length; index++) {
  20825. if (this.cameras[index].name === name) {
  20826. return this.cameras[index];
  20827. }
  20828. }
  20829. return null;
  20830. };
  20831. /**
  20832. * get a bone using its id
  20833. * @param {string} the bone's id
  20834. * @return {BABYLON.Bone|null} the bone or null if not found
  20835. */
  20836. Scene.prototype.getBoneByID = function (id) {
  20837. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  20838. var skeleton = this.skeletons[skeletonIndex];
  20839. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  20840. if (skeleton.bones[boneIndex].id === id) {
  20841. return skeleton.bones[boneIndex];
  20842. }
  20843. }
  20844. }
  20845. return null;
  20846. };
  20847. /**
  20848. * get a bone using its id
  20849. * @param {string} the bone's name
  20850. * @return {BABYLON.Bone|null} the bone or null if not found
  20851. */
  20852. Scene.prototype.getBoneByName = function (name) {
  20853. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  20854. var skeleton = this.skeletons[skeletonIndex];
  20855. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  20856. if (skeleton.bones[boneIndex].name === name) {
  20857. return skeleton.bones[boneIndex];
  20858. }
  20859. }
  20860. }
  20861. return null;
  20862. };
  20863. /**
  20864. * get a light node using its name
  20865. * @param {string} the light's name
  20866. * @return {BABYLON.Light|null} the light or null if none found.
  20867. */
  20868. Scene.prototype.getLightByName = function (name) {
  20869. for (var index = 0; index < this.lights.length; index++) {
  20870. if (this.lights[index].name === name) {
  20871. return this.lights[index];
  20872. }
  20873. }
  20874. return null;
  20875. };
  20876. /**
  20877. * get a light node using its ID
  20878. * @param {string} the light's id
  20879. * @return {BABYLON.Light|null} the light or null if none found.
  20880. */
  20881. Scene.prototype.getLightByID = function (id) {
  20882. for (var index = 0; index < this.lights.length; index++) {
  20883. if (this.lights[index].id === id) {
  20884. return this.lights[index];
  20885. }
  20886. }
  20887. return null;
  20888. };
  20889. /**
  20890. * get a light node using its scene-generated unique ID
  20891. * @param {number} the light's unique id
  20892. * @return {BABYLON.Light|null} the light or null if none found.
  20893. */
  20894. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  20895. for (var index = 0; index < this.lights.length; index++) {
  20896. if (this.lights[index].uniqueId === uniqueId) {
  20897. return this.lights[index];
  20898. }
  20899. }
  20900. return null;
  20901. };
  20902. /**
  20903. * get a particle system by id
  20904. * @param id {number} the particle system id
  20905. * @return {BABYLON.ParticleSystem|null} the corresponding system or null if none found.
  20906. */
  20907. Scene.prototype.getParticleSystemByID = function (id) {
  20908. for (var index = 0; index < this.particleSystems.length; index++) {
  20909. if (this.particleSystems[index].id === id) {
  20910. return this.particleSystems[index];
  20911. }
  20912. }
  20913. return null;
  20914. };
  20915. /**
  20916. * get a geometry using its ID
  20917. * @param {string} the geometry's id
  20918. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  20919. */
  20920. Scene.prototype.getGeometryByID = function (id) {
  20921. for (var index = 0; index < this._geometries.length; index++) {
  20922. if (this._geometries[index].id === id) {
  20923. return this._geometries[index];
  20924. }
  20925. }
  20926. return null;
  20927. };
  20928. /**
  20929. * add a new geometry to this scene.
  20930. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  20931. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  20932. * @return {boolean} was the geometry added or not
  20933. */
  20934. Scene.prototype.pushGeometry = function (geometry, force) {
  20935. if (!force && this.getGeometryByID(geometry.id)) {
  20936. return false;
  20937. }
  20938. this._geometries.push(geometry);
  20939. //notify the collision coordinator
  20940. this.collisionCoordinator.onGeometryAdded(geometry);
  20941. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  20942. return true;
  20943. };
  20944. /**
  20945. * Removes an existing geometry
  20946. * @param {BABYLON.Geometry} geometry - the geometry to be removed from the scene.
  20947. * @return {boolean} was the geometry removed or not
  20948. */
  20949. Scene.prototype.removeGeometry = function (geometry) {
  20950. var index = this._geometries.indexOf(geometry);
  20951. if (index > -1) {
  20952. this._geometries.splice(index, 1);
  20953. //notify the collision coordinator
  20954. this.collisionCoordinator.onGeometryDeleted(geometry);
  20955. this.onGeometryRemovedObservable.notifyObservers(geometry);
  20956. return true;
  20957. }
  20958. return false;
  20959. };
  20960. Scene.prototype.getGeometries = function () {
  20961. return this._geometries;
  20962. };
  20963. /**
  20964. * Get the first added mesh found of a given ID
  20965. * @param {string} id - the id to search for
  20966. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  20967. */
  20968. Scene.prototype.getMeshByID = function (id) {
  20969. for (var index = 0; index < this.meshes.length; index++) {
  20970. if (this.meshes[index].id === id) {
  20971. return this.meshes[index];
  20972. }
  20973. }
  20974. return null;
  20975. };
  20976. Scene.prototype.getMeshesByID = function (id) {
  20977. return this.meshes.filter(function (m) {
  20978. return m.id === id;
  20979. });
  20980. };
  20981. /**
  20982. * Get a mesh with its auto-generated unique id
  20983. * @param {number} uniqueId - the unique id to search for
  20984. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  20985. */
  20986. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  20987. for (var index = 0; index < this.meshes.length; index++) {
  20988. if (this.meshes[index].uniqueId === uniqueId) {
  20989. return this.meshes[index];
  20990. }
  20991. }
  20992. return null;
  20993. };
  20994. /**
  20995. * Get a the last added mesh found of a given ID
  20996. * @param {string} id - the id to search for
  20997. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  20998. */
  20999. Scene.prototype.getLastMeshByID = function (id) {
  21000. for (var index = this.meshes.length - 1; index >= 0; index--) {
  21001. if (this.meshes[index].id === id) {
  21002. return this.meshes[index];
  21003. }
  21004. }
  21005. return null;
  21006. };
  21007. /**
  21008. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  21009. * @param {string} id - the id to search for
  21010. * @return {BABYLON.Node|null} the node found or null if not found at all.
  21011. */
  21012. Scene.prototype.getLastEntryByID = function (id) {
  21013. var index;
  21014. for (index = this.meshes.length - 1; index >= 0; index--) {
  21015. if (this.meshes[index].id === id) {
  21016. return this.meshes[index];
  21017. }
  21018. }
  21019. for (index = this.cameras.length - 1; index >= 0; index--) {
  21020. if (this.cameras[index].id === id) {
  21021. return this.cameras[index];
  21022. }
  21023. }
  21024. for (index = this.lights.length - 1; index >= 0; index--) {
  21025. if (this.lights[index].id === id) {
  21026. return this.lights[index];
  21027. }
  21028. }
  21029. return null;
  21030. };
  21031. Scene.prototype.getNodeByID = function (id) {
  21032. var mesh = this.getMeshByID(id);
  21033. if (mesh) {
  21034. return mesh;
  21035. }
  21036. var light = this.getLightByID(id);
  21037. if (light) {
  21038. return light;
  21039. }
  21040. var camera = this.getCameraByID(id);
  21041. if (camera) {
  21042. return camera;
  21043. }
  21044. var bone = this.getBoneByID(id);
  21045. return bone;
  21046. };
  21047. Scene.prototype.getNodeByName = function (name) {
  21048. var mesh = this.getMeshByName(name);
  21049. if (mesh) {
  21050. return mesh;
  21051. }
  21052. var light = this.getLightByName(name);
  21053. if (light) {
  21054. return light;
  21055. }
  21056. var camera = this.getCameraByName(name);
  21057. if (camera) {
  21058. return camera;
  21059. }
  21060. var bone = this.getBoneByName(name);
  21061. return bone;
  21062. };
  21063. Scene.prototype.getMeshByName = function (name) {
  21064. for (var index = 0; index < this.meshes.length; index++) {
  21065. if (this.meshes[index].name === name) {
  21066. return this.meshes[index];
  21067. }
  21068. }
  21069. return null;
  21070. };
  21071. Scene.prototype.getSoundByName = function (name) {
  21072. var index;
  21073. if (BABYLON.AudioEngine) {
  21074. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  21075. if (this.mainSoundTrack.soundCollection[index].name === name) {
  21076. return this.mainSoundTrack.soundCollection[index];
  21077. }
  21078. }
  21079. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  21080. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  21081. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  21082. return this.soundTracks[sdIndex].soundCollection[index];
  21083. }
  21084. }
  21085. }
  21086. }
  21087. return null;
  21088. };
  21089. Scene.prototype.getLastSkeletonByID = function (id) {
  21090. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  21091. if (this.skeletons[index].id === id) {
  21092. return this.skeletons[index];
  21093. }
  21094. }
  21095. return null;
  21096. };
  21097. Scene.prototype.getSkeletonById = function (id) {
  21098. for (var index = 0; index < this.skeletons.length; index++) {
  21099. if (this.skeletons[index].id === id) {
  21100. return this.skeletons[index];
  21101. }
  21102. }
  21103. return null;
  21104. };
  21105. Scene.prototype.getSkeletonByName = function (name) {
  21106. for (var index = 0; index < this.skeletons.length; index++) {
  21107. if (this.skeletons[index].name === name) {
  21108. return this.skeletons[index];
  21109. }
  21110. }
  21111. return null;
  21112. };
  21113. Scene.prototype.isActiveMesh = function (mesh) {
  21114. return (this._activeMeshes.indexOf(mesh) !== -1);
  21115. };
  21116. /**
  21117. * Return a the first highlight layer of the scene with a given name.
  21118. * @param name The name of the highlight layer to look for.
  21119. * @return The highlight layer if found otherwise null.
  21120. */
  21121. Scene.prototype.getHighlightLayerByName = function (name) {
  21122. for (var index = 0; index < this.highlightLayers.length; index++) {
  21123. if (this.highlightLayers[index].name === name) {
  21124. return this.highlightLayers[index];
  21125. }
  21126. }
  21127. return null;
  21128. };
  21129. Object.defineProperty(Scene.prototype, "uid", {
  21130. /**
  21131. * Return a unique id as a string which can serve as an identifier for the scene
  21132. */
  21133. get: function () {
  21134. if (!this._uid) {
  21135. this._uid = BABYLON.Tools.RandomId();
  21136. }
  21137. return this._uid;
  21138. },
  21139. enumerable: true,
  21140. configurable: true
  21141. });
  21142. /**
  21143. * Add an externaly attached data from its key.
  21144. * This method call will fail and return false, if such key already exists.
  21145. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  21146. * @param key the unique key that identifies the data
  21147. * @param data the data object to associate to the key for this Engine instance
  21148. * @return true if no such key were already present and the data was added successfully, false otherwise
  21149. */
  21150. Scene.prototype.addExternalData = function (key, data) {
  21151. return this._externalData.add(key, data);
  21152. };
  21153. /**
  21154. * Get an externaly attached data from its key
  21155. * @param key the unique key that identifies the data
  21156. * @return the associated data, if present (can be null), or undefined if not present
  21157. */
  21158. Scene.prototype.getExternalData = function (key) {
  21159. return this._externalData.get(key);
  21160. };
  21161. /**
  21162. * Get an externaly attached data from its key, create it using a factory if it's not already present
  21163. * @param key the unique key that identifies the data
  21164. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  21165. * @return the associated data, can be null if the factory returned null.
  21166. */
  21167. Scene.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  21168. return this._externalData.getOrAddWithFactory(key, factory);
  21169. };
  21170. /**
  21171. * Remove an externaly attached data from the Engine instance
  21172. * @param key the unique key that identifies the data
  21173. * @return true if the data was successfully removed, false if it doesn't exist
  21174. */
  21175. Scene.prototype.removeExternalData = function (key) {
  21176. return this._externalData.remove(key);
  21177. };
  21178. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  21179. if (mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  21180. var material = subMesh.getMaterial();
  21181. if (mesh.showSubMeshesBoundingBox) {
  21182. this._boundingBoxRenderer.renderList.push(subMesh.getBoundingInfo().boundingBox);
  21183. }
  21184. if (material) {
  21185. // Render targets
  21186. if (material.getRenderTargetTextures) {
  21187. if (this._processedMaterials.indexOf(material) === -1) {
  21188. this._processedMaterials.push(material);
  21189. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  21190. }
  21191. }
  21192. // Dispatch
  21193. this._activeIndices.addCount(subMesh.indexCount, false);
  21194. this._renderingManager.dispatch(subMesh);
  21195. }
  21196. }
  21197. };
  21198. Scene.prototype._isInIntermediateRendering = function () {
  21199. return this._intermediateRendering;
  21200. };
  21201. Scene.prototype._evaluateActiveMeshes = function () {
  21202. this.activeCamera._activeMeshes.reset();
  21203. this._activeMeshes.reset();
  21204. this._renderingManager.reset();
  21205. this._processedMaterials.reset();
  21206. this._activeParticleSystems.reset();
  21207. this._activeSkeletons.reset();
  21208. this._softwareSkinnedMeshes.reset();
  21209. this._boundingBoxRenderer.reset();
  21210. this._edgesRenderers.reset();
  21211. // Meshes
  21212. var meshes;
  21213. var len;
  21214. if (this._selectionOctree) {
  21215. var selection = this._selectionOctree.select(this._frustumPlanes);
  21216. meshes = selection.data;
  21217. len = selection.length;
  21218. }
  21219. else {
  21220. len = this.meshes.length;
  21221. meshes = this.meshes;
  21222. }
  21223. for (var meshIndex = 0; meshIndex < len; meshIndex++) {
  21224. var mesh = meshes[meshIndex];
  21225. if (mesh.isBlocked) {
  21226. continue;
  21227. }
  21228. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  21229. if (!mesh.isReady() || !mesh.isEnabled()) {
  21230. continue;
  21231. }
  21232. mesh.computeWorldMatrix();
  21233. // Intersections
  21234. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  21235. this._meshesForIntersections.pushNoDuplicate(mesh);
  21236. }
  21237. // Switch to current LOD
  21238. var meshLOD = mesh.getLOD(this.activeCamera);
  21239. if (!meshLOD) {
  21240. continue;
  21241. }
  21242. mesh._preActivate();
  21243. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  21244. this._activeMeshes.push(mesh);
  21245. this.activeCamera._activeMeshes.push(mesh);
  21246. mesh._activate(this._renderId);
  21247. this._activeMesh(mesh, meshLOD);
  21248. }
  21249. }
  21250. // Particle systems
  21251. this._particlesDuration.beginMonitoring();
  21252. var beforeParticlesDate = BABYLON.Tools.Now;
  21253. if (this.particlesEnabled) {
  21254. BABYLON.Tools.StartPerformanceCounter("Particles", this.particleSystems.length > 0);
  21255. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  21256. var particleSystem = this.particleSystems[particleIndex];
  21257. if (!particleSystem.isStarted()) {
  21258. continue;
  21259. }
  21260. if (!particleSystem.emitter.position || (particleSystem.emitter && particleSystem.emitter.isEnabled())) {
  21261. this._activeParticleSystems.push(particleSystem);
  21262. particleSystem.animate();
  21263. this._renderingManager.dispatchParticles(particleSystem);
  21264. }
  21265. }
  21266. BABYLON.Tools.EndPerformanceCounter("Particles", this.particleSystems.length > 0);
  21267. }
  21268. this._particlesDuration.endMonitoring(false);
  21269. };
  21270. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  21271. if (mesh.skeleton && this.skeletonsEnabled) {
  21272. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  21273. mesh.skeleton.prepare();
  21274. }
  21275. if (!mesh.computeBonesUsingShaders) {
  21276. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  21277. }
  21278. }
  21279. if (sourceMesh.showBoundingBox || this.forceShowBoundingBoxes) {
  21280. this._boundingBoxRenderer.renderList.push(sourceMesh.getBoundingInfo().boundingBox);
  21281. }
  21282. if (sourceMesh._edgesRenderer) {
  21283. this._edgesRenderers.push(sourceMesh._edgesRenderer);
  21284. }
  21285. if (mesh && mesh.subMeshes) {
  21286. // Submeshes Octrees
  21287. var len;
  21288. var subMeshes;
  21289. if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) {
  21290. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  21291. len = intersections.length;
  21292. subMeshes = intersections.data;
  21293. }
  21294. else {
  21295. subMeshes = mesh.subMeshes;
  21296. len = subMeshes.length;
  21297. }
  21298. for (var subIndex = 0; subIndex < len; subIndex++) {
  21299. var subMesh = subMeshes[subIndex];
  21300. this._evaluateSubMesh(subMesh, mesh);
  21301. }
  21302. }
  21303. };
  21304. Scene.prototype.updateTransformMatrix = function (force) {
  21305. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  21306. };
  21307. Scene.prototype._renderForCamera = function (camera) {
  21308. var engine = this._engine;
  21309. var startTime = BABYLON.Tools.Now;
  21310. this.activeCamera = camera;
  21311. if (!this.activeCamera)
  21312. throw new Error("Active camera not set");
  21313. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  21314. // Viewport
  21315. engine.setViewport(this.activeCamera.viewport);
  21316. // Camera
  21317. this.resetCachedMaterial();
  21318. this._renderId++;
  21319. this.updateTransformMatrix();
  21320. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  21321. // Meshes
  21322. this._evaluateActiveMeshesDuration.beginMonitoring();
  21323. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  21324. this._evaluateActiveMeshes();
  21325. this._evaluateActiveMeshesDuration.endMonitoring(false);
  21326. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  21327. // Software skinning
  21328. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  21329. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  21330. mesh.applySkeleton(mesh.skeleton);
  21331. }
  21332. // Render targets
  21333. this._renderTargetsDuration.beginMonitoring();
  21334. var needsRestoreFrameBuffer = false;
  21335. var beforeRenderTargetDate = BABYLON.Tools.Now;
  21336. if (this.renderTargetsEnabled && this._renderTargets.length > 0) {
  21337. this._intermediateRendering = true;
  21338. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  21339. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  21340. var renderTarget = this._renderTargets.data[renderIndex];
  21341. if (renderTarget._shouldRender()) {
  21342. this._renderId++;
  21343. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  21344. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  21345. }
  21346. }
  21347. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  21348. this._intermediateRendering = false;
  21349. this._renderId++;
  21350. needsRestoreFrameBuffer = true; // Restore back buffer
  21351. }
  21352. // Render HighlightLayer Texture
  21353. var stencilState = this._engine.getStencilBuffer();
  21354. var renderhighlights = false;
  21355. if (this.renderTargetsEnabled && this.highlightLayers && this.highlightLayers.length > 0) {
  21356. this._intermediateRendering = true;
  21357. for (var i = 0; i < this.highlightLayers.length; i++) {
  21358. var highlightLayer = this.highlightLayers[i];
  21359. if (highlightLayer.shouldRender() &&
  21360. (!highlightLayer.camera ||
  21361. (highlightLayer.camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE && camera === highlightLayer.camera) ||
  21362. (highlightLayer.camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE && highlightLayer.camera._rigCameras.indexOf(camera) > -1))) {
  21363. renderhighlights = true;
  21364. var renderTarget = highlightLayer._mainTexture;
  21365. if (renderTarget._shouldRender()) {
  21366. this._renderId++;
  21367. renderTarget.render(false, false);
  21368. needsRestoreFrameBuffer = true;
  21369. }
  21370. }
  21371. }
  21372. this._intermediateRendering = false;
  21373. this._renderId++;
  21374. }
  21375. if (needsRestoreFrameBuffer) {
  21376. engine.restoreDefaultFramebuffer();
  21377. }
  21378. this._renderTargetsDuration.endMonitoring(false);
  21379. // Prepare Frame
  21380. this.postProcessManager._prepareFrame();
  21381. this._renderDuration.beginMonitoring();
  21382. // Backgrounds
  21383. var layerIndex;
  21384. var layer;
  21385. if (this.layers.length) {
  21386. engine.setDepthBuffer(false);
  21387. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  21388. layer = this.layers[layerIndex];
  21389. if (layer.isBackground) {
  21390. layer.render();
  21391. }
  21392. }
  21393. engine.setDepthBuffer(true);
  21394. }
  21395. // Render
  21396. BABYLON.Tools.StartPerformanceCounter("Main render");
  21397. // Activate HighlightLayer stencil
  21398. if (renderhighlights) {
  21399. this._engine.setStencilBuffer(true);
  21400. }
  21401. this._renderingManager.render(null, null, true, true);
  21402. // Restore HighlightLayer stencil
  21403. if (renderhighlights) {
  21404. this._engine.setStencilBuffer(stencilState);
  21405. }
  21406. BABYLON.Tools.EndPerformanceCounter("Main render");
  21407. // Bounding boxes
  21408. this._boundingBoxRenderer.render();
  21409. // Edges
  21410. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  21411. this._edgesRenderers.data[edgesRendererIndex].render();
  21412. }
  21413. // Lens flares
  21414. if (this.lensFlaresEnabled) {
  21415. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  21416. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  21417. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  21418. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  21419. lensFlareSystem.render();
  21420. }
  21421. }
  21422. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  21423. }
  21424. // Foregrounds
  21425. if (this.layers.length) {
  21426. engine.setDepthBuffer(false);
  21427. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  21428. layer = this.layers[layerIndex];
  21429. if (!layer.isBackground) {
  21430. layer.render();
  21431. }
  21432. }
  21433. engine.setDepthBuffer(true);
  21434. }
  21435. // Highlight Layer
  21436. if (renderhighlights) {
  21437. engine.setDepthBuffer(false);
  21438. for (var i = 0; i < this.highlightLayers.length; i++) {
  21439. if (this.highlightLayers[i].shouldRender()) {
  21440. this.highlightLayers[i].render();
  21441. }
  21442. }
  21443. engine.setDepthBuffer(true);
  21444. }
  21445. this._renderDuration.endMonitoring(false);
  21446. // Finalize frame
  21447. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  21448. // Update camera
  21449. this.activeCamera._updateFromScene();
  21450. // Reset some special arrays
  21451. this._renderTargets.reset();
  21452. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  21453. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  21454. };
  21455. Scene.prototype._processSubCameras = function (camera) {
  21456. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  21457. this._renderForCamera(camera);
  21458. return;
  21459. }
  21460. // rig cameras
  21461. for (var index = 0; index < camera._rigCameras.length; index++) {
  21462. this._renderForCamera(camera._rigCameras[index]);
  21463. }
  21464. this.activeCamera = camera;
  21465. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  21466. // Update camera
  21467. this.activeCamera._updateFromScene();
  21468. };
  21469. Scene.prototype._checkIntersections = function () {
  21470. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  21471. var sourceMesh = this._meshesForIntersections.data[index];
  21472. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  21473. var action = sourceMesh.actionManager.actions[actionIndex];
  21474. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  21475. var parameters = action.getTriggerParameter();
  21476. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  21477. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  21478. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  21479. if (areIntersecting && currentIntersectionInProgress === -1) {
  21480. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  21481. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  21482. sourceMesh._intersectionsInProgress.push(otherMesh);
  21483. }
  21484. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  21485. sourceMesh._intersectionsInProgress.push(otherMesh);
  21486. }
  21487. }
  21488. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  21489. //They intersected, and now they don't.
  21490. //is this trigger an exit trigger? execute an event.
  21491. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  21492. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  21493. }
  21494. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  21495. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  21496. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  21497. }
  21498. }
  21499. }
  21500. }
  21501. }
  21502. };
  21503. Scene.prototype.render = function () {
  21504. this._lastFrameDuration.beginMonitoring();
  21505. this._particlesDuration.fetchNewFrame();
  21506. this._spritesDuration.fetchNewFrame();
  21507. this._activeParticles.fetchNewFrame();
  21508. this._renderDuration.fetchNewFrame();
  21509. this._renderTargetsDuration.fetchNewFrame();
  21510. this._evaluateActiveMeshesDuration.fetchNewFrame();
  21511. this._totalVertices.fetchNewFrame();
  21512. this._activeIndices.fetchNewFrame();
  21513. this._activeBones.fetchNewFrame();
  21514. this.getEngine().drawCallsPerfCounter.fetchNewFrame();
  21515. this._meshesForIntersections.reset();
  21516. this.resetCachedMaterial();
  21517. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  21518. // Actions
  21519. if (this.actionManager) {
  21520. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger, null);
  21521. }
  21522. //Simplification Queue
  21523. if (this.simplificationQueue && !this.simplificationQueue.running) {
  21524. this.simplificationQueue.executeNext();
  21525. }
  21526. // Animations
  21527. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  21528. this._animationRatio = deltaTime * (60.0 / 1000.0);
  21529. this._animate();
  21530. // Physics
  21531. if (this._physicsEngine) {
  21532. BABYLON.Tools.StartPerformanceCounter("Physics");
  21533. this._physicsEngine._step(deltaTime / 1000.0);
  21534. BABYLON.Tools.EndPerformanceCounter("Physics");
  21535. }
  21536. // Before render
  21537. this.onBeforeRenderObservable.notifyObservers(this);
  21538. // Customs render targets
  21539. this._renderTargetsDuration.beginMonitoring();
  21540. var beforeRenderTargetDate = BABYLON.Tools.Now;
  21541. var engine = this.getEngine();
  21542. var currentActiveCamera = this.activeCamera;
  21543. if (this.renderTargetsEnabled) {
  21544. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  21545. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  21546. var renderTarget = this.customRenderTargets[customIndex];
  21547. if (renderTarget._shouldRender()) {
  21548. this._renderId++;
  21549. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  21550. if (!this.activeCamera)
  21551. throw new Error("Active camera not set");
  21552. // Viewport
  21553. engine.setViewport(this.activeCamera.viewport);
  21554. // Camera
  21555. this.updateTransformMatrix();
  21556. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  21557. }
  21558. }
  21559. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  21560. this._renderId++;
  21561. }
  21562. if (this.customRenderTargets.length > 0) {
  21563. engine.restoreDefaultFramebuffer();
  21564. }
  21565. this._renderTargetsDuration.endMonitoring();
  21566. this.activeCamera = currentActiveCamera;
  21567. // Procedural textures
  21568. if (this.proceduralTexturesEnabled) {
  21569. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  21570. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  21571. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  21572. if (proceduralTexture._shouldRender()) {
  21573. proceduralTexture.render();
  21574. }
  21575. }
  21576. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  21577. }
  21578. // Clear
  21579. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, true, true);
  21580. // Shadows
  21581. if (this.shadowsEnabled) {
  21582. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  21583. var light = this.lights[lightIndex];
  21584. var shadowGenerator = light.getShadowGenerator();
  21585. if (light.isEnabled() && shadowGenerator && shadowGenerator.getShadowMap().getScene().textures.indexOf(shadowGenerator.getShadowMap()) !== -1) {
  21586. this._renderTargets.push(shadowGenerator.getShadowMap());
  21587. }
  21588. }
  21589. }
  21590. // Depth renderer
  21591. if (this._depthRenderer) {
  21592. this._renderTargets.push(this._depthRenderer.getDepthMap());
  21593. }
  21594. // RenderPipeline
  21595. this.postProcessRenderPipelineManager.update();
  21596. // Multi-cameras?
  21597. if (this.activeCameras.length > 0) {
  21598. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  21599. if (cameraIndex > 0) {
  21600. this._engine.clear(null, false, true, true);
  21601. }
  21602. this._processSubCameras(this.activeCameras[cameraIndex]);
  21603. }
  21604. }
  21605. else {
  21606. if (!this.activeCamera) {
  21607. throw new Error("No camera defined");
  21608. }
  21609. this._processSubCameras(this.activeCamera);
  21610. }
  21611. // Intersection checks
  21612. this._checkIntersections();
  21613. // Update the audio listener attached to the camera
  21614. if (BABYLON.AudioEngine) {
  21615. this._updateAudioParameters();
  21616. }
  21617. // After render
  21618. if (this.afterRender) {
  21619. this.afterRender();
  21620. }
  21621. this.onAfterRenderObservable.notifyObservers(this);
  21622. // Cleaning
  21623. for (var index = 0; index < this._toBeDisposed.length; index++) {
  21624. this._toBeDisposed.data[index].dispose();
  21625. this._toBeDisposed[index] = null;
  21626. }
  21627. this._toBeDisposed.reset();
  21628. if (this.dumpNextRenderTargets) {
  21629. this.dumpNextRenderTargets = false;
  21630. }
  21631. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  21632. this._lastFrameDuration.endMonitoring();
  21633. this._totalMeshesCounter.addCount(this.meshes.length, true);
  21634. this._totalLightsCounter.addCount(this.lights.length, true);
  21635. this._totalMaterialsCounter.addCount(this.materials.length, true);
  21636. this._totalTexturesCounter.addCount(this.textures.length, true);
  21637. this._activeBones.addCount(0, true);
  21638. this._activeIndices.addCount(0, true);
  21639. this._activeParticles.addCount(0, true);
  21640. };
  21641. Scene.prototype._updateAudioParameters = function () {
  21642. if (!this.audioEnabled || (this.mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  21643. return;
  21644. }
  21645. var listeningCamera;
  21646. var audioEngine = BABYLON.Engine.audioEngine;
  21647. if (this.activeCameras.length > 0) {
  21648. listeningCamera = this.activeCameras[0];
  21649. }
  21650. else {
  21651. listeningCamera = this.activeCamera;
  21652. }
  21653. if (listeningCamera && audioEngine.canUseWebAudio) {
  21654. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  21655. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  21656. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  21657. cameraDirection.normalize();
  21658. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  21659. var i;
  21660. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  21661. var sound = this.mainSoundTrack.soundCollection[i];
  21662. if (sound.useCustomAttenuation) {
  21663. sound.updateDistanceFromListener();
  21664. }
  21665. }
  21666. for (i = 0; i < this.soundTracks.length; i++) {
  21667. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  21668. sound = this.soundTracks[i].soundCollection[j];
  21669. if (sound.useCustomAttenuation) {
  21670. sound.updateDistanceFromListener();
  21671. }
  21672. }
  21673. }
  21674. }
  21675. };
  21676. Object.defineProperty(Scene.prototype, "audioEnabled", {
  21677. // Audio
  21678. get: function () {
  21679. return this._audioEnabled;
  21680. },
  21681. set: function (value) {
  21682. this._audioEnabled = value;
  21683. if (BABYLON.AudioEngine) {
  21684. if (this._audioEnabled) {
  21685. this._enableAudio();
  21686. }
  21687. else {
  21688. this._disableAudio();
  21689. }
  21690. }
  21691. },
  21692. enumerable: true,
  21693. configurable: true
  21694. });
  21695. Scene.prototype._disableAudio = function () {
  21696. var i;
  21697. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  21698. this.mainSoundTrack.soundCollection[i].pause();
  21699. }
  21700. for (i = 0; i < this.soundTracks.length; i++) {
  21701. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  21702. this.soundTracks[i].soundCollection[j].pause();
  21703. }
  21704. }
  21705. };
  21706. Scene.prototype._enableAudio = function () {
  21707. var i;
  21708. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  21709. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  21710. this.mainSoundTrack.soundCollection[i].play();
  21711. }
  21712. }
  21713. for (i = 0; i < this.soundTracks.length; i++) {
  21714. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  21715. if (this.soundTracks[i].soundCollection[j].isPaused) {
  21716. this.soundTracks[i].soundCollection[j].play();
  21717. }
  21718. }
  21719. }
  21720. };
  21721. Object.defineProperty(Scene.prototype, "headphone", {
  21722. get: function () {
  21723. return this._headphone;
  21724. },
  21725. set: function (value) {
  21726. this._headphone = value;
  21727. if (BABYLON.AudioEngine) {
  21728. if (this._headphone) {
  21729. this._switchAudioModeForHeadphones();
  21730. }
  21731. else {
  21732. this._switchAudioModeForNormalSpeakers();
  21733. }
  21734. }
  21735. },
  21736. enumerable: true,
  21737. configurable: true
  21738. });
  21739. Scene.prototype._switchAudioModeForHeadphones = function () {
  21740. this.mainSoundTrack.switchPanningModelToHRTF();
  21741. for (var i = 0; i < this.soundTracks.length; i++) {
  21742. this.soundTracks[i].switchPanningModelToHRTF();
  21743. }
  21744. };
  21745. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  21746. this.mainSoundTrack.switchPanningModelToEqualPower();
  21747. for (var i = 0; i < this.soundTracks.length; i++) {
  21748. this.soundTracks[i].switchPanningModelToEqualPower();
  21749. }
  21750. };
  21751. Scene.prototype.enableDepthRenderer = function () {
  21752. if (this._depthRenderer) {
  21753. return this._depthRenderer;
  21754. }
  21755. this._depthRenderer = new BABYLON.DepthRenderer(this);
  21756. return this._depthRenderer;
  21757. };
  21758. Scene.prototype.disableDepthRenderer = function () {
  21759. if (!this._depthRenderer) {
  21760. return;
  21761. }
  21762. this._depthRenderer.dispose();
  21763. this._depthRenderer = null;
  21764. };
  21765. Scene.prototype.freezeMaterials = function () {
  21766. for (var i = 0; i < this.materials.length; i++) {
  21767. this.materials[i].freeze();
  21768. }
  21769. };
  21770. Scene.prototype.unfreezeMaterials = function () {
  21771. for (var i = 0; i < this.materials.length; i++) {
  21772. this.materials[i].unfreeze();
  21773. }
  21774. };
  21775. Scene.prototype.dispose = function () {
  21776. this.beforeRender = null;
  21777. this.afterRender = null;
  21778. this.skeletons = [];
  21779. this._boundingBoxRenderer.dispose();
  21780. if (this._depthRenderer) {
  21781. this._depthRenderer.dispose();
  21782. }
  21783. // Smart arrays
  21784. if (this.activeCamera) {
  21785. this.activeCamera._activeMeshes.dispose();
  21786. this.activeCamera = null;
  21787. }
  21788. this._activeMeshes.dispose();
  21789. this._renderingManager.dispose();
  21790. this._processedMaterials.dispose();
  21791. this._activeParticleSystems.dispose();
  21792. this._activeSkeletons.dispose();
  21793. this._softwareSkinnedMeshes.dispose();
  21794. this._boundingBoxRenderer.dispose();
  21795. this._edgesRenderers.dispose();
  21796. this._meshesForIntersections.dispose();
  21797. this._toBeDisposed.dispose();
  21798. // Debug layer
  21799. if (this._debugLayer) {
  21800. this._debugLayer.hide();
  21801. }
  21802. // Events
  21803. this.onDisposeObservable.notifyObservers(this);
  21804. this.onDisposeObservable.clear();
  21805. this.onBeforeRenderObservable.clear();
  21806. this.onAfterRenderObservable.clear();
  21807. this.detachControl();
  21808. // Release sounds & sounds tracks
  21809. if (BABYLON.AudioEngine) {
  21810. this.disposeSounds();
  21811. }
  21812. // Detach cameras
  21813. var canvas = this._engine.getRenderingCanvas();
  21814. var index;
  21815. for (index = 0; index < this.cameras.length; index++) {
  21816. this.cameras[index].detachControl(canvas);
  21817. }
  21818. // Release lights
  21819. while (this.lights.length) {
  21820. this.lights[0].dispose();
  21821. }
  21822. // Release meshes
  21823. while (this.meshes.length) {
  21824. this.meshes[0].dispose(true);
  21825. }
  21826. // Release cameras
  21827. while (this.cameras.length) {
  21828. this.cameras[0].dispose();
  21829. }
  21830. // Release materials
  21831. while (this.materials.length) {
  21832. this.materials[0].dispose();
  21833. }
  21834. // Release particles
  21835. while (this.particleSystems.length) {
  21836. this.particleSystems[0].dispose();
  21837. }
  21838. // Release sprites
  21839. while (this.spriteManagers.length) {
  21840. this.spriteManagers[0].dispose();
  21841. }
  21842. // Release layers
  21843. while (this.layers.length) {
  21844. this.layers[0].dispose();
  21845. }
  21846. while (this.highlightLayers.length) {
  21847. this.highlightLayers[0].dispose();
  21848. }
  21849. // Release textures
  21850. while (this.textures.length) {
  21851. this.textures[0].dispose();
  21852. }
  21853. // Post-processes
  21854. this.postProcessManager.dispose();
  21855. // Physics
  21856. if (this._physicsEngine) {
  21857. this.disablePhysicsEngine();
  21858. }
  21859. // Remove from engine
  21860. index = this._engine.scenes.indexOf(this);
  21861. if (index > -1) {
  21862. this._engine.scenes.splice(index, 1);
  21863. }
  21864. this._engine.wipeCaches();
  21865. };
  21866. // Release sounds & sounds tracks
  21867. Scene.prototype.disposeSounds = function () {
  21868. this.mainSoundTrack.dispose();
  21869. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  21870. this.soundTracks[scIndex].dispose();
  21871. }
  21872. };
  21873. // Octrees
  21874. Scene.prototype.getWorldExtends = function () {
  21875. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  21876. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  21877. for (var index = 0; index < this.meshes.length; index++) {
  21878. var mesh = this.meshes[index];
  21879. mesh.computeWorldMatrix(true);
  21880. var minBox = mesh.getBoundingInfo().boundingBox.minimumWorld;
  21881. var maxBox = mesh.getBoundingInfo().boundingBox.maximumWorld;
  21882. BABYLON.Tools.CheckExtends(minBox, min, max);
  21883. BABYLON.Tools.CheckExtends(maxBox, min, max);
  21884. }
  21885. return {
  21886. min: min,
  21887. max: max
  21888. };
  21889. };
  21890. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  21891. if (maxCapacity === void 0) { maxCapacity = 64; }
  21892. if (maxDepth === void 0) { maxDepth = 2; }
  21893. if (!this._selectionOctree) {
  21894. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  21895. }
  21896. var worldExtends = this.getWorldExtends();
  21897. // Update octree
  21898. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  21899. return this._selectionOctree;
  21900. };
  21901. // Picking
  21902. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  21903. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  21904. var engine = this._engine;
  21905. if (!camera) {
  21906. if (!this.activeCamera)
  21907. throw new Error("Active camera not set");
  21908. camera = this.activeCamera;
  21909. }
  21910. var cameraViewport = camera.viewport;
  21911. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  21912. // Moving coordinates to local viewport world
  21913. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  21914. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  21915. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  21916. // return BABYLON.Ray.CreateNew(x / window.devicePixelRatio, y / window.devicePixelRatio, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  21917. };
  21918. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  21919. var engine = this._engine;
  21920. if (!camera) {
  21921. if (!this.activeCamera)
  21922. throw new Error("Active camera not set");
  21923. camera = this.activeCamera;
  21924. }
  21925. var cameraViewport = camera.viewport;
  21926. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  21927. var identity = BABYLON.Matrix.Identity();
  21928. // Moving coordinates to local viewport world
  21929. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  21930. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  21931. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  21932. };
  21933. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  21934. var pickingInfo = null;
  21935. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  21936. var mesh = this.meshes[meshIndex];
  21937. if (predicate) {
  21938. if (!predicate(mesh)) {
  21939. continue;
  21940. }
  21941. }
  21942. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  21943. continue;
  21944. }
  21945. var world = mesh.getWorldMatrix();
  21946. var ray = rayFunction(world);
  21947. var result = mesh.intersects(ray, fastCheck);
  21948. if (!result || !result.hit)
  21949. continue;
  21950. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  21951. continue;
  21952. pickingInfo = result;
  21953. if (fastCheck) {
  21954. break;
  21955. }
  21956. }
  21957. return pickingInfo || new BABYLON.PickingInfo();
  21958. };
  21959. Scene.prototype._internalMultiPick = function (rayFunction, predicate) {
  21960. var pickingInfos = new Array();
  21961. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  21962. var mesh = this.meshes[meshIndex];
  21963. if (predicate) {
  21964. if (!predicate(mesh)) {
  21965. continue;
  21966. }
  21967. }
  21968. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  21969. continue;
  21970. }
  21971. var world = mesh.getWorldMatrix();
  21972. var ray = rayFunction(world);
  21973. var result = mesh.intersects(ray, false);
  21974. if (!result || !result.hit)
  21975. continue;
  21976. pickingInfos.push(result);
  21977. }
  21978. return pickingInfos;
  21979. };
  21980. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  21981. var pickingInfo = null;
  21982. camera = camera || this.activeCamera;
  21983. if (this.spriteManagers.length > 0) {
  21984. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  21985. var spriteManager = this.spriteManagers[spriteIndex];
  21986. if (!spriteManager.isPickable) {
  21987. continue;
  21988. }
  21989. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  21990. if (!result || !result.hit)
  21991. continue;
  21992. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  21993. continue;
  21994. pickingInfo = result;
  21995. if (fastCheck) {
  21996. break;
  21997. }
  21998. }
  21999. }
  22000. return pickingInfo || new BABYLON.PickingInfo();
  22001. };
  22002. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  22003. /// <param name="x">X position on screen</param>
  22004. /// <param name="y">Y position on screen</param>
  22005. /// <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>
  22006. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  22007. /// <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>
  22008. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  22009. var _this = this;
  22010. return this._internalPick(function (world) { return _this.createPickingRay(x, y, world, camera); }, predicate, fastCheck);
  22011. };
  22012. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  22013. /// <param name="x">X position on screen</param>
  22014. /// <param name="y">Y position on screen</param>
  22015. /// <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>
  22016. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  22017. /// <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>
  22018. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  22019. return this._internalPickSprites(this.createPickingRayInCameraSpace(x, y, camera), predicate, fastCheck, camera);
  22020. };
  22021. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  22022. var _this = this;
  22023. return this._internalPick(function (world) {
  22024. if (!_this._pickWithRayInverseMatrix) {
  22025. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  22026. }
  22027. world.invertToRef(_this._pickWithRayInverseMatrix);
  22028. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  22029. }, predicate, fastCheck);
  22030. };
  22031. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  22032. /// <param name="x">X position on screen</param>
  22033. /// <param name="y">Y position on screen</param>
  22034. /// <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>
  22035. /// <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>
  22036. Scene.prototype.multiPick = function (x, y, predicate, camera) {
  22037. var _this = this;
  22038. return this._internalMultiPick(function (world) { return _this.createPickingRay(x, y, world, camera); }, predicate);
  22039. };
  22040. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  22041. /// <param name="ray">Ray to use</param>
  22042. /// <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>
  22043. Scene.prototype.multiPickWithRay = function (ray, predicate) {
  22044. var _this = this;
  22045. return this._internalMultiPick(function (world) {
  22046. if (!_this._pickWithRayInverseMatrix) {
  22047. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  22048. }
  22049. world.invertToRef(_this._pickWithRayInverseMatrix);
  22050. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  22051. }, predicate);
  22052. };
  22053. Scene.prototype.setPointerOverMesh = function (mesh) {
  22054. if (this._pointerOverMesh === mesh) {
  22055. return;
  22056. }
  22057. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  22058. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  22059. }
  22060. this._pointerOverMesh = mesh;
  22061. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  22062. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  22063. }
  22064. };
  22065. Scene.prototype.getPointerOverMesh = function () {
  22066. return this._pointerOverMesh;
  22067. };
  22068. Scene.prototype.setPointerOverSprite = function (sprite) {
  22069. if (this._pointerOverSprite === sprite) {
  22070. return;
  22071. }
  22072. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  22073. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  22074. }
  22075. this._pointerOverSprite = sprite;
  22076. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  22077. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  22078. }
  22079. };
  22080. Scene.prototype.getPointerOverSprite = function () {
  22081. return this._pointerOverSprite;
  22082. };
  22083. // Physics
  22084. Scene.prototype.getPhysicsEngine = function () {
  22085. return this._physicsEngine;
  22086. };
  22087. /**
  22088. * Enables physics to the current scene
  22089. * @param {BABYLON.Vector3} [gravity] - the scene's gravity for the physics engine
  22090. * @param {BABYLON.IPhysicsEnginePlugin} [plugin] - The physics engine to be used. defaults to OimoJS.
  22091. * @return {boolean} was the physics engine initialized
  22092. */
  22093. Scene.prototype.enablePhysics = function (gravity, plugin) {
  22094. if (this._physicsEngine) {
  22095. return true;
  22096. }
  22097. try {
  22098. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  22099. return true;
  22100. }
  22101. catch (e) {
  22102. BABYLON.Tools.Error(e.message);
  22103. return false;
  22104. }
  22105. };
  22106. Scene.prototype.disablePhysicsEngine = function () {
  22107. if (!this._physicsEngine) {
  22108. return;
  22109. }
  22110. this._physicsEngine.dispose();
  22111. this._physicsEngine = undefined;
  22112. };
  22113. Scene.prototype.isPhysicsEnabled = function () {
  22114. return this._physicsEngine !== undefined;
  22115. };
  22116. Scene.prototype.deleteCompoundImpostor = function (compound) {
  22117. var mesh = compound.parts[0].mesh;
  22118. mesh.physicsImpostor.dispose();
  22119. mesh.physicsImpostor = null;
  22120. };
  22121. // Misc.
  22122. Scene.prototype.createDefaultCameraOrLight = function (createArcRotateCamera) {
  22123. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  22124. // Light
  22125. if (this.lights.length === 0) {
  22126. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  22127. }
  22128. // Camera
  22129. if (!this.activeCamera) {
  22130. // Compute position
  22131. var worldExtends = this.getWorldExtends();
  22132. var worldCenter = worldExtends.min.add(worldExtends.max.subtract(worldExtends.min).scale(0.5));
  22133. var camera;
  22134. if (createArcRotateCamera) {
  22135. camera = new BABYLON.ArcRotateCamera("default camera", 0, 0, 10, BABYLON.Vector3.Zero(), this);
  22136. camera.setPosition(new BABYLON.Vector3(worldCenter.x, worldCenter.y, worldExtends.min.z - (worldExtends.max.z - worldExtends.min.z)));
  22137. camera.setTarget(worldCenter);
  22138. }
  22139. else {
  22140. camera = new BABYLON.FreeCamera("default camera", BABYLON.Vector3.Zero(), this);
  22141. camera.position = new BABYLON.Vector3(worldCenter.x, worldCenter.y, worldExtends.min.z - (worldExtends.max.z - worldExtends.min.z));
  22142. camera.setTarget(worldCenter);
  22143. }
  22144. this.activeCamera = camera;
  22145. }
  22146. };
  22147. // Tags
  22148. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  22149. if (tagsQuery === undefined) {
  22150. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  22151. return list;
  22152. }
  22153. var listByTags = [];
  22154. forEach = forEach || (function (item) { return; });
  22155. for (var i in list) {
  22156. var item = list[i];
  22157. if (BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  22158. listByTags.push(item);
  22159. forEach(item);
  22160. }
  22161. }
  22162. return listByTags;
  22163. };
  22164. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  22165. return this._getByTags(this.meshes, tagsQuery, forEach);
  22166. };
  22167. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  22168. return this._getByTags(this.cameras, tagsQuery, forEach);
  22169. };
  22170. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  22171. return this._getByTags(this.lights, tagsQuery, forEach);
  22172. };
  22173. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  22174. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  22175. };
  22176. /**
  22177. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  22178. * This allowed control for front to back rendering or reversly depending of the special needs.
  22179. *
  22180. * @param renderingGroupId The rendering group id corresponding to its index
  22181. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  22182. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  22183. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  22184. */
  22185. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  22186. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  22187. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  22188. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  22189. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  22190. };
  22191. /**
  22192. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  22193. *
  22194. * @param renderingGroupId The rendering group id corresponding to its index
  22195. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  22196. * @param depth Automatically clears depth between groups if true and autoClear is true.
  22197. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  22198. */
  22199. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  22200. if (depth === void 0) { depth = true; }
  22201. if (stencil === void 0) { stencil = true; }
  22202. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
  22203. };
  22204. return Scene;
  22205. }());
  22206. // Statics
  22207. Scene._FOGMODE_NONE = 0;
  22208. Scene._FOGMODE_EXP = 1;
  22209. Scene._FOGMODE_EXP2 = 2;
  22210. Scene._FOGMODE_LINEAR = 3;
  22211. Scene.MinDeltaTime = 1.0;
  22212. Scene.MaxDeltaTime = 1000.0;
  22213. Scene.DragMovementThreshold = 10; // in pixels
  22214. Scene.LongPressDelay = 500; // in milliseconds
  22215. Scene.DoubleClickDelay = 300; // in milliseconds
  22216. Scene.ExclusiveDoubleClickMode = false; // If you need to check double click without raising a single click at first click, enable this flag
  22217. BABYLON.Scene = Scene;
  22218. })(BABYLON || (BABYLON = {}));
  22219. //# sourceMappingURL=babylon.scene.js.map
  22220. var BABYLON;
  22221. (function (BABYLON) {
  22222. var Buffer = (function () {
  22223. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced) {
  22224. if (engine instanceof BABYLON.Mesh) {
  22225. this._engine = engine.getScene().getEngine();
  22226. }
  22227. else {
  22228. this._engine = engine;
  22229. }
  22230. this._updatable = updatable;
  22231. this._data = data;
  22232. this._strideSize = stride;
  22233. if (!postponeInternalCreation) {
  22234. this.create();
  22235. }
  22236. this._instanced = instanced;
  22237. }
  22238. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride) {
  22239. // a lot of these parameters are ignored as they are overriden by the buffer
  22240. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, stride ? stride : this._strideSize, this._instanced, offset, size);
  22241. };
  22242. // Properties
  22243. Buffer.prototype.isUpdatable = function () {
  22244. return this._updatable;
  22245. };
  22246. Buffer.prototype.getData = function () {
  22247. return this._data;
  22248. };
  22249. Buffer.prototype.getBuffer = function () {
  22250. return this._buffer;
  22251. };
  22252. Buffer.prototype.getStrideSize = function () {
  22253. return this._strideSize;
  22254. };
  22255. Buffer.prototype.getIsInstanced = function () {
  22256. return this._instanced;
  22257. };
  22258. // Methods
  22259. Buffer.prototype.create = function (data) {
  22260. if (!data && this._buffer) {
  22261. return; // nothing to do
  22262. }
  22263. data = data || this._data;
  22264. if (!this._buffer) {
  22265. if (this._updatable) {
  22266. this._buffer = this._engine.createDynamicVertexBuffer(data);
  22267. this._data = data;
  22268. }
  22269. else {
  22270. this._buffer = this._engine.createVertexBuffer(data);
  22271. }
  22272. }
  22273. else if (this._updatable) {
  22274. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  22275. this._data = data;
  22276. }
  22277. };
  22278. Buffer.prototype.update = function (data) {
  22279. this.create(data);
  22280. };
  22281. Buffer.prototype.updateDirectly = function (data, offset, vertexCount) {
  22282. if (!this._buffer) {
  22283. return;
  22284. }
  22285. if (this._updatable) {
  22286. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset, (vertexCount ? vertexCount * this.getStrideSize() : undefined));
  22287. this._data = null;
  22288. }
  22289. };
  22290. Buffer.prototype.dispose = function () {
  22291. if (!this._buffer) {
  22292. return;
  22293. }
  22294. if (this._engine._releaseBuffer(this._buffer)) {
  22295. this._buffer = null;
  22296. }
  22297. };
  22298. return Buffer;
  22299. }());
  22300. BABYLON.Buffer = Buffer;
  22301. })(BABYLON || (BABYLON = {}));
  22302. //# sourceMappingURL=babylon.buffer.js.map
  22303. var BABYLON;
  22304. (function (BABYLON) {
  22305. var VertexBuffer = (function () {
  22306. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size) {
  22307. if (!stride) {
  22308. // Deduce stride from kind
  22309. switch (kind) {
  22310. case VertexBuffer.PositionKind:
  22311. stride = 3;
  22312. break;
  22313. case VertexBuffer.NormalKind:
  22314. stride = 3;
  22315. break;
  22316. case VertexBuffer.UVKind:
  22317. case VertexBuffer.UV2Kind:
  22318. case VertexBuffer.UV3Kind:
  22319. case VertexBuffer.UV4Kind:
  22320. case VertexBuffer.UV5Kind:
  22321. case VertexBuffer.UV6Kind:
  22322. stride = 2;
  22323. break;
  22324. case VertexBuffer.TangentKind:
  22325. case VertexBuffer.ColorKind:
  22326. stride = 4;
  22327. break;
  22328. case VertexBuffer.MatricesIndicesKind:
  22329. case VertexBuffer.MatricesIndicesExtraKind:
  22330. stride = 4;
  22331. break;
  22332. case VertexBuffer.MatricesWeightsKind:
  22333. case VertexBuffer.MatricesWeightsExtraKind:
  22334. stride = 4;
  22335. break;
  22336. }
  22337. }
  22338. if (data instanceof BABYLON.Buffer) {
  22339. if (!stride) {
  22340. stride = data.getStrideSize();
  22341. }
  22342. this._buffer = data;
  22343. this._ownsBuffer = false;
  22344. }
  22345. else {
  22346. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced);
  22347. this._ownsBuffer = true;
  22348. }
  22349. this._stride = stride;
  22350. this._offset = offset ? offset : 0;
  22351. this._size = size ? size : stride;
  22352. this._kind = kind;
  22353. }
  22354. /**
  22355. * Returns the kind of the VertexBuffer (string).
  22356. */
  22357. VertexBuffer.prototype.getKind = function () {
  22358. return this._kind;
  22359. };
  22360. // Properties
  22361. /**
  22362. * Boolean : is the VertexBuffer updatable ?
  22363. */
  22364. VertexBuffer.prototype.isUpdatable = function () {
  22365. return this._buffer.isUpdatable();
  22366. };
  22367. /**
  22368. * Returns an array of numbers or a Float32Array containing the VertexBuffer data.
  22369. */
  22370. VertexBuffer.prototype.getData = function () {
  22371. return this._buffer.getData();
  22372. };
  22373. /**
  22374. * Returns the WebGLBuffer associated to the VertexBuffer.
  22375. */
  22376. VertexBuffer.prototype.getBuffer = function () {
  22377. return this._buffer.getBuffer();
  22378. };
  22379. /**
  22380. * Returns the stride of the VertexBuffer (integer).
  22381. */
  22382. VertexBuffer.prototype.getStrideSize = function () {
  22383. return this._stride;
  22384. };
  22385. /**
  22386. * Returns the offset (integer).
  22387. */
  22388. VertexBuffer.prototype.getOffset = function () {
  22389. return this._offset;
  22390. };
  22391. /**
  22392. * Returns the VertexBuffer total size (integer).
  22393. */
  22394. VertexBuffer.prototype.getSize = function () {
  22395. return this._size;
  22396. };
  22397. /**
  22398. * Boolean : is the WebGLBuffer of the VertexBuffer instanced now ?
  22399. */
  22400. VertexBuffer.prototype.getIsInstanced = function () {
  22401. return this._buffer.getIsInstanced();
  22402. };
  22403. // Methods
  22404. /**
  22405. * Creates the underlying WebGLBuffer from the passed numeric array or Float32Array.
  22406. * Returns the created WebGLBuffer.
  22407. */
  22408. VertexBuffer.prototype.create = function (data) {
  22409. return this._buffer.create(data);
  22410. };
  22411. /**
  22412. * Updates the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  22413. * Returns the updated WebGLBuffer.
  22414. */
  22415. VertexBuffer.prototype.update = function (data) {
  22416. return this._buffer.update(data);
  22417. };
  22418. /**
  22419. * Updates directly the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  22420. * Returns the directly updated WebGLBuffer.
  22421. */
  22422. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  22423. return this._buffer.updateDirectly(data, offset);
  22424. };
  22425. /**
  22426. * Disposes the VertexBuffer and the underlying WebGLBuffer.
  22427. */
  22428. VertexBuffer.prototype.dispose = function () {
  22429. if (this._ownsBuffer) {
  22430. this._buffer.dispose();
  22431. }
  22432. };
  22433. Object.defineProperty(VertexBuffer, "PositionKind", {
  22434. get: function () {
  22435. return VertexBuffer._PositionKind;
  22436. },
  22437. enumerable: true,
  22438. configurable: true
  22439. });
  22440. Object.defineProperty(VertexBuffer, "NormalKind", {
  22441. get: function () {
  22442. return VertexBuffer._NormalKind;
  22443. },
  22444. enumerable: true,
  22445. configurable: true
  22446. });
  22447. Object.defineProperty(VertexBuffer, "TangentKind", {
  22448. get: function () {
  22449. return VertexBuffer._TangentKind;
  22450. },
  22451. enumerable: true,
  22452. configurable: true
  22453. });
  22454. Object.defineProperty(VertexBuffer, "UVKind", {
  22455. get: function () {
  22456. return VertexBuffer._UVKind;
  22457. },
  22458. enumerable: true,
  22459. configurable: true
  22460. });
  22461. Object.defineProperty(VertexBuffer, "UV2Kind", {
  22462. get: function () {
  22463. return VertexBuffer._UV2Kind;
  22464. },
  22465. enumerable: true,
  22466. configurable: true
  22467. });
  22468. Object.defineProperty(VertexBuffer, "UV3Kind", {
  22469. get: function () {
  22470. return VertexBuffer._UV3Kind;
  22471. },
  22472. enumerable: true,
  22473. configurable: true
  22474. });
  22475. Object.defineProperty(VertexBuffer, "UV4Kind", {
  22476. get: function () {
  22477. return VertexBuffer._UV4Kind;
  22478. },
  22479. enumerable: true,
  22480. configurable: true
  22481. });
  22482. Object.defineProperty(VertexBuffer, "UV5Kind", {
  22483. get: function () {
  22484. return VertexBuffer._UV5Kind;
  22485. },
  22486. enumerable: true,
  22487. configurable: true
  22488. });
  22489. Object.defineProperty(VertexBuffer, "UV6Kind", {
  22490. get: function () {
  22491. return VertexBuffer._UV6Kind;
  22492. },
  22493. enumerable: true,
  22494. configurable: true
  22495. });
  22496. Object.defineProperty(VertexBuffer, "ColorKind", {
  22497. get: function () {
  22498. return VertexBuffer._ColorKind;
  22499. },
  22500. enumerable: true,
  22501. configurable: true
  22502. });
  22503. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  22504. get: function () {
  22505. return VertexBuffer._MatricesIndicesKind;
  22506. },
  22507. enumerable: true,
  22508. configurable: true
  22509. });
  22510. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  22511. get: function () {
  22512. return VertexBuffer._MatricesWeightsKind;
  22513. },
  22514. enumerable: true,
  22515. configurable: true
  22516. });
  22517. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  22518. get: function () {
  22519. return VertexBuffer._MatricesIndicesExtraKind;
  22520. },
  22521. enumerable: true,
  22522. configurable: true
  22523. });
  22524. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  22525. get: function () {
  22526. return VertexBuffer._MatricesWeightsExtraKind;
  22527. },
  22528. enumerable: true,
  22529. configurable: true
  22530. });
  22531. return VertexBuffer;
  22532. }());
  22533. // Enums
  22534. VertexBuffer._PositionKind = "position";
  22535. VertexBuffer._NormalKind = "normal";
  22536. VertexBuffer._TangentKind = "tangent";
  22537. VertexBuffer._UVKind = "uv";
  22538. VertexBuffer._UV2Kind = "uv2";
  22539. VertexBuffer._UV3Kind = "uv3";
  22540. VertexBuffer._UV4Kind = "uv4";
  22541. VertexBuffer._UV5Kind = "uv5";
  22542. VertexBuffer._UV6Kind = "uv6";
  22543. VertexBuffer._ColorKind = "color";
  22544. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  22545. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  22546. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  22547. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  22548. BABYLON.VertexBuffer = VertexBuffer;
  22549. })(BABYLON || (BABYLON = {}));
  22550. //# sourceMappingURL=babylon.vertexBuffer.js.map
  22551. var BABYLON;
  22552. (function (BABYLON) {
  22553. /**
  22554. * Creates an instance based on a source mesh.
  22555. */
  22556. var InstancedMesh = (function (_super) {
  22557. __extends(InstancedMesh, _super);
  22558. function InstancedMesh(name, source) {
  22559. var _this = _super.call(this, name, source.getScene()) || this;
  22560. source.instances.push(_this);
  22561. _this._sourceMesh = source;
  22562. _this.position.copyFrom(source.position);
  22563. _this.rotation.copyFrom(source.rotation);
  22564. _this.scaling.copyFrom(source.scaling);
  22565. if (source.rotationQuaternion) {
  22566. _this.rotationQuaternion = source.rotationQuaternion.clone();
  22567. }
  22568. _this.infiniteDistance = source.infiniteDistance;
  22569. _this.setPivotMatrix(source.getPivotMatrix());
  22570. _this.refreshBoundingInfo();
  22571. _this._syncSubMeshes();
  22572. return _this;
  22573. }
  22574. /**
  22575. * Returns the string "InstancedMesh".
  22576. */
  22577. InstancedMesh.prototype.getClassName = function () {
  22578. return "InstancedMesh";
  22579. };
  22580. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  22581. // Methods
  22582. get: function () {
  22583. return this._sourceMesh.receiveShadows;
  22584. },
  22585. enumerable: true,
  22586. configurable: true
  22587. });
  22588. Object.defineProperty(InstancedMesh.prototype, "material", {
  22589. get: function () {
  22590. return this._sourceMesh.material;
  22591. },
  22592. enumerable: true,
  22593. configurable: true
  22594. });
  22595. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  22596. get: function () {
  22597. return this._sourceMesh.visibility;
  22598. },
  22599. enumerable: true,
  22600. configurable: true
  22601. });
  22602. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  22603. get: function () {
  22604. return this._sourceMesh.skeleton;
  22605. },
  22606. enumerable: true,
  22607. configurable: true
  22608. });
  22609. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  22610. get: function () {
  22611. return this._sourceMesh.renderingGroupId;
  22612. },
  22613. enumerable: true,
  22614. configurable: true
  22615. });
  22616. /**
  22617. * Returns the total number of vertices (integer).
  22618. */
  22619. InstancedMesh.prototype.getTotalVertices = function () {
  22620. return this._sourceMesh.getTotalVertices();
  22621. };
  22622. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  22623. get: function () {
  22624. return this._sourceMesh;
  22625. },
  22626. enumerable: true,
  22627. configurable: true
  22628. });
  22629. /**
  22630. * Returns a float array or a Float32Array of the requested kind of data : positons, normals, uvs, etc.
  22631. */
  22632. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  22633. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  22634. };
  22635. /**
  22636. * Boolean : True if the mesh owns the requested kind of data.
  22637. */
  22638. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  22639. return this._sourceMesh.isVerticesDataPresent(kind);
  22640. };
  22641. /**
  22642. * Returns an array of indices (IndicesArray).
  22643. */
  22644. InstancedMesh.prototype.getIndices = function () {
  22645. return this._sourceMesh.getIndices();
  22646. };
  22647. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  22648. get: function () {
  22649. return this._sourceMesh._positions;
  22650. },
  22651. enumerable: true,
  22652. configurable: true
  22653. });
  22654. /**
  22655. * Sets a new updated BoundingInfo to the mesh.
  22656. * Returns the mesh.
  22657. */
  22658. InstancedMesh.prototype.refreshBoundingInfo = function () {
  22659. var meshBB = this._sourceMesh.getBoundingInfo();
  22660. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  22661. this._updateBoundingInfo();
  22662. return this;
  22663. };
  22664. InstancedMesh.prototype._preActivate = function () {
  22665. if (this._currentLOD) {
  22666. this._currentLOD._preActivate();
  22667. }
  22668. return this;
  22669. };
  22670. InstancedMesh.prototype._activate = function (renderId) {
  22671. if (this._currentLOD) {
  22672. this._currentLOD._registerInstanceForRenderId(this, renderId);
  22673. }
  22674. return this;
  22675. };
  22676. /**
  22677. * Returns the current associated LOD AbstractMesh.
  22678. */
  22679. InstancedMesh.prototype.getLOD = function (camera) {
  22680. this._currentLOD = this.sourceMesh.getLOD(this.getScene().activeCamera, this.getBoundingInfo().boundingSphere);
  22681. if (this._currentLOD === this.sourceMesh) {
  22682. return this;
  22683. }
  22684. return this._currentLOD;
  22685. };
  22686. InstancedMesh.prototype._syncSubMeshes = function () {
  22687. this.releaseSubMeshes();
  22688. if (this._sourceMesh.subMeshes) {
  22689. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  22690. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  22691. }
  22692. }
  22693. return this;
  22694. };
  22695. InstancedMesh.prototype._generatePointsArray = function () {
  22696. return this._sourceMesh._generatePointsArray();
  22697. };
  22698. /**
  22699. * Creates a new InstancedMesh from the current mesh.
  22700. * - name (string) : the cloned mesh name
  22701. * - newParent (optional Node) : the optional Node to parent the clone to.
  22702. * - doNotCloneChildren (optional boolean, default `false`) : if `true` the model children aren't cloned.
  22703. *
  22704. * Returns the clone.
  22705. */
  22706. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  22707. var result = this._sourceMesh.createInstance(name);
  22708. // Deep copy
  22709. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes", "uniqueId"], []);
  22710. // Bounding info
  22711. this.refreshBoundingInfo();
  22712. // Parent
  22713. if (newParent) {
  22714. result.parent = newParent;
  22715. }
  22716. if (!doNotCloneChildren) {
  22717. // Children
  22718. for (var index = 0; index < this.getScene().meshes.length; index++) {
  22719. var mesh = this.getScene().meshes[index];
  22720. if (mesh.parent === this) {
  22721. mesh.clone(mesh.name, result);
  22722. }
  22723. }
  22724. }
  22725. result.computeWorldMatrix(true);
  22726. return result;
  22727. };
  22728. /**
  22729. * Disposes the InstancedMesh.
  22730. * Returns nothing.
  22731. */
  22732. InstancedMesh.prototype.dispose = function (doNotRecurse) {
  22733. // Remove from mesh
  22734. var index = this._sourceMesh.instances.indexOf(this);
  22735. this._sourceMesh.instances.splice(index, 1);
  22736. _super.prototype.dispose.call(this, doNotRecurse);
  22737. };
  22738. return InstancedMesh;
  22739. }(BABYLON.AbstractMesh));
  22740. BABYLON.InstancedMesh = InstancedMesh;
  22741. })(BABYLON || (BABYLON = {}));
  22742. //# sourceMappingURL=babylon.instancedMesh.js.map
  22743. var BABYLON;
  22744. (function (BABYLON) {
  22745. var _InstancesBatch = (function () {
  22746. function _InstancesBatch() {
  22747. this.mustReturn = false;
  22748. this.visibleInstances = new Array();
  22749. this.renderSelf = new Array();
  22750. }
  22751. return _InstancesBatch;
  22752. }());
  22753. BABYLON._InstancesBatch = _InstancesBatch;
  22754. var Mesh = (function (_super) {
  22755. __extends(Mesh, _super);
  22756. /**
  22757. * @constructor
  22758. * @param {string} name The value used by scene.getMeshByName() to do a lookup.
  22759. * @param {Scene} scene The scene to add this mesh to.
  22760. * @param {Node} parent The parent of this mesh, if it has one
  22761. * @param {Mesh} source An optional Mesh from which geometry is shared, cloned.
  22762. * @param {boolean} doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  22763. * When false, achieved by calling a clone(), also passing False.
  22764. * This will make creation of children, recursive.
  22765. * @param {boolean} clonePhysicsImpostor When cloning, include cloning mesh physics impostor, default True.
  22766. */
  22767. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  22768. if (parent === void 0) { parent = null; }
  22769. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  22770. var _this = _super.call(this, name, scene) || this;
  22771. // Events
  22772. /**
  22773. * An event triggered before rendering the mesh
  22774. * @type {BABYLON.Observable}
  22775. */
  22776. _this.onBeforeRenderObservable = new BABYLON.Observable();
  22777. /**
  22778. * An event triggered after rendering the mesh
  22779. * @type {BABYLON.Observable}
  22780. */
  22781. _this.onAfterRenderObservable = new BABYLON.Observable();
  22782. /**
  22783. * An event triggered before drawing the mesh
  22784. * @type {BABYLON.Observable}
  22785. */
  22786. _this.onBeforeDrawObservable = new BABYLON.Observable();
  22787. // Members
  22788. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  22789. _this.instances = new Array();
  22790. _this._LODLevels = new Array();
  22791. _this._visibleInstances = {};
  22792. _this._renderIdForInstances = new Array();
  22793. _this._batchCache = new _InstancesBatch();
  22794. _this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  22795. _this._sideOrientation = Mesh._DEFAULTSIDE;
  22796. _this._areNormalsFrozen = false; // Will be used by ribbons mainly
  22797. // Will be used to save a source mesh reference, If any
  22798. _this._source = null;
  22799. if (source) {
  22800. // Source mesh
  22801. _this._source = source;
  22802. // Geometry
  22803. if (source._geometry) {
  22804. source._geometry.applyToMesh(_this);
  22805. }
  22806. // Deep copy
  22807. BABYLON.Tools.DeepCopy(source, _this, ["name", "material", "skeleton", "instances", "parent", "uniqueId"], ["_poseMatrix"]);
  22808. // Parent
  22809. _this.parent = source.parent;
  22810. // Pivot
  22811. _this.setPivotMatrix(source.getPivotMatrix());
  22812. _this.id = name + "." + source.id;
  22813. // Material
  22814. _this.material = source.material;
  22815. var index;
  22816. if (!doNotCloneChildren) {
  22817. // Children
  22818. for (index = 0; index < scene.meshes.length; index++) {
  22819. var mesh = scene.meshes[index];
  22820. if (mesh.parent === source) {
  22821. // doNotCloneChildren is always going to be False
  22822. var newChild = mesh.clone(name + "." + mesh.name, _this, doNotCloneChildren);
  22823. }
  22824. }
  22825. }
  22826. // Physics clone
  22827. var physicsEngine = _this.getScene().getPhysicsEngine();
  22828. if (clonePhysicsImpostor && physicsEngine) {
  22829. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  22830. if (impostor) {
  22831. _this.physicsImpostor = impostor.clone(_this);
  22832. }
  22833. }
  22834. // Particles
  22835. for (index = 0; index < scene.particleSystems.length; index++) {
  22836. var system = scene.particleSystems[index];
  22837. if (system.emitter === source) {
  22838. system.clone(system.name, _this);
  22839. }
  22840. }
  22841. _this.computeWorldMatrix(true);
  22842. }
  22843. // Parent
  22844. if (parent !== null) {
  22845. _this.parent = parent;
  22846. }
  22847. return _this;
  22848. }
  22849. Object.defineProperty(Mesh, "FRONTSIDE", {
  22850. /**
  22851. * Mesh side orientation : usually the external or front surface
  22852. */
  22853. get: function () {
  22854. return Mesh._FRONTSIDE;
  22855. },
  22856. enumerable: true,
  22857. configurable: true
  22858. });
  22859. Object.defineProperty(Mesh, "BACKSIDE", {
  22860. /**
  22861. * Mesh side orientation : usually the internal or back surface
  22862. */
  22863. get: function () {
  22864. return Mesh._BACKSIDE;
  22865. },
  22866. enumerable: true,
  22867. configurable: true
  22868. });
  22869. Object.defineProperty(Mesh, "DOUBLESIDE", {
  22870. /**
  22871. * Mesh side orientation : both internal and external or front and back surfaces
  22872. */
  22873. get: function () {
  22874. return Mesh._DOUBLESIDE;
  22875. },
  22876. enumerable: true,
  22877. configurable: true
  22878. });
  22879. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  22880. /**
  22881. * Mesh side orientation : by default, `FRONTSIDE`
  22882. */
  22883. get: function () {
  22884. return Mesh._DEFAULTSIDE;
  22885. },
  22886. enumerable: true,
  22887. configurable: true
  22888. });
  22889. Object.defineProperty(Mesh, "NO_CAP", {
  22890. /**
  22891. * Mesh cap setting : no cap
  22892. */
  22893. get: function () {
  22894. return Mesh._NO_CAP;
  22895. },
  22896. enumerable: true,
  22897. configurable: true
  22898. });
  22899. Object.defineProperty(Mesh, "CAP_START", {
  22900. /**
  22901. * Mesh cap setting : one cap at the beginning of the mesh
  22902. */
  22903. get: function () {
  22904. return Mesh._CAP_START;
  22905. },
  22906. enumerable: true,
  22907. configurable: true
  22908. });
  22909. Object.defineProperty(Mesh, "CAP_END", {
  22910. /**
  22911. * Mesh cap setting : one cap at the end of the mesh
  22912. */
  22913. get: function () {
  22914. return Mesh._CAP_END;
  22915. },
  22916. enumerable: true,
  22917. configurable: true
  22918. });
  22919. Object.defineProperty(Mesh, "CAP_ALL", {
  22920. /**
  22921. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  22922. */
  22923. get: function () {
  22924. return Mesh._CAP_ALL;
  22925. },
  22926. enumerable: true,
  22927. configurable: true
  22928. });
  22929. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  22930. set: function (callback) {
  22931. if (this._onBeforeDrawObserver) {
  22932. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  22933. }
  22934. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  22935. },
  22936. enumerable: true,
  22937. configurable: true
  22938. });
  22939. Object.defineProperty(Mesh.prototype, "source", {
  22940. get: function () {
  22941. return this._source;
  22942. },
  22943. enumerable: true,
  22944. configurable: true
  22945. });
  22946. // Methods
  22947. /**
  22948. * Returns the string "Mesh".
  22949. */
  22950. Mesh.prototype.getClassName = function () {
  22951. return "Mesh";
  22952. };
  22953. /**
  22954. * Returns a string.
  22955. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  22956. */
  22957. Mesh.prototype.toString = function (fullDetails) {
  22958. var ret = _super.prototype.toString.call(this, fullDetails);
  22959. ret += ", n vertices: " + this.getTotalVertices();
  22960. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  22961. if (this.animations) {
  22962. for (var i = 0; i < this.animations.length; i++) {
  22963. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  22964. }
  22965. }
  22966. if (fullDetails) {
  22967. ret += ", flat shading: " + (this._geometry ? (this.getVerticesData(BABYLON.VertexBuffer.PositionKind).length / 3 === this.getIndices().length ? "YES" : "NO") : "UNKNOWN");
  22968. }
  22969. return ret;
  22970. };
  22971. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  22972. /**
  22973. * True if the mesh has some Levels Of Details (LOD).
  22974. * Returns a boolean.
  22975. */
  22976. get: function () {
  22977. return this._LODLevels.length > 0;
  22978. },
  22979. enumerable: true,
  22980. configurable: true
  22981. });
  22982. Mesh.prototype._sortLODLevels = function () {
  22983. this._LODLevels.sort(function (a, b) {
  22984. if (a.distance < b.distance) {
  22985. return 1;
  22986. }
  22987. if (a.distance > b.distance) {
  22988. return -1;
  22989. }
  22990. return 0;
  22991. });
  22992. };
  22993. /**
  22994. * Add a mesh as LOD level triggered at the given distance.
  22995. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  22996. * @param {number} distance The distance from the center of the object to show this level
  22997. * @param {Mesh} mesh The mesh to be added as LOD level
  22998. * @return {Mesh} This mesh (for chaining)
  22999. */
  23000. Mesh.prototype.addLODLevel = function (distance, mesh) {
  23001. if (mesh && mesh._masterMesh) {
  23002. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  23003. return this;
  23004. }
  23005. var level = new BABYLON.Internals.MeshLODLevel(distance, mesh);
  23006. this._LODLevels.push(level);
  23007. if (mesh) {
  23008. mesh._masterMesh = this;
  23009. }
  23010. this._sortLODLevels();
  23011. return this;
  23012. };
  23013. /**
  23014. * Returns the LOD level mesh at the passed distance or null if not found.
  23015. * It is related to the method `addLODLevel(distance, mesh)`.
  23016. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  23017. * Returns an object Mesh or `null`.
  23018. */
  23019. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  23020. for (var index = 0; index < this._LODLevels.length; index++) {
  23021. var level = this._LODLevels[index];
  23022. if (level.distance === distance) {
  23023. return level.mesh;
  23024. }
  23025. }
  23026. return null;
  23027. };
  23028. /**
  23029. * Remove a mesh from the LOD array
  23030. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  23031. * @param {Mesh} mesh The mesh to be removed.
  23032. * @return {Mesh} This mesh (for chaining)
  23033. */
  23034. Mesh.prototype.removeLODLevel = function (mesh) {
  23035. for (var index = 0; index < this._LODLevels.length; index++) {
  23036. if (this._LODLevels[index].mesh === mesh) {
  23037. this._LODLevels.splice(index, 1);
  23038. if (mesh) {
  23039. mesh._masterMesh = null;
  23040. }
  23041. }
  23042. }
  23043. this._sortLODLevels();
  23044. return this;
  23045. };
  23046. /**
  23047. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  23048. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  23049. */
  23050. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  23051. if (!this._LODLevels || this._LODLevels.length === 0) {
  23052. return this;
  23053. }
  23054. var distanceToCamera = (boundingSphere ? boundingSphere : this.getBoundingInfo().boundingSphere).centerWorld.subtract(camera.globalPosition).length();
  23055. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  23056. if (this.onLODLevelSelection) {
  23057. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  23058. }
  23059. return this;
  23060. }
  23061. for (var index = 0; index < this._LODLevels.length; index++) {
  23062. var level = this._LODLevels[index];
  23063. if (level.distance < distanceToCamera) {
  23064. if (level.mesh) {
  23065. level.mesh._preActivate();
  23066. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  23067. }
  23068. if (this.onLODLevelSelection) {
  23069. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  23070. }
  23071. return level.mesh;
  23072. }
  23073. }
  23074. if (this.onLODLevelSelection) {
  23075. this.onLODLevelSelection(distanceToCamera, this, this);
  23076. }
  23077. return this;
  23078. };
  23079. Object.defineProperty(Mesh.prototype, "geometry", {
  23080. /**
  23081. * Returns the mesh internal Geometry object.
  23082. */
  23083. get: function () {
  23084. return this._geometry;
  23085. },
  23086. enumerable: true,
  23087. configurable: true
  23088. });
  23089. /**
  23090. * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  23091. */
  23092. Mesh.prototype.getTotalVertices = function () {
  23093. if (!this._geometry) {
  23094. return 0;
  23095. }
  23096. return this._geometry.getTotalVertices();
  23097. };
  23098. /**
  23099. * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
  23100. * 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.
  23101. * Returns null if the mesh has no geometry or no vertex buffer.
  23102. * Possible `kind` values :
  23103. * - BABYLON.VertexBuffer.PositionKind
  23104. * - BABYLON.VertexBuffer.UVKind
  23105. * - BABYLON.VertexBuffer.UV2Kind
  23106. * - BABYLON.VertexBuffer.UV3Kind
  23107. * - BABYLON.VertexBuffer.UV4Kind
  23108. * - BABYLON.VertexBuffer.UV5Kind
  23109. * - BABYLON.VertexBuffer.UV6Kind
  23110. * - BABYLON.VertexBuffer.ColorKind
  23111. * - BABYLON.VertexBuffer.MatricesIndicesKind
  23112. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  23113. * - BABYLON.VertexBuffer.MatricesWeightsKind
  23114. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  23115. */
  23116. Mesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  23117. if (!this._geometry) {
  23118. return null;
  23119. }
  23120. return this._geometry.getVerticesData(kind, copyWhenShared);
  23121. };
  23122. /**
  23123. * Returns the mesh VertexBuffer object from the requested `kind` : positions, indices, normals, etc.
  23124. * Returns `undefined` if the mesh has no geometry.
  23125. * Possible `kind` values :
  23126. * - BABYLON.VertexBuffer.PositionKind
  23127. * - BABYLON.VertexBuffer.UVKind
  23128. * - BABYLON.VertexBuffer.UV2Kind
  23129. * - BABYLON.VertexBuffer.UV3Kind
  23130. * - BABYLON.VertexBuffer.UV4Kind
  23131. * - BABYLON.VertexBuffer.UV5Kind
  23132. * - BABYLON.VertexBuffer.UV6Kind
  23133. * - BABYLON.VertexBuffer.ColorKind
  23134. * - BABYLON.VertexBuffer.MatricesIndicesKind
  23135. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  23136. * - BABYLON.VertexBuffer.MatricesWeightsKind
  23137. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  23138. */
  23139. Mesh.prototype.getVertexBuffer = function (kind) {
  23140. if (!this._geometry) {
  23141. return undefined;
  23142. }
  23143. return this._geometry.getVertexBuffer(kind);
  23144. };
  23145. /**
  23146. * Returns a boolean depending on the existence of the Vertex Data for the requested `kind`.
  23147. * Possible `kind` values :
  23148. * - BABYLON.VertexBuffer.PositionKind
  23149. * - BABYLON.VertexBuffer.UVKind
  23150. * - BABYLON.VertexBuffer.UV2Kind
  23151. * - BABYLON.VertexBuffer.UV3Kind
  23152. * - BABYLON.VertexBuffer.UV4Kind
  23153. * - BABYLON.VertexBuffer.UV5Kind
  23154. * - BABYLON.VertexBuffer.UV6Kind
  23155. * - BABYLON.VertexBuffer.ColorKind
  23156. * - BABYLON.VertexBuffer.MatricesIndicesKind
  23157. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  23158. * - BABYLON.VertexBuffer.MatricesWeightsKind
  23159. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  23160. */
  23161. Mesh.prototype.isVerticesDataPresent = function (kind) {
  23162. if (!this._geometry) {
  23163. if (this._delayInfo) {
  23164. return this._delayInfo.indexOf(kind) !== -1;
  23165. }
  23166. return false;
  23167. }
  23168. return this._geometry.isVerticesDataPresent(kind);
  23169. };
  23170. /**
  23171. * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
  23172. * Possible `kind` values :
  23173. * - BABYLON.VertexBuffer.PositionKind
  23174. * - BABYLON.VertexBuffer.UVKind
  23175. * - BABYLON.VertexBuffer.UV2Kind
  23176. * - BABYLON.VertexBuffer.UV3Kind
  23177. * - BABYLON.VertexBuffer.UV4Kind
  23178. * - BABYLON.VertexBuffer.UV5Kind
  23179. * - BABYLON.VertexBuffer.UV6Kind
  23180. * - BABYLON.VertexBuffer.ColorKind
  23181. * - BABYLON.VertexBuffer.MatricesIndicesKind
  23182. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  23183. * - BABYLON.VertexBuffer.MatricesWeightsKind
  23184. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  23185. */
  23186. Mesh.prototype.getVerticesDataKinds = function () {
  23187. if (!this._geometry) {
  23188. var result = [];
  23189. if (this._delayInfo) {
  23190. this._delayInfo.forEach(function (kind, index, array) {
  23191. result.push(kind);
  23192. });
  23193. }
  23194. return result;
  23195. }
  23196. return this._geometry.getVerticesDataKinds();
  23197. };
  23198. /**
  23199. * Returns a positive integer : the total number of indices in this mesh geometry.
  23200. * Returns zero if the mesh has no geometry.
  23201. */
  23202. Mesh.prototype.getTotalIndices = function () {
  23203. if (!this._geometry) {
  23204. return 0;
  23205. }
  23206. return this._geometry.getTotalIndices();
  23207. };
  23208. /**
  23209. * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
  23210. * 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.
  23211. * Returns an empty array if the mesh has no geometry.
  23212. */
  23213. Mesh.prototype.getIndices = function (copyWhenShared) {
  23214. if (!this._geometry) {
  23215. return [];
  23216. }
  23217. return this._geometry.getIndices(copyWhenShared);
  23218. };
  23219. Object.defineProperty(Mesh.prototype, "isBlocked", {
  23220. get: function () {
  23221. return this._masterMesh !== null && this._masterMesh !== undefined;
  23222. },
  23223. enumerable: true,
  23224. configurable: true
  23225. });
  23226. /**
  23227. * Boolean : true once the mesh is ready after all the delayed process (loading, etc) are complete.
  23228. */
  23229. Mesh.prototype.isReady = function () {
  23230. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  23231. return false;
  23232. }
  23233. return _super.prototype.isReady.call(this);
  23234. };
  23235. /**
  23236. * Boolean : true if the mesh has been disposed.
  23237. */
  23238. Mesh.prototype.isDisposed = function () {
  23239. return this._isDisposed;
  23240. };
  23241. Object.defineProperty(Mesh.prototype, "sideOrientation", {
  23242. get: function () {
  23243. return this._sideOrientation;
  23244. },
  23245. /**
  23246. * Sets the mesh side orientation : BABYLON.Mesh.FRONTSIDE, BABYLON.Mesh.BACKSIDE, BABYLON.Mesh.DOUBLESIDE or BABYLON.Mesh.DEFAULTSIDE
  23247. * tuto : http://doc.babylonjs.com/tutorials/Discover_Basic_Elements#side-orientation
  23248. */
  23249. set: function (sideO) {
  23250. this._sideOrientation = sideO;
  23251. },
  23252. enumerable: true,
  23253. configurable: true
  23254. });
  23255. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  23256. /**
  23257. * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
  23258. * This property is pertinent only for updatable parametric shapes.
  23259. */
  23260. get: function () {
  23261. return this._areNormalsFrozen;
  23262. },
  23263. enumerable: true,
  23264. configurable: true
  23265. });
  23266. /**
  23267. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  23268. * It has no effect at all on other shapes.
  23269. * It prevents the mesh normals from being recomputed on next `positions` array update.
  23270. * Returns the Mesh.
  23271. */
  23272. Mesh.prototype.freezeNormals = function () {
  23273. this._areNormalsFrozen = true;
  23274. return this;
  23275. };
  23276. /**
  23277. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  23278. * It has no effect at all on other shapes.
  23279. * It reactivates the mesh normals computation if it was previously frozen.
  23280. * Returns the Mesh.
  23281. */
  23282. Mesh.prototype.unfreezeNormals = function () {
  23283. this._areNormalsFrozen = false;
  23284. return this;
  23285. };
  23286. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  23287. /**
  23288. * Overrides instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  23289. */
  23290. set: function (count) {
  23291. this._overridenInstanceCount = count;
  23292. },
  23293. enumerable: true,
  23294. configurable: true
  23295. });
  23296. // Methods
  23297. Mesh.prototype._preActivate = function () {
  23298. var sceneRenderId = this.getScene().getRenderId();
  23299. if (this._preActivateId === sceneRenderId) {
  23300. return this;
  23301. }
  23302. this._preActivateId = sceneRenderId;
  23303. this._visibleInstances = null;
  23304. return this;
  23305. };
  23306. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  23307. if (this._visibleInstances) {
  23308. this._visibleInstances.intermediateDefaultRenderId = renderId;
  23309. }
  23310. return this;
  23311. };
  23312. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  23313. if (!this._visibleInstances) {
  23314. this._visibleInstances = {};
  23315. this._visibleInstances.defaultRenderId = renderId;
  23316. this._visibleInstances.selfDefaultRenderId = this._renderId;
  23317. }
  23318. if (!this._visibleInstances[renderId]) {
  23319. this._visibleInstances[renderId] = new Array();
  23320. }
  23321. this._visibleInstances[renderId].push(instance);
  23322. return this;
  23323. };
  23324. /**
  23325. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  23326. * This means the mesh underlying bounding box and sphere are recomputed.
  23327. * Returns the Mesh.
  23328. */
  23329. Mesh.prototype.refreshBoundingInfo = function () {
  23330. if (this._boundingInfo.isLocked) {
  23331. return;
  23332. }
  23333. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  23334. if (data) {
  23335. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  23336. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  23337. }
  23338. if (this.subMeshes) {
  23339. for (var index = 0; index < this.subMeshes.length; index++) {
  23340. this.subMeshes[index].refreshBoundingInfo();
  23341. }
  23342. }
  23343. this._updateBoundingInfo();
  23344. return this;
  23345. };
  23346. Mesh.prototype._createGlobalSubMesh = function () {
  23347. var totalVertices = this.getTotalVertices();
  23348. if (!totalVertices || !this.getIndices()) {
  23349. return null;
  23350. }
  23351. this.releaseSubMeshes();
  23352. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  23353. };
  23354. Mesh.prototype.subdivide = function (count) {
  23355. if (count < 1) {
  23356. return;
  23357. }
  23358. var totalIndices = this.getTotalIndices();
  23359. var subdivisionSize = (totalIndices / count) | 0;
  23360. var offset = 0;
  23361. // Ensure that subdivisionSize is a multiple of 3
  23362. while (subdivisionSize % 3 !== 0) {
  23363. subdivisionSize++;
  23364. }
  23365. this.releaseSubMeshes();
  23366. for (var index = 0; index < count; index++) {
  23367. if (offset >= totalIndices) {
  23368. break;
  23369. }
  23370. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  23371. offset += subdivisionSize;
  23372. }
  23373. this.synchronizeInstances();
  23374. };
  23375. /**
  23376. * Sets the vertex data of the mesh geometry for the requested `kind`.
  23377. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  23378. * The `data` are either a numeric array either a Float32Array.
  23379. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  23380. * 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).
  23381. * Note that a new underlying VertexBuffer object is created each call.
  23382. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  23383. *
  23384. * Possible `kind` values :
  23385. * - BABYLON.VertexBuffer.PositionKind
  23386. * - BABYLON.VertexBuffer.UVKind
  23387. * - BABYLON.VertexBuffer.UV2Kind
  23388. * - BABYLON.VertexBuffer.UV3Kind
  23389. * - BABYLON.VertexBuffer.UV4Kind
  23390. * - BABYLON.VertexBuffer.UV5Kind
  23391. * - BABYLON.VertexBuffer.UV6Kind
  23392. * - BABYLON.VertexBuffer.ColorKind
  23393. * - BABYLON.VertexBuffer.MatricesIndicesKind
  23394. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  23395. * - BABYLON.VertexBuffer.MatricesWeightsKind
  23396. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  23397. *
  23398. * Returns the Mesh.
  23399. */
  23400. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  23401. if (!this._geometry) {
  23402. var vertexData = new BABYLON.VertexData();
  23403. vertexData.set(data, kind);
  23404. var scene = this.getScene();
  23405. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  23406. }
  23407. else {
  23408. this._geometry.setVerticesData(kind, data, updatable, stride);
  23409. }
  23410. return this;
  23411. };
  23412. Mesh.prototype.markVerticesDataAsUpdatable = function (kind, updatable) {
  23413. if (updatable === void 0) { updatable = true; }
  23414. if (this.getVertexBuffer(kind).isUpdatable() === updatable) {
  23415. return;
  23416. }
  23417. this.setVerticesData(kind, this.getVerticesData(kind), updatable);
  23418. };
  23419. /**
  23420. * Sets the mesh VertexBuffer.
  23421. * Returns the Mesh.
  23422. */
  23423. Mesh.prototype.setVerticesBuffer = function (buffer) {
  23424. if (!this._geometry) {
  23425. var scene = this.getScene();
  23426. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene).applyToMesh(this);
  23427. }
  23428. this._geometry.setVerticesBuffer(buffer);
  23429. return this;
  23430. };
  23431. /**
  23432. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  23433. * If the mesh has no geometry, it is simply returned as it is.
  23434. * The `data` are either a numeric array either a Float32Array.
  23435. * No new underlying VertexBuffer object is created.
  23436. * 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.
  23437. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  23438. *
  23439. * Possible `kind` values :
  23440. * - BABYLON.VertexBuffer.PositionKind
  23441. * - BABYLON.VertexBuffer.UVKind
  23442. * - BABYLON.VertexBuffer.UV2Kind
  23443. * - BABYLON.VertexBuffer.UV3Kind
  23444. * - BABYLON.VertexBuffer.UV4Kind
  23445. * - BABYLON.VertexBuffer.UV5Kind
  23446. * - BABYLON.VertexBuffer.UV6Kind
  23447. * - BABYLON.VertexBuffer.ColorKind
  23448. * - BABYLON.VertexBuffer.MatricesIndicesKind
  23449. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  23450. * - BABYLON.VertexBuffer.MatricesWeightsKind
  23451. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  23452. *
  23453. * Returns the Mesh.
  23454. */
  23455. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  23456. if (!this._geometry) {
  23457. return;
  23458. }
  23459. if (!makeItUnique) {
  23460. this._geometry.updateVerticesData(kind, data, updateExtends);
  23461. }
  23462. else {
  23463. this.makeGeometryUnique();
  23464. this.updateVerticesData(kind, data, updateExtends, false);
  23465. }
  23466. return this;
  23467. };
  23468. /**
  23469. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  23470. * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  23471. * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
  23472. * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
  23473. * Returns the Mesh.
  23474. */
  23475. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  23476. if (computeNormals === void 0) { computeNormals = true; }
  23477. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  23478. positionFunction(positions);
  23479. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  23480. if (computeNormals) {
  23481. var indices = this.getIndices();
  23482. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  23483. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  23484. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  23485. }
  23486. return this;
  23487. };
  23488. /**
  23489. * Creates a un-shared specific occurence of the geometry for the mesh.
  23490. * Returns the Mesh.
  23491. */
  23492. Mesh.prototype.makeGeometryUnique = function () {
  23493. if (!this._geometry) {
  23494. return;
  23495. }
  23496. var oldGeometry = this._geometry;
  23497. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  23498. oldGeometry.releaseForMesh(this, true);
  23499. geometry.applyToMesh(this);
  23500. return this;
  23501. };
  23502. /**
  23503. * Sets the mesh indices.
  23504. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  23505. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  23506. * This method creates a new index buffer each call.
  23507. * Returns the Mesh.
  23508. */
  23509. Mesh.prototype.setIndices = function (indices, totalVertices) {
  23510. if (!this._geometry) {
  23511. var vertexData = new BABYLON.VertexData();
  23512. vertexData.indices = indices;
  23513. var scene = this.getScene();
  23514. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, false, this);
  23515. }
  23516. else {
  23517. this._geometry.setIndices(indices, totalVertices);
  23518. }
  23519. return this;
  23520. };
  23521. /**
  23522. * Invert the geometry to move from a right handed system to a left handed one.
  23523. * Returns the Mesh.
  23524. */
  23525. Mesh.prototype.toLeftHanded = function () {
  23526. if (!this._geometry) {
  23527. return;
  23528. }
  23529. this._geometry.toLeftHanded();
  23530. return this;
  23531. };
  23532. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  23533. var engine = this.getScene().getEngine();
  23534. // Wireframe
  23535. var indexToBind;
  23536. if (this._unIndexed) {
  23537. indexToBind = null;
  23538. }
  23539. else {
  23540. switch (fillMode) {
  23541. case BABYLON.Material.PointFillMode:
  23542. indexToBind = null;
  23543. break;
  23544. case BABYLON.Material.WireFrameFillMode:
  23545. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  23546. break;
  23547. default:
  23548. case BABYLON.Material.TriangleFillMode:
  23549. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  23550. break;
  23551. }
  23552. }
  23553. // VBOs
  23554. this._geometry._bind(effect, indexToBind);
  23555. return this;
  23556. };
  23557. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  23558. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  23559. return this;
  23560. }
  23561. this.onBeforeDrawObservable.notifyObservers(this);
  23562. var engine = this.getScene().getEngine();
  23563. // Draw order
  23564. switch (fillMode) {
  23565. case BABYLON.Material.PointFillMode:
  23566. engine.drawPointClouds(subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  23567. break;
  23568. case BABYLON.Material.WireFrameFillMode:
  23569. if (this._unIndexed) {
  23570. engine.drawUnIndexed(false, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  23571. }
  23572. else {
  23573. engine.draw(false, 0, instancesCount > 0 ? subMesh.linesIndexCount / 2 : subMesh.linesIndexCount, instancesCount);
  23574. }
  23575. break;
  23576. default:
  23577. if (this._unIndexed) {
  23578. engine.drawUnIndexed(true, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  23579. }
  23580. else {
  23581. engine.draw(true, subMesh.indexStart, subMesh.indexCount, instancesCount);
  23582. }
  23583. }
  23584. return this;
  23585. };
  23586. /**
  23587. * Registers for this mesh a javascript function called just before the rendering process.
  23588. * This function is passed the current mesh.
  23589. * Return the Mesh.
  23590. */
  23591. Mesh.prototype.registerBeforeRender = function (func) {
  23592. this.onBeforeRenderObservable.add(func);
  23593. return this;
  23594. };
  23595. /**
  23596. * Disposes a previously registered javascript function called before the rendering.
  23597. * This function is passed the current mesh.
  23598. * Returns the Mesh.
  23599. */
  23600. Mesh.prototype.unregisterBeforeRender = function (func) {
  23601. this.onBeforeRenderObservable.removeCallback(func);
  23602. return this;
  23603. };
  23604. /**
  23605. * Registers for this mesh a javascript function called just after the rendering is complete.
  23606. * This function is passed the current mesh.
  23607. * Returns the Mesh.
  23608. */
  23609. Mesh.prototype.registerAfterRender = function (func) {
  23610. this.onAfterRenderObservable.add(func);
  23611. return this;
  23612. };
  23613. /**
  23614. * Disposes a previously registered javascript function called after the rendering.
  23615. * This function is passed the current mesh.
  23616. * Return the Mesh.
  23617. */
  23618. Mesh.prototype.unregisterAfterRender = function (func) {
  23619. this.onAfterRenderObservable.removeCallback(func);
  23620. return this;
  23621. };
  23622. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  23623. var scene = this.getScene();
  23624. this._batchCache.mustReturn = false;
  23625. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  23626. this._batchCache.visibleInstances[subMeshId] = null;
  23627. if (this._visibleInstances) {
  23628. var currentRenderId = scene.getRenderId();
  23629. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  23630. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  23631. var selfRenderId = this._renderId;
  23632. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  23633. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  23634. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  23635. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  23636. }
  23637. if (this._batchCache.visibleInstances[subMeshId] && this._batchCache.visibleInstances[subMeshId].length) {
  23638. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  23639. this._batchCache.mustReturn = true;
  23640. return this._batchCache;
  23641. }
  23642. if (currentRenderId !== selfRenderId) {
  23643. this._batchCache.renderSelf[subMeshId] = false;
  23644. }
  23645. }
  23646. this._renderIdForInstances[subMeshId] = currentRenderId;
  23647. }
  23648. return this._batchCache;
  23649. };
  23650. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  23651. var visibleInstances = batch.visibleInstances[subMesh._id];
  23652. var matricesCount = visibleInstances.length + 1;
  23653. var bufferSize = matricesCount * 16 * 4;
  23654. var currentInstancesBufferSize = this._instancesBufferSize;
  23655. var instancesBuffer = this._instancesBuffer;
  23656. while (this._instancesBufferSize < bufferSize) {
  23657. this._instancesBufferSize *= 2;
  23658. }
  23659. if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) {
  23660. this._instancesData = new Float32Array(this._instancesBufferSize / 4);
  23661. }
  23662. var offset = 0;
  23663. var instancesCount = 0;
  23664. var world = this.getWorldMatrix();
  23665. if (batch.renderSelf[subMesh._id]) {
  23666. world.copyToArray(this._instancesData, offset);
  23667. offset += 16;
  23668. instancesCount++;
  23669. }
  23670. if (visibleInstances) {
  23671. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  23672. var instance = visibleInstances[instanceIndex];
  23673. instance.getWorldMatrix().copyToArray(this._instancesData, offset);
  23674. offset += 16;
  23675. instancesCount++;
  23676. }
  23677. }
  23678. if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) {
  23679. if (instancesBuffer) {
  23680. instancesBuffer.dispose();
  23681. }
  23682. instancesBuffer = new BABYLON.Buffer(engine, this._instancesData, true, 16, false, true);
  23683. this._instancesBuffer = instancesBuffer;
  23684. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  23685. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  23686. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  23687. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  23688. }
  23689. else {
  23690. instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount);
  23691. }
  23692. this.geometry._bind(effect);
  23693. this._draw(subMesh, fillMode, instancesCount);
  23694. engine.unbindInstanceAttributes();
  23695. return this;
  23696. };
  23697. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  23698. var scene = this.getScene();
  23699. var engine = scene.getEngine();
  23700. if (hardwareInstancedRendering) {
  23701. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  23702. }
  23703. else {
  23704. if (batch.renderSelf[subMesh._id]) {
  23705. // Draw
  23706. if (onBeforeDraw) {
  23707. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  23708. }
  23709. this._draw(subMesh, fillMode, this._overridenInstanceCount);
  23710. }
  23711. if (batch.visibleInstances[subMesh._id]) {
  23712. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  23713. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  23714. // World
  23715. var world = instance.getWorldMatrix();
  23716. if (onBeforeDraw) {
  23717. onBeforeDraw(true, world, effectiveMaterial);
  23718. }
  23719. // Draw
  23720. this._draw(subMesh, fillMode);
  23721. }
  23722. }
  23723. }
  23724. return this;
  23725. };
  23726. /**
  23727. * Triggers the draw call for the mesh.
  23728. * Usually, you don't need to call this method by your own because the mesh rendering is handled by the scene rendering manager.
  23729. * Returns the Mesh.
  23730. */
  23731. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  23732. var scene = this.getScene();
  23733. // Managing instances
  23734. var batch = this._getInstancesRenderList(subMesh._id);
  23735. if (batch.mustReturn) {
  23736. return this;
  23737. }
  23738. // Checking geometry state
  23739. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  23740. return this;
  23741. }
  23742. var callbackIndex;
  23743. this.onBeforeRenderObservable.notifyObservers(this);
  23744. var engine = scene.getEngine();
  23745. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  23746. // Material
  23747. var effectiveMaterial = subMesh.getMaterial();
  23748. if (!effectiveMaterial || !effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  23749. return this;
  23750. }
  23751. // Outline - step 1
  23752. var savedDepthWrite = engine.getDepthWrite();
  23753. if (this.renderOutline) {
  23754. engine.setDepthWrite(false);
  23755. scene.getOutlineRenderer().render(subMesh, batch);
  23756. engine.setDepthWrite(savedDepthWrite);
  23757. }
  23758. effectiveMaterial._preBind();
  23759. var effect = effectiveMaterial.getEffect();
  23760. // Bind
  23761. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : effectiveMaterial.fillMode);
  23762. this._bind(subMesh, effect, fillMode);
  23763. var world = this.getWorldMatrix();
  23764. effectiveMaterial.bind(world, this);
  23765. // Alpha mode
  23766. if (enableAlphaMode) {
  23767. engine.setAlphaMode(effectiveMaterial.alphaMode);
  23768. }
  23769. // Draw
  23770. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, effectiveMaterial);
  23771. // Unbind
  23772. effectiveMaterial.unbind();
  23773. // Outline - step 2
  23774. if (this.renderOutline && savedDepthWrite) {
  23775. engine.setDepthWrite(true);
  23776. engine.setColorWrite(false);
  23777. scene.getOutlineRenderer().render(subMesh, batch);
  23778. engine.setColorWrite(true);
  23779. }
  23780. // Overlay
  23781. if (this.renderOverlay) {
  23782. var currentMode = engine.getAlphaMode();
  23783. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  23784. scene.getOutlineRenderer().render(subMesh, batch, true);
  23785. engine.setAlphaMode(currentMode);
  23786. }
  23787. this.onAfterRenderObservable.notifyObservers(this);
  23788. return this;
  23789. };
  23790. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  23791. if (isInstance) {
  23792. effectiveMaterial.bindOnlyWorldMatrix(world);
  23793. }
  23794. return this;
  23795. };
  23796. /**
  23797. * Returns an array populated with ParticleSystem objects whose the mesh is the emitter.
  23798. */
  23799. Mesh.prototype.getEmittedParticleSystems = function () {
  23800. var results = new Array();
  23801. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  23802. var particleSystem = this.getScene().particleSystems[index];
  23803. if (particleSystem.emitter === this) {
  23804. results.push(particleSystem);
  23805. }
  23806. }
  23807. return results;
  23808. };
  23809. /**
  23810. * Returns an array populated with ParticleSystem objects whose the mesh or its children are the emitter.
  23811. */
  23812. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  23813. var results = new Array();
  23814. var descendants = this.getDescendants();
  23815. descendants.push(this);
  23816. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  23817. var particleSystem = this.getScene().particleSystems[index];
  23818. if (descendants.indexOf(particleSystem.emitter) !== -1) {
  23819. results.push(particleSystem);
  23820. }
  23821. }
  23822. return results;
  23823. };
  23824. Mesh.prototype._checkDelayState = function () {
  23825. var scene = this.getScene();
  23826. if (this._geometry) {
  23827. this._geometry.load(scene);
  23828. }
  23829. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  23830. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  23831. this._queueLoad(this, scene);
  23832. }
  23833. return this;
  23834. };
  23835. Mesh.prototype._queueLoad = function (mesh, scene) {
  23836. var _this = this;
  23837. scene._addPendingData(mesh);
  23838. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  23839. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  23840. if (data instanceof ArrayBuffer) {
  23841. _this._delayLoadingFunction(data, _this);
  23842. }
  23843. else {
  23844. _this._delayLoadingFunction(JSON.parse(data), _this);
  23845. }
  23846. _this.instances.forEach(function (instance) {
  23847. instance._syncSubMeshes();
  23848. });
  23849. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  23850. scene._removePendingData(_this);
  23851. }, function () { }, scene.database, getBinaryData);
  23852. return this;
  23853. };
  23854. /**
  23855. * Boolean, true is the mesh in the frustum defined by the Plane objects from the `frustumPlanes` array parameter.
  23856. */
  23857. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  23858. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  23859. return false;
  23860. }
  23861. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  23862. return false;
  23863. }
  23864. this._checkDelayState();
  23865. return true;
  23866. };
  23867. /**
  23868. * Sets the mesh material by the material or multiMaterial `id` property.
  23869. * The material `id` is a string identifying the material or the multiMaterial.
  23870. * This method returns the Mesh.
  23871. */
  23872. Mesh.prototype.setMaterialByID = function (id) {
  23873. var materials = this.getScene().materials;
  23874. var index;
  23875. for (index = 0; index < materials.length; index++) {
  23876. if (materials[index].id === id) {
  23877. this.material = materials[index];
  23878. return this;
  23879. }
  23880. }
  23881. // Multi
  23882. var multiMaterials = this.getScene().multiMaterials;
  23883. for (index = 0; index < multiMaterials.length; index++) {
  23884. if (multiMaterials[index].id === id) {
  23885. this.material = multiMaterials[index];
  23886. return this;
  23887. }
  23888. }
  23889. return this;
  23890. };
  23891. /**
  23892. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  23893. */
  23894. Mesh.prototype.getAnimatables = function () {
  23895. var results = [];
  23896. if (this.material) {
  23897. results.push(this.material);
  23898. }
  23899. if (this.skeleton) {
  23900. results.push(this.skeleton);
  23901. }
  23902. return results;
  23903. };
  23904. /**
  23905. * Modifies the mesh geometry according to the passed transformation matrix.
  23906. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  23907. * The mesh normals are modified accordingly the same transformation.
  23908. * tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  23909. * Note that, under the hood, this method sets a new VertexBuffer each call.
  23910. * Returns the Mesh.
  23911. */
  23912. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  23913. // Position
  23914. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  23915. return this;
  23916. }
  23917. var submeshes = this.subMeshes.splice(0);
  23918. this._resetPointsArrayCache();
  23919. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  23920. var temp = [];
  23921. var index;
  23922. for (index = 0; index < data.length; index += 3) {
  23923. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  23924. }
  23925. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  23926. // Normals
  23927. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  23928. return this;
  23929. }
  23930. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  23931. temp = [];
  23932. for (index = 0; index < data.length; index += 3) {
  23933. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  23934. }
  23935. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  23936. // flip faces?
  23937. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  23938. this.flipFaces();
  23939. }
  23940. // Restore submeshes
  23941. this.releaseSubMeshes();
  23942. this.subMeshes = submeshes;
  23943. return this;
  23944. };
  23945. /**
  23946. * Modifies the mesh geometry according to its own current World Matrix.
  23947. * The mesh World Matrix is then reset.
  23948. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  23949. * tuto : tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  23950. * Note that, under the hood, this method sets a new VertexBuffer each call.
  23951. * Returns the Mesh.
  23952. */
  23953. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  23954. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  23955. this.scaling.copyFromFloats(1, 1, 1);
  23956. this.position.copyFromFloats(0, 0, 0);
  23957. this.rotation.copyFromFloats(0, 0, 0);
  23958. //only if quaternion is already set
  23959. if (this.rotationQuaternion) {
  23960. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  23961. }
  23962. this._worldMatrix = BABYLON.Matrix.Identity();
  23963. return this;
  23964. };
  23965. // Cache
  23966. Mesh.prototype._resetPointsArrayCache = function () {
  23967. this._positions = null;
  23968. return this;
  23969. };
  23970. Mesh.prototype._generatePointsArray = function () {
  23971. if (this._positions)
  23972. return true;
  23973. this._positions = [];
  23974. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  23975. if (!data) {
  23976. return false;
  23977. }
  23978. for (var index = 0; index < data.length; index += 3) {
  23979. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  23980. }
  23981. return true;
  23982. };
  23983. /**
  23984. * Returns a new Mesh object generated from the current mesh properties.
  23985. * This method must not get confused with createInstance().
  23986. * The parameter `name` is a string, the name given to the new mesh.
  23987. * The optional parameter `newParent` can be any Node object (default `null`).
  23988. * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any.
  23989. * 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.
  23990. */
  23991. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  23992. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  23993. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  23994. };
  23995. /**
  23996. * Disposes the mesh.
  23997. * This also frees the memory allocated under the hood to all the buffers used by WebGL.
  23998. */
  23999. Mesh.prototype.dispose = function (doNotRecurse) {
  24000. var _this = this;
  24001. if (this._geometry) {
  24002. this._geometry.releaseForMesh(this, true);
  24003. }
  24004. // Sources
  24005. var meshes = this.getScene().meshes;
  24006. meshes.forEach(function (mesh) {
  24007. if (mesh._source && mesh._source === _this) {
  24008. mesh._source = null;
  24009. }
  24010. });
  24011. this._source = null;
  24012. // Instances
  24013. if (this._instancesBuffer) {
  24014. this._instancesBuffer.dispose();
  24015. this._instancesBuffer = null;
  24016. }
  24017. while (this.instances.length) {
  24018. this.instances[0].dispose();
  24019. }
  24020. // Highlight layers.
  24021. var highlightLayers = this.getScene().highlightLayers;
  24022. for (var i = 0; i < highlightLayers.length; i++) {
  24023. var highlightLayer = highlightLayers[i];
  24024. if (highlightLayer) {
  24025. highlightLayer.removeMesh(this);
  24026. highlightLayer.removeExcludedMesh(this);
  24027. }
  24028. }
  24029. _super.prototype.dispose.call(this, doNotRecurse);
  24030. };
  24031. /**
  24032. * Modifies the mesh geometry according to a displacement map.
  24033. * 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.
  24034. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  24035. * This method returns nothing.
  24036. * The parameter `url` is a string, the URL from the image file is to be downloaded.
  24037. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  24038. * 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.
  24039. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  24040. * The parameter `uvScale` is an optional vector2 used to scale UV.
  24041. *
  24042. * Returns the Mesh.
  24043. */
  24044. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess, uvOffset, uvScale) {
  24045. var _this = this;
  24046. var scene = this.getScene();
  24047. var onload = function (img) {
  24048. // Getting height map data
  24049. var canvas = document.createElement("canvas");
  24050. var context = canvas.getContext("2d");
  24051. var heightMapWidth = img.width;
  24052. var heightMapHeight = img.height;
  24053. canvas.width = heightMapWidth;
  24054. canvas.height = heightMapHeight;
  24055. context.drawImage(img, 0, 0);
  24056. // Create VertexData from map data
  24057. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  24058. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  24059. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale);
  24060. //execute success callback, if set
  24061. if (onSuccess) {
  24062. onSuccess(_this);
  24063. }
  24064. };
  24065. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  24066. return this;
  24067. };
  24068. /**
  24069. * Modifies the mesh geometry according to a displacementMap buffer.
  24070. * 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.
  24071. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  24072. * This method returns nothing.
  24073. * 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.
  24074. * The parameters `heightMapWidth` and `heightMapHeight` are positive integers to set the width and height of the buffer image.
  24075. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  24076. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  24077. * The parameter `uvScale` is an optional vector2 used to scale UV.
  24078. *
  24079. * Returns the Mesh.
  24080. */
  24081. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale) {
  24082. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  24083. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  24084. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  24085. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  24086. return this;
  24087. }
  24088. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  24089. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  24090. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  24091. var position = BABYLON.Vector3.Zero();
  24092. var normal = BABYLON.Vector3.Zero();
  24093. var uv = BABYLON.Vector2.Zero();
  24094. uvOffset = uvOffset || BABYLON.Vector2.Zero();
  24095. uvScale = uvScale || new BABYLON.Vector2(1, 1);
  24096. for (var index = 0; index < positions.length; index += 3) {
  24097. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  24098. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  24099. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  24100. // Compute height
  24101. var u = ((Math.abs(uv.x * uvScale.x + uvOffset.x) * heightMapWidth) % heightMapWidth) | 0;
  24102. var v = ((Math.abs(uv.y * uvScale.y + uvOffset.y) * heightMapHeight) % heightMapHeight) | 0;
  24103. var pos = (u + v * heightMapWidth) * 4;
  24104. var r = buffer[pos] / 255.0;
  24105. var g = buffer[pos + 1] / 255.0;
  24106. var b = buffer[pos + 2] / 255.0;
  24107. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  24108. normal.normalize();
  24109. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  24110. position = position.add(normal);
  24111. position.toArray(positions, index);
  24112. }
  24113. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  24114. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  24115. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  24116. return this;
  24117. };
  24118. /**
  24119. * Modify the mesh to get a flat shading rendering.
  24120. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  24121. * This method returns the Mesh.
  24122. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  24123. */
  24124. Mesh.prototype.convertToFlatShadedMesh = function () {
  24125. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  24126. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  24127. var kinds = this.getVerticesDataKinds();
  24128. var vbs = [];
  24129. var data = [];
  24130. var newdata = [];
  24131. var updatableNormals = false;
  24132. var kindIndex;
  24133. var kind;
  24134. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  24135. kind = kinds[kindIndex];
  24136. var vertexBuffer = this.getVertexBuffer(kind);
  24137. if (kind === BABYLON.VertexBuffer.NormalKind) {
  24138. updatableNormals = vertexBuffer.isUpdatable();
  24139. kinds.splice(kindIndex, 1);
  24140. kindIndex--;
  24141. continue;
  24142. }
  24143. vbs[kind] = vertexBuffer;
  24144. data[kind] = vbs[kind].getData();
  24145. newdata[kind] = [];
  24146. }
  24147. // Save previous submeshes
  24148. var previousSubmeshes = this.subMeshes.slice(0);
  24149. var indices = this.getIndices();
  24150. var totalIndices = this.getTotalIndices();
  24151. // Generating unique vertices per face
  24152. var index;
  24153. for (index = 0; index < totalIndices; index++) {
  24154. var vertexIndex = indices[index];
  24155. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  24156. kind = kinds[kindIndex];
  24157. var stride = vbs[kind].getStrideSize();
  24158. for (var offset = 0; offset < stride; offset++) {
  24159. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  24160. }
  24161. }
  24162. }
  24163. // Updating faces & normal
  24164. var normals = [];
  24165. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  24166. for (index = 0; index < totalIndices; index += 3) {
  24167. indices[index] = index;
  24168. indices[index + 1] = index + 1;
  24169. indices[index + 2] = index + 2;
  24170. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  24171. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  24172. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  24173. var p1p2 = p1.subtract(p2);
  24174. var p3p2 = p3.subtract(p2);
  24175. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  24176. // Store same normals for every vertex
  24177. for (var localIndex = 0; localIndex < 3; localIndex++) {
  24178. normals.push(normal.x);
  24179. normals.push(normal.y);
  24180. normals.push(normal.z);
  24181. }
  24182. }
  24183. this.setIndices(indices);
  24184. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  24185. // Updating vertex buffers
  24186. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  24187. kind = kinds[kindIndex];
  24188. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  24189. }
  24190. // Updating submeshes
  24191. this.releaseSubMeshes();
  24192. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  24193. var previousOne = previousSubmeshes[submeshIndex];
  24194. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  24195. }
  24196. this.synchronizeInstances();
  24197. return this;
  24198. };
  24199. /**
  24200. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  24201. * In other words, more vertices, no more indices and a single bigger VBO.
  24202. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  24203. * Returns the Mesh.
  24204. */
  24205. Mesh.prototype.convertToUnIndexedMesh = function () {
  24206. /// <summary>Remove indices by unfolding faces into buffers</summary>
  24207. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  24208. var kinds = this.getVerticesDataKinds();
  24209. var vbs = [];
  24210. var data = [];
  24211. var newdata = [];
  24212. var updatableNormals = false;
  24213. var kindIndex;
  24214. var kind;
  24215. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  24216. kind = kinds[kindIndex];
  24217. var vertexBuffer = this.getVertexBuffer(kind);
  24218. vbs[kind] = vertexBuffer;
  24219. data[kind] = vbs[kind].getData();
  24220. newdata[kind] = [];
  24221. }
  24222. // Save previous submeshes
  24223. var previousSubmeshes = this.subMeshes.slice(0);
  24224. var indices = this.getIndices();
  24225. var totalIndices = this.getTotalIndices();
  24226. // Generating unique vertices per face
  24227. var index;
  24228. for (index = 0; index < totalIndices; index++) {
  24229. var vertexIndex = indices[index];
  24230. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  24231. kind = kinds[kindIndex];
  24232. var stride = vbs[kind].getStrideSize();
  24233. for (var offset = 0; offset < stride; offset++) {
  24234. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  24235. }
  24236. }
  24237. }
  24238. // Updating indices
  24239. for (index = 0; index < totalIndices; index += 3) {
  24240. indices[index] = index;
  24241. indices[index + 1] = index + 1;
  24242. indices[index + 2] = index + 2;
  24243. }
  24244. this.setIndices(indices);
  24245. // Updating vertex buffers
  24246. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  24247. kind = kinds[kindIndex];
  24248. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  24249. }
  24250. // Updating submeshes
  24251. this.releaseSubMeshes();
  24252. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  24253. var previousOne = previousSubmeshes[submeshIndex];
  24254. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  24255. }
  24256. this._unIndexed = true;
  24257. this.synchronizeInstances();
  24258. return this;
  24259. };
  24260. /**
  24261. * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true.
  24262. * This method returns the Mesh.
  24263. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  24264. */
  24265. Mesh.prototype.flipFaces = function (flipNormals) {
  24266. if (flipNormals === void 0) { flipNormals = false; }
  24267. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  24268. var i;
  24269. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  24270. for (i = 0; i < vertex_data.normals.length; i++) {
  24271. vertex_data.normals[i] *= -1;
  24272. }
  24273. }
  24274. var temp;
  24275. for (i = 0; i < vertex_data.indices.length; i += 3) {
  24276. // reassign indices
  24277. temp = vertex_data.indices[i + 1];
  24278. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  24279. vertex_data.indices[i + 2] = temp;
  24280. }
  24281. vertex_data.applyToMesh(this);
  24282. return this;
  24283. };
  24284. // Instances
  24285. /**
  24286. * Creates a new InstancedMesh object from the mesh model.
  24287. * An instance shares the same properties and the same material than its model.
  24288. * Only these properties of each instance can then be set individually :
  24289. * - position
  24290. * - rotation
  24291. * - rotationQuaternion
  24292. * - setPivotMatrix
  24293. * - scaling
  24294. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_Instances
  24295. * Warning : this method is not supported for Line mesh and LineSystem
  24296. */
  24297. Mesh.prototype.createInstance = function (name) {
  24298. return new BABYLON.InstancedMesh(name, this);
  24299. };
  24300. /**
  24301. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  24302. * After this call, all the mesh instances have the same submeshes than the current mesh.
  24303. * This method returns the Mesh.
  24304. */
  24305. Mesh.prototype.synchronizeInstances = function () {
  24306. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  24307. var instance = this.instances[instanceIndex];
  24308. instance._syncSubMeshes();
  24309. }
  24310. return this;
  24311. };
  24312. /**
  24313. * Simplify the mesh according to the given array of settings.
  24314. * Function will return immediately and will simplify async. It returns the Mesh.
  24315. * @param settings a collection of simplification settings.
  24316. * @param parallelProcessing should all levels calculate parallel or one after the other.
  24317. * @param type the type of simplification to run.
  24318. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  24319. */
  24320. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  24321. if (parallelProcessing === void 0) { parallelProcessing = true; }
  24322. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  24323. this.getScene().simplificationQueue.addTask({
  24324. settings: settings,
  24325. parallelProcessing: parallelProcessing,
  24326. mesh: this,
  24327. simplificationType: simplificationType,
  24328. successCallback: successCallback
  24329. });
  24330. return this;
  24331. };
  24332. /**
  24333. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  24334. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  24335. * This should be used together with the simplification to avoid disappearing triangles.
  24336. * Returns the Mesh.
  24337. * @param successCallback an optional success callback to be called after the optimization finished.
  24338. */
  24339. Mesh.prototype.optimizeIndices = function (successCallback) {
  24340. var _this = this;
  24341. var indices = this.getIndices();
  24342. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  24343. var vectorPositions = [];
  24344. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  24345. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  24346. }
  24347. var dupes = [];
  24348. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  24349. var realPos = vectorPositions.length - 1 - iteration;
  24350. var testedPosition = vectorPositions[realPos];
  24351. for (var j = 0; j < realPos; ++j) {
  24352. var againstPosition = vectorPositions[j];
  24353. if (testedPosition.equals(againstPosition)) {
  24354. dupes[realPos] = j;
  24355. break;
  24356. }
  24357. }
  24358. }, function () {
  24359. for (var i = 0; i < indices.length; ++i) {
  24360. indices[i] = dupes[indices[i]] || indices[i];
  24361. }
  24362. //indices are now reordered
  24363. var originalSubMeshes = _this.subMeshes.slice(0);
  24364. _this.setIndices(indices);
  24365. _this.subMeshes = originalSubMeshes;
  24366. if (successCallback) {
  24367. successCallback(_this);
  24368. }
  24369. });
  24370. return this;
  24371. };
  24372. Mesh.prototype.serialize = function (serializationObject) {
  24373. serializationObject.name = this.name;
  24374. serializationObject.id = this.id;
  24375. serializationObject.type = this.getClassName();
  24376. if (BABYLON.Tags.HasTags(this)) {
  24377. serializationObject.tags = BABYLON.Tags.GetTags(this);
  24378. }
  24379. serializationObject.position = this.position.asArray();
  24380. if (this.rotationQuaternion) {
  24381. serializationObject.rotationQuaternion = this.rotationQuaternion.asArray();
  24382. }
  24383. else if (this.rotation) {
  24384. serializationObject.rotation = this.rotation.asArray();
  24385. }
  24386. serializationObject.scaling = this.scaling.asArray();
  24387. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  24388. serializationObject.isEnabled = this.isEnabled();
  24389. serializationObject.isVisible = this.isVisible;
  24390. serializationObject.infiniteDistance = this.infiniteDistance;
  24391. serializationObject.pickable = this.isPickable;
  24392. serializationObject.receiveShadows = this.receiveShadows;
  24393. serializationObject.billboardMode = this.billboardMode;
  24394. serializationObject.visibility = this.visibility;
  24395. serializationObject.checkCollisions = this.checkCollisions;
  24396. serializationObject.isBlocker = this.isBlocker;
  24397. // Parent
  24398. if (this.parent) {
  24399. serializationObject.parentId = this.parent.id;
  24400. }
  24401. // Geometry
  24402. var geometry = this._geometry;
  24403. if (geometry) {
  24404. var geometryId = geometry.id;
  24405. serializationObject.geometryId = geometryId;
  24406. // SubMeshes
  24407. serializationObject.subMeshes = [];
  24408. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  24409. var subMesh = this.subMeshes[subIndex];
  24410. serializationObject.subMeshes.push({
  24411. materialIndex: subMesh.materialIndex,
  24412. verticesStart: subMesh.verticesStart,
  24413. verticesCount: subMesh.verticesCount,
  24414. indexStart: subMesh.indexStart,
  24415. indexCount: subMesh.indexCount
  24416. });
  24417. }
  24418. }
  24419. // Material
  24420. if (this.material) {
  24421. serializationObject.materialId = this.material.id;
  24422. }
  24423. else {
  24424. this.material = null;
  24425. }
  24426. // Skeleton
  24427. if (this.skeleton) {
  24428. serializationObject.skeletonId = this.skeleton.id;
  24429. }
  24430. // Physics
  24431. //TODO implement correct serialization for physics impostors.
  24432. if (this.getPhysicsImpostor()) {
  24433. var impostor = this.getPhysicsImpostor();
  24434. serializationObject.physicsMass = impostor.getParam("mass");
  24435. serializationObject.physicsFriction = impostor.getParam("friction");
  24436. serializationObject.physicsRestitution = impostor.getParam("mass");
  24437. serializationObject.physicsImpostor = this.getPhysicsImpostor().type;
  24438. }
  24439. // Metadata
  24440. if (this.metadata) {
  24441. serializationObject.metadata = this.metadata;
  24442. }
  24443. // Instances
  24444. serializationObject.instances = [];
  24445. for (var index = 0; index < this.instances.length; index++) {
  24446. var instance = this.instances[index];
  24447. var serializationInstance = {
  24448. name: instance.name,
  24449. position: instance.position.asArray(),
  24450. scaling: instance.scaling.asArray()
  24451. };
  24452. if (instance.rotationQuaternion) {
  24453. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  24454. }
  24455. else if (instance.rotation) {
  24456. serializationInstance.rotation = instance.rotation.asArray();
  24457. }
  24458. serializationObject.instances.push(serializationInstance);
  24459. // Animations
  24460. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  24461. serializationInstance.ranges = instance.serializeAnimationRanges();
  24462. }
  24463. // Animations
  24464. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  24465. serializationObject.ranges = this.serializeAnimationRanges();
  24466. // Layer mask
  24467. serializationObject.layerMask = this.layerMask;
  24468. // Alpha
  24469. serializationObject.alphaIndex = this.alphaIndex;
  24470. serializationObject.hasVertexAlpha = this.hasVertexAlpha;
  24471. // Overlay
  24472. serializationObject.overlayAlpha = this.overlayAlpha;
  24473. serializationObject.overlayColor = this.overlayColor.asArray();
  24474. serializationObject.renderOverlay = this.renderOverlay;
  24475. // Fog
  24476. serializationObject.applyFog = this.applyFog;
  24477. // Action Manager
  24478. if (this.actionManager) {
  24479. serializationObject.actions = this.actionManager.serialize(this.name);
  24480. }
  24481. };
  24482. // Statics
  24483. /**
  24484. * Returns a new Mesh object what is a deep copy of the passed mesh.
  24485. * The parameter `parsedMesh` is the mesh to be copied.
  24486. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  24487. */
  24488. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  24489. var mesh;
  24490. if (parsedMesh.type && parsedMesh.type === "GroundMesh") {
  24491. mesh = BABYLON.GroundMesh.Parse(parsedMesh, scene);
  24492. }
  24493. else {
  24494. mesh = new Mesh(parsedMesh.name, scene);
  24495. }
  24496. mesh.id = parsedMesh.id;
  24497. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  24498. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  24499. if (parsedMesh.metadata !== undefined) {
  24500. mesh.metadata = parsedMesh.metadata;
  24501. }
  24502. if (parsedMesh.rotationQuaternion) {
  24503. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  24504. }
  24505. else if (parsedMesh.rotation) {
  24506. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  24507. }
  24508. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  24509. if (parsedMesh.localMatrix) {
  24510. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  24511. }
  24512. else if (parsedMesh.pivotMatrix) {
  24513. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  24514. }
  24515. mesh.setEnabled(parsedMesh.isEnabled);
  24516. mesh.isVisible = parsedMesh.isVisible;
  24517. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  24518. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  24519. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  24520. if (parsedMesh.applyFog !== undefined) {
  24521. mesh.applyFog = parsedMesh.applyFog;
  24522. }
  24523. if (parsedMesh.pickable !== undefined) {
  24524. mesh.isPickable = parsedMesh.pickable;
  24525. }
  24526. if (parsedMesh.alphaIndex !== undefined) {
  24527. mesh.alphaIndex = parsedMesh.alphaIndex;
  24528. }
  24529. mesh.receiveShadows = parsedMesh.receiveShadows;
  24530. mesh.billboardMode = parsedMesh.billboardMode;
  24531. if (parsedMesh.visibility !== undefined) {
  24532. mesh.visibility = parsedMesh.visibility;
  24533. }
  24534. mesh.checkCollisions = parsedMesh.checkCollisions;
  24535. if (parsedMesh.isBlocker !== undefined) {
  24536. mesh.isBlocker = parsedMesh.isBlocker;
  24537. }
  24538. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  24539. // freezeWorldMatrix
  24540. if (parsedMesh.freezeWorldMatrix) {
  24541. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  24542. }
  24543. // Parent
  24544. if (parsedMesh.parentId) {
  24545. mesh._waitingParentId = parsedMesh.parentId;
  24546. }
  24547. // Actions
  24548. if (parsedMesh.actions !== undefined) {
  24549. mesh._waitingActions = parsedMesh.actions;
  24550. }
  24551. // Overlay
  24552. if (parsedMesh.overlayAlpha !== undefined) {
  24553. mesh.overlayAlpha = parsedMesh.overlayAlpha;
  24554. }
  24555. if (parsedMesh.overlayColor !== undefined) {
  24556. mesh.overlayColor = BABYLON.Color3.FromArray(parsedMesh.overlayColor);
  24557. }
  24558. if (parsedMesh.renderOverlay !== undefined) {
  24559. mesh.renderOverlay = parsedMesh.renderOverlay;
  24560. }
  24561. // Geometry
  24562. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  24563. if (parsedMesh.delayLoadingFile) {
  24564. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  24565. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  24566. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  24567. if (parsedMesh._binaryInfo) {
  24568. mesh._binaryInfo = parsedMesh._binaryInfo;
  24569. }
  24570. mesh._delayInfo = [];
  24571. if (parsedMesh.hasUVs) {
  24572. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  24573. }
  24574. if (parsedMesh.hasUVs2) {
  24575. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  24576. }
  24577. if (parsedMesh.hasUVs3) {
  24578. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  24579. }
  24580. if (parsedMesh.hasUVs4) {
  24581. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  24582. }
  24583. if (parsedMesh.hasUVs5) {
  24584. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  24585. }
  24586. if (parsedMesh.hasUVs6) {
  24587. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  24588. }
  24589. if (parsedMesh.hasColors) {
  24590. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  24591. }
  24592. if (parsedMesh.hasMatricesIndices) {
  24593. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  24594. }
  24595. if (parsedMesh.hasMatricesWeights) {
  24596. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  24597. }
  24598. mesh._delayLoadingFunction = BABYLON.Geometry.ImportGeometry;
  24599. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  24600. mesh._checkDelayState();
  24601. }
  24602. }
  24603. else {
  24604. BABYLON.Geometry.ImportGeometry(parsedMesh, mesh);
  24605. }
  24606. // Material
  24607. if (parsedMesh.materialId) {
  24608. mesh.setMaterialByID(parsedMesh.materialId);
  24609. }
  24610. else {
  24611. mesh.material = null;
  24612. }
  24613. // Skeleton
  24614. if (parsedMesh.skeletonId > -1) {
  24615. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  24616. if (parsedMesh.numBoneInfluencers) {
  24617. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  24618. }
  24619. }
  24620. // Animations
  24621. if (parsedMesh.animations) {
  24622. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  24623. var parsedAnimation = parsedMesh.animations[animationIndex];
  24624. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  24625. }
  24626. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  24627. }
  24628. if (parsedMesh.autoAnimate) {
  24629. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  24630. }
  24631. // Layer Mask
  24632. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  24633. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  24634. }
  24635. else {
  24636. mesh.layerMask = 0x0FFFFFFF;
  24637. }
  24638. // Physics
  24639. if (parsedMesh.physicsImpostor) {
  24640. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  24641. mass: parsedMesh.physicsMass,
  24642. friction: parsedMesh.physicsFriction,
  24643. restitution: parsedMesh.physicsRestitution
  24644. }, scene);
  24645. }
  24646. // Instances
  24647. if (parsedMesh.instances) {
  24648. for (var index = 0; index < parsedMesh.instances.length; index++) {
  24649. var parsedInstance = parsedMesh.instances[index];
  24650. var instance = mesh.createInstance(parsedInstance.name);
  24651. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  24652. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  24653. if (parsedInstance.parentId) {
  24654. instance._waitingParentId = parsedInstance.parentId;
  24655. }
  24656. if (parsedInstance.rotationQuaternion) {
  24657. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  24658. }
  24659. else if (parsedInstance.rotation) {
  24660. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  24661. }
  24662. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  24663. instance.checkCollisions = mesh.checkCollisions;
  24664. if (parsedMesh.animations) {
  24665. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  24666. parsedAnimation = parsedMesh.animations[animationIndex];
  24667. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  24668. }
  24669. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  24670. }
  24671. }
  24672. }
  24673. return mesh;
  24674. };
  24675. /**
  24676. * Creates a ribbon mesh.
  24677. * Please consider using the same method from the MeshBuilder class instead.
  24678. * 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.
  24679. *
  24680. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  24681. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  24682. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  24683. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  24684. * 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.
  24685. * 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.
  24686. * 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
  24687. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  24688. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  24689. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24690. */
  24691. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  24692. return BABYLON.MeshBuilder.CreateRibbon(name, {
  24693. pathArray: pathArray,
  24694. closeArray: closeArray,
  24695. closePath: closePath,
  24696. offset: offset,
  24697. updatable: updatable,
  24698. sideOrientation: sideOrientation,
  24699. instance: instance
  24700. }, scene);
  24701. };
  24702. /**
  24703. * Creates a plane polygonal mesh. By default, this is a disc.
  24704. * Please consider using the same method from the MeshBuilder class instead.
  24705. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  24706. * 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.
  24707. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  24708. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  24709. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24710. */
  24711. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  24712. var options = {
  24713. radius: radius,
  24714. tessellation: tessellation,
  24715. sideOrientation: sideOrientation,
  24716. updatable: updatable
  24717. };
  24718. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  24719. };
  24720. /**
  24721. * Creates a box mesh.
  24722. * Please consider using the same method from the MeshBuilder class instead.
  24723. * The parameter `size` sets the size (float) of each box side (default 1).
  24724. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  24725. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  24726. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24727. */
  24728. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  24729. var options = {
  24730. size: size,
  24731. sideOrientation: sideOrientation,
  24732. updatable: updatable
  24733. };
  24734. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  24735. };
  24736. /**
  24737. * Creates a sphere mesh.
  24738. * Please consider using the same method from the MeshBuilder class instead.
  24739. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  24740. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  24741. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  24742. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  24743. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24744. */
  24745. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  24746. var options = {
  24747. segments: segments,
  24748. diameterX: diameter,
  24749. diameterY: diameter,
  24750. diameterZ: diameter,
  24751. sideOrientation: sideOrientation,
  24752. updatable: updatable
  24753. };
  24754. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  24755. };
  24756. /**
  24757. * Creates a cylinder or a cone mesh.
  24758. * Please consider using the same method from the MeshBuilder class instead.
  24759. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  24760. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  24761. * 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.
  24762. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  24763. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  24764. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  24765. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  24766. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24767. */
  24768. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  24769. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  24770. if (scene !== undefined) {
  24771. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  24772. updatable = scene;
  24773. }
  24774. scene = subdivisions;
  24775. subdivisions = 1;
  24776. }
  24777. var options = {
  24778. height: height,
  24779. diameterTop: diameterTop,
  24780. diameterBottom: diameterBottom,
  24781. tessellation: tessellation,
  24782. subdivisions: subdivisions,
  24783. sideOrientation: sideOrientation,
  24784. updatable: updatable
  24785. };
  24786. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  24787. };
  24788. // Torus (Code from SharpDX.org)
  24789. /**
  24790. * Creates a torus mesh.
  24791. * Please consider using the same method from the MeshBuilder class instead.
  24792. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  24793. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  24794. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  24795. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  24796. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  24797. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24798. */
  24799. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  24800. var options = {
  24801. diameter: diameter,
  24802. thickness: thickness,
  24803. tessellation: tessellation,
  24804. sideOrientation: sideOrientation,
  24805. updatable: updatable
  24806. };
  24807. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  24808. };
  24809. /**
  24810. * Creates a torus knot mesh.
  24811. * Please consider using the same method from the MeshBuilder class instead.
  24812. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  24813. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  24814. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  24815. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  24816. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  24817. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  24818. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24819. */
  24820. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  24821. var options = {
  24822. radius: radius,
  24823. tube: tube,
  24824. radialSegments: radialSegments,
  24825. tubularSegments: tubularSegments,
  24826. p: p,
  24827. q: q,
  24828. sideOrientation: sideOrientation,
  24829. updatable: updatable
  24830. };
  24831. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  24832. };
  24833. /**
  24834. * Creates a line mesh.
  24835. * Please consider using the same method from the MeshBuilder class instead.
  24836. * 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.
  24837. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  24838. * The parameter `points` is an array successive Vector3.
  24839. * 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
  24840. * When updating an instance, remember that only point positions can change, not the number of points.
  24841. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24842. */
  24843. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  24844. var options = {
  24845. points: points,
  24846. updatable: updatable,
  24847. instance: instance
  24848. };
  24849. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  24850. };
  24851. /**
  24852. * Creates a dashed line mesh.
  24853. * Please consider using the same method from the MeshBuilder class instead.
  24854. * 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.
  24855. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  24856. * The parameter `points` is an array successive Vector3.
  24857. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  24858. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  24859. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  24860. * 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
  24861. * When updating an instance, remember that only point positions can change, not the number of points.
  24862. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24863. */
  24864. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  24865. var options = {
  24866. points: points,
  24867. dashSize: dashSize,
  24868. gapSize: gapSize,
  24869. dashNb: dashNb,
  24870. updatable: updatable,
  24871. instance: instance
  24872. };
  24873. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  24874. };
  24875. /**
  24876. * Creates an extruded shape mesh.
  24877. * 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.
  24878. * Please consider using the same method from the MeshBuilder class instead.
  24879. *
  24880. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  24881. * 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
  24882. * extruded along the Z axis.
  24883. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  24884. * 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.
  24885. * The parameter `scale` (float, default 1) is the value to scale the shape.
  24886. * 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
  24887. * 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
  24888. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  24889. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  24890. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  24891. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24892. */
  24893. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  24894. var options = {
  24895. shape: shape,
  24896. path: path,
  24897. scale: scale,
  24898. rotation: rotation,
  24899. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  24900. sideOrientation: sideOrientation,
  24901. instance: instance,
  24902. updatable: updatable
  24903. };
  24904. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  24905. };
  24906. /**
  24907. * Creates an custom extruded shape mesh.
  24908. * 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.
  24909. * Please consider using the same method from the MeshBuilder class instead.
  24910. *
  24911. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  24912. * 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
  24913. * extruded along the Z axis.
  24914. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  24915. * 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
  24916. * and the distance of this point from the begining of the path :
  24917. * ```javascript
  24918. * var rotationFunction = function(i, distance) {
  24919. * // do things
  24920. * return rotationValue; }
  24921. * ```
  24922. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  24923. * 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
  24924. * and the distance of this point from the begining of the path :
  24925. * ```javascript
  24926. * var scaleFunction = function(i, distance) {
  24927. * // do things
  24928. * return scaleValue;}
  24929. * ```
  24930. * It must returns a float value that will be the scale value applied to the shape on each path point.
  24931. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  24932. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  24933. * 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
  24934. * 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
  24935. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  24936. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  24937. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  24938. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24939. */
  24940. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  24941. var options = {
  24942. shape: shape,
  24943. path: path,
  24944. scaleFunction: scaleFunction,
  24945. rotationFunction: rotationFunction,
  24946. ribbonCloseArray: ribbonCloseArray,
  24947. ribbonClosePath: ribbonClosePath,
  24948. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  24949. sideOrientation: sideOrientation,
  24950. instance: instance,
  24951. updatable: updatable
  24952. };
  24953. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  24954. };
  24955. /**
  24956. * Creates lathe mesh.
  24957. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  24958. * Please consider using the same method from the MeshBuilder class instead.
  24959. * 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
  24960. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  24961. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  24962. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  24963. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  24964. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  24965. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24966. */
  24967. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  24968. var options = {
  24969. shape: shape,
  24970. radius: radius,
  24971. tessellation: tessellation,
  24972. sideOrientation: sideOrientation,
  24973. updatable: updatable
  24974. };
  24975. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  24976. };
  24977. /**
  24978. * Creates a plane mesh.
  24979. * Please consider using the same method from the MeshBuilder class instead.
  24980. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  24981. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  24982. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  24983. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24984. */
  24985. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  24986. var options = {
  24987. size: size,
  24988. width: size,
  24989. height: size,
  24990. sideOrientation: sideOrientation,
  24991. updatable: updatable
  24992. };
  24993. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  24994. };
  24995. /**
  24996. * Creates a ground mesh.
  24997. * Please consider using the same method from the MeshBuilder class instead.
  24998. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  24999. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  25000. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25001. */
  25002. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  25003. var options = {
  25004. width: width,
  25005. height: height,
  25006. subdivisions: subdivisions,
  25007. updatable: updatable
  25008. };
  25009. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  25010. };
  25011. /**
  25012. * Creates a tiled ground mesh.
  25013. * Please consider using the same method from the MeshBuilder class instead.
  25014. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  25015. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  25016. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  25017. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  25018. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  25019. * numbers of subdivisions on the ground width and height of each tile.
  25020. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25021. */
  25022. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  25023. var options = {
  25024. xmin: xmin,
  25025. zmin: zmin,
  25026. xmax: xmax,
  25027. zmax: zmax,
  25028. subdivisions: subdivisions,
  25029. precision: precision,
  25030. updatable: updatable
  25031. };
  25032. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  25033. };
  25034. /**
  25035. * Creates a ground mesh from a height map.
  25036. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  25037. * Please consider using the same method from the MeshBuilder class instead.
  25038. * The parameter `url` sets the URL of the height map image resource.
  25039. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  25040. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  25041. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  25042. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  25043. * 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).
  25044. * This function is passed the newly built mesh :
  25045. * ```javascript
  25046. * function(mesh) { // do things
  25047. * return; }
  25048. * ```
  25049. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25050. */
  25051. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  25052. var options = {
  25053. width: width,
  25054. height: height,
  25055. subdivisions: subdivisions,
  25056. minHeight: minHeight,
  25057. maxHeight: maxHeight,
  25058. updatable: updatable,
  25059. onReady: onReady
  25060. };
  25061. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  25062. };
  25063. /**
  25064. * Creates a tube mesh.
  25065. * 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.
  25066. * Please consider using the same method from the MeshBuilder class instead.
  25067. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  25068. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  25069. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  25070. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  25071. * 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.
  25072. * It must return a radius value (positive float) :
  25073. * ```javascript
  25074. * var radiusFunction = function(i, distance) {
  25075. * // do things
  25076. * return radius; }
  25077. * ```
  25078. * 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
  25079. * 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
  25080. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  25081. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  25082. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25083. */
  25084. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  25085. var options = {
  25086. path: path,
  25087. radius: radius,
  25088. tessellation: tessellation,
  25089. radiusFunction: radiusFunction,
  25090. arc: 1,
  25091. cap: cap,
  25092. updatable: updatable,
  25093. sideOrientation: sideOrientation,
  25094. instance: instance
  25095. };
  25096. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  25097. };
  25098. /**
  25099. * Creates a polyhedron mesh.
  25100. * Please consider using the same method from the MeshBuilder class instead.
  25101. * 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
  25102. * to choose the wanted type.
  25103. * The parameter `size` (positive float, default 1) sets the polygon size.
  25104. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  25105. * 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`.
  25106. * 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
  25107. * 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)`).
  25108. * 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
  25109. * 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.
  25110. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  25111. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  25112. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25113. */
  25114. Mesh.CreatePolyhedron = function (name, options, scene) {
  25115. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  25116. };
  25117. /**
  25118. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  25119. * Please consider using the same method from the MeshBuilder class instead.
  25120. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  25121. * 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`).
  25122. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  25123. * 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.
  25124. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  25125. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  25126. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25127. */
  25128. Mesh.CreateIcoSphere = function (name, options, scene) {
  25129. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  25130. };
  25131. /**
  25132. * Creates a decal mesh.
  25133. * Please consider using the same method from the MeshBuilder class instead.
  25134. * 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.
  25135. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  25136. * The parameter `normal` (Vector3, default Vector3.Up) sets the normal of the mesh where the decal is applied onto in World coordinates.
  25137. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  25138. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  25139. */
  25140. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  25141. var options = {
  25142. position: position,
  25143. normal: normal,
  25144. size: size,
  25145. angle: angle
  25146. };
  25147. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  25148. };
  25149. // Skeletons
  25150. /**
  25151. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  25152. */
  25153. Mesh.prototype.setPositionsForCPUSkinning = function () {
  25154. var source;
  25155. if (!this._sourcePositions) {
  25156. source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  25157. this._sourcePositions = new Float32Array(source);
  25158. if (!this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable()) {
  25159. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  25160. }
  25161. }
  25162. return this._sourcePositions;
  25163. };
  25164. /**
  25165. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  25166. */
  25167. Mesh.prototype.setNormalsForCPUSkinning = function () {
  25168. var source;
  25169. if (!this._sourceNormals) {
  25170. source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  25171. this._sourceNormals = new Float32Array(source);
  25172. if (!this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable()) {
  25173. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  25174. }
  25175. }
  25176. return this._sourceNormals;
  25177. };
  25178. /**
  25179. * Updates the vertex buffer by applying transformation from the bones.
  25180. * Returns the Mesh.
  25181. *
  25182. * @param {skeleton} skeleton to apply
  25183. */
  25184. Mesh.prototype.applySkeleton = function (skeleton) {
  25185. if (!this.geometry) {
  25186. return this;
  25187. }
  25188. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  25189. return this;
  25190. }
  25191. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  25192. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  25193. return this;
  25194. }
  25195. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  25196. return this;
  25197. }
  25198. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  25199. return this;
  25200. }
  25201. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  25202. return this;
  25203. }
  25204. if (!this._sourcePositions) {
  25205. var submeshes = this.subMeshes.slice();
  25206. this.setPositionsForCPUSkinning();
  25207. this.subMeshes = submeshes;
  25208. }
  25209. if (!this._sourceNormals) {
  25210. this.setNormalsForCPUSkinning();
  25211. }
  25212. // positionsData checks for not being Float32Array will only pass at most once
  25213. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  25214. if (!(positionsData instanceof Float32Array)) {
  25215. positionsData = new Float32Array(positionsData);
  25216. }
  25217. // normalsData checks for not being Float32Array will only pass at most once
  25218. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  25219. if (!(normalsData instanceof Float32Array)) {
  25220. normalsData = new Float32Array(normalsData);
  25221. }
  25222. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  25223. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  25224. var needExtras = this.numBoneInfluencers > 4;
  25225. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  25226. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  25227. var skeletonMatrices = skeleton.getTransformMatrices(this);
  25228. var tempVector3 = BABYLON.Vector3.Zero();
  25229. var finalMatrix = new BABYLON.Matrix();
  25230. var tempMatrix = new BABYLON.Matrix();
  25231. var matWeightIdx = 0;
  25232. var inf;
  25233. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  25234. var weight;
  25235. for (inf = 0; inf < 4; inf++) {
  25236. weight = matricesWeightsData[matWeightIdx + inf];
  25237. if (weight > 0) {
  25238. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[matWeightIdx + inf] * 16, weight, tempMatrix);
  25239. finalMatrix.addToSelf(tempMatrix);
  25240. }
  25241. else
  25242. break;
  25243. }
  25244. if (needExtras) {
  25245. for (inf = 0; inf < 4; inf++) {
  25246. weight = matricesWeightsExtraData[matWeightIdx + inf];
  25247. if (weight > 0) {
  25248. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesExtraData[matWeightIdx + inf] * 16, weight, tempMatrix);
  25249. finalMatrix.addToSelf(tempMatrix);
  25250. }
  25251. else
  25252. break;
  25253. }
  25254. }
  25255. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  25256. tempVector3.toArray(positionsData, index);
  25257. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  25258. tempVector3.toArray(normalsData, index);
  25259. finalMatrix.reset();
  25260. }
  25261. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  25262. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  25263. return this;
  25264. };
  25265. // Tools
  25266. /**
  25267. * Returns an object `{min:` Vector3`, max:` Vector3`}`
  25268. * This min and max Vector3 are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system
  25269. */
  25270. Mesh.MinMax = function (meshes) {
  25271. var minVector = null;
  25272. var maxVector = null;
  25273. meshes.forEach(function (mesh, index, array) {
  25274. var boundingBox = mesh.getBoundingInfo().boundingBox;
  25275. if (!minVector) {
  25276. minVector = boundingBox.minimumWorld;
  25277. maxVector = boundingBox.maximumWorld;
  25278. }
  25279. else {
  25280. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  25281. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  25282. }
  25283. });
  25284. return {
  25285. min: minVector,
  25286. max: maxVector
  25287. };
  25288. };
  25289. /**
  25290. * Returns a Vector3, the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array.
  25291. */
  25292. Mesh.Center = function (meshesOrMinMaxVector) {
  25293. var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? BABYLON.Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
  25294. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  25295. };
  25296. /**
  25297. * Merge the array of meshes into a single mesh for performance reasons.
  25298. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  25299. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  25300. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  25301. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  25302. * @param {boolean} subdivideWithSubMeshes - When true (false default), subdivide mesh to his subMesh array with meshes source.
  25303. */
  25304. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes) {
  25305. if (disposeSource === void 0) { disposeSource = true; }
  25306. var index;
  25307. if (!allow32BitsIndices) {
  25308. var totalVertices = 0;
  25309. // Counting vertices
  25310. for (index = 0; index < meshes.length; index++) {
  25311. if (meshes[index]) {
  25312. totalVertices += meshes[index].getTotalVertices();
  25313. if (totalVertices > 65536) {
  25314. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  25315. return null;
  25316. }
  25317. }
  25318. }
  25319. }
  25320. // Merge
  25321. var vertexData;
  25322. var otherVertexData;
  25323. var indiceArray = new Array();
  25324. var source;
  25325. for (index = 0; index < meshes.length; index++) {
  25326. if (meshes[index]) {
  25327. meshes[index].computeWorldMatrix(true);
  25328. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  25329. otherVertexData.transform(meshes[index].getWorldMatrix());
  25330. if (vertexData) {
  25331. vertexData.merge(otherVertexData);
  25332. }
  25333. else {
  25334. vertexData = otherVertexData;
  25335. source = meshes[index];
  25336. }
  25337. if (subdivideWithSubMeshes) {
  25338. indiceArray.push(meshes[index].getTotalIndices());
  25339. }
  25340. }
  25341. }
  25342. if (!meshSubclass) {
  25343. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  25344. }
  25345. vertexData.applyToMesh(meshSubclass);
  25346. // Setting properties
  25347. meshSubclass.material = source.material;
  25348. meshSubclass.checkCollisions = source.checkCollisions;
  25349. // Cleaning
  25350. if (disposeSource) {
  25351. for (index = 0; index < meshes.length; index++) {
  25352. if (meshes[index]) {
  25353. meshes[index].dispose();
  25354. }
  25355. }
  25356. }
  25357. // Subdivide
  25358. if (subdivideWithSubMeshes) {
  25359. //-- Suppresions du submesh global
  25360. meshSubclass.releaseSubMeshes();
  25361. index = 0;
  25362. var offset = 0;
  25363. //-- aplique la subdivision en fonction du tableau d'indices
  25364. while (index < indiceArray.length) {
  25365. BABYLON.SubMesh.CreateFromIndices(0, offset, indiceArray[index], meshSubclass);
  25366. offset += indiceArray[index];
  25367. index++;
  25368. }
  25369. }
  25370. return meshSubclass;
  25371. };
  25372. return Mesh;
  25373. }(BABYLON.AbstractMesh));
  25374. // Consts
  25375. Mesh._FRONTSIDE = 0;
  25376. Mesh._BACKSIDE = 1;
  25377. Mesh._DOUBLESIDE = 2;
  25378. Mesh._DEFAULTSIDE = 0;
  25379. Mesh._NO_CAP = 0;
  25380. Mesh._CAP_START = 1;
  25381. Mesh._CAP_END = 2;
  25382. Mesh._CAP_ALL = 3;
  25383. BABYLON.Mesh = Mesh;
  25384. })(BABYLON || (BABYLON = {}));
  25385. //# sourceMappingURL=babylon.mesh.js.map
  25386. var BABYLON;
  25387. (function (BABYLON) {
  25388. var SubMesh = (function () {
  25389. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  25390. if (createBoundingBox === void 0) { createBoundingBox = true; }
  25391. this.materialIndex = materialIndex;
  25392. this.verticesStart = verticesStart;
  25393. this.verticesCount = verticesCount;
  25394. this.indexStart = indexStart;
  25395. this.indexCount = indexCount;
  25396. this._renderId = 0;
  25397. this._mesh = mesh;
  25398. this._renderingMesh = renderingMesh || mesh;
  25399. mesh.subMeshes.push(this);
  25400. this._trianglePlanes = [];
  25401. this._id = mesh.subMeshes.length - 1;
  25402. if (createBoundingBox) {
  25403. this.refreshBoundingInfo();
  25404. mesh.computeWorldMatrix(true);
  25405. }
  25406. }
  25407. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  25408. get: function () {
  25409. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  25410. },
  25411. enumerable: true,
  25412. configurable: true
  25413. });
  25414. /**
  25415. * Returns the submesh BoudingInfo object.
  25416. */
  25417. SubMesh.prototype.getBoundingInfo = function () {
  25418. if (this.IsGlobal) {
  25419. return this._mesh.getBoundingInfo();
  25420. }
  25421. return this._boundingInfo;
  25422. };
  25423. /**
  25424. * Sets the submesh BoundingInfo.
  25425. * Return the SubMesh.
  25426. */
  25427. SubMesh.prototype.setBoundingInfo = function (boundingInfo) {
  25428. this._boundingInfo = boundingInfo;
  25429. return this;
  25430. };
  25431. /**
  25432. * Returns the mesh of the current submesh.
  25433. */
  25434. SubMesh.prototype.getMesh = function () {
  25435. return this._mesh;
  25436. };
  25437. /**
  25438. * Returns the rendering mesh of the submesh.
  25439. */
  25440. SubMesh.prototype.getRenderingMesh = function () {
  25441. return this._renderingMesh;
  25442. };
  25443. /**
  25444. * Returns the submesh material.
  25445. */
  25446. SubMesh.prototype.getMaterial = function () {
  25447. var rootMaterial = this._renderingMesh.material;
  25448. if (rootMaterial && rootMaterial instanceof BABYLON.MultiMaterial) {
  25449. var multiMaterial = rootMaterial;
  25450. return multiMaterial.getSubMaterial(this.materialIndex);
  25451. }
  25452. if (!rootMaterial) {
  25453. return this._mesh.getScene().defaultMaterial;
  25454. }
  25455. return rootMaterial;
  25456. };
  25457. // Methods
  25458. /**
  25459. * Sets a new updated BoundingInfo object to the submesh.
  25460. * Returns the SubMesh.
  25461. */
  25462. SubMesh.prototype.refreshBoundingInfo = function () {
  25463. this._lastColliderWorldVertices = null;
  25464. if (this.IsGlobal) {
  25465. return;
  25466. }
  25467. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  25468. if (!data) {
  25469. this._boundingInfo = this._mesh._boundingInfo;
  25470. return;
  25471. }
  25472. var indices = this._renderingMesh.getIndices();
  25473. var extend;
  25474. //is this the only submesh?
  25475. if (this.indexStart === 0 && this.indexCount === indices.length) {
  25476. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  25477. extend = { minimum: this._renderingMesh.getBoundingInfo().minimum.clone(), maximum: this._renderingMesh.getBoundingInfo().maximum.clone() };
  25478. }
  25479. else {
  25480. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  25481. }
  25482. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  25483. return this;
  25484. };
  25485. SubMesh.prototype._checkCollision = function (collider) {
  25486. return this.getBoundingInfo()._checkCollision(collider);
  25487. };
  25488. /**
  25489. * Updates the submesh BoundingInfo.
  25490. * Returns the Submesh.
  25491. */
  25492. SubMesh.prototype.updateBoundingInfo = function (world) {
  25493. if (!this.getBoundingInfo()) {
  25494. this.refreshBoundingInfo();
  25495. }
  25496. this.getBoundingInfo().update(world);
  25497. return this;
  25498. };
  25499. /**
  25500. * True is the submesh bounding box intersects the frustum defined by the passed array of planes.
  25501. * Boolean returned.
  25502. */
  25503. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  25504. return this.getBoundingInfo().isInFrustum(frustumPlanes);
  25505. };
  25506. /**
  25507. * True is the submesh bounding box is completely inside the frustum defined by the passed array of planes.
  25508. * Boolean returned.
  25509. */
  25510. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  25511. return this.getBoundingInfo().isCompletelyInFrustum(frustumPlanes);
  25512. };
  25513. /**
  25514. * Renders the submesh.
  25515. * Returns it.
  25516. */
  25517. SubMesh.prototype.render = function (enableAlphaMode) {
  25518. this._renderingMesh.render(this, enableAlphaMode);
  25519. return this;
  25520. };
  25521. /**
  25522. * Returns a new Index Buffer.
  25523. * Type returned : WebGLBuffer.
  25524. */
  25525. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  25526. if (!this._linesIndexBuffer) {
  25527. var linesIndices = [];
  25528. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  25529. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  25530. }
  25531. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  25532. this.linesIndexCount = linesIndices.length;
  25533. }
  25534. return this._linesIndexBuffer;
  25535. };
  25536. /**
  25537. * True is the passed Ray intersects the submesh bounding box.
  25538. * Boolean returned.
  25539. */
  25540. SubMesh.prototype.canIntersects = function (ray) {
  25541. return ray.intersectsBox(this.getBoundingInfo().boundingBox);
  25542. };
  25543. /**
  25544. * Returns an object IntersectionInfo.
  25545. */
  25546. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  25547. var intersectInfo = null;
  25548. // LineMesh first as it's also a Mesh...
  25549. if (this._mesh instanceof BABYLON.LinesMesh) {
  25550. var lineMesh = this._mesh;
  25551. // Line test
  25552. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  25553. var p0 = positions[indices[index]];
  25554. var p1 = positions[indices[index + 1]];
  25555. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  25556. if (length < 0) {
  25557. continue;
  25558. }
  25559. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  25560. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  25561. if (fastCheck) {
  25562. break;
  25563. }
  25564. }
  25565. }
  25566. }
  25567. else {
  25568. // Triangles test
  25569. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  25570. var p0 = positions[indices[index]];
  25571. var p1 = positions[indices[index + 1]];
  25572. var p2 = positions[indices[index + 2]];
  25573. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  25574. if (currentIntersectInfo) {
  25575. if (currentIntersectInfo.distance < 0) {
  25576. continue;
  25577. }
  25578. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  25579. intersectInfo = currentIntersectInfo;
  25580. intersectInfo.faceId = index / 3;
  25581. if (fastCheck) {
  25582. break;
  25583. }
  25584. }
  25585. }
  25586. }
  25587. }
  25588. return intersectInfo;
  25589. };
  25590. // Clone
  25591. /**
  25592. * Creates a new Submesh from the passed Mesh.
  25593. */
  25594. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  25595. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  25596. if (!this.IsGlobal) {
  25597. result._boundingInfo = new BABYLON.BoundingInfo(this.getBoundingInfo().minimum, this.getBoundingInfo().maximum);
  25598. }
  25599. return result;
  25600. };
  25601. // Dispose
  25602. /**
  25603. * Disposes the Submesh.
  25604. * Returns nothing.
  25605. */
  25606. SubMesh.prototype.dispose = function () {
  25607. if (this._linesIndexBuffer) {
  25608. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  25609. this._linesIndexBuffer = null;
  25610. }
  25611. // Remove from mesh
  25612. var index = this._mesh.subMeshes.indexOf(this);
  25613. this._mesh.subMeshes.splice(index, 1);
  25614. };
  25615. // Statics
  25616. /**
  25617. * Creates a new Submesh from the passed parameters :
  25618. * - materialIndex (integer) : the index of the main mesh material.
  25619. * - startIndex (integer) : the index where to start the copy in the mesh indices array.
  25620. * - indexCount (integer) : the number of indices to copy then from the startIndex.
  25621. * - mesh (Mesh) : the main mesh to create the submesh from.
  25622. * - renderingMesh (optional Mesh) : rendering mesh.
  25623. */
  25624. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  25625. var minVertexIndex = Number.MAX_VALUE;
  25626. var maxVertexIndex = -Number.MAX_VALUE;
  25627. renderingMesh = renderingMesh || mesh;
  25628. var indices = renderingMesh.getIndices();
  25629. for (var index = startIndex; index < startIndex + indexCount; index++) {
  25630. var vertexIndex = indices[index];
  25631. if (vertexIndex < minVertexIndex)
  25632. minVertexIndex = vertexIndex;
  25633. if (vertexIndex > maxVertexIndex)
  25634. maxVertexIndex = vertexIndex;
  25635. }
  25636. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  25637. };
  25638. return SubMesh;
  25639. }());
  25640. BABYLON.SubMesh = SubMesh;
  25641. })(BABYLON || (BABYLON = {}));
  25642. //# sourceMappingURL=babylon.subMesh.js.map
  25643. var BABYLON;
  25644. (function (BABYLON) {
  25645. var MeshBuilder = (function () {
  25646. function MeshBuilder() {
  25647. }
  25648. MeshBuilder.updateSideOrientation = function (orientation, scene) {
  25649. if (orientation == BABYLON.Mesh.DOUBLESIDE) {
  25650. return BABYLON.Mesh.DOUBLESIDE;
  25651. }
  25652. if (orientation === undefined || orientation === null) {
  25653. return BABYLON.Mesh.FRONTSIDE;
  25654. }
  25655. return orientation;
  25656. };
  25657. /**
  25658. * Creates a box mesh.
  25659. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  25660. * The parameter `size` sets the size (float) of each box side (default 1).
  25661. * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`).
  25662. * 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).
  25663. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  25664. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  25665. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  25666. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25667. */
  25668. MeshBuilder.CreateBox = function (name, options, scene) {
  25669. var box = new BABYLON.Mesh(name, scene);
  25670. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  25671. box.sideOrientation = options.sideOrientation;
  25672. var vertexData = BABYLON.VertexData.CreateBox(options);
  25673. vertexData.applyToMesh(box, options.updatable);
  25674. return box;
  25675. };
  25676. /**
  25677. * Creates a sphere mesh.
  25678. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  25679. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  25680. * 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`).
  25681. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  25682. * 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
  25683. * 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).
  25684. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  25685. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  25686. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25687. */
  25688. MeshBuilder.CreateSphere = function (name, options, scene) {
  25689. var sphere = new BABYLON.Mesh(name, scene);
  25690. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  25691. sphere.sideOrientation = options.sideOrientation;
  25692. var vertexData = BABYLON.VertexData.CreateSphere(options);
  25693. vertexData.applyToMesh(sphere, options.updatable);
  25694. return sphere;
  25695. };
  25696. /**
  25697. * Creates a plane polygonal mesh. By default, this is a disc.
  25698. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#disc
  25699. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  25700. * 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.
  25701. * 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
  25702. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  25703. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  25704. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25705. */
  25706. MeshBuilder.CreateDisc = function (name, options, scene) {
  25707. var disc = new BABYLON.Mesh(name, scene);
  25708. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  25709. disc.sideOrientation = options.sideOrientation;
  25710. var vertexData = BABYLON.VertexData.CreateDisc(options);
  25711. vertexData.applyToMesh(disc, options.updatable);
  25712. return disc;
  25713. };
  25714. /**
  25715. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  25716. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#icosphere
  25717. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  25718. * 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`).
  25719. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  25720. * 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.
  25721. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  25722. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  25723. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25724. */
  25725. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  25726. var sphere = new BABYLON.Mesh(name, scene);
  25727. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  25728. sphere.sideOrientation = options.sideOrientation;
  25729. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  25730. vertexData.applyToMesh(sphere, options.updatable);
  25731. return sphere;
  25732. };
  25733. ;
  25734. /**
  25735. * Creates a ribbon mesh.
  25736. * 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.
  25737. *
  25738. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  25739. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  25740. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  25741. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  25742. * 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.
  25743. * 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.
  25744. * 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
  25745. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  25746. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  25747. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  25748. * The parameter `uvs` is an optional flat array of `Vector4` to update/set each ribbon vertex with its own custom UV values instead of the computed ones.
  25749. * The parameters `colors` is an optional flat array of `Color4` to set/update each ribbon vertex with its own custom color values.
  25750. * Note that if you use the parameters `uvs` or `colors`, the passed arrays must be populated with the right number of elements, it is to say the number of ribbon vertices. Remember that
  25751. * if you set `closePath` to `true`, there's one extra vertex per path in the geometry.
  25752. * Moreover, you can use the parameter `color` with `instance` (to update the ribbon), only if you previously used it at creation time.
  25753. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25754. */
  25755. MeshBuilder.CreateRibbon = function (name, options, scene) {
  25756. var pathArray = options.pathArray;
  25757. var closeArray = options.closeArray;
  25758. var closePath = options.closePath;
  25759. var offset = options.offset;
  25760. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  25761. var instance = options.instance;
  25762. var updatable = options.updatable;
  25763. if (instance) {
  25764. // positionFunction : ribbon case
  25765. // only pathArray and sideOrientation parameters are taken into account for positions update
  25766. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum
  25767. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]);
  25768. var positionFunction = function (positions) {
  25769. var minlg = pathArray[0].length;
  25770. var i = 0;
  25771. var ns = (instance.sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  25772. for (var si = 1; si <= ns; si++) {
  25773. for (var p = 0; p < pathArray.length; p++) {
  25774. var path = pathArray[p];
  25775. var l = path.length;
  25776. minlg = (minlg < l) ? minlg : l;
  25777. var j = 0;
  25778. while (j < minlg) {
  25779. positions[i] = path[j].x;
  25780. positions[i + 1] = path[j].y;
  25781. positions[i + 2] = path[j].z;
  25782. if (path[j].x < BABYLON.Tmp.Vector3[0].x) {
  25783. BABYLON.Tmp.Vector3[0].x = path[j].x;
  25784. }
  25785. if (path[j].x > BABYLON.Tmp.Vector3[1].x) {
  25786. BABYLON.Tmp.Vector3[1].x = path[j].x;
  25787. }
  25788. if (path[j].y < BABYLON.Tmp.Vector3[0].y) {
  25789. BABYLON.Tmp.Vector3[0].y = path[j].y;
  25790. }
  25791. if (path[j].y > BABYLON.Tmp.Vector3[1].y) {
  25792. BABYLON.Tmp.Vector3[1].y = path[j].y;
  25793. }
  25794. if (path[j].z < BABYLON.Tmp.Vector3[0].z) {
  25795. BABYLON.Tmp.Vector3[0].z = path[j].z;
  25796. }
  25797. if (path[j].z > BABYLON.Tmp.Vector3[1].z) {
  25798. BABYLON.Tmp.Vector3[1].z = path[j].z;
  25799. }
  25800. j++;
  25801. i += 3;
  25802. }
  25803. if (instance._closePath) {
  25804. positions[i] = path[0].x;
  25805. positions[i + 1] = path[0].y;
  25806. positions[i + 2] = path[0].z;
  25807. i += 3;
  25808. }
  25809. }
  25810. }
  25811. };
  25812. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  25813. positionFunction(positions);
  25814. instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Vector3[1]);
  25815. instance._boundingInfo.update(instance._worldMatrix);
  25816. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  25817. if (options.colors) {
  25818. var colors = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  25819. for (var c = 0; c < options.colors.length; c++) {
  25820. colors[c * 4] = options.colors[c].r;
  25821. colors[c * 4 + 1] = options.colors[c].g;
  25822. colors[c * 4 + 2] = options.colors[c].b;
  25823. colors[c * 4 + 3] = options.colors[c].a;
  25824. }
  25825. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, colors, false, false);
  25826. }
  25827. if (options.uvs) {
  25828. var uvs = instance.getVerticesData(BABYLON.VertexBuffer.UVKind);
  25829. for (var i = 0; i < options.uvs.length; i++) {
  25830. uvs[i * 2] = options.uvs[i].x;
  25831. uvs[i * 2 + 1] = options.uvs[i].y;
  25832. }
  25833. instance.updateVerticesData(BABYLON.VertexBuffer.UVKind, uvs, false, false);
  25834. }
  25835. if (!instance.areNormalsFrozen || instance.isFacetDataEnabled) {
  25836. var indices = instance.getIndices();
  25837. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  25838. var params = instance.isFacetDataEnabled ? instance.getFacetDataParameters() : null;
  25839. BABYLON.VertexData.ComputeNormals(positions, indices, normals, params);
  25840. if (instance._closePath) {
  25841. var indexFirst = 0;
  25842. var indexLast = 0;
  25843. for (var p = 0; p < pathArray.length; p++) {
  25844. indexFirst = instance._idx[p] * 3;
  25845. if (p + 1 < pathArray.length) {
  25846. indexLast = (instance._idx[p + 1] - 1) * 3;
  25847. }
  25848. else {
  25849. indexLast = normals.length - 3;
  25850. }
  25851. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  25852. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  25853. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  25854. normals[indexLast] = normals[indexFirst];
  25855. normals[indexLast + 1] = normals[indexFirst + 1];
  25856. normals[indexLast + 2] = normals[indexFirst + 2];
  25857. }
  25858. }
  25859. if (!(instance.areNormalsFrozen)) {
  25860. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  25861. }
  25862. }
  25863. return instance;
  25864. }
  25865. else {
  25866. var ribbon = new BABYLON.Mesh(name, scene);
  25867. ribbon.sideOrientation = sideOrientation;
  25868. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  25869. if (closePath) {
  25870. ribbon._idx = vertexData._idx;
  25871. }
  25872. ribbon._closePath = closePath;
  25873. ribbon._closeArray = closeArray;
  25874. vertexData.applyToMesh(ribbon, updatable);
  25875. return ribbon;
  25876. }
  25877. };
  25878. /**
  25879. * Creates a cylinder or a cone mesh.
  25880. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  25881. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  25882. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  25883. * 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.
  25884. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  25885. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  25886. * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  25887. * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  25888. * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  25889. * 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).
  25890. * 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
  25891. * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  25892. * 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
  25893. * 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.
  25894. * If `enclose` is false, a ring surface is one element.
  25895. * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  25896. * 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
  25897. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  25898. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  25899. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25900. */
  25901. MeshBuilder.CreateCylinder = function (name, options, scene) {
  25902. var cylinder = new BABYLON.Mesh(name, scene);
  25903. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  25904. cylinder.sideOrientation = options.sideOrientation;
  25905. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  25906. vertexData.applyToMesh(cylinder, options.updatable);
  25907. return cylinder;
  25908. };
  25909. /**
  25910. * Creates a torus mesh.
  25911. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  25912. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  25913. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  25914. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  25915. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  25916. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  25917. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25918. */
  25919. MeshBuilder.CreateTorus = function (name, options, scene) {
  25920. var torus = new BABYLON.Mesh(name, scene);
  25921. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  25922. torus.sideOrientation = options.sideOrientation;
  25923. var vertexData = BABYLON.VertexData.CreateTorus(options);
  25924. vertexData.applyToMesh(torus, options.updatable);
  25925. return torus;
  25926. };
  25927. /**
  25928. * Creates a torus knot mesh.
  25929. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  25930. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  25931. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  25932. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  25933. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  25934. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  25935. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  25936. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25937. */
  25938. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  25939. var torusKnot = new BABYLON.Mesh(name, scene);
  25940. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  25941. torusKnot.sideOrientation = options.sideOrientation;
  25942. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  25943. vertexData.applyToMesh(torusKnot, options.updatable);
  25944. return torusKnot;
  25945. };
  25946. /**
  25947. * Creates a line system mesh.
  25948. * A line system is a pool of many lines gathered in a single mesh.
  25949. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#linesystem
  25950. * 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.
  25951. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function.
  25952. * The parameter `lines` is an array of lines, each line being an array of successive Vector3.
  25953. * 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
  25954. * 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
  25955. * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines.
  25956. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25957. */
  25958. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  25959. var instance = options.instance;
  25960. var lines = options.lines;
  25961. if (instance) {
  25962. var positionFunction = function (positions) {
  25963. var i = 0;
  25964. for (var l = 0; l < lines.length; l++) {
  25965. var points = lines[l];
  25966. for (var p = 0; p < points.length; p++) {
  25967. positions[i] = points[p].x;
  25968. positions[i + 1] = points[p].y;
  25969. positions[i + 2] = points[p].z;
  25970. i += 3;
  25971. }
  25972. }
  25973. };
  25974. instance.updateMeshPositions(positionFunction, false);
  25975. return instance;
  25976. }
  25977. // line system creation
  25978. var lineSystem = new BABYLON.LinesMesh(name, scene);
  25979. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  25980. vertexData.applyToMesh(lineSystem, options.updatable);
  25981. return lineSystem;
  25982. };
  25983. /**
  25984. * Creates a line mesh.
  25985. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lines
  25986. * 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.
  25987. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  25988. * The parameter `points` is an array successive Vector3.
  25989. * 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
  25990. * When updating an instance, remember that only point positions can change, not the number of points.
  25991. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25992. */
  25993. MeshBuilder.CreateLines = function (name, options, scene) {
  25994. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance }, scene);
  25995. return lines;
  25996. };
  25997. /**
  25998. * Creates a dashed line mesh.
  25999. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#dashed-lines
  26000. * 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.
  26001. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  26002. * The parameter `points` is an array successive Vector3.
  26003. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  26004. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  26005. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  26006. * 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
  26007. * When updating an instance, remember that only point positions can change, not the number of points.
  26008. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  26009. */
  26010. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  26011. var points = options.points;
  26012. var instance = options.instance;
  26013. var gapSize = options.gapSize;
  26014. var dashNb = options.dashNb;
  26015. var dashSize = options.dashSize;
  26016. if (instance) {
  26017. var positionFunction = function (positions) {
  26018. var curvect = BABYLON.Vector3.Zero();
  26019. var nbSeg = positions.length / 6;
  26020. var lg = 0;
  26021. var nb = 0;
  26022. var shft = 0;
  26023. var dashshft = 0;
  26024. var curshft = 0;
  26025. var p = 0;
  26026. var i = 0;
  26027. var j = 0;
  26028. for (i = 0; i < points.length - 1; i++) {
  26029. points[i + 1].subtractToRef(points[i], curvect);
  26030. lg += curvect.length();
  26031. }
  26032. shft = lg / nbSeg;
  26033. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  26034. for (i = 0; i < points.length - 1; i++) {
  26035. points[i + 1].subtractToRef(points[i], curvect);
  26036. nb = Math.floor(curvect.length() / shft);
  26037. curvect.normalize();
  26038. j = 0;
  26039. while (j < nb && p < positions.length) {
  26040. curshft = shft * j;
  26041. positions[p] = points[i].x + curshft * curvect.x;
  26042. positions[p + 1] = points[i].y + curshft * curvect.y;
  26043. positions[p + 2] = points[i].z + curshft * curvect.z;
  26044. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  26045. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  26046. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  26047. p += 6;
  26048. j++;
  26049. }
  26050. }
  26051. while (p < positions.length) {
  26052. positions[p] = points[i].x;
  26053. positions[p + 1] = points[i].y;
  26054. positions[p + 2] = points[i].z;
  26055. p += 3;
  26056. }
  26057. };
  26058. instance.updateMeshPositions(positionFunction, false);
  26059. return instance;
  26060. }
  26061. // dashed lines creation
  26062. var dashedLines = new BABYLON.LinesMesh(name, scene);
  26063. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  26064. vertexData.applyToMesh(dashedLines, options.updatable);
  26065. dashedLines.dashSize = dashSize;
  26066. dashedLines.gapSize = gapSize;
  26067. return dashedLines;
  26068. };
  26069. /**
  26070. * Creates an extruded shape mesh.
  26071. * 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.
  26072. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#extruded-shapes
  26073. *
  26074. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  26075. * 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
  26076. * extruded along the Z axis.
  26077. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  26078. * 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.
  26079. * The parameter `scale` (float, default 1) is the value to scale the shape.
  26080. * 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
  26081. * 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
  26082. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  26083. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  26084. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  26085. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  26086. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  26087. */
  26088. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  26089. var path = options.path;
  26090. var shape = options.shape;
  26091. var scale = options.scale || 1;
  26092. var rotation = options.rotation || 0;
  26093. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  26094. var updatable = options.updatable;
  26095. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  26096. var instance = options.instance;
  26097. var invertUV = options.invertUV || false;
  26098. return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, scale, rotation, null, null, false, false, cap, false, scene, updatable, sideOrientation, instance, invertUV);
  26099. };
  26100. /**
  26101. * Creates an custom extruded shape mesh.
  26102. * 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.
  26103. * tuto :http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#custom-extruded-shapes
  26104. *
  26105. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  26106. * 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
  26107. * extruded along the Z axis.
  26108. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  26109. * 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
  26110. * and the distance of this point from the begining of the path :
  26111. * ```javascript
  26112. * var rotationFunction = function(i, distance) {
  26113. * // do things
  26114. * return rotationValue; }
  26115. * ```
  26116. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  26117. * 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
  26118. * and the distance of this point from the begining of the path :
  26119. * ```javascript
  26120. * var scaleFunction = function(i, distance) {
  26121. * // do things
  26122. * return scaleValue;}
  26123. * ```
  26124. * It must returns a float value that will be the scale value applied to the shape on each path point.
  26125. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  26126. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  26127. * 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
  26128. * 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
  26129. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  26130. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  26131. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  26132. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  26133. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  26134. */
  26135. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  26136. var path = options.path;
  26137. var shape = options.shape;
  26138. var scaleFunction = options.scaleFunction || (function () { return 1; });
  26139. var rotationFunction = options.rotationFunction || (function () { return 0; });
  26140. var ribbonCloseArray = options.ribbonCloseArray || false;
  26141. var ribbonClosePath = options.ribbonClosePath || false;
  26142. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  26143. var updatable = options.updatable;
  26144. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  26145. var instance = options.instance;
  26146. var invertUV = options.invertUV || false;
  26147. return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, null, null, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, true, scene, updatable, sideOrientation, instance, invertUV);
  26148. };
  26149. /**
  26150. * Creates lathe mesh.
  26151. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  26152. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lathe
  26153. *
  26154. * 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
  26155. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  26156. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  26157. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  26158. * 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.
  26159. * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc".
  26160. * 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
  26161. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  26162. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  26163. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  26164. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  26165. */
  26166. MeshBuilder.CreateLathe = function (name, options, scene) {
  26167. var arc = options.arc ? ((options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc) : 1.0;
  26168. var closed = (options.closed === undefined) ? true : options.closed;
  26169. var shape = options.shape;
  26170. var radius = options.radius || 1;
  26171. var tessellation = options.tessellation || 64;
  26172. var updatable = options.updatable;
  26173. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  26174. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  26175. var pi2 = Math.PI * 2;
  26176. var paths = new Array();
  26177. var invertUV = options.invertUV || false;
  26178. var i = 0;
  26179. var p = 0;
  26180. var step = pi2 / tessellation * arc;
  26181. var rotated;
  26182. var path = new Array();
  26183. ;
  26184. for (i = 0; i <= tessellation; i++) {
  26185. var path = [];
  26186. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  26187. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  26188. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  26189. }
  26190. for (p = 0; p < shape.length; p++) {
  26191. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  26192. path.push(rotated);
  26193. }
  26194. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  26195. 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));
  26196. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  26197. }
  26198. paths.push(path);
  26199. }
  26200. // lathe ribbon
  26201. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV }, scene);
  26202. return lathe;
  26203. };
  26204. /**
  26205. * Creates a plane mesh.
  26206. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  26207. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  26208. * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`).
  26209. * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane.
  26210. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  26211. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  26212. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  26213. */
  26214. MeshBuilder.CreatePlane = function (name, options, scene) {
  26215. var plane = new BABYLON.Mesh(name, scene);
  26216. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  26217. plane.sideOrientation = options.sideOrientation;
  26218. var vertexData = BABYLON.VertexData.CreatePlane(options);
  26219. vertexData.applyToMesh(plane, options.updatable);
  26220. if (options.sourcePlane) {
  26221. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  26222. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  26223. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  26224. plane.rotate(vectorProduct, product);
  26225. }
  26226. return plane;
  26227. };
  26228. /**
  26229. * Creates a ground mesh.
  26230. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  26231. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  26232. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  26233. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  26234. */
  26235. MeshBuilder.CreateGround = function (name, options, scene) {
  26236. var ground = new BABYLON.GroundMesh(name, scene);
  26237. ground._setReady(false);
  26238. ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  26239. ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  26240. ground._width = options.width || 1;
  26241. ground._height = options.height || 1;
  26242. ground._maxX = ground._width / 2;
  26243. ground._maxZ = ground._height / 2;
  26244. ground._minX = -ground._maxX;
  26245. ground._minZ = -ground._maxZ;
  26246. var vertexData = BABYLON.VertexData.CreateGround(options);
  26247. vertexData.applyToMesh(ground, options.updatable);
  26248. ground._setReady(true);
  26249. return ground;
  26250. };
  26251. /**
  26252. * Creates a tiled ground mesh.
  26253. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  26254. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  26255. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  26256. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  26257. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  26258. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  26259. * numbers of subdivisions on the ground width and height of each tile.
  26260. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  26261. */
  26262. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  26263. var tiledGround = new BABYLON.Mesh(name, scene);
  26264. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  26265. vertexData.applyToMesh(tiledGround, options.updatable);
  26266. return tiledGround;
  26267. };
  26268. /**
  26269. * Creates a ground mesh from a height map.
  26270. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  26271. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  26272. * The parameter `url` sets the URL of the height map image resource.
  26273. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  26274. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  26275. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  26276. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  26277. * The parameter `colorFilter` (optional Color3, default (0.3, 0.59, 0.11) ) is the filter to apply to the image pixel colors to compute the height.
  26278. * 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).
  26279. * This function is passed the newly built mesh :
  26280. * ```javascript
  26281. * function(mesh) { // do things
  26282. * return; }
  26283. * ```
  26284. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  26285. */
  26286. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  26287. var width = options.width || 10.0;
  26288. var height = options.height || 10.0;
  26289. var subdivisions = options.subdivisions || 1 | 0;
  26290. var minHeight = options.minHeight || 0.0;
  26291. var maxHeight = options.maxHeight || 10.0;
  26292. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  26293. var updatable = options.updatable;
  26294. var onReady = options.onReady;
  26295. var ground = new BABYLON.GroundMesh(name, scene);
  26296. ground._subdivisionsX = subdivisions;
  26297. ground._subdivisionsY = subdivisions;
  26298. ground._width = width;
  26299. ground._height = height;
  26300. ground._maxX = ground._width / 2.0;
  26301. ground._maxZ = ground._height / 2.0;
  26302. ground._minX = -ground._maxX;
  26303. ground._minZ = -ground._maxZ;
  26304. ground._setReady(false);
  26305. var onload = function (img) {
  26306. // Getting height map data
  26307. var canvas = document.createElement("canvas");
  26308. var context = canvas.getContext("2d");
  26309. var bufferWidth = img.width;
  26310. var bufferHeight = img.height;
  26311. canvas.width = bufferWidth;
  26312. canvas.height = bufferHeight;
  26313. context.drawImage(img, 0, 0);
  26314. // Create VertexData from map data
  26315. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  26316. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  26317. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  26318. width: width, height: height,
  26319. subdivisions: subdivisions,
  26320. minHeight: minHeight, maxHeight: maxHeight, colorFilter: filter,
  26321. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  26322. });
  26323. vertexData.applyToMesh(ground, updatable);
  26324. ground._setReady(true);
  26325. //execute ready callback, if set
  26326. if (onReady) {
  26327. onReady(ground);
  26328. }
  26329. };
  26330. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  26331. return ground;
  26332. };
  26333. /**
  26334. * Creates a tube mesh.
  26335. * 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.
  26336. *
  26337. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  26338. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  26339. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  26340. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  26341. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  26342. * 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.
  26343. * It must return a radius value (positive float) :
  26344. * ```javascript
  26345. * var radiusFunction = function(i, distance) {
  26346. * // do things
  26347. * return radius; }
  26348. * ```
  26349. * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc.
  26350. * 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
  26351. * 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
  26352. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  26353. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  26354. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  26355. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  26356. */
  26357. MeshBuilder.CreateTube = function (name, options, scene) {
  26358. var path = options.path;
  26359. var radius = options.radius || 1.0;
  26360. var tessellation = options.tessellation || 64 | 0;
  26361. var radiusFunction = options.radiusFunction;
  26362. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  26363. var invertUV = options.invertUV || false;
  26364. var updatable = options.updatable;
  26365. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  26366. var instance = options.instance;
  26367. options.arc = (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  26368. // tube geometry
  26369. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  26370. var tangents = path3D.getTangents();
  26371. var normals = path3D.getNormals();
  26372. var distances = path3D.getDistances();
  26373. var pi2 = Math.PI * 2;
  26374. var step = pi2 / tessellation * arc;
  26375. var returnRadius = function () { return radius; };
  26376. var radiusFunctionFinal = radiusFunction || returnRadius;
  26377. var circlePath;
  26378. var rad;
  26379. var normal;
  26380. var rotated;
  26381. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  26382. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  26383. for (var i = 0; i < path.length; i++) {
  26384. rad = radiusFunctionFinal(i, distances[i]); // current radius
  26385. circlePath = Array(); // current circle array
  26386. normal = normals[i]; // current normal
  26387. for (var t = 0; t < tessellation; t++) {
  26388. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  26389. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  26390. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  26391. rotated.scaleInPlace(rad).addInPlace(path[i]);
  26392. circlePath[t] = rotated;
  26393. }
  26394. circlePaths[index] = circlePath;
  26395. index++;
  26396. }
  26397. // cap
  26398. var capPath = function (nbPoints, pathIndex) {
  26399. var pointCap = Array();
  26400. for (var i = 0; i < nbPoints; i++) {
  26401. pointCap.push(path[pathIndex]);
  26402. }
  26403. return pointCap;
  26404. };
  26405. switch (cap) {
  26406. case BABYLON.Mesh.NO_CAP:
  26407. break;
  26408. case BABYLON.Mesh.CAP_START:
  26409. circlePaths[0] = capPath(tessellation, 0);
  26410. circlePaths[1] = circlePaths[2].slice(0);
  26411. break;
  26412. case BABYLON.Mesh.CAP_END:
  26413. circlePaths[index] = circlePaths[index - 1].slice(0);
  26414. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  26415. break;
  26416. case BABYLON.Mesh.CAP_ALL:
  26417. circlePaths[0] = capPath(tessellation, 0);
  26418. circlePaths[1] = circlePaths[2].slice(0);
  26419. circlePaths[index] = circlePaths[index - 1].slice(0);
  26420. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  26421. break;
  26422. default:
  26423. break;
  26424. }
  26425. return circlePaths;
  26426. };
  26427. var path3D;
  26428. var pathArray;
  26429. if (instance) {
  26430. var arc = options.arc || instance.arc;
  26431. path3D = (instance.path3D).update(path);
  26432. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  26433. instance = MeshBuilder.CreateRibbon(null, { pathArray: pathArray, instance: instance });
  26434. instance.path3D = path3D;
  26435. instance.pathArray = pathArray;
  26436. instance.arc = arc;
  26437. return instance;
  26438. }
  26439. // tube creation
  26440. path3D = new BABYLON.Path3D(path);
  26441. var newPathArray = new Array();
  26442. cap = (cap < 0 || cap > 3) ? 0 : cap;
  26443. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  26444. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV }, scene);
  26445. tube.pathArray = pathArray;
  26446. tube.path3D = path3D;
  26447. tube.tessellation = tessellation;
  26448. tube.cap = cap;
  26449. tube.arc = options.arc;
  26450. return tube;
  26451. };
  26452. /**
  26453. * Creates a polyhedron mesh.
  26454. *
  26455. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#polyhedron
  26456. * 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
  26457. * to choose the wanted type.
  26458. * The parameter `size` (positive float, default 1) sets the polygon size.
  26459. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  26460. * 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`.
  26461. * 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
  26462. * 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)`).
  26463. * 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
  26464. * 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.
  26465. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  26466. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  26467. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  26468. */
  26469. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  26470. var polyhedron = new BABYLON.Mesh(name, scene);
  26471. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  26472. polyhedron.sideOrientation = options.sideOrientation;
  26473. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  26474. vertexData.applyToMesh(polyhedron, options.updatable);
  26475. return polyhedron;
  26476. };
  26477. /**
  26478. * Creates a decal mesh.
  26479. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#decals
  26480. * 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.
  26481. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  26482. * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates.
  26483. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  26484. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  26485. */
  26486. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  26487. var indices = sourceMesh.getIndices();
  26488. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  26489. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  26490. var position = options.position || BABYLON.Vector3.Zero();
  26491. var normal = options.normal || BABYLON.Vector3.Up();
  26492. var size = options.size || new BABYLON.Vector3(1, 1, 1);
  26493. var angle = options.angle || 0;
  26494. // Getting correct rotation
  26495. if (!normal) {
  26496. var target = new BABYLON.Vector3(0, 0, 1);
  26497. var camera = sourceMesh.getScene().activeCamera;
  26498. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  26499. normal = camera.globalPosition.subtract(cameraWorldTarget);
  26500. }
  26501. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  26502. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  26503. var pitch = Math.atan2(normal.y, len);
  26504. // Matrix
  26505. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  26506. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  26507. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  26508. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  26509. var vertexData = new BABYLON.VertexData();
  26510. vertexData.indices = [];
  26511. vertexData.positions = [];
  26512. vertexData.normals = [];
  26513. vertexData.uvs = [];
  26514. var currentVertexDataIndex = 0;
  26515. var extractDecalVector3 = function (indexId) {
  26516. var vertexId = indices[indexId];
  26517. var result = new BABYLON.PositionNormalVertex();
  26518. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  26519. // Send vector to decal local world
  26520. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  26521. // Get normal
  26522. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  26523. result.normal = BABYLON.Vector3.TransformNormal(result.normal, transformMatrix);
  26524. return result;
  26525. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  26526. var clip = function (vertices, axis) {
  26527. if (vertices.length === 0) {
  26528. return vertices;
  26529. }
  26530. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  26531. var clipVertices = function (v0, v1) {
  26532. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  26533. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  26534. };
  26535. var result = new Array();
  26536. for (var index = 0; index < vertices.length; index += 3) {
  26537. var v1Out;
  26538. var v2Out;
  26539. var v3Out;
  26540. var total = 0;
  26541. var nV1, nV2, nV3, nV4;
  26542. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  26543. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  26544. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  26545. v1Out = d1 > 0;
  26546. v2Out = d2 > 0;
  26547. v3Out = d3 > 0;
  26548. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  26549. switch (total) {
  26550. case 0:
  26551. result.push(vertices[index]);
  26552. result.push(vertices[index + 1]);
  26553. result.push(vertices[index + 2]);
  26554. break;
  26555. case 1:
  26556. if (v1Out) {
  26557. nV1 = vertices[index + 1];
  26558. nV2 = vertices[index + 2];
  26559. nV3 = clipVertices(vertices[index], nV1);
  26560. nV4 = clipVertices(vertices[index], nV2);
  26561. }
  26562. if (v2Out) {
  26563. nV1 = vertices[index];
  26564. nV2 = vertices[index + 2];
  26565. nV3 = clipVertices(vertices[index + 1], nV1);
  26566. nV4 = clipVertices(vertices[index + 1], nV2);
  26567. result.push(nV3);
  26568. result.push(nV2.clone());
  26569. result.push(nV1.clone());
  26570. result.push(nV2.clone());
  26571. result.push(nV3.clone());
  26572. result.push(nV4);
  26573. break;
  26574. }
  26575. if (v3Out) {
  26576. nV1 = vertices[index];
  26577. nV2 = vertices[index + 1];
  26578. nV3 = clipVertices(vertices[index + 2], nV1);
  26579. nV4 = clipVertices(vertices[index + 2], nV2);
  26580. }
  26581. result.push(nV1.clone());
  26582. result.push(nV2.clone());
  26583. result.push(nV3);
  26584. result.push(nV4);
  26585. result.push(nV3.clone());
  26586. result.push(nV2.clone());
  26587. break;
  26588. case 2:
  26589. if (!v1Out) {
  26590. nV1 = vertices[index].clone();
  26591. nV2 = clipVertices(nV1, vertices[index + 1]);
  26592. nV3 = clipVertices(nV1, vertices[index + 2]);
  26593. result.push(nV1);
  26594. result.push(nV2);
  26595. result.push(nV3);
  26596. }
  26597. if (!v2Out) {
  26598. nV1 = vertices[index + 1].clone();
  26599. nV2 = clipVertices(nV1, vertices[index + 2]);
  26600. nV3 = clipVertices(nV1, vertices[index]);
  26601. result.push(nV1);
  26602. result.push(nV2);
  26603. result.push(nV3);
  26604. }
  26605. if (!v3Out) {
  26606. nV1 = vertices[index + 2].clone();
  26607. nV2 = clipVertices(nV1, vertices[index]);
  26608. nV3 = clipVertices(nV1, vertices[index + 1]);
  26609. result.push(nV1);
  26610. result.push(nV2);
  26611. result.push(nV3);
  26612. }
  26613. break;
  26614. case 3:
  26615. break;
  26616. }
  26617. }
  26618. return result;
  26619. };
  26620. for (var index = 0; index < indices.length; index += 3) {
  26621. var faceVertices = new Array();
  26622. faceVertices.push(extractDecalVector3(index));
  26623. faceVertices.push(extractDecalVector3(index + 1));
  26624. faceVertices.push(extractDecalVector3(index + 2));
  26625. // Clip
  26626. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  26627. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  26628. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  26629. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  26630. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  26631. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  26632. if (faceVertices.length === 0) {
  26633. continue;
  26634. }
  26635. // Add UVs and get back to world
  26636. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  26637. var vertex = faceVertices[vIndex];
  26638. //TODO check for Int32Array | Uint32Array | Uint16Array
  26639. vertexData.indices.push(currentVertexDataIndex);
  26640. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  26641. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  26642. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  26643. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  26644. currentVertexDataIndex++;
  26645. }
  26646. }
  26647. // Return mesh
  26648. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  26649. vertexData.applyToMesh(decal);
  26650. decal.position = position.clone();
  26651. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  26652. return decal;
  26653. };
  26654. // Privates
  26655. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV) {
  26656. // extrusion geometry
  26657. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  26658. var tangents = path3D.getTangents();
  26659. var normals = path3D.getNormals();
  26660. var binormals = path3D.getBinormals();
  26661. var distances = path3D.getDistances();
  26662. var angle = 0;
  26663. var returnScale = function () { return scale; };
  26664. var returnRotation = function () { return rotation; };
  26665. var rotate = custom ? rotateFunction : returnRotation;
  26666. var scl = custom ? scaleFunction : returnScale;
  26667. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  26668. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  26669. for (var i = 0; i < curve.length; i++) {
  26670. var shapePath = new Array();
  26671. var angleStep = rotate(i, distances[i]);
  26672. var scaleRatio = scl(i, distances[i]);
  26673. for (var p = 0; p < shape.length; p++) {
  26674. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  26675. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  26676. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  26677. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  26678. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  26679. shapePath[p] = rotated;
  26680. }
  26681. shapePaths[index] = shapePath;
  26682. angle += angleStep;
  26683. index++;
  26684. }
  26685. // cap
  26686. var capPath = function (shapePath) {
  26687. var pointCap = Array();
  26688. var barycenter = BABYLON.Vector3.Zero();
  26689. var i;
  26690. for (i = 0; i < shapePath.length; i++) {
  26691. barycenter.addInPlace(shapePath[i]);
  26692. }
  26693. barycenter.scaleInPlace(1.0 / shapePath.length);
  26694. for (i = 0; i < shapePath.length; i++) {
  26695. pointCap.push(barycenter);
  26696. }
  26697. return pointCap;
  26698. };
  26699. switch (cap) {
  26700. case BABYLON.Mesh.NO_CAP:
  26701. break;
  26702. case BABYLON.Mesh.CAP_START:
  26703. shapePaths[0] = capPath(shapePaths[2]);
  26704. shapePaths[1] = shapePaths[2];
  26705. break;
  26706. case BABYLON.Mesh.CAP_END:
  26707. shapePaths[index] = shapePaths[index - 1];
  26708. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  26709. break;
  26710. case BABYLON.Mesh.CAP_ALL:
  26711. shapePaths[0] = capPath(shapePaths[2]);
  26712. shapePaths[1] = shapePaths[2];
  26713. shapePaths[index] = shapePaths[index - 1];
  26714. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  26715. break;
  26716. default:
  26717. break;
  26718. }
  26719. return shapePaths;
  26720. };
  26721. var path3D;
  26722. var pathArray;
  26723. if (instance) {
  26724. path3D = (instance.path3D).update(curve);
  26725. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  26726. instance = BABYLON.Mesh.CreateRibbon(null, pathArray, null, null, null, scene, null, null, instance);
  26727. return instance;
  26728. }
  26729. // extruded shape creation
  26730. path3D = new BABYLON.Path3D(curve);
  26731. var newShapePaths = new Array();
  26732. cap = (cap < 0 || cap > 3) ? 0 : cap;
  26733. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  26734. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV }, scene);
  26735. extrudedGeneric.pathArray = pathArray;
  26736. extrudedGeneric.path3D = path3D;
  26737. extrudedGeneric.cap = cap;
  26738. return extrudedGeneric;
  26739. };
  26740. return MeshBuilder;
  26741. }());
  26742. BABYLON.MeshBuilder = MeshBuilder;
  26743. })(BABYLON || (BABYLON = {}));
  26744. //# sourceMappingURL=babylon.meshBuilder.js.map
  26745. var BABYLON;
  26746. (function (BABYLON) {
  26747. var BaseTexture = (function () {
  26748. function BaseTexture(scene) {
  26749. this.hasAlpha = false;
  26750. this.getAlphaFromRGB = false;
  26751. this.level = 1;
  26752. this.coordinatesIndex = 0;
  26753. this.coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  26754. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  26755. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  26756. this.anisotropicFilteringLevel = 4;
  26757. this.isCube = false;
  26758. this.isRenderTarget = false;
  26759. this.animations = new Array();
  26760. /**
  26761. * An event triggered when the texture is disposed.
  26762. * @type {BABYLON.Observable}
  26763. */
  26764. this.onDisposeObservable = new BABYLON.Observable();
  26765. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  26766. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  26767. this._scene.textures.push(this);
  26768. this._uid = null;
  26769. }
  26770. Object.defineProperty(BaseTexture.prototype, "uid", {
  26771. get: function () {
  26772. if (!this._uid) {
  26773. this._uid = BABYLON.Tools.RandomId();
  26774. }
  26775. return this._uid;
  26776. },
  26777. enumerable: true,
  26778. configurable: true
  26779. });
  26780. BaseTexture.prototype.toString = function () {
  26781. return this.name;
  26782. };
  26783. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  26784. set: function (callback) {
  26785. if (this._onDisposeObserver) {
  26786. this.onDisposeObservable.remove(this._onDisposeObserver);
  26787. }
  26788. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  26789. },
  26790. enumerable: true,
  26791. configurable: true
  26792. });
  26793. BaseTexture.prototype.getScene = function () {
  26794. return this._scene;
  26795. };
  26796. BaseTexture.prototype.getTextureMatrix = function () {
  26797. return null;
  26798. };
  26799. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  26800. return null;
  26801. };
  26802. BaseTexture.prototype.getInternalTexture = function () {
  26803. return this._texture;
  26804. };
  26805. BaseTexture.prototype.isReady = function () {
  26806. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  26807. return true;
  26808. }
  26809. if (this._texture) {
  26810. return this._texture.isReady;
  26811. }
  26812. return false;
  26813. };
  26814. BaseTexture.prototype.getSize = function () {
  26815. if (this._texture._width) {
  26816. return new BABYLON.Size(this._texture._width, this._texture._height);
  26817. }
  26818. if (this._texture._size) {
  26819. return new BABYLON.Size(this._texture._size, this._texture._size);
  26820. }
  26821. return BABYLON.Size.Zero();
  26822. };
  26823. BaseTexture.prototype.getBaseSize = function () {
  26824. if (!this.isReady() || !this._texture)
  26825. return BABYLON.Size.Zero();
  26826. if (this._texture._size) {
  26827. return new BABYLON.Size(this._texture._size, this._texture._size);
  26828. }
  26829. return new BABYLON.Size(this._texture._baseWidth, this._texture._baseHeight);
  26830. };
  26831. BaseTexture.prototype.scale = function (ratio) {
  26832. };
  26833. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  26834. get: function () {
  26835. return false;
  26836. },
  26837. enumerable: true,
  26838. configurable: true
  26839. });
  26840. BaseTexture.prototype._removeFromCache = function (url, noMipmap) {
  26841. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  26842. for (var index = 0; index < texturesCache.length; index++) {
  26843. var texturesCacheEntry = texturesCache[index];
  26844. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  26845. texturesCache.splice(index, 1);
  26846. return;
  26847. }
  26848. }
  26849. };
  26850. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  26851. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  26852. for (var index = 0; index < texturesCache.length; index++) {
  26853. var texturesCacheEntry = texturesCache[index];
  26854. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  26855. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  26856. texturesCacheEntry.references++;
  26857. return texturesCacheEntry;
  26858. }
  26859. }
  26860. }
  26861. return null;
  26862. };
  26863. BaseTexture.prototype.delayLoad = function () {
  26864. };
  26865. BaseTexture.prototype.clone = function () {
  26866. return null;
  26867. };
  26868. BaseTexture.prototype.releaseInternalTexture = function () {
  26869. if (this._texture) {
  26870. this._scene.getEngine().releaseInternalTexture(this._texture);
  26871. delete this._texture;
  26872. }
  26873. };
  26874. BaseTexture.prototype.dispose = function () {
  26875. // Animations
  26876. this.getScene().stopAnimation(this);
  26877. // Remove from scene
  26878. this._scene._removePendingData(this);
  26879. var index = this._scene.textures.indexOf(this);
  26880. if (index >= 0) {
  26881. this._scene.textures.splice(index, 1);
  26882. }
  26883. if (this._texture === undefined) {
  26884. return;
  26885. }
  26886. // Release
  26887. this.releaseInternalTexture();
  26888. // Callback
  26889. this.onDisposeObservable.notifyObservers(this);
  26890. this.onDisposeObservable.clear();
  26891. };
  26892. BaseTexture.prototype.serialize = function () {
  26893. if (!this.name) {
  26894. return null;
  26895. }
  26896. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  26897. // Animations
  26898. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  26899. return serializationObject;
  26900. };
  26901. return BaseTexture;
  26902. }());
  26903. __decorate([
  26904. BABYLON.serialize()
  26905. ], BaseTexture.prototype, "name", void 0);
  26906. __decorate([
  26907. BABYLON.serialize()
  26908. ], BaseTexture.prototype, "hasAlpha", void 0);
  26909. __decorate([
  26910. BABYLON.serialize()
  26911. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  26912. __decorate([
  26913. BABYLON.serialize()
  26914. ], BaseTexture.prototype, "level", void 0);
  26915. __decorate([
  26916. BABYLON.serialize()
  26917. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  26918. __decorate([
  26919. BABYLON.serialize()
  26920. ], BaseTexture.prototype, "coordinatesMode", void 0);
  26921. __decorate([
  26922. BABYLON.serialize()
  26923. ], BaseTexture.prototype, "wrapU", void 0);
  26924. __decorate([
  26925. BABYLON.serialize()
  26926. ], BaseTexture.prototype, "wrapV", void 0);
  26927. __decorate([
  26928. BABYLON.serialize()
  26929. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  26930. __decorate([
  26931. BABYLON.serialize()
  26932. ], BaseTexture.prototype, "isCube", void 0);
  26933. __decorate([
  26934. BABYLON.serialize()
  26935. ], BaseTexture.prototype, "isRenderTarget", void 0);
  26936. BABYLON.BaseTexture = BaseTexture;
  26937. })(BABYLON || (BABYLON = {}));
  26938. //# sourceMappingURL=babylon.baseTexture.js.map
  26939. var BABYLON;
  26940. (function (BABYLON) {
  26941. var Texture = (function (_super) {
  26942. __extends(Texture, _super);
  26943. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format) {
  26944. if (noMipmap === void 0) { noMipmap = false; }
  26945. if (invertY === void 0) { invertY = true; }
  26946. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  26947. if (onLoad === void 0) { onLoad = null; }
  26948. if (onError === void 0) { onError = null; }
  26949. if (buffer === void 0) { buffer = null; }
  26950. if (deleteBuffer === void 0) { deleteBuffer = false; }
  26951. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  26952. var _this = _super.call(this, scene) || this;
  26953. _this.uOffset = 0;
  26954. _this.vOffset = 0;
  26955. _this.uScale = 1.0;
  26956. _this.vScale = 1.0;
  26957. _this.uAng = 0;
  26958. _this.vAng = 0;
  26959. _this.wAng = 0;
  26960. _this.name = url;
  26961. _this.url = url;
  26962. _this._noMipmap = noMipmap;
  26963. _this._invertY = invertY;
  26964. _this._samplingMode = samplingMode;
  26965. _this._buffer = buffer;
  26966. _this._deleteBuffer = deleteBuffer;
  26967. _this._format = format;
  26968. if (!url) {
  26969. return _this;
  26970. }
  26971. _this._texture = _this._getFromCache(url, noMipmap, samplingMode);
  26972. var load = function () {
  26973. if (_this._onLoadObservarble && _this._onLoadObservarble.hasObservers()) {
  26974. _this.onLoadObservable.notifyObservers(true);
  26975. }
  26976. if (onLoad) {
  26977. onLoad();
  26978. }
  26979. };
  26980. if (!_this._texture) {
  26981. if (!scene.useDelayedTextureLoading) {
  26982. _this._texture = scene.getEngine().createTexture(url, noMipmap, invertY, scene, _this._samplingMode, load, onError, _this._buffer, null, _this._format);
  26983. if (deleteBuffer) {
  26984. delete _this._buffer;
  26985. }
  26986. }
  26987. else {
  26988. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  26989. _this._delayedOnLoad = load;
  26990. _this._delayedOnError = onError;
  26991. }
  26992. }
  26993. else {
  26994. if (_this._texture.isReady) {
  26995. BABYLON.Tools.SetImmediate(function () { return load(); });
  26996. }
  26997. else {
  26998. _this._texture.onLoadedCallbacks.push(load);
  26999. }
  27000. }
  27001. return _this;
  27002. }
  27003. Object.defineProperty(Texture.prototype, "noMipmap", {
  27004. get: function () {
  27005. return this._noMipmap;
  27006. },
  27007. enumerable: true,
  27008. configurable: true
  27009. });
  27010. Texture.prototype.delayLoad = function () {
  27011. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  27012. return;
  27013. }
  27014. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  27015. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  27016. if (!this._texture) {
  27017. this._texture = this.getScene().getEngine().createTexture(this.url, this._noMipmap, this._invertY, this.getScene(), this._samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer, null, this._format);
  27018. if (this._deleteBuffer) {
  27019. delete this._buffer;
  27020. }
  27021. }
  27022. };
  27023. Texture.prototype.updateSamplingMode = function (samplingMode) {
  27024. if (!this._texture) {
  27025. return;
  27026. }
  27027. this._samplingMode = samplingMode;
  27028. this.getScene().getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  27029. };
  27030. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  27031. x *= this.uScale;
  27032. y *= this.vScale;
  27033. x -= 0.5 * this.uScale;
  27034. y -= 0.5 * this.vScale;
  27035. z -= 0.5;
  27036. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  27037. t.x += 0.5 * this.uScale + this.uOffset;
  27038. t.y += 0.5 * this.vScale + this.vOffset;
  27039. t.z += 0.5;
  27040. };
  27041. Texture.prototype.getTextureMatrix = function () {
  27042. if (this.uOffset === this._cachedUOffset &&
  27043. this.vOffset === this._cachedVOffset &&
  27044. this.uScale === this._cachedUScale &&
  27045. this.vScale === this._cachedVScale &&
  27046. this.uAng === this._cachedUAng &&
  27047. this.vAng === this._cachedVAng &&
  27048. this.wAng === this._cachedWAng) {
  27049. return this._cachedTextureMatrix;
  27050. }
  27051. this._cachedUOffset = this.uOffset;
  27052. this._cachedVOffset = this.vOffset;
  27053. this._cachedUScale = this.uScale;
  27054. this._cachedVScale = this.vScale;
  27055. this._cachedUAng = this.uAng;
  27056. this._cachedVAng = this.vAng;
  27057. this._cachedWAng = this.wAng;
  27058. if (!this._cachedTextureMatrix) {
  27059. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  27060. this._rowGenerationMatrix = new BABYLON.Matrix();
  27061. this._t0 = BABYLON.Vector3.Zero();
  27062. this._t1 = BABYLON.Vector3.Zero();
  27063. this._t2 = BABYLON.Vector3.Zero();
  27064. }
  27065. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  27066. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  27067. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  27068. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  27069. this._t1.subtractInPlace(this._t0);
  27070. this._t2.subtractInPlace(this._t0);
  27071. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  27072. this._cachedTextureMatrix.m[0] = this._t1.x;
  27073. this._cachedTextureMatrix.m[1] = this._t1.y;
  27074. this._cachedTextureMatrix.m[2] = this._t1.z;
  27075. this._cachedTextureMatrix.m[4] = this._t2.x;
  27076. this._cachedTextureMatrix.m[5] = this._t2.y;
  27077. this._cachedTextureMatrix.m[6] = this._t2.z;
  27078. this._cachedTextureMatrix.m[8] = this._t0.x;
  27079. this._cachedTextureMatrix.m[9] = this._t0.y;
  27080. this._cachedTextureMatrix.m[10] = this._t0.z;
  27081. return this._cachedTextureMatrix;
  27082. };
  27083. Texture.prototype.getReflectionTextureMatrix = function () {
  27084. if (this.uOffset === this._cachedUOffset &&
  27085. this.vOffset === this._cachedVOffset &&
  27086. this.uScale === this._cachedUScale &&
  27087. this.vScale === this._cachedVScale &&
  27088. this.coordinatesMode === this._cachedCoordinatesMode) {
  27089. return this._cachedTextureMatrix;
  27090. }
  27091. if (!this._cachedTextureMatrix) {
  27092. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  27093. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  27094. }
  27095. this._cachedCoordinatesMode = this.coordinatesMode;
  27096. switch (this.coordinatesMode) {
  27097. case Texture.PLANAR_MODE:
  27098. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  27099. this._cachedTextureMatrix[0] = this.uScale;
  27100. this._cachedTextureMatrix[5] = this.vScale;
  27101. this._cachedTextureMatrix[12] = this.uOffset;
  27102. this._cachedTextureMatrix[13] = this.vOffset;
  27103. break;
  27104. case Texture.PROJECTION_MODE:
  27105. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  27106. this._projectionModeMatrix.m[0] = 0.5;
  27107. this._projectionModeMatrix.m[5] = -0.5;
  27108. this._projectionModeMatrix.m[10] = 0.0;
  27109. this._projectionModeMatrix.m[12] = 0.5;
  27110. this._projectionModeMatrix.m[13] = 0.5;
  27111. this._projectionModeMatrix.m[14] = 1.0;
  27112. this._projectionModeMatrix.m[15] = 1.0;
  27113. this.getScene().getProjectionMatrix().multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  27114. break;
  27115. default:
  27116. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  27117. break;
  27118. }
  27119. return this._cachedTextureMatrix;
  27120. };
  27121. Texture.prototype.clone = function () {
  27122. var _this = this;
  27123. return BABYLON.SerializationHelper.Clone(function () {
  27124. return new Texture(_this._texture.url, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  27125. }, this);
  27126. };
  27127. Object.defineProperty(Texture.prototype, "onLoadObservable", {
  27128. get: function () {
  27129. if (!this._onLoadObservarble) {
  27130. this._onLoadObservarble = new BABYLON.Observable();
  27131. }
  27132. return this._onLoadObservarble;
  27133. },
  27134. enumerable: true,
  27135. configurable: true
  27136. });
  27137. // Statics
  27138. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  27139. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  27140. if (onLoad === void 0) { onLoad = null; }
  27141. if (onError === void 0) { onError = null; }
  27142. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  27143. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data, false, format);
  27144. };
  27145. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  27146. if (parsedTexture.customType) {
  27147. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  27148. return customTexture.Parse(parsedTexture, scene, rootUrl);
  27149. }
  27150. if (parsedTexture.isCube) {
  27151. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  27152. }
  27153. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  27154. return null;
  27155. }
  27156. var texture = BABYLON.SerializationHelper.Parse(function () {
  27157. if (parsedTexture.mirrorPlane) {
  27158. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  27159. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  27160. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  27161. return mirrorTexture;
  27162. }
  27163. else if (parsedTexture.isRenderTarget) {
  27164. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  27165. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  27166. return renderTargetTexture;
  27167. }
  27168. else {
  27169. var texture;
  27170. if (parsedTexture.base64String) {
  27171. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene);
  27172. }
  27173. else {
  27174. texture = new Texture(rootUrl + parsedTexture.name, scene);
  27175. }
  27176. return texture;
  27177. }
  27178. }, parsedTexture, scene);
  27179. // Animations
  27180. if (parsedTexture.animations) {
  27181. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  27182. var parsedAnimation = parsedTexture.animations[animationIndex];
  27183. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  27184. }
  27185. }
  27186. return texture;
  27187. };
  27188. Texture.LoadFromDataString = function (name, buffer, scene, deleteBuffer, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  27189. if (deleteBuffer === void 0) { deleteBuffer = false; }
  27190. if (noMipmap === void 0) { noMipmap = false; }
  27191. if (invertY === void 0) { invertY = true; }
  27192. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  27193. if (onLoad === void 0) { onLoad = null; }
  27194. if (onError === void 0) { onError = null; }
  27195. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  27196. if (name.substr(0, 5) !== "data:") {
  27197. name = "data:" + name;
  27198. }
  27199. return new Texture(name, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format);
  27200. };
  27201. return Texture;
  27202. }(BABYLON.BaseTexture));
  27203. // Constants
  27204. Texture.NEAREST_SAMPLINGMODE = 1;
  27205. Texture.BILINEAR_SAMPLINGMODE = 2;
  27206. Texture.TRILINEAR_SAMPLINGMODE = 3;
  27207. Texture.EXPLICIT_MODE = 0;
  27208. Texture.SPHERICAL_MODE = 1;
  27209. Texture.PLANAR_MODE = 2;
  27210. Texture.CUBIC_MODE = 3;
  27211. Texture.PROJECTION_MODE = 4;
  27212. Texture.SKYBOX_MODE = 5;
  27213. Texture.INVCUBIC_MODE = 6;
  27214. Texture.EQUIRECTANGULAR_MODE = 7;
  27215. Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
  27216. Texture.CLAMP_ADDRESSMODE = 0;
  27217. Texture.WRAP_ADDRESSMODE = 1;
  27218. Texture.MIRROR_ADDRESSMODE = 2;
  27219. __decorate([
  27220. BABYLON.serialize()
  27221. ], Texture.prototype, "url", void 0);
  27222. __decorate([
  27223. BABYLON.serialize()
  27224. ], Texture.prototype, "uOffset", void 0);
  27225. __decorate([
  27226. BABYLON.serialize()
  27227. ], Texture.prototype, "vOffset", void 0);
  27228. __decorate([
  27229. BABYLON.serialize()
  27230. ], Texture.prototype, "uScale", void 0);
  27231. __decorate([
  27232. BABYLON.serialize()
  27233. ], Texture.prototype, "vScale", void 0);
  27234. __decorate([
  27235. BABYLON.serialize()
  27236. ], Texture.prototype, "uAng", void 0);
  27237. __decorate([
  27238. BABYLON.serialize()
  27239. ], Texture.prototype, "vAng", void 0);
  27240. __decorate([
  27241. BABYLON.serialize()
  27242. ], Texture.prototype, "wAng", void 0);
  27243. BABYLON.Texture = Texture;
  27244. })(BABYLON || (BABYLON = {}));
  27245. //# sourceMappingURL=babylon.texture.js.map
  27246. var BABYLON;
  27247. (function (BABYLON) {
  27248. var CubeTexture = (function (_super) {
  27249. __extends(CubeTexture, _super);
  27250. function CubeTexture(rootUrl, scene, extensions, noMipmap, files, onLoad, onError, format) {
  27251. if (onLoad === void 0) { onLoad = null; }
  27252. if (onError === void 0) { onError = null; }
  27253. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  27254. var _this = _super.call(this, scene) || this;
  27255. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  27256. _this.name = rootUrl;
  27257. _this.url = rootUrl;
  27258. _this._noMipmap = noMipmap;
  27259. _this.hasAlpha = false;
  27260. _this._format = format;
  27261. if (!rootUrl && !files) {
  27262. return _this;
  27263. }
  27264. _this._texture = _this._getFromCache(rootUrl, noMipmap);
  27265. if (!files) {
  27266. if (!extensions) {
  27267. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  27268. }
  27269. files = [];
  27270. for (var index = 0; index < extensions.length; index++) {
  27271. files.push(rootUrl + extensions[index]);
  27272. }
  27273. _this._extensions = extensions;
  27274. }
  27275. _this._files = files;
  27276. if (!_this._texture) {
  27277. if (!scene.useDelayedTextureLoading) {
  27278. _this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap, onLoad, onError, _this._format);
  27279. }
  27280. else {
  27281. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  27282. }
  27283. }
  27284. else if (onLoad) {
  27285. if (_this._texture.isReady) {
  27286. BABYLON.Tools.SetImmediate(function () { return onLoad(); });
  27287. }
  27288. else {
  27289. _this._texture.onLoadedCallbacks.push(onLoad);
  27290. }
  27291. }
  27292. _this.isCube = true;
  27293. _this._textureMatrix = BABYLON.Matrix.Identity();
  27294. return _this;
  27295. }
  27296. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  27297. return new CubeTexture("", scene, null, noMipmap, files);
  27298. };
  27299. // Methods
  27300. CubeTexture.prototype.delayLoad = function () {
  27301. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  27302. return;
  27303. }
  27304. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  27305. this._texture = this._getFromCache(this.url, this._noMipmap);
  27306. if (!this._texture) {
  27307. this._texture = this.getScene().getEngine().createCubeTexture(this.url, this.getScene(), this._files, this._noMipmap, undefined, undefined, this._format);
  27308. }
  27309. };
  27310. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  27311. return this._textureMatrix;
  27312. };
  27313. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  27314. var texture = BABYLON.SerializationHelper.Parse(function () {
  27315. return new BABYLON.CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions);
  27316. }, parsedTexture, scene);
  27317. // Animations
  27318. if (parsedTexture.animations) {
  27319. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  27320. var parsedAnimation = parsedTexture.animations[animationIndex];
  27321. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  27322. }
  27323. }
  27324. return texture;
  27325. };
  27326. CubeTexture.prototype.clone = function () {
  27327. var _this = this;
  27328. return BABYLON.SerializationHelper.Clone(function () {
  27329. return new CubeTexture(_this.url, _this.getScene(), _this._extensions, _this._noMipmap, _this._files);
  27330. }, this);
  27331. };
  27332. return CubeTexture;
  27333. }(BABYLON.BaseTexture));
  27334. BABYLON.CubeTexture = CubeTexture;
  27335. })(BABYLON || (BABYLON = {}));
  27336. //# sourceMappingURL=babylon.cubeTexture.js.map
  27337. var BABYLON;
  27338. (function (BABYLON) {
  27339. var RenderTargetTexture = (function (_super) {
  27340. __extends(RenderTargetTexture, _super);
  27341. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer) {
  27342. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  27343. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  27344. if (isCube === void 0) { isCube = false; }
  27345. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  27346. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  27347. if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
  27348. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  27349. _this.isCube = isCube;
  27350. /**
  27351. * Use this list to define the list of mesh you want to render.
  27352. */
  27353. _this.renderList = new Array();
  27354. _this.renderParticles = true;
  27355. _this.renderSprites = false;
  27356. _this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  27357. // Events
  27358. /**
  27359. * An event triggered when the texture is unbind.
  27360. * @type {BABYLON.Observable}
  27361. */
  27362. _this.onAfterUnbindObservable = new BABYLON.Observable();
  27363. /**
  27364. * An event triggered before rendering the texture
  27365. * @type {BABYLON.Observable}
  27366. */
  27367. _this.onBeforeRenderObservable = new BABYLON.Observable();
  27368. /**
  27369. * An event triggered after rendering the texture
  27370. * @type {BABYLON.Observable}
  27371. */
  27372. _this.onAfterRenderObservable = new BABYLON.Observable();
  27373. /**
  27374. * An event triggered after the texture clear
  27375. * @type {BABYLON.Observable}
  27376. */
  27377. _this.onClearObservable = new BABYLON.Observable();
  27378. _this._currentRefreshId = -1;
  27379. _this._refreshRate = 1;
  27380. _this._samples = 1;
  27381. _this.name = name;
  27382. _this.isRenderTarget = true;
  27383. _this._size = size;
  27384. _this._generateMipMaps = generateMipMaps;
  27385. _this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  27386. _this._renderTargetOptions = {
  27387. generateMipMaps: generateMipMaps,
  27388. type: type,
  27389. samplingMode: samplingMode,
  27390. generateDepthBuffer: generateDepthBuffer,
  27391. generateStencilBuffer: generateStencilBuffer
  27392. };
  27393. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  27394. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  27395. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  27396. }
  27397. if (isCube) {
  27398. _this._texture = scene.getEngine().createRenderTargetCubeTexture(size, _this._renderTargetOptions);
  27399. _this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  27400. _this._textureMatrix = BABYLON.Matrix.Identity();
  27401. }
  27402. else {
  27403. _this._texture = scene.getEngine().createRenderTargetTexture(size, _this._renderTargetOptions);
  27404. }
  27405. // Rendering groups
  27406. _this._renderingManager = new BABYLON.RenderingManager(scene);
  27407. return _this;
  27408. }
  27409. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  27410. get: function () {
  27411. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  27412. },
  27413. enumerable: true,
  27414. configurable: true
  27415. });
  27416. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  27417. get: function () {
  27418. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  27419. },
  27420. enumerable: true,
  27421. configurable: true
  27422. });
  27423. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  27424. get: function () {
  27425. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  27426. },
  27427. enumerable: true,
  27428. configurable: true
  27429. });
  27430. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  27431. set: function (callback) {
  27432. if (this._onAfterUnbindObserver) {
  27433. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  27434. }
  27435. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  27436. },
  27437. enumerable: true,
  27438. configurable: true
  27439. });
  27440. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  27441. set: function (callback) {
  27442. if (this._onBeforeRenderObserver) {
  27443. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  27444. }
  27445. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  27446. },
  27447. enumerable: true,
  27448. configurable: true
  27449. });
  27450. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  27451. set: function (callback) {
  27452. if (this._onAfterRenderObserver) {
  27453. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  27454. }
  27455. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  27456. },
  27457. enumerable: true,
  27458. configurable: true
  27459. });
  27460. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  27461. set: function (callback) {
  27462. if (this._onClearObserver) {
  27463. this.onClearObservable.remove(this._onClearObserver);
  27464. }
  27465. this._onClearObserver = this.onClearObservable.add(callback);
  27466. },
  27467. enumerable: true,
  27468. configurable: true
  27469. });
  27470. Object.defineProperty(RenderTargetTexture.prototype, "samples", {
  27471. get: function () {
  27472. return this._samples;
  27473. },
  27474. set: function (value) {
  27475. if (this._samples === value) {
  27476. return;
  27477. }
  27478. this._samples = this.getScene().getEngine().updateRenderTargetTextureSampleCount(this._texture, value);
  27479. },
  27480. enumerable: true,
  27481. configurable: true
  27482. });
  27483. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  27484. this._currentRefreshId = -1;
  27485. };
  27486. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  27487. get: function () {
  27488. return this._refreshRate;
  27489. },
  27490. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  27491. set: function (value) {
  27492. this._refreshRate = value;
  27493. this.resetRefreshCounter();
  27494. },
  27495. enumerable: true,
  27496. configurable: true
  27497. });
  27498. RenderTargetTexture.prototype._shouldRender = function () {
  27499. if (this._currentRefreshId === -1) {
  27500. this._currentRefreshId = 1;
  27501. return true;
  27502. }
  27503. if (this.refreshRate === this._currentRefreshId) {
  27504. this._currentRefreshId = 1;
  27505. return true;
  27506. }
  27507. this._currentRefreshId++;
  27508. return false;
  27509. };
  27510. RenderTargetTexture.prototype.isReady = function () {
  27511. if (!this.getScene().renderTargetsEnabled) {
  27512. return false;
  27513. }
  27514. return _super.prototype.isReady.call(this);
  27515. };
  27516. RenderTargetTexture.prototype.getRenderSize = function () {
  27517. return this._size;
  27518. };
  27519. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  27520. get: function () {
  27521. return true;
  27522. },
  27523. enumerable: true,
  27524. configurable: true
  27525. });
  27526. RenderTargetTexture.prototype.scale = function (ratio) {
  27527. var newSize = this._size * ratio;
  27528. this.resize(newSize);
  27529. };
  27530. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  27531. if (this.isCube) {
  27532. return this._textureMatrix;
  27533. }
  27534. return _super.prototype.getReflectionTextureMatrix.call(this);
  27535. };
  27536. RenderTargetTexture.prototype.resize = function (size) {
  27537. this.releaseInternalTexture();
  27538. if (this.isCube) {
  27539. this._texture = this.getScene().getEngine().createRenderTargetCubeTexture(size, this._renderTargetOptions);
  27540. }
  27541. else {
  27542. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, this._renderTargetOptions);
  27543. }
  27544. };
  27545. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  27546. var scene = this.getScene();
  27547. var engine = scene.getEngine();
  27548. if (this.useCameraPostProcesses !== undefined) {
  27549. useCameraPostProcess = this.useCameraPostProcesses;
  27550. }
  27551. if (this._waitingRenderList) {
  27552. this.renderList = [];
  27553. for (var index = 0; index < this._waitingRenderList.length; index++) {
  27554. var id = this._waitingRenderList[index];
  27555. this.renderList.push(scene.getMeshByID(id));
  27556. }
  27557. delete this._waitingRenderList;
  27558. }
  27559. // Is predicate defined?
  27560. if (this.renderListPredicate) {
  27561. this.renderList.splice(0); // Clear previous renderList
  27562. var sceneMeshes = this.getScene().meshes;
  27563. for (var index = 0; index < sceneMeshes.length; index++) {
  27564. var mesh = sceneMeshes[index];
  27565. if (this.renderListPredicate(mesh)) {
  27566. this.renderList.push(mesh);
  27567. }
  27568. }
  27569. }
  27570. if (this.renderList && this.renderList.length === 0) {
  27571. return;
  27572. }
  27573. // Set custom projection.
  27574. // Needs to be before binding to prevent changing the aspect ratio.
  27575. if (this.activeCamera) {
  27576. engine.setViewport(this.activeCamera.viewport);
  27577. if (this.activeCamera !== scene.activeCamera) {
  27578. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  27579. }
  27580. }
  27581. else {
  27582. engine.setViewport(scene.activeCamera.viewport);
  27583. }
  27584. // Prepare renderingManager
  27585. this._renderingManager.reset();
  27586. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  27587. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  27588. var sceneRenderId = scene.getRenderId();
  27589. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  27590. var mesh = currentRenderList[meshIndex];
  27591. if (mesh) {
  27592. if (!mesh.isReady()) {
  27593. // Reset _currentRefreshId
  27594. this.resetRefreshCounter();
  27595. continue;
  27596. }
  27597. mesh._preActivateForIntermediateRendering(sceneRenderId);
  27598. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && ((mesh.layerMask & scene.activeCamera.layerMask) !== 0)) {
  27599. mesh._activate(sceneRenderId);
  27600. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  27601. var subMesh = mesh.subMeshes[subIndex];
  27602. scene._activeIndices.addCount(subMesh.indexCount, false);
  27603. this._renderingManager.dispatch(subMesh);
  27604. }
  27605. }
  27606. }
  27607. }
  27608. for (var particleIndex = 0; particleIndex < scene.particleSystems.length; particleIndex++) {
  27609. var particleSystem = scene.particleSystems[particleIndex];
  27610. if (!particleSystem.isStarted() || !particleSystem.emitter || !particleSystem.emitter.position || !particleSystem.emitter.isEnabled()) {
  27611. continue;
  27612. }
  27613. if (currentRenderList.indexOf(particleSystem.emitter) >= 0) {
  27614. this._renderingManager.dispatchParticles(particleSystem);
  27615. }
  27616. }
  27617. if (this.isCube) {
  27618. for (var face = 0; face < 6; face++) {
  27619. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  27620. scene.incrementRenderId();
  27621. scene.resetCachedMaterial();
  27622. }
  27623. }
  27624. else {
  27625. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  27626. }
  27627. this.onAfterUnbindObservable.notifyObservers(this);
  27628. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  27629. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  27630. }
  27631. engine.setViewport(scene.activeCamera.viewport);
  27632. scene.resetCachedMaterial();
  27633. };
  27634. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  27635. var _this = this;
  27636. var scene = this.getScene();
  27637. var engine = scene.getEngine();
  27638. // Bind
  27639. if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  27640. if (this.isCube) {
  27641. engine.bindFramebuffer(this._texture, faceIndex);
  27642. }
  27643. else {
  27644. engine.bindFramebuffer(this._texture);
  27645. }
  27646. }
  27647. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  27648. // Clear
  27649. if (this.onClearObservable.hasObservers()) {
  27650. this.onClearObservable.notifyObservers(engine);
  27651. }
  27652. else {
  27653. engine.clear(scene.clearColor, true, true, true);
  27654. }
  27655. if (!this._doNotChangeAspectRatio) {
  27656. scene.updateTransformMatrix(true);
  27657. }
  27658. // Render
  27659. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  27660. if (useCameraPostProcess) {
  27661. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  27662. }
  27663. if (!this._doNotChangeAspectRatio) {
  27664. scene.updateTransformMatrix(true);
  27665. }
  27666. // Dump ?
  27667. if (dumpForDebug) {
  27668. BABYLON.Tools.DumpFramebuffer(this._size, this._size, engine);
  27669. }
  27670. // Unbind
  27671. if (!this.isCube || faceIndex === 5) {
  27672. if (this.isCube) {
  27673. if (faceIndex === 5) {
  27674. engine.generateMipMapsForCubemap(this._texture);
  27675. }
  27676. }
  27677. engine.unBindFramebuffer(this._texture, this.isCube, function () {
  27678. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  27679. });
  27680. }
  27681. else {
  27682. this.onAfterRenderObservable.notifyObservers(faceIndex);
  27683. }
  27684. };
  27685. /**
  27686. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  27687. * This allowed control for front to back rendering or reversly depending of the special needs.
  27688. *
  27689. * @param renderingGroupId The rendering group id corresponding to its index
  27690. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  27691. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  27692. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  27693. */
  27694. RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  27695. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  27696. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  27697. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  27698. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  27699. };
  27700. /**
  27701. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  27702. *
  27703. * @param renderingGroupId The rendering group id corresponding to its index
  27704. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  27705. */
  27706. RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  27707. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  27708. };
  27709. RenderTargetTexture.prototype.clone = function () {
  27710. var textureSize = this.getSize();
  27711. 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);
  27712. // Base texture
  27713. newTexture.hasAlpha = this.hasAlpha;
  27714. newTexture.level = this.level;
  27715. // RenderTarget Texture
  27716. newTexture.coordinatesMode = this.coordinatesMode;
  27717. newTexture.renderList = this.renderList.slice(0);
  27718. return newTexture;
  27719. };
  27720. RenderTargetTexture.prototype.serialize = function () {
  27721. if (!this.name) {
  27722. return null;
  27723. }
  27724. var serializationObject = _super.prototype.serialize.call(this);
  27725. serializationObject.renderTargetSize = this.getRenderSize();
  27726. serializationObject.renderList = [];
  27727. for (var index = 0; index < this.renderList.length; index++) {
  27728. serializationObject.renderList.push(this.renderList[index].id);
  27729. }
  27730. return serializationObject;
  27731. };
  27732. return RenderTargetTexture;
  27733. }(BABYLON.Texture));
  27734. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  27735. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  27736. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  27737. BABYLON.RenderTargetTexture = RenderTargetTexture;
  27738. })(BABYLON || (BABYLON = {}));
  27739. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  27740. var BABYLON;
  27741. (function (BABYLON) {
  27742. var ProceduralTexture = (function (_super) {
  27743. __extends(ProceduralTexture, _super);
  27744. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  27745. if (generateMipMaps === void 0) { generateMipMaps = true; }
  27746. if (isCube === void 0) { isCube = false; }
  27747. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  27748. _this.isCube = isCube;
  27749. _this.isEnabled = true;
  27750. _this._currentRefreshId = -1;
  27751. _this._refreshRate = 1;
  27752. _this._vertexBuffers = {};
  27753. _this._uniforms = new Array();
  27754. _this._samplers = new Array();
  27755. _this._textures = new Array();
  27756. _this._floats = new Array();
  27757. _this._floatsArrays = {};
  27758. _this._colors3 = new Array();
  27759. _this._colors4 = new Array();
  27760. _this._vectors2 = new Array();
  27761. _this._vectors3 = new Array();
  27762. _this._matrices = new Array();
  27763. _this._fallbackTextureUsed = false;
  27764. scene._proceduralTextures.push(_this);
  27765. _this.name = name;
  27766. _this.isRenderTarget = true;
  27767. _this._size = size;
  27768. _this._generateMipMaps = generateMipMaps;
  27769. _this.setFragment(fragment);
  27770. _this._fallbackTexture = fallbackTexture;
  27771. var engine = scene.getEngine();
  27772. if (isCube) {
  27773. _this._texture = engine.createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  27774. _this.setFloat("face", 0);
  27775. }
  27776. else {
  27777. _this._texture = engine.createRenderTargetTexture(size, generateMipMaps);
  27778. }
  27779. // VBO
  27780. var vertices = [];
  27781. vertices.push(1, 1);
  27782. vertices.push(-1, 1);
  27783. vertices.push(-1, -1);
  27784. vertices.push(1, -1);
  27785. _this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  27786. // Indices
  27787. var indices = [];
  27788. indices.push(0);
  27789. indices.push(1);
  27790. indices.push(2);
  27791. indices.push(0);
  27792. indices.push(2);
  27793. indices.push(3);
  27794. _this._indexBuffer = engine.createIndexBuffer(indices);
  27795. return _this;
  27796. }
  27797. ProceduralTexture.prototype.reset = function () {
  27798. if (this._effect === undefined) {
  27799. return;
  27800. }
  27801. var engine = this.getScene().getEngine();
  27802. engine._releaseEffect(this._effect);
  27803. };
  27804. ProceduralTexture.prototype.isReady = function () {
  27805. var _this = this;
  27806. var engine = this.getScene().getEngine();
  27807. var shaders;
  27808. if (!this._fragment) {
  27809. return false;
  27810. }
  27811. if (this._fallbackTextureUsed) {
  27812. return true;
  27813. }
  27814. if (this._fragment.fragmentElement !== undefined) {
  27815. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  27816. }
  27817. else {
  27818. shaders = { vertex: "procedural", fragment: this._fragment };
  27819. }
  27820. this._effect = engine.createEffect(shaders, [BABYLON.VertexBuffer.PositionKind], this._uniforms, this._samplers, "", null, null, function () {
  27821. _this.releaseInternalTexture();
  27822. if (_this._fallbackTexture) {
  27823. _this._texture = _this._fallbackTexture._texture;
  27824. _this._texture.references++;
  27825. }
  27826. _this._fallbackTextureUsed = true;
  27827. });
  27828. return this._effect.isReady();
  27829. };
  27830. ProceduralTexture.prototype.resetRefreshCounter = function () {
  27831. this._currentRefreshId = -1;
  27832. };
  27833. ProceduralTexture.prototype.setFragment = function (fragment) {
  27834. this._fragment = fragment;
  27835. };
  27836. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  27837. get: function () {
  27838. return this._refreshRate;
  27839. },
  27840. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  27841. set: function (value) {
  27842. this._refreshRate = value;
  27843. this.resetRefreshCounter();
  27844. },
  27845. enumerable: true,
  27846. configurable: true
  27847. });
  27848. ProceduralTexture.prototype._shouldRender = function () {
  27849. if (!this.isEnabled || !this.isReady() || !this._texture) {
  27850. return false;
  27851. }
  27852. if (this._fallbackTextureUsed) {
  27853. return false;
  27854. }
  27855. if (this._currentRefreshId === -1) {
  27856. this._currentRefreshId = 1;
  27857. return true;
  27858. }
  27859. if (this.refreshRate === this._currentRefreshId) {
  27860. this._currentRefreshId = 1;
  27861. return true;
  27862. }
  27863. this._currentRefreshId++;
  27864. return false;
  27865. };
  27866. ProceduralTexture.prototype.getRenderSize = function () {
  27867. return this._size;
  27868. };
  27869. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  27870. if (this._fallbackTextureUsed) {
  27871. return;
  27872. }
  27873. this.releaseInternalTexture();
  27874. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  27875. };
  27876. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  27877. if (this._uniforms.indexOf(uniformName) === -1) {
  27878. this._uniforms.push(uniformName);
  27879. }
  27880. };
  27881. ProceduralTexture.prototype.setTexture = function (name, texture) {
  27882. if (this._samplers.indexOf(name) === -1) {
  27883. this._samplers.push(name);
  27884. }
  27885. this._textures[name] = texture;
  27886. return this;
  27887. };
  27888. ProceduralTexture.prototype.setFloat = function (name, value) {
  27889. this._checkUniform(name);
  27890. this._floats[name] = value;
  27891. return this;
  27892. };
  27893. ProceduralTexture.prototype.setFloats = function (name, value) {
  27894. this._checkUniform(name);
  27895. this._floatsArrays[name] = value;
  27896. return this;
  27897. };
  27898. ProceduralTexture.prototype.setColor3 = function (name, value) {
  27899. this._checkUniform(name);
  27900. this._colors3[name] = value;
  27901. return this;
  27902. };
  27903. ProceduralTexture.prototype.setColor4 = function (name, value) {
  27904. this._checkUniform(name);
  27905. this._colors4[name] = value;
  27906. return this;
  27907. };
  27908. ProceduralTexture.prototype.setVector2 = function (name, value) {
  27909. this._checkUniform(name);
  27910. this._vectors2[name] = value;
  27911. return this;
  27912. };
  27913. ProceduralTexture.prototype.setVector3 = function (name, value) {
  27914. this._checkUniform(name);
  27915. this._vectors3[name] = value;
  27916. return this;
  27917. };
  27918. ProceduralTexture.prototype.setMatrix = function (name, value) {
  27919. this._checkUniform(name);
  27920. this._matrices[name] = value;
  27921. return this;
  27922. };
  27923. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  27924. var scene = this.getScene();
  27925. var engine = scene.getEngine();
  27926. // Render
  27927. engine.enableEffect(this._effect);
  27928. engine.setState(false);
  27929. // Texture
  27930. for (var name in this._textures) {
  27931. this._effect.setTexture(name, this._textures[name]);
  27932. }
  27933. // Float
  27934. for (name in this._floats) {
  27935. this._effect.setFloat(name, this._floats[name]);
  27936. }
  27937. // Floats
  27938. for (name in this._floatsArrays) {
  27939. this._effect.setArray(name, this._floatsArrays[name]);
  27940. }
  27941. // Color3
  27942. for (name in this._colors3) {
  27943. this._effect.setColor3(name, this._colors3[name]);
  27944. }
  27945. // Color4
  27946. for (name in this._colors4) {
  27947. var color = this._colors4[name];
  27948. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  27949. }
  27950. // Vector2
  27951. for (name in this._vectors2) {
  27952. this._effect.setVector2(name, this._vectors2[name]);
  27953. }
  27954. // Vector3
  27955. for (name in this._vectors3) {
  27956. this._effect.setVector3(name, this._vectors3[name]);
  27957. }
  27958. // Matrix
  27959. for (name in this._matrices) {
  27960. this._effect.setMatrix(name, this._matrices[name]);
  27961. }
  27962. if (this.isCube) {
  27963. for (var face = 0; face < 6; face++) {
  27964. engine.bindFramebuffer(this._texture, face);
  27965. // VBOs
  27966. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  27967. this._effect.setFloat("face", face);
  27968. // Clear
  27969. engine.clear(scene.clearColor, true, true, true);
  27970. // Draw order
  27971. engine.draw(true, 0, 6);
  27972. // Mipmaps
  27973. if (face === 5) {
  27974. engine.generateMipMapsForCubemap(this._texture);
  27975. }
  27976. }
  27977. }
  27978. else {
  27979. engine.bindFramebuffer(this._texture);
  27980. // VBOs
  27981. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  27982. // Clear
  27983. engine.clear(scene.clearColor, true, true, true);
  27984. // Draw order
  27985. engine.draw(true, 0, 6);
  27986. }
  27987. // Unbind
  27988. engine.unBindFramebuffer(this._texture, this.isCube);
  27989. if (this.onGenerated) {
  27990. this.onGenerated();
  27991. }
  27992. };
  27993. ProceduralTexture.prototype.clone = function () {
  27994. var textureSize = this.getSize();
  27995. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  27996. // Base texture
  27997. newTexture.hasAlpha = this.hasAlpha;
  27998. newTexture.level = this.level;
  27999. // RenderTarget Texture
  28000. newTexture.coordinatesMode = this.coordinatesMode;
  28001. return newTexture;
  28002. };
  28003. ProceduralTexture.prototype.dispose = function () {
  28004. var index = this.getScene()._proceduralTextures.indexOf(this);
  28005. if (index >= 0) {
  28006. this.getScene()._proceduralTextures.splice(index, 1);
  28007. }
  28008. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  28009. if (vertexBuffer) {
  28010. vertexBuffer.dispose();
  28011. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  28012. }
  28013. if (this._indexBuffer && this.getScene().getEngine()._releaseBuffer(this._indexBuffer)) {
  28014. this._indexBuffer = null;
  28015. }
  28016. _super.prototype.dispose.call(this);
  28017. };
  28018. return ProceduralTexture;
  28019. }(BABYLON.Texture));
  28020. BABYLON.ProceduralTexture = ProceduralTexture;
  28021. })(BABYLON || (BABYLON = {}));
  28022. //# sourceMappingURL=babylon.proceduralTexture.js.map
  28023. /// <reference path="babylon.renderTargetTexture.ts" />
  28024. var BABYLON;
  28025. (function (BABYLON) {
  28026. var MirrorTexture = (function (_super) {
  28027. __extends(MirrorTexture, _super);
  28028. function MirrorTexture(name, size, scene, generateMipMaps, type, samplingMode, generateDepthBuffer) {
  28029. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  28030. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  28031. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  28032. var _this = _super.call(this, name, size, scene, generateMipMaps, true, type, false, samplingMode, generateDepthBuffer) || this;
  28033. _this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  28034. _this._transformMatrix = BABYLON.Matrix.Zero();
  28035. _this._mirrorMatrix = BABYLON.Matrix.Zero();
  28036. _this.onBeforeRenderObservable.add(function () {
  28037. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  28038. _this._savedViewMatrix = scene.getViewMatrix();
  28039. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  28040. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  28041. scene.clipPlane = _this.mirrorPlane;
  28042. scene.getEngine().cullBackFaces = false;
  28043. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.position, _this._mirrorMatrix);
  28044. });
  28045. _this.onAfterRenderObservable.add(function () {
  28046. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  28047. scene.getEngine().cullBackFaces = true;
  28048. scene._mirroredCameraPosition = null;
  28049. delete scene.clipPlane;
  28050. });
  28051. return _this;
  28052. }
  28053. MirrorTexture.prototype.clone = function () {
  28054. var textureSize = this.getSize();
  28055. var newTexture = new MirrorTexture(this.name, textureSize.width, this.getScene(), this._renderTargetOptions.generateMipMaps, this._renderTargetOptions.type, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer);
  28056. // Base texture
  28057. newTexture.hasAlpha = this.hasAlpha;
  28058. newTexture.level = this.level;
  28059. // Mirror Texture
  28060. newTexture.mirrorPlane = this.mirrorPlane.clone();
  28061. newTexture.renderList = this.renderList.slice(0);
  28062. return newTexture;
  28063. };
  28064. MirrorTexture.prototype.serialize = function () {
  28065. if (!this.name) {
  28066. return null;
  28067. }
  28068. var serializationObject = _super.prototype.serialize.call(this);
  28069. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  28070. return serializationObject;
  28071. };
  28072. return MirrorTexture;
  28073. }(BABYLON.RenderTargetTexture));
  28074. BABYLON.MirrorTexture = MirrorTexture;
  28075. })(BABYLON || (BABYLON = {}));
  28076. //# sourceMappingURL=babylon.mirrorTexture.js.map
  28077. /// <reference path="babylon.renderTargetTexture.ts" />
  28078. var BABYLON;
  28079. (function (BABYLON) {
  28080. /**
  28081. * Creates a refraction texture used by refraction channel of the standard material.
  28082. * @param name the texture name
  28083. * @param size size of the underlying texture
  28084. * @param scene root scene
  28085. */
  28086. var RefractionTexture = (function (_super) {
  28087. __extends(RefractionTexture, _super);
  28088. function RefractionTexture(name, size, scene, generateMipMaps) {
  28089. var _this = _super.call(this, name, size, scene, generateMipMaps, true) || this;
  28090. _this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  28091. _this.depth = 2.0;
  28092. _this.onBeforeRenderObservable.add(function () {
  28093. scene.clipPlane = _this.refractionPlane;
  28094. });
  28095. _this.onAfterRenderObservable.add(function () {
  28096. delete scene.clipPlane;
  28097. });
  28098. return _this;
  28099. }
  28100. RefractionTexture.prototype.clone = function () {
  28101. var textureSize = this.getSize();
  28102. var newTexture = new RefractionTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  28103. // Base texture
  28104. newTexture.hasAlpha = this.hasAlpha;
  28105. newTexture.level = this.level;
  28106. // Refraction Texture
  28107. newTexture.refractionPlane = this.refractionPlane.clone();
  28108. newTexture.renderList = this.renderList.slice(0);
  28109. newTexture.depth = this.depth;
  28110. return newTexture;
  28111. };
  28112. RefractionTexture.prototype.serialize = function () {
  28113. if (!this.name) {
  28114. return null;
  28115. }
  28116. var serializationObject = _super.prototype.serialize.call(this);
  28117. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  28118. serializationObject.depth = this.depth;
  28119. return serializationObject;
  28120. };
  28121. return RefractionTexture;
  28122. }(BABYLON.RenderTargetTexture));
  28123. BABYLON.RefractionTexture = RefractionTexture;
  28124. })(BABYLON || (BABYLON = {}));
  28125. //# sourceMappingURL=babylon.refractionTexture.js.map
  28126. /// <reference path="babylon.texture.ts" />
  28127. var BABYLON;
  28128. (function (BABYLON) {
  28129. var DynamicTexture = (function (_super) {
  28130. __extends(DynamicTexture, _super);
  28131. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode, format) {
  28132. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  28133. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  28134. var _this = _super.call(this, null, scene, !generateMipMaps, undefined, samplingMode, undefined, undefined, undefined, undefined, format) || this;
  28135. _this.name = name;
  28136. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  28137. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  28138. _this._generateMipMaps = generateMipMaps;
  28139. if (options.getContext) {
  28140. _this._canvas = options;
  28141. _this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  28142. }
  28143. else {
  28144. _this._canvas = document.createElement("canvas");
  28145. if (options.width) {
  28146. _this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  28147. }
  28148. else {
  28149. _this._texture = scene.getEngine().createDynamicTexture(options, options, generateMipMaps, samplingMode);
  28150. }
  28151. }
  28152. var textureSize = _this.getSize();
  28153. _this._canvas.width = textureSize.width;
  28154. _this._canvas.height = textureSize.height;
  28155. _this._context = _this._canvas.getContext("2d");
  28156. return _this;
  28157. }
  28158. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  28159. get: function () {
  28160. return true;
  28161. },
  28162. enumerable: true,
  28163. configurable: true
  28164. });
  28165. DynamicTexture.prototype.scale = function (ratio) {
  28166. var textureSize = this.getSize();
  28167. textureSize.width *= ratio;
  28168. textureSize.height *= ratio;
  28169. this._canvas.width = textureSize.width;
  28170. this._canvas.height = textureSize.height;
  28171. this.releaseInternalTexture();
  28172. this._texture = this.getScene().getEngine().createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  28173. };
  28174. DynamicTexture.prototype.getContext = function () {
  28175. return this._context;
  28176. };
  28177. DynamicTexture.prototype.clear = function () {
  28178. var size = this.getSize();
  28179. this._context.fillRect(0, 0, size.width, size.height);
  28180. };
  28181. DynamicTexture.prototype.update = function (invertY) {
  28182. this.getScene().getEngine().updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY, undefined, this._format);
  28183. };
  28184. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  28185. if (update === void 0) { update = true; }
  28186. var size = this.getSize();
  28187. if (clearColor) {
  28188. this._context.fillStyle = clearColor;
  28189. this._context.fillRect(0, 0, size.width, size.height);
  28190. }
  28191. this._context.font = font;
  28192. if (x === null || x === undefined) {
  28193. var textSize = this._context.measureText(text);
  28194. x = (size.width - textSize.width) / 2;
  28195. }
  28196. if (y === null || y === undefined) {
  28197. var fontSize = parseInt((font.replace(/\D/g, '')));
  28198. ;
  28199. y = (size.height / 2) + (fontSize / 3.65);
  28200. }
  28201. this._context.fillStyle = color;
  28202. this._context.fillText(text, x, y);
  28203. if (update) {
  28204. this.update(invertY);
  28205. }
  28206. };
  28207. DynamicTexture.prototype.clone = function () {
  28208. var textureSize = this.getSize();
  28209. var newTexture = new DynamicTexture(this.name, textureSize, this.getScene(), this._generateMipMaps);
  28210. // Base texture
  28211. newTexture.hasAlpha = this.hasAlpha;
  28212. newTexture.level = this.level;
  28213. // Dynamic Texture
  28214. newTexture.wrapU = this.wrapU;
  28215. newTexture.wrapV = this.wrapV;
  28216. return newTexture;
  28217. };
  28218. return DynamicTexture;
  28219. }(BABYLON.Texture));
  28220. BABYLON.DynamicTexture = DynamicTexture;
  28221. })(BABYLON || (BABYLON = {}));
  28222. //# sourceMappingURL=babylon.dynamicTexture.js.map
  28223. var BABYLON;
  28224. (function (BABYLON) {
  28225. var VideoTexture = (function (_super) {
  28226. __extends(VideoTexture, _super);
  28227. /**
  28228. * Creates a video texture.
  28229. * Sample : https://doc.babylonjs.com/tutorials/01._Advanced_Texturing
  28230. * @param {Array} urlsOrVideo can be used to provide an array of urls or an already setup HTML video element.
  28231. * @param {BABYLON.Scene} scene is obviously the current scene.
  28232. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  28233. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  28234. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  28235. */
  28236. function VideoTexture(name, urlsOrVideo, scene, generateMipMaps, invertY, samplingMode) {
  28237. if (generateMipMaps === void 0) { generateMipMaps = false; }
  28238. if (invertY === void 0) { invertY = false; }
  28239. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  28240. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  28241. _this._autoLaunch = true;
  28242. var urls;
  28243. _this.name = name;
  28244. if (urlsOrVideo instanceof HTMLVideoElement) {
  28245. _this.video = urlsOrVideo;
  28246. }
  28247. else {
  28248. urls = urlsOrVideo;
  28249. _this.video = document.createElement("video");
  28250. _this.video.autoplay = false;
  28251. _this.video.loop = true;
  28252. }
  28253. _this._generateMipMaps = generateMipMaps;
  28254. _this._samplingMode = samplingMode;
  28255. if (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight)) {
  28256. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  28257. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  28258. }
  28259. else {
  28260. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  28261. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  28262. _this._generateMipMaps = false;
  28263. }
  28264. if (urls) {
  28265. _this.video.addEventListener("canplaythrough", function () {
  28266. _this._createTexture();
  28267. });
  28268. urls.forEach(function (url) {
  28269. var source = document.createElement("source");
  28270. source.src = url;
  28271. _this.video.appendChild(source);
  28272. });
  28273. }
  28274. else {
  28275. _this._createTexture();
  28276. }
  28277. _this._lastUpdate = BABYLON.Tools.Now;
  28278. return _this;
  28279. }
  28280. VideoTexture.prototype._createTexture = function () {
  28281. this._texture = this.getScene().getEngine().createDynamicTexture(this.video.videoWidth, this.video.videoHeight, this._generateMipMaps, this._samplingMode);
  28282. this._texture.isReady = true;
  28283. };
  28284. VideoTexture.prototype.update = function () {
  28285. if (this._autoLaunch) {
  28286. this._autoLaunch = false;
  28287. this.video.play();
  28288. }
  28289. var now = BABYLON.Tools.Now;
  28290. if (now - this._lastUpdate < 15 || this.video.readyState !== this.video.HAVE_ENOUGH_DATA) {
  28291. return false;
  28292. }
  28293. this._lastUpdate = now;
  28294. this.getScene().getEngine().updateVideoTexture(this._texture, this.video, this._invertY);
  28295. return true;
  28296. };
  28297. VideoTexture.CreateFromWebCam = function (scene, onReady, constraints) {
  28298. var video = document.createElement("video");
  28299. var constraintsDeviceId;
  28300. if (constraints && constraints.deviceId) {
  28301. constraintsDeviceId = {
  28302. exact: constraints.deviceId
  28303. };
  28304. }
  28305. navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia;
  28306. window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
  28307. if (navigator.getUserMedia) {
  28308. navigator.getUserMedia({
  28309. video: {
  28310. deviceId: constraintsDeviceId,
  28311. width: {
  28312. min: (constraints && constraints.minWidth) || 256,
  28313. max: (constraints && constraints.maxWidth) || 640
  28314. },
  28315. height: {
  28316. min: (constraints && constraints.minHeight) || 256,
  28317. max: (constraints && constraints.maxHeight) || 480
  28318. }
  28319. }
  28320. }, function (stream) {
  28321. if (video.mozSrcObject !== undefined) {
  28322. video.mozSrcObject = stream;
  28323. }
  28324. else {
  28325. video.src = (window.URL && window.URL.createObjectURL(stream)) || stream;
  28326. }
  28327. video.play();
  28328. if (onReady) {
  28329. onReady(new BABYLON.VideoTexture("video", video, scene, true, true));
  28330. }
  28331. }, function (e) {
  28332. BABYLON.Tools.Error(e.name);
  28333. });
  28334. }
  28335. };
  28336. return VideoTexture;
  28337. }(BABYLON.Texture));
  28338. BABYLON.VideoTexture = VideoTexture;
  28339. })(BABYLON || (BABYLON = {}));
  28340. //# sourceMappingURL=babylon.videoTexture.js.map
  28341. /// <reference path="babylon.proceduralTexture.ts" />
  28342. var BABYLON;
  28343. (function (BABYLON) {
  28344. var CustomProceduralTexture = (function (_super) {
  28345. __extends(CustomProceduralTexture, _super);
  28346. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  28347. var _this = _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps) || this;
  28348. _this._animate = true;
  28349. _this._time = 0;
  28350. _this._texturePath = texturePath;
  28351. //Try to load json
  28352. _this.loadJson(texturePath);
  28353. _this.refreshRate = 1;
  28354. return _this;
  28355. }
  28356. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  28357. var _this = this;
  28358. var that = this;
  28359. function noConfigFile() {
  28360. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  28361. try {
  28362. that.setFragment(that._texturePath);
  28363. }
  28364. catch (ex) {
  28365. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  28366. }
  28367. }
  28368. var configFileUrl = jsonUrl + "/config.json";
  28369. var xhr = new XMLHttpRequest();
  28370. xhr.open("GET", configFileUrl, true);
  28371. xhr.addEventListener("load", function () {
  28372. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  28373. try {
  28374. _this._config = JSON.parse(xhr.response);
  28375. _this.updateShaderUniforms();
  28376. _this.updateTextures();
  28377. _this.setFragment(_this._texturePath + "/custom");
  28378. _this._animate = _this._config.animate;
  28379. _this.refreshRate = _this._config.refreshrate;
  28380. }
  28381. catch (ex) {
  28382. noConfigFile();
  28383. }
  28384. }
  28385. else {
  28386. noConfigFile();
  28387. }
  28388. }, false);
  28389. xhr.addEventListener("error", function () {
  28390. noConfigFile();
  28391. }, false);
  28392. try {
  28393. xhr.send();
  28394. }
  28395. catch (ex) {
  28396. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  28397. }
  28398. };
  28399. CustomProceduralTexture.prototype.isReady = function () {
  28400. if (!_super.prototype.isReady.call(this)) {
  28401. return false;
  28402. }
  28403. for (var name in this._textures) {
  28404. var texture = this._textures[name];
  28405. if (!texture.isReady()) {
  28406. return false;
  28407. }
  28408. }
  28409. return true;
  28410. };
  28411. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  28412. if (this._animate) {
  28413. this._time += this.getScene().getAnimationRatio() * 0.03;
  28414. this.updateShaderUniforms();
  28415. }
  28416. _super.prototype.render.call(this, useCameraPostProcess);
  28417. };
  28418. CustomProceduralTexture.prototype.updateTextures = function () {
  28419. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  28420. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  28421. }
  28422. };
  28423. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  28424. if (this._config) {
  28425. for (var j = 0; j < this._config.uniforms.length; j++) {
  28426. var uniform = this._config.uniforms[j];
  28427. switch (uniform.type) {
  28428. case "float":
  28429. this.setFloat(uniform.name, uniform.value);
  28430. break;
  28431. case "color3":
  28432. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  28433. break;
  28434. case "color4":
  28435. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  28436. break;
  28437. case "vector2":
  28438. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  28439. break;
  28440. case "vector3":
  28441. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  28442. break;
  28443. }
  28444. }
  28445. }
  28446. this.setFloat("time", this._time);
  28447. };
  28448. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  28449. get: function () {
  28450. return this._animate;
  28451. },
  28452. set: function (value) {
  28453. this._animate = value;
  28454. },
  28455. enumerable: true,
  28456. configurable: true
  28457. });
  28458. return CustomProceduralTexture;
  28459. }(BABYLON.ProceduralTexture));
  28460. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  28461. })(BABYLON || (BABYLON = {}));
  28462. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  28463. var BABYLON;
  28464. (function (BABYLON) {
  28465. var EffectFallbacks = (function () {
  28466. function EffectFallbacks() {
  28467. this._defines = {};
  28468. this._currentRank = 32;
  28469. this._maxRank = -1;
  28470. }
  28471. EffectFallbacks.prototype.addFallback = function (rank, define) {
  28472. if (!this._defines[rank]) {
  28473. if (rank < this._currentRank) {
  28474. this._currentRank = rank;
  28475. }
  28476. if (rank > this._maxRank) {
  28477. this._maxRank = rank;
  28478. }
  28479. this._defines[rank] = new Array();
  28480. }
  28481. this._defines[rank].push(define);
  28482. };
  28483. EffectFallbacks.prototype.addCPUSkinningFallback = function (rank, mesh) {
  28484. this._meshRank = rank;
  28485. this._mesh = mesh;
  28486. if (rank < this._currentRank) {
  28487. this._currentRank = rank;
  28488. }
  28489. if (rank > this._maxRank) {
  28490. this._maxRank = rank;
  28491. }
  28492. };
  28493. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  28494. get: function () {
  28495. return this._currentRank <= this._maxRank;
  28496. },
  28497. enumerable: true,
  28498. configurable: true
  28499. });
  28500. EffectFallbacks.prototype.reduce = function (currentDefines) {
  28501. // First we try to switch to CPU skinning
  28502. if (this._mesh && this._mesh.computeBonesUsingShaders && this._mesh.numBoneInfluencers > 0) {
  28503. this._mesh.computeBonesUsingShaders = false;
  28504. currentDefines = currentDefines.replace("#define NUM_BONE_INFLUENCERS " + this._mesh.numBoneInfluencers, "#define NUM_BONE_INFLUENCERS 0");
  28505. BABYLON.Tools.Log("Falling back to CPU skinning for " + this._mesh.name);
  28506. var scene = this._mesh.getScene();
  28507. for (var index = 0; index < scene.meshes.length; index++) {
  28508. var otherMesh = scene.meshes[index];
  28509. if (otherMesh.material === this._mesh.material && otherMesh.computeBonesUsingShaders && otherMesh.numBoneInfluencers > 0) {
  28510. otherMesh.computeBonesUsingShaders = false;
  28511. }
  28512. }
  28513. }
  28514. else {
  28515. var currentFallbacks = this._defines[this._currentRank];
  28516. if (currentFallbacks) {
  28517. for (var index = 0; index < currentFallbacks.length; index++) {
  28518. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  28519. }
  28520. }
  28521. this._currentRank++;
  28522. }
  28523. return currentDefines;
  28524. };
  28525. return EffectFallbacks;
  28526. }());
  28527. BABYLON.EffectFallbacks = EffectFallbacks;
  28528. var Effect = (function () {
  28529. function Effect(baseName, attributesNames, uniformsNames, samplers, engine, defines, fallbacks, onCompiled, onError, indexParameters) {
  28530. var _this = this;
  28531. this.uniqueId = 0;
  28532. this._isReady = false;
  28533. this._compilationError = "";
  28534. this._valueCache = {};
  28535. this._engine = engine;
  28536. this.name = baseName;
  28537. this.defines = defines;
  28538. this._uniformsNames = uniformsNames.concat(samplers);
  28539. this._samplers = samplers;
  28540. this._attributesNames = attributesNames;
  28541. this.onError = onError;
  28542. this.onCompiled = onCompiled;
  28543. this._indexParameters = indexParameters;
  28544. this.uniqueId = Effect._uniqueIdSeed++;
  28545. var vertexSource;
  28546. var fragmentSource;
  28547. if (baseName.vertexElement) {
  28548. vertexSource = document.getElementById(baseName.vertexElement);
  28549. if (!vertexSource) {
  28550. vertexSource = baseName.vertexElement;
  28551. }
  28552. }
  28553. else {
  28554. vertexSource = baseName.vertex || baseName;
  28555. }
  28556. if (baseName.fragmentElement) {
  28557. fragmentSource = document.getElementById(baseName.fragmentElement);
  28558. if (!fragmentSource) {
  28559. fragmentSource = baseName.fragmentElement;
  28560. }
  28561. }
  28562. else {
  28563. fragmentSource = baseName.fragment || baseName;
  28564. }
  28565. this._loadVertexShader(vertexSource, function (vertexCode) {
  28566. _this._processIncludes(vertexCode, function (vertexCodeWithIncludes) {
  28567. _this._processShaderConversion(vertexCodeWithIncludes, false, function (migratedVertexCode) {
  28568. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  28569. _this._processIncludes(fragmentCode, function (fragmentCodeWithIncludes) {
  28570. _this._processShaderConversion(fragmentCodeWithIncludes, true, function (migratedFragmentCode) {
  28571. _this._prepareEffect(migratedVertexCode, migratedFragmentCode, attributesNames, defines, fallbacks);
  28572. });
  28573. });
  28574. });
  28575. });
  28576. });
  28577. });
  28578. }
  28579. Object.defineProperty(Effect.prototype, "key", {
  28580. get: function () {
  28581. return this._key;
  28582. },
  28583. enumerable: true,
  28584. configurable: true
  28585. });
  28586. // Properties
  28587. Effect.prototype.isReady = function () {
  28588. return this._isReady;
  28589. };
  28590. Effect.prototype.getProgram = function () {
  28591. return this._program;
  28592. };
  28593. Effect.prototype.getAttributesNames = function () {
  28594. return this._attributesNames;
  28595. };
  28596. Effect.prototype.getAttributeLocation = function (index) {
  28597. return this._attributes[index];
  28598. };
  28599. Effect.prototype.getAttributeLocationByName = function (name) {
  28600. var index = this._attributesNames.indexOf(name);
  28601. return this._attributes[index];
  28602. };
  28603. Effect.prototype.getAttributesCount = function () {
  28604. return this._attributes.length;
  28605. };
  28606. Effect.prototype.getUniformIndex = function (uniformName) {
  28607. return this._uniformsNames.indexOf(uniformName);
  28608. };
  28609. Effect.prototype.getUniform = function (uniformName) {
  28610. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  28611. };
  28612. Effect.prototype.getSamplers = function () {
  28613. return this._samplers;
  28614. };
  28615. Effect.prototype.getCompilationError = function () {
  28616. return this._compilationError;
  28617. };
  28618. Effect.prototype.getVertexShaderSource = function () {
  28619. return this._evaluateDefinesOnString(this._engine.getVertexShaderSource(this._program));
  28620. };
  28621. Effect.prototype.getFragmentShaderSource = function () {
  28622. return this._evaluateDefinesOnString(this._engine.getFragmentShaderSource(this._program));
  28623. };
  28624. // Methods
  28625. Effect.prototype._loadVertexShader = function (vertex, callback) {
  28626. // DOM element ?
  28627. if (vertex instanceof HTMLElement) {
  28628. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  28629. callback(vertexCode);
  28630. return;
  28631. }
  28632. // Base64 encoded ?
  28633. if (vertex.substr(0, 7) === "base64:") {
  28634. var vertexBinary = window.atob(vertex.substr(7));
  28635. callback(vertexBinary);
  28636. return;
  28637. }
  28638. // Is in local store ?
  28639. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  28640. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  28641. return;
  28642. }
  28643. var vertexShaderUrl;
  28644. if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
  28645. vertexShaderUrl = vertex;
  28646. }
  28647. else {
  28648. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  28649. }
  28650. // Vertex shader
  28651. BABYLON.Tools.LoadFile(vertexShaderUrl + ".vertex.fx", callback);
  28652. };
  28653. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  28654. // DOM element ?
  28655. if (fragment instanceof HTMLElement) {
  28656. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  28657. callback(fragmentCode);
  28658. return;
  28659. }
  28660. // Base64 encoded ?
  28661. if (fragment.substr(0, 7) === "base64:") {
  28662. var fragmentBinary = window.atob(fragment.substr(7));
  28663. callback(fragmentBinary);
  28664. return;
  28665. }
  28666. // Is in local store ?
  28667. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  28668. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  28669. return;
  28670. }
  28671. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  28672. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  28673. return;
  28674. }
  28675. var fragmentShaderUrl;
  28676. if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
  28677. fragmentShaderUrl = fragment;
  28678. }
  28679. else {
  28680. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  28681. }
  28682. // Fragment shader
  28683. BABYLON.Tools.LoadFile(fragmentShaderUrl + ".fragment.fx", callback);
  28684. };
  28685. Effect.prototype._dumpShadersName = function () {
  28686. if (this.name.vertexElement) {
  28687. BABYLON.Tools.Error("Vertex shader:" + this.name.vertexElement);
  28688. BABYLON.Tools.Error("Fragment shader:" + this.name.fragmentElement);
  28689. }
  28690. else if (this.name.vertex) {
  28691. BABYLON.Tools.Error("Vertex shader:" + this.name.vertex);
  28692. BABYLON.Tools.Error("Fragment shader:" + this.name.fragment);
  28693. }
  28694. else {
  28695. BABYLON.Tools.Error("Vertex shader:" + this.name);
  28696. BABYLON.Tools.Error("Fragment shader:" + this.name);
  28697. }
  28698. };
  28699. Effect.prototype._processShaderConversion = function (sourceCode, isFragment, callback) {
  28700. var preparedSourceCode = this._processPrecision(sourceCode);
  28701. if (this._engine.webGLVersion == 1) {
  28702. callback(preparedSourceCode);
  28703. return;
  28704. }
  28705. // Already converted
  28706. if (preparedSourceCode.indexOf("#version 3") !== -1) {
  28707. callback(preparedSourceCode);
  28708. return;
  28709. }
  28710. // Remove extensions
  28711. // #extension GL_OES_standard_derivatives : enable
  28712. // #extension GL_EXT_shader_texture_lod : enable
  28713. // #extension GL_EXT_frag_depth : enable
  28714. var regex = /#extension.+(GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_frag_depth).+enable/g;
  28715. var result = preparedSourceCode.replace(regex, "");
  28716. // Migrate to GLSL v300
  28717. result = result.replace(/varying\s/g, isFragment ? "in " : "out ");
  28718. result = result.replace(/attribute[ \t]/g, "in ");
  28719. result = result.replace(/[ \t]attribute/g, " in");
  28720. if (isFragment) {
  28721. result = result.replace(/texture2DLodEXT\(/g, "textureLod(");
  28722. result = result.replace(/textureCubeLodEXT\(/g, "textureLod(");
  28723. result = result.replace(/texture2D\(/g, "texture(");
  28724. result = result.replace(/textureCube\(/g, "texture(");
  28725. result = result.replace(/gl_FragDepthEXT/g, "gl_FragDepth");
  28726. result = result.replace(/gl_FragColor/g, "glFragColor");
  28727. result = result.replace(/void\s+?main\(/g, "out vec4 glFragColor;\nvoid main(");
  28728. }
  28729. callback(result);
  28730. };
  28731. Effect.prototype._processIncludes = function (sourceCode, callback) {
  28732. var _this = this;
  28733. var regex = /#include<(.+)>(\((.*)\))*(\[(.*)\])*/g;
  28734. var match = regex.exec(sourceCode);
  28735. var returnValue = new String(sourceCode);
  28736. while (match != null) {
  28737. var includeFile = match[1];
  28738. if (Effect.IncludesShadersStore[includeFile]) {
  28739. // Substitution
  28740. var includeContent = Effect.IncludesShadersStore[includeFile];
  28741. if (match[2]) {
  28742. var splits = match[3].split(",");
  28743. for (var index = 0; index < splits.length; index += 2) {
  28744. var source = new RegExp(splits[index], "g");
  28745. var dest = splits[index + 1];
  28746. includeContent = includeContent.replace(source, dest);
  28747. }
  28748. }
  28749. if (match[4]) {
  28750. var indexString = match[5];
  28751. if (indexString.indexOf("..") !== -1) {
  28752. var indexSplits = indexString.split("..");
  28753. var minIndex = parseInt(indexSplits[0]);
  28754. var maxIndex = parseInt(indexSplits[1]);
  28755. var sourceIncludeContent = includeContent.slice(0);
  28756. includeContent = "";
  28757. if (isNaN(maxIndex)) {
  28758. maxIndex = this._indexParameters[indexSplits[1]];
  28759. }
  28760. for (var i = minIndex; i <= maxIndex; i++) {
  28761. includeContent += sourceIncludeContent.replace(/\{X\}/g, i) + "\n";
  28762. }
  28763. }
  28764. else {
  28765. includeContent = includeContent.replace(/\{X\}/g, indexString);
  28766. }
  28767. }
  28768. // Replace
  28769. returnValue = returnValue.replace(match[0], includeContent);
  28770. }
  28771. else {
  28772. var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
  28773. BABYLON.Tools.LoadFile(includeShaderUrl, function (fileContent) {
  28774. Effect.IncludesShadersStore[includeFile] = fileContent;
  28775. _this._processIncludes(returnValue, callback);
  28776. });
  28777. return;
  28778. }
  28779. match = regex.exec(sourceCode);
  28780. }
  28781. callback(returnValue);
  28782. };
  28783. Effect.prototype._processPrecision = function (source) {
  28784. if (source.indexOf("precision highp float") === -1) {
  28785. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  28786. source = "precision mediump float;\n" + source;
  28787. }
  28788. else {
  28789. source = "precision highp float;\n" + source;
  28790. }
  28791. }
  28792. else {
  28793. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  28794. source = source.replace("precision highp float", "precision mediump float");
  28795. }
  28796. }
  28797. return source;
  28798. };
  28799. Effect.prototype._prepareEffect = function (vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks) {
  28800. try {
  28801. var engine = this._engine;
  28802. this._program = engine.createShaderProgram(vertexSourceCode, fragmentSourceCode, defines);
  28803. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  28804. this._attributes = engine.getAttributes(this._program, attributesNames);
  28805. var index;
  28806. for (index = 0; index < this._samplers.length; index++) {
  28807. var sampler = this.getUniform(this._samplers[index]);
  28808. if (sampler == null) {
  28809. this._samplers.splice(index, 1);
  28810. index--;
  28811. }
  28812. }
  28813. engine.bindSamplers(this);
  28814. this._compilationError = "";
  28815. this._isReady = true;
  28816. if (this.onCompiled) {
  28817. this.onCompiled(this);
  28818. }
  28819. }
  28820. catch (e) {
  28821. this._compilationError = e.message;
  28822. // Let's go through fallbacks then
  28823. BABYLON.Tools.Error("Unable to compile effect: ");
  28824. BABYLON.Tools.Error("Defines: " + defines);
  28825. BABYLON.Tools.Error("Error: " + this._compilationError);
  28826. this._dumpShadersName();
  28827. if (fallbacks && fallbacks.isMoreFallbacks) {
  28828. BABYLON.Tools.Error("Trying next fallback.");
  28829. defines = fallbacks.reduce(defines);
  28830. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  28831. }
  28832. else {
  28833. if (this.onError) {
  28834. this.onError(this, this._compilationError);
  28835. }
  28836. }
  28837. }
  28838. };
  28839. Object.defineProperty(Effect.prototype, "isSupported", {
  28840. get: function () {
  28841. return this._compilationError === "";
  28842. },
  28843. enumerable: true,
  28844. configurable: true
  28845. });
  28846. Effect.prototype._bindTexture = function (channel, texture) {
  28847. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  28848. };
  28849. Effect.prototype.setTexture = function (channel, texture) {
  28850. this._engine.setTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  28851. };
  28852. Effect.prototype.setTextureArray = function (channel, textures) {
  28853. if (this._samplers.indexOf(channel + "Ex") === -1) {
  28854. var initialPos = this._samplers.indexOf(channel);
  28855. for (var index = 1; index < textures.length; index++) {
  28856. this._samplers.splice(initialPos + index, 0, channel + "Ex");
  28857. }
  28858. }
  28859. this._engine.setTextureArray(this._samplers.indexOf(channel), this.getUniform(channel), textures);
  28860. };
  28861. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  28862. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  28863. };
  28864. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  28865. var changed = false;
  28866. var cache = this._valueCache[uniformName];
  28867. if (!cache || !(cache instanceof BABYLON.Matrix)) {
  28868. changed = true;
  28869. cache = new BABYLON.Matrix();
  28870. }
  28871. var tm = cache.m;
  28872. var om = matrix.m;
  28873. for (var index = 0; index < 16; index++) {
  28874. if (tm[index] !== om[index]) {
  28875. tm[index] = om[index];
  28876. changed = true;
  28877. }
  28878. }
  28879. this._valueCache[uniformName] = cache;
  28880. return changed;
  28881. };
  28882. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  28883. var cache = this._valueCache[uniformName];
  28884. if (!cache) {
  28885. cache = [x, y];
  28886. this._valueCache[uniformName] = cache;
  28887. return true;
  28888. }
  28889. var changed = false;
  28890. if (cache[0] !== x) {
  28891. cache[0] = x;
  28892. changed = true;
  28893. }
  28894. if (cache[1] !== y) {
  28895. cache[1] = y;
  28896. changed = true;
  28897. }
  28898. return changed;
  28899. };
  28900. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  28901. var cache = this._valueCache[uniformName];
  28902. if (!cache) {
  28903. cache = [x, y, z];
  28904. this._valueCache[uniformName] = cache;
  28905. return true;
  28906. }
  28907. var changed = false;
  28908. if (cache[0] !== x) {
  28909. cache[0] = x;
  28910. changed = true;
  28911. }
  28912. if (cache[1] !== y) {
  28913. cache[1] = y;
  28914. changed = true;
  28915. }
  28916. if (cache[2] !== z) {
  28917. cache[2] = z;
  28918. changed = true;
  28919. }
  28920. return changed;
  28921. };
  28922. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  28923. var cache = this._valueCache[uniformName];
  28924. if (!cache) {
  28925. cache = [x, y, z, w];
  28926. this._valueCache[uniformName] = cache;
  28927. return true;
  28928. }
  28929. var changed = false;
  28930. if (cache[0] !== x) {
  28931. cache[0] = x;
  28932. changed = true;
  28933. }
  28934. if (cache[1] !== y) {
  28935. cache[1] = y;
  28936. changed = true;
  28937. }
  28938. if (cache[2] !== z) {
  28939. cache[2] = z;
  28940. changed = true;
  28941. }
  28942. if (cache[3] !== w) {
  28943. cache[3] = w;
  28944. changed = true;
  28945. }
  28946. return changed;
  28947. };
  28948. Effect.prototype.setIntArray = function (uniformName, array) {
  28949. this._valueCache[uniformName] = null;
  28950. this._engine.setIntArray(this.getUniform(uniformName), array);
  28951. return this;
  28952. };
  28953. Effect.prototype.setIntArray2 = function (uniformName, array) {
  28954. this._valueCache[uniformName] = null;
  28955. this._engine.setIntArray2(this.getUniform(uniformName), array);
  28956. return this;
  28957. };
  28958. Effect.prototype.setIntArray3 = function (uniformName, array) {
  28959. this._valueCache[uniformName] = null;
  28960. this._engine.setIntArray3(this.getUniform(uniformName), array);
  28961. return this;
  28962. };
  28963. Effect.prototype.setIntArray4 = function (uniformName, array) {
  28964. this._valueCache[uniformName] = null;
  28965. this._engine.setIntArray4(this.getUniform(uniformName), array);
  28966. return this;
  28967. };
  28968. Effect.prototype.setFloatArray = function (uniformName, array) {
  28969. this._valueCache[uniformName] = null;
  28970. this._engine.setFloatArray(this.getUniform(uniformName), array);
  28971. return this;
  28972. };
  28973. Effect.prototype.setFloatArray2 = function (uniformName, array) {
  28974. this._valueCache[uniformName] = null;
  28975. this._engine.setFloatArray2(this.getUniform(uniformName), array);
  28976. return this;
  28977. };
  28978. Effect.prototype.setFloatArray3 = function (uniformName, array) {
  28979. this._valueCache[uniformName] = null;
  28980. this._engine.setFloatArray3(this.getUniform(uniformName), array);
  28981. return this;
  28982. };
  28983. Effect.prototype.setFloatArray4 = function (uniformName, array) {
  28984. this._valueCache[uniformName] = null;
  28985. this._engine.setFloatArray4(this.getUniform(uniformName), array);
  28986. return this;
  28987. };
  28988. Effect.prototype.setArray = function (uniformName, array) {
  28989. this._valueCache[uniformName] = null;
  28990. this._engine.setArray(this.getUniform(uniformName), array);
  28991. return this;
  28992. };
  28993. Effect.prototype.setArray2 = function (uniformName, array) {
  28994. this._valueCache[uniformName] = null;
  28995. this._engine.setArray2(this.getUniform(uniformName), array);
  28996. return this;
  28997. };
  28998. Effect.prototype.setArray3 = function (uniformName, array) {
  28999. this._valueCache[uniformName] = null;
  29000. this._engine.setArray3(this.getUniform(uniformName), array);
  29001. return this;
  29002. };
  29003. Effect.prototype.setArray4 = function (uniformName, array) {
  29004. this._valueCache[uniformName] = null;
  29005. this._engine.setArray4(this.getUniform(uniformName), array);
  29006. return this;
  29007. };
  29008. Effect.prototype.setMatrices = function (uniformName, matrices) {
  29009. this._valueCache[uniformName] = null;
  29010. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  29011. return this;
  29012. };
  29013. Effect.prototype.setMatrix = function (uniformName, matrix) {
  29014. if (this._cacheMatrix(uniformName, matrix)) {
  29015. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  29016. }
  29017. return this;
  29018. };
  29019. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  29020. this._valueCache[uniformName] = null;
  29021. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  29022. return this;
  29023. };
  29024. Effect.prototype.setMatrix2x2 = function (uniformName, matrix) {
  29025. this._valueCache[uniformName] = null;
  29026. this._engine.setMatrix2x2(this.getUniform(uniformName), matrix);
  29027. return this;
  29028. };
  29029. Effect.prototype.setFloat = function (uniformName, value) {
  29030. var cache = this._valueCache[uniformName];
  29031. if (cache !== undefined && cache === value)
  29032. return this;
  29033. this._valueCache[uniformName] = value;
  29034. this._engine.setFloat(this.getUniform(uniformName), value);
  29035. return this;
  29036. };
  29037. Effect.prototype.setBool = function (uniformName, bool) {
  29038. var cache = this._valueCache[uniformName];
  29039. if (cache !== undefined && cache === bool)
  29040. return this;
  29041. this._valueCache[uniformName] = bool;
  29042. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  29043. return this;
  29044. };
  29045. Effect.prototype.setVector2 = function (uniformName, vector2) {
  29046. if (this._cacheFloat2(uniformName, vector2.x, vector2.y)) {
  29047. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  29048. }
  29049. return this;
  29050. };
  29051. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  29052. if (this._cacheFloat2(uniformName, x, y)) {
  29053. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  29054. }
  29055. return this;
  29056. };
  29057. Effect.prototype.setVector3 = function (uniformName, vector3) {
  29058. if (this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z)) {
  29059. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  29060. }
  29061. return this;
  29062. };
  29063. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  29064. if (this._cacheFloat3(uniformName, x, y, z)) {
  29065. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  29066. }
  29067. return this;
  29068. };
  29069. Effect.prototype.setVector4 = function (uniformName, vector4) {
  29070. if (this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w)) {
  29071. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  29072. }
  29073. return this;
  29074. };
  29075. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  29076. if (this._cacheFloat4(uniformName, x, y, z, w)) {
  29077. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  29078. }
  29079. return this;
  29080. };
  29081. Effect.prototype.setColor3 = function (uniformName, color3) {
  29082. if (this._cacheFloat3(uniformName, color3.r, color3.g, color3.b)) {
  29083. this._engine.setColor3(this.getUniform(uniformName), color3);
  29084. }
  29085. return this;
  29086. };
  29087. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  29088. if (this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha)) {
  29089. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  29090. }
  29091. return this;
  29092. };
  29093. Effect.prototype._recombineShader = function (node) {
  29094. if (node.define) {
  29095. if (node.condition) {
  29096. var defineIndex = this.defines.indexOf("#define " + node.define);
  29097. if (defineIndex === -1) {
  29098. return null;
  29099. }
  29100. var nextComma = this.defines.indexOf("\n", defineIndex);
  29101. var defineValue = this.defines.substr(defineIndex + 7, nextComma - defineIndex - 7).replace(node.define, "").trim();
  29102. var condition = defineValue + node.condition;
  29103. if (!eval(condition)) {
  29104. return null;
  29105. }
  29106. }
  29107. else if (node.ndef) {
  29108. if (this.defines.indexOf("#define " + node.define) !== -1) {
  29109. return null;
  29110. }
  29111. }
  29112. else if (this.defines.indexOf("#define " + node.define) === -1) {
  29113. return null;
  29114. }
  29115. }
  29116. var result = "";
  29117. for (var index = 0; index < node.children.length; index++) {
  29118. var line = node.children[index];
  29119. if (line.children) {
  29120. var combined = this._recombineShader(line);
  29121. if (combined !== null) {
  29122. result += combined + "\r\n";
  29123. }
  29124. continue;
  29125. }
  29126. if (line.length > 0) {
  29127. result += line + "\r\n";
  29128. }
  29129. }
  29130. return result;
  29131. };
  29132. Effect.prototype._evaluateDefinesOnString = function (shaderString) {
  29133. var root = {
  29134. children: []
  29135. };
  29136. var currentNode = root;
  29137. var lines = shaderString.split("\n");
  29138. for (var index = 0; index < lines.length; index++) {
  29139. var line = lines[index].trim();
  29140. // #ifdef
  29141. var pos = line.indexOf("#ifdef ");
  29142. if (pos !== -1) {
  29143. var define = line.substr(pos + 7);
  29144. var newNode = {
  29145. condition: null,
  29146. ndef: false,
  29147. define: define,
  29148. children: [],
  29149. parent: currentNode
  29150. };
  29151. currentNode.children.push(newNode);
  29152. currentNode = newNode;
  29153. continue;
  29154. }
  29155. // #ifndef
  29156. var pos = line.indexOf("#ifndef ");
  29157. if (pos !== -1) {
  29158. var define = line.substr(pos + 8);
  29159. newNode = {
  29160. condition: null,
  29161. define: define,
  29162. ndef: true,
  29163. children: [],
  29164. parent: currentNode
  29165. };
  29166. currentNode.children.push(newNode);
  29167. currentNode = newNode;
  29168. continue;
  29169. }
  29170. // #if
  29171. var pos = line.indexOf("#if ");
  29172. if (pos !== -1) {
  29173. var define = line.substr(pos + 4).trim();
  29174. var conditionPos = define.indexOf(" ");
  29175. newNode = {
  29176. condition: define.substr(conditionPos + 1),
  29177. define: define.substr(0, conditionPos),
  29178. ndef: false,
  29179. children: [],
  29180. parent: currentNode
  29181. };
  29182. currentNode.children.push(newNode);
  29183. currentNode = newNode;
  29184. continue;
  29185. }
  29186. // #endif
  29187. pos = line.indexOf("#endif");
  29188. if (pos !== -1) {
  29189. currentNode = currentNode.parent;
  29190. continue;
  29191. }
  29192. currentNode.children.push(line);
  29193. }
  29194. // Recombine
  29195. return this._recombineShader(root);
  29196. };
  29197. return Effect;
  29198. }());
  29199. Effect._uniqueIdSeed = 0;
  29200. // Statics
  29201. Effect.ShadersStore = {};
  29202. Effect.IncludesShadersStore = {};
  29203. BABYLON.Effect = Effect;
  29204. })(BABYLON || (BABYLON = {}));
  29205. //# sourceMappingURL=babylon.effect.js.map
  29206. var BABYLON;
  29207. (function (BABYLON) {
  29208. var MaterialHelper = (function () {
  29209. function MaterialHelper() {
  29210. }
  29211. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, maxSimultaneousLights) {
  29212. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  29213. var lightIndex = 0;
  29214. var needNormals = false;
  29215. var needRebuild = false;
  29216. var needShadows = false;
  29217. var lightmapMode = false;
  29218. for (var index = 0; index < scene.lights.length; index++) {
  29219. var light = scene.lights[index];
  29220. if (!light.isEnabled()) {
  29221. continue;
  29222. }
  29223. // Excluded check
  29224. if (light._excludedMeshesIds.length > 0) {
  29225. for (var excludedIndex = 0; excludedIndex < light._excludedMeshesIds.length; excludedIndex++) {
  29226. var excludedMesh = scene.getMeshByID(light._excludedMeshesIds[excludedIndex]);
  29227. if (excludedMesh) {
  29228. light.excludedMeshes.push(excludedMesh);
  29229. }
  29230. }
  29231. light._excludedMeshesIds = [];
  29232. }
  29233. // Included check
  29234. if (light._includedOnlyMeshesIds.length > 0) {
  29235. for (var includedOnlyIndex = 0; includedOnlyIndex < light._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  29236. var includedOnlyMesh = scene.getMeshByID(light._includedOnlyMeshesIds[includedOnlyIndex]);
  29237. if (includedOnlyMesh) {
  29238. light.includedOnlyMeshes.push(includedOnlyMesh);
  29239. }
  29240. }
  29241. light._includedOnlyMeshesIds = [];
  29242. }
  29243. if (!light.canAffectMesh(mesh)) {
  29244. continue;
  29245. }
  29246. needNormals = true;
  29247. if (defines["LIGHT" + lightIndex] === undefined) {
  29248. needRebuild = true;
  29249. }
  29250. defines["LIGHT" + lightIndex] = true;
  29251. var type;
  29252. if (light instanceof BABYLON.SpotLight) {
  29253. type = "SPOTLIGHT" + lightIndex;
  29254. }
  29255. else if (light instanceof BABYLON.HemisphericLight) {
  29256. type = "HEMILIGHT" + lightIndex;
  29257. }
  29258. else if (light instanceof BABYLON.PointLight) {
  29259. type = "POINTLIGHT" + lightIndex;
  29260. }
  29261. else {
  29262. type = "DIRLIGHT" + lightIndex;
  29263. }
  29264. if (defines[type] === undefined) {
  29265. needRebuild = true;
  29266. }
  29267. defines[type] = true;
  29268. // Specular
  29269. if (!light.specular.equalsFloats(0, 0, 0) && defines["SPECULARTERM"] !== undefined) {
  29270. defines["SPECULARTERM"] = true;
  29271. }
  29272. // Shadows
  29273. if (scene.shadowsEnabled) {
  29274. var shadowGenerator = light.getShadowGenerator();
  29275. if (mesh && mesh.receiveShadows && shadowGenerator) {
  29276. if (defines["SHADOW" + lightIndex] === undefined) {
  29277. needRebuild = true;
  29278. }
  29279. defines["SHADOW" + lightIndex] = true;
  29280. defines["SHADOWS"] = true;
  29281. if (shadowGenerator.useVarianceShadowMap || shadowGenerator.useBlurVarianceShadowMap) {
  29282. if (defines["SHADOWVSM" + lightIndex] === undefined) {
  29283. needRebuild = true;
  29284. }
  29285. defines["SHADOWVSM" + lightIndex] = true;
  29286. }
  29287. else if (shadowGenerator.usePoissonSampling) {
  29288. if (defines["SHADOWPCF" + lightIndex] === undefined) {
  29289. needRebuild = true;
  29290. }
  29291. defines["SHADOWPCF" + lightIndex] = true;
  29292. }
  29293. else if (shadowGenerator.useExponentialShadowMap) {
  29294. if (defines["SHADOWESM" + lightIndex] === undefined) {
  29295. needRebuild = true;
  29296. }
  29297. defines["SHADOWESM" + lightIndex] = true;
  29298. }
  29299. needShadows = true;
  29300. }
  29301. }
  29302. if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
  29303. lightmapMode = true;
  29304. if (defines["LIGHTMAPEXCLUDED" + lightIndex] === undefined) {
  29305. needRebuild = true;
  29306. }
  29307. if (defines["LIGHTMAPNOSPECULAR" + lightIndex] === undefined) {
  29308. needRebuild = true;
  29309. }
  29310. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  29311. if (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY) {
  29312. defines["LIGHTMAPNOSPECULAR" + lightIndex] = true;
  29313. }
  29314. }
  29315. lightIndex++;
  29316. if (lightIndex === maxSimultaneousLights)
  29317. break;
  29318. }
  29319. var caps = scene.getEngine().getCaps();
  29320. if (needShadows && caps.textureFloat && caps.textureFloatLinearFiltering && caps.textureFloatRender) {
  29321. if (defines["SHADOWFULLFLOAT"] === undefined) {
  29322. needRebuild = true;
  29323. }
  29324. defines["SHADOWFULLFLOAT"] = true;
  29325. }
  29326. if (defines["LIGHTMAPEXCLUDED"] === undefined) {
  29327. needRebuild = true;
  29328. }
  29329. if (lightmapMode) {
  29330. defines["LIGHTMAPEXCLUDED"] = true;
  29331. }
  29332. if (needRebuild) {
  29333. defines.rebuild();
  29334. }
  29335. return needNormals;
  29336. };
  29337. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsList, samplersList, defines, maxSimultaneousLights) {
  29338. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  29339. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  29340. if (!defines["LIGHT" + lightIndex]) {
  29341. break;
  29342. }
  29343. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex);
  29344. samplersList.push("shadowSampler" + lightIndex);
  29345. }
  29346. };
  29347. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights) {
  29348. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  29349. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  29350. if (!defines["LIGHT" + lightIndex]) {
  29351. break;
  29352. }
  29353. if (lightIndex > 0) {
  29354. fallbacks.addFallback(lightIndex, "LIGHT" + lightIndex);
  29355. }
  29356. if (defines["SHADOW" + lightIndex]) {
  29357. fallbacks.addFallback(0, "SHADOW" + lightIndex);
  29358. }
  29359. if (defines["SHADOWPCF" + lightIndex]) {
  29360. fallbacks.addFallback(0, "SHADOWPCF" + lightIndex);
  29361. }
  29362. if (defines["SHADOWVSM" + lightIndex]) {
  29363. fallbacks.addFallback(0, "SHADOWVSM" + lightIndex);
  29364. }
  29365. if (defines["SHADOWESM" + lightIndex]) {
  29366. fallbacks.addFallback(0, "SHADOWESM" + lightIndex);
  29367. }
  29368. }
  29369. };
  29370. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  29371. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  29372. fallbacks.addCPUSkinningFallback(0, mesh);
  29373. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  29374. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  29375. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  29376. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  29377. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  29378. }
  29379. }
  29380. };
  29381. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  29382. if (defines["INSTANCES"]) {
  29383. attribs.push("world0");
  29384. attribs.push("world1");
  29385. attribs.push("world2");
  29386. attribs.push("world3");
  29387. }
  29388. };
  29389. // Bindings
  29390. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect, depthValuesAlreadySet) {
  29391. var shadowGenerator = light.getShadowGenerator();
  29392. if (mesh.receiveShadows && shadowGenerator) {
  29393. if (!light.needCube()) {
  29394. effect.setMatrix("lightMatrix" + lightIndex, shadowGenerator.getTransformMatrix());
  29395. }
  29396. else {
  29397. if (!depthValuesAlreadySet) {
  29398. depthValuesAlreadySet = true;
  29399. effect.setFloat2("depthValues", scene.activeCamera.minZ, scene.activeCamera.maxZ);
  29400. }
  29401. }
  29402. effect.setTexture("shadowSampler" + lightIndex, shadowGenerator.getShadowMapForRendering());
  29403. effect.setFloat3("shadowsInfo" + lightIndex, shadowGenerator.getDarkness(), shadowGenerator.blurScale / shadowGenerator.getShadowMap().getSize().width, shadowGenerator.bias);
  29404. }
  29405. return depthValuesAlreadySet;
  29406. };
  29407. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  29408. if (light instanceof BABYLON.PointLight) {
  29409. // Point Light
  29410. light.transferToEffect(effect, "vLightData" + lightIndex);
  29411. }
  29412. else if (light instanceof BABYLON.DirectionalLight) {
  29413. // Directional Light
  29414. light.transferToEffect(effect, "vLightData" + lightIndex);
  29415. }
  29416. else if (light instanceof BABYLON.SpotLight) {
  29417. // Spot Light
  29418. light.transferToEffect(effect, "vLightData" + lightIndex, "vLightDirection" + lightIndex);
  29419. }
  29420. else if (light instanceof BABYLON.HemisphericLight) {
  29421. // Hemispheric Light
  29422. light.transferToEffect(effect, "vLightData" + lightIndex, "vLightGround" + lightIndex);
  29423. }
  29424. };
  29425. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights) {
  29426. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  29427. var lightIndex = 0;
  29428. var depthValuesAlreadySet = false;
  29429. for (var index = 0; index < scene.lights.length; index++) {
  29430. var light = scene.lights[index];
  29431. if (!light.isEnabled()) {
  29432. continue;
  29433. }
  29434. if (!light.canAffectMesh(mesh)) {
  29435. continue;
  29436. }
  29437. MaterialHelper.BindLightProperties(light, effect, lightIndex);
  29438. light.diffuse.scaleToRef(light.intensity, BABYLON.Tmp.Color3[0]);
  29439. effect.setColor4("vLightDiffuse" + lightIndex, BABYLON.Tmp.Color3[0], light.range);
  29440. if (defines["SPECULARTERM"]) {
  29441. light.specular.scaleToRef(light.intensity, BABYLON.Tmp.Color3[1]);
  29442. effect.setColor3("vLightSpecular" + lightIndex, BABYLON.Tmp.Color3[1]);
  29443. }
  29444. // Shadows
  29445. if (scene.shadowsEnabled) {
  29446. depthValuesAlreadySet = this.BindLightShadow(light, scene, mesh, lightIndex, effect, depthValuesAlreadySet);
  29447. }
  29448. lightIndex++;
  29449. if (lightIndex === maxSimultaneousLights)
  29450. break;
  29451. }
  29452. };
  29453. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  29454. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  29455. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  29456. effect.setColor3("vFogColor", scene.fogColor);
  29457. }
  29458. };
  29459. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  29460. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  29461. var matrices = mesh.skeleton.getTransformMatrices(mesh);
  29462. if (matrices) {
  29463. effect.setMatrices("mBones", matrices);
  29464. }
  29465. }
  29466. };
  29467. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  29468. if (defines["LOGARITHMICDEPTH"]) {
  29469. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  29470. }
  29471. };
  29472. MaterialHelper.BindClipPlane = function (effect, scene) {
  29473. if (scene.clipPlane) {
  29474. var clipPlane = scene.clipPlane;
  29475. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  29476. }
  29477. };
  29478. return MaterialHelper;
  29479. }());
  29480. BABYLON.MaterialHelper = MaterialHelper;
  29481. })(BABYLON || (BABYLON = {}));
  29482. //# sourceMappingURL=babylon.materialHelper.js.map
  29483. var BABYLON;
  29484. (function (BABYLON) {
  29485. var FresnelParameters = (function () {
  29486. function FresnelParameters() {
  29487. this.isEnabled = true;
  29488. this.leftColor = BABYLON.Color3.White();
  29489. this.rightColor = BABYLON.Color3.Black();
  29490. this.bias = 0;
  29491. this.power = 1;
  29492. }
  29493. FresnelParameters.prototype.clone = function () {
  29494. var newFresnelParameters = new FresnelParameters();
  29495. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  29496. return newFresnelParameters;
  29497. };
  29498. FresnelParameters.prototype.serialize = function () {
  29499. var serializationObject = {};
  29500. serializationObject.isEnabled = this.isEnabled;
  29501. serializationObject.leftColor = this.leftColor;
  29502. serializationObject.rightColor = this.rightColor;
  29503. serializationObject.bias = this.bias;
  29504. serializationObject.power = this.power;
  29505. return serializationObject;
  29506. };
  29507. FresnelParameters.Parse = function (parsedFresnelParameters) {
  29508. var fresnelParameters = new FresnelParameters();
  29509. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  29510. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  29511. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  29512. fresnelParameters.bias = parsedFresnelParameters.bias;
  29513. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  29514. return fresnelParameters;
  29515. };
  29516. return FresnelParameters;
  29517. }());
  29518. BABYLON.FresnelParameters = FresnelParameters;
  29519. })(BABYLON || (BABYLON = {}));
  29520. //# sourceMappingURL=babylon.fresnelParameters.js.map
  29521. var BABYLON;
  29522. (function (BABYLON) {
  29523. var MaterialDefines = (function () {
  29524. function MaterialDefines() {
  29525. }
  29526. MaterialDefines.prototype.rebuild = function () {
  29527. if (this._keys) {
  29528. delete this._keys;
  29529. }
  29530. this._keys = Object.keys(this);
  29531. };
  29532. MaterialDefines.prototype.isEqual = function (other) {
  29533. if (this._keys.length !== other._keys.length) {
  29534. return false;
  29535. }
  29536. for (var index = 0; index < this._keys.length; index++) {
  29537. var prop = this._keys[index];
  29538. if (this[prop] !== other[prop]) {
  29539. return false;
  29540. }
  29541. }
  29542. return true;
  29543. };
  29544. MaterialDefines.prototype.cloneTo = function (other) {
  29545. if (this._keys.length !== other._keys.length) {
  29546. other._keys = this._keys.slice(0);
  29547. }
  29548. for (var index = 0; index < this._keys.length; index++) {
  29549. var prop = this._keys[index];
  29550. other[prop] = this[prop];
  29551. }
  29552. };
  29553. MaterialDefines.prototype.reset = function () {
  29554. for (var index = 0; index < this._keys.length; index++) {
  29555. var prop = this._keys[index];
  29556. if (typeof (this[prop]) === "number") {
  29557. this[prop] = 0;
  29558. }
  29559. else {
  29560. this[prop] = false;
  29561. }
  29562. }
  29563. };
  29564. MaterialDefines.prototype.toString = function () {
  29565. var result = "";
  29566. for (var index = 0; index < this._keys.length; index++) {
  29567. var prop = this._keys[index];
  29568. if (typeof (this[prop]) === "number") {
  29569. result += "#define " + prop + " " + this[prop] + "\n";
  29570. }
  29571. else if (this[prop]) {
  29572. result += "#define " + prop + "\n";
  29573. }
  29574. }
  29575. return result;
  29576. };
  29577. return MaterialDefines;
  29578. }());
  29579. BABYLON.MaterialDefines = MaterialDefines;
  29580. var Material = (function () {
  29581. function Material(name, scene, doNotAdd) {
  29582. this.checkReadyOnEveryCall = false;
  29583. this.checkReadyOnlyOnce = false;
  29584. this.state = "";
  29585. this.alpha = 1.0;
  29586. this.backFaceCulling = true;
  29587. this.doNotSerialize = false;
  29588. /**
  29589. * An event triggered when the material is disposed.
  29590. * @type {BABYLON.Observable}
  29591. */
  29592. this.onDisposeObservable = new BABYLON.Observable();
  29593. /**
  29594. * An event triggered when the material is bound.
  29595. * @type {BABYLON.Observable}
  29596. */
  29597. this.onBindObservable = new BABYLON.Observable();
  29598. /**
  29599. * An event triggered when the material is unbound.
  29600. * @type {BABYLON.Observable}
  29601. */
  29602. this.onUnBindObservable = new BABYLON.Observable();
  29603. this.alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  29604. this.disableDepthWrite = false;
  29605. this.fogEnabled = true;
  29606. this.pointSize = 1.0;
  29607. this.zOffset = 0;
  29608. this._wasPreviouslyReady = false;
  29609. this._fillMode = Material.TriangleFillMode;
  29610. this.name = name;
  29611. this.id = name;
  29612. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  29613. if (this._scene.useRightHandedSystem) {
  29614. this.sideOrientation = Material.ClockWiseSideOrientation;
  29615. }
  29616. else {
  29617. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  29618. }
  29619. if (!doNotAdd) {
  29620. this._scene.materials.push(this);
  29621. }
  29622. }
  29623. Object.defineProperty(Material, "TriangleFillMode", {
  29624. get: function () {
  29625. return Material._TriangleFillMode;
  29626. },
  29627. enumerable: true,
  29628. configurable: true
  29629. });
  29630. Object.defineProperty(Material, "WireFrameFillMode", {
  29631. get: function () {
  29632. return Material._WireFrameFillMode;
  29633. },
  29634. enumerable: true,
  29635. configurable: true
  29636. });
  29637. Object.defineProperty(Material, "PointFillMode", {
  29638. get: function () {
  29639. return Material._PointFillMode;
  29640. },
  29641. enumerable: true,
  29642. configurable: true
  29643. });
  29644. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  29645. get: function () {
  29646. return Material._ClockWiseSideOrientation;
  29647. },
  29648. enumerable: true,
  29649. configurable: true
  29650. });
  29651. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  29652. get: function () {
  29653. return Material._CounterClockWiseSideOrientation;
  29654. },
  29655. enumerable: true,
  29656. configurable: true
  29657. });
  29658. Object.defineProperty(Material.prototype, "onDispose", {
  29659. set: function (callback) {
  29660. if (this._onDisposeObserver) {
  29661. this.onDisposeObservable.remove(this._onDisposeObserver);
  29662. }
  29663. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  29664. },
  29665. enumerable: true,
  29666. configurable: true
  29667. });
  29668. Object.defineProperty(Material.prototype, "onBind", {
  29669. set: function (callback) {
  29670. if (this._onBindObserver) {
  29671. this.onBindObservable.remove(this._onBindObserver);
  29672. }
  29673. this._onBindObserver = this.onBindObservable.add(callback);
  29674. },
  29675. enumerable: true,
  29676. configurable: true
  29677. });
  29678. Object.defineProperty(Material.prototype, "wireframe", {
  29679. get: function () {
  29680. return this._fillMode === Material.WireFrameFillMode;
  29681. },
  29682. set: function (value) {
  29683. this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  29684. },
  29685. enumerable: true,
  29686. configurable: true
  29687. });
  29688. Object.defineProperty(Material.prototype, "pointsCloud", {
  29689. get: function () {
  29690. return this._fillMode === Material.PointFillMode;
  29691. },
  29692. set: function (value) {
  29693. this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  29694. },
  29695. enumerable: true,
  29696. configurable: true
  29697. });
  29698. Object.defineProperty(Material.prototype, "fillMode", {
  29699. get: function () {
  29700. return this._fillMode;
  29701. },
  29702. set: function (value) {
  29703. this._fillMode = value;
  29704. },
  29705. enumerable: true,
  29706. configurable: true
  29707. });
  29708. /**
  29709. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  29710. * subclasses should override adding information pertainent to themselves
  29711. */
  29712. Material.prototype.toString = function (fullDetails) {
  29713. var ret = "Name: " + this.name;
  29714. if (fullDetails) {
  29715. }
  29716. return ret;
  29717. };
  29718. Material.prototype.getClassName = function () {
  29719. return "Material";
  29720. };
  29721. Object.defineProperty(Material.prototype, "isFrozen", {
  29722. get: function () {
  29723. return this.checkReadyOnlyOnce;
  29724. },
  29725. enumerable: true,
  29726. configurable: true
  29727. });
  29728. Material.prototype.freeze = function () {
  29729. this.checkReadyOnlyOnce = true;
  29730. };
  29731. Material.prototype.unfreeze = function () {
  29732. this.checkReadyOnlyOnce = false;
  29733. };
  29734. Material.prototype.isReady = function (mesh, useInstances) {
  29735. return true;
  29736. };
  29737. Material.prototype.getEffect = function () {
  29738. return this._effect;
  29739. };
  29740. Material.prototype.getScene = function () {
  29741. return this._scene;
  29742. };
  29743. Material.prototype.needAlphaBlending = function () {
  29744. return (this.alpha < 1.0);
  29745. };
  29746. Material.prototype.needAlphaTesting = function () {
  29747. return false;
  29748. };
  29749. Material.prototype.getAlphaTestTexture = function () {
  29750. return null;
  29751. };
  29752. Material.prototype.markDirty = function () {
  29753. this._wasPreviouslyReady = false;
  29754. };
  29755. Material.prototype._preBind = function () {
  29756. var engine = this._scene.getEngine();
  29757. var reverse = this.sideOrientation === Material.ClockWiseSideOrientation;
  29758. engine.enableEffect(this._effect);
  29759. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  29760. };
  29761. Material.prototype.bind = function (world, mesh) {
  29762. this._scene._cachedMaterial = this;
  29763. this.onBindObservable.notifyObservers(mesh);
  29764. if (this.disableDepthWrite) {
  29765. var engine = this._scene.getEngine();
  29766. this._cachedDepthWriteState = engine.getDepthWrite();
  29767. engine.setDepthWrite(false);
  29768. }
  29769. };
  29770. Material.prototype.bindOnlyWorldMatrix = function (world) {
  29771. };
  29772. Material.prototype.unbind = function () {
  29773. this.onUnBindObservable.notifyObservers(this);
  29774. if (this.disableDepthWrite) {
  29775. var engine = this._scene.getEngine();
  29776. engine.setDepthWrite(this._cachedDepthWriteState);
  29777. }
  29778. };
  29779. Material.prototype.clone = function (name) {
  29780. return null;
  29781. };
  29782. Material.prototype.getBindedMeshes = function () {
  29783. var result = new Array();
  29784. for (var index = 0; index < this._scene.meshes.length; index++) {
  29785. var mesh = this._scene.meshes[index];
  29786. if (mesh.material === this) {
  29787. result.push(mesh);
  29788. }
  29789. }
  29790. return result;
  29791. };
  29792. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  29793. // Animations
  29794. this.getScene().stopAnimation(this);
  29795. // Remove from scene
  29796. var index = this._scene.materials.indexOf(this);
  29797. if (index >= 0) {
  29798. this._scene.materials.splice(index, 1);
  29799. }
  29800. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  29801. if (forceDisposeEffect && this._effect) {
  29802. this._scene.getEngine()._releaseEffect(this._effect);
  29803. this._effect = null;
  29804. }
  29805. // Remove from meshes
  29806. for (index = 0; index < this._scene.meshes.length; index++) {
  29807. var mesh = this._scene.meshes[index];
  29808. if (mesh.material === this) {
  29809. mesh.material = null;
  29810. }
  29811. }
  29812. // Callback
  29813. this.onDisposeObservable.notifyObservers(this);
  29814. this.onDisposeObservable.clear();
  29815. this.onBindObservable.clear();
  29816. this.onUnBindObservable.clear();
  29817. };
  29818. Material.prototype.serialize = function () {
  29819. return BABYLON.SerializationHelper.Serialize(this);
  29820. };
  29821. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  29822. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  29823. multiMaterial.id = parsedMultiMaterial.id;
  29824. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  29825. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  29826. var subMatId = parsedMultiMaterial.materials[matIndex];
  29827. if (subMatId) {
  29828. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  29829. }
  29830. else {
  29831. multiMaterial.subMaterials.push(null);
  29832. }
  29833. }
  29834. return multiMaterial;
  29835. };
  29836. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  29837. if (!parsedMaterial.customType) {
  29838. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  29839. }
  29840. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  29841. return materialType.Parse(parsedMaterial, scene, rootUrl);
  29842. ;
  29843. };
  29844. return Material;
  29845. }());
  29846. Material._TriangleFillMode = 0;
  29847. Material._WireFrameFillMode = 1;
  29848. Material._PointFillMode = 2;
  29849. Material._ClockWiseSideOrientation = 0;
  29850. Material._CounterClockWiseSideOrientation = 1;
  29851. __decorate([
  29852. BABYLON.serialize()
  29853. ], Material.prototype, "id", void 0);
  29854. __decorate([
  29855. BABYLON.serialize()
  29856. ], Material.prototype, "name", void 0);
  29857. __decorate([
  29858. BABYLON.serialize()
  29859. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  29860. __decorate([
  29861. BABYLON.serialize()
  29862. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  29863. __decorate([
  29864. BABYLON.serialize()
  29865. ], Material.prototype, "state", void 0);
  29866. __decorate([
  29867. BABYLON.serialize()
  29868. ], Material.prototype, "alpha", void 0);
  29869. __decorate([
  29870. BABYLON.serialize()
  29871. ], Material.prototype, "backFaceCulling", void 0);
  29872. __decorate([
  29873. BABYLON.serialize()
  29874. ], Material.prototype, "sideOrientation", void 0);
  29875. __decorate([
  29876. BABYLON.serialize()
  29877. ], Material.prototype, "alphaMode", void 0);
  29878. __decorate([
  29879. BABYLON.serialize()
  29880. ], Material.prototype, "disableDepthWrite", void 0);
  29881. __decorate([
  29882. BABYLON.serialize()
  29883. ], Material.prototype, "fogEnabled", void 0);
  29884. __decorate([
  29885. BABYLON.serialize()
  29886. ], Material.prototype, "pointSize", void 0);
  29887. __decorate([
  29888. BABYLON.serialize()
  29889. ], Material.prototype, "zOffset", void 0);
  29890. __decorate([
  29891. BABYLON.serialize()
  29892. ], Material.prototype, "wireframe", null);
  29893. __decorate([
  29894. BABYLON.serialize()
  29895. ], Material.prototype, "pointsCloud", null);
  29896. __decorate([
  29897. BABYLON.serialize()
  29898. ], Material.prototype, "fillMode", null);
  29899. BABYLON.Material = Material;
  29900. })(BABYLON || (BABYLON = {}));
  29901. //# sourceMappingURL=babylon.material.js.map
  29902. var BABYLON;
  29903. (function (BABYLON) {
  29904. var StandardMaterialDefines = (function (_super) {
  29905. __extends(StandardMaterialDefines, _super);
  29906. function StandardMaterialDefines() {
  29907. var _this = _super.call(this) || this;
  29908. _this.DIFFUSE = false;
  29909. _this.AMBIENT = false;
  29910. _this.OPACITY = false;
  29911. _this.OPACITYRGB = false;
  29912. _this.REFLECTION = false;
  29913. _this.EMISSIVE = false;
  29914. _this.SPECULAR = false;
  29915. _this.BUMP = false;
  29916. _this.PARALLAX = false;
  29917. _this.PARALLAXOCCLUSION = false;
  29918. _this.SPECULAROVERALPHA = false;
  29919. _this.CLIPPLANE = false;
  29920. _this.ALPHATEST = false;
  29921. _this.ALPHAFROMDIFFUSE = false;
  29922. _this.POINTSIZE = false;
  29923. _this.FOG = false;
  29924. _this.SPECULARTERM = false;
  29925. _this.DIFFUSEFRESNEL = false;
  29926. _this.OPACITYFRESNEL = false;
  29927. _this.REFLECTIONFRESNEL = false;
  29928. _this.REFRACTIONFRESNEL = false;
  29929. _this.EMISSIVEFRESNEL = false;
  29930. _this.FRESNEL = false;
  29931. _this.NORMAL = false;
  29932. _this.UV1 = false;
  29933. _this.UV2 = false;
  29934. _this.VERTEXCOLOR = false;
  29935. _this.VERTEXALPHA = false;
  29936. _this.NUM_BONE_INFLUENCERS = 0;
  29937. _this.BonesPerMesh = 0;
  29938. _this.INSTANCES = false;
  29939. _this.GLOSSINESS = false;
  29940. _this.ROUGHNESS = false;
  29941. _this.EMISSIVEASILLUMINATION = false;
  29942. _this.LINKEMISSIVEWITHDIFFUSE = false;
  29943. _this.REFLECTIONFRESNELFROMSPECULAR = false;
  29944. _this.LIGHTMAP = false;
  29945. _this.USELIGHTMAPASSHADOWMAP = false;
  29946. _this.REFLECTIONMAP_3D = false;
  29947. _this.REFLECTIONMAP_SPHERICAL = false;
  29948. _this.REFLECTIONMAP_PLANAR = false;
  29949. _this.REFLECTIONMAP_CUBIC = false;
  29950. _this.REFLECTIONMAP_PROJECTION = false;
  29951. _this.REFLECTIONMAP_SKYBOX = false;
  29952. _this.REFLECTIONMAP_EXPLICIT = false;
  29953. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  29954. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  29955. _this.INVERTCUBICMAP = false;
  29956. _this.LOGARITHMICDEPTH = false;
  29957. _this.REFRACTION = false;
  29958. _this.REFRACTIONMAP_3D = false;
  29959. _this.REFLECTIONOVERALPHA = false;
  29960. _this.INVERTNORMALMAPX = false;
  29961. _this.INVERTNORMALMAPY = false;
  29962. _this.SHADOWFULLFLOAT = false;
  29963. _this.CAMERACOLORGRADING = false;
  29964. _this.CAMERACOLORCURVES = false;
  29965. _this.rebuild();
  29966. return _this;
  29967. }
  29968. return StandardMaterialDefines;
  29969. }(BABYLON.MaterialDefines));
  29970. BABYLON.StandardMaterialDefines = StandardMaterialDefines;
  29971. var StandardMaterial = (function (_super) {
  29972. __extends(StandardMaterial, _super);
  29973. function StandardMaterial(name, scene) {
  29974. var _this = _super.call(this, name, scene) || this;
  29975. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  29976. _this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  29977. _this.specularColor = new BABYLON.Color3(1, 1, 1);
  29978. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  29979. _this.specularPower = 64;
  29980. _this.useAlphaFromDiffuseTexture = false;
  29981. _this.useEmissiveAsIllumination = false;
  29982. _this.linkEmissiveWithDiffuse = false;
  29983. _this.useReflectionFresnelFromSpecular = false;
  29984. _this.useSpecularOverAlpha = false;
  29985. _this.useReflectionOverAlpha = false;
  29986. _this.disableLighting = false;
  29987. _this.useParallax = false;
  29988. _this.useParallaxOcclusion = false;
  29989. _this.parallaxScaleBias = 0.05;
  29990. _this.roughness = 0;
  29991. _this.indexOfRefraction = 0.98;
  29992. _this.invertRefractionY = true;
  29993. _this.useLightmapAsShadowmap = false;
  29994. _this.useGlossinessFromSpecularMapAlpha = false;
  29995. _this.maxSimultaneousLights = 4;
  29996. /**
  29997. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  29998. */
  29999. _this.invertNormalMapX = false;
  30000. /**
  30001. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  30002. */
  30003. _this.invertNormalMapY = false;
  30004. /**
  30005. * Color Grading 2D Lookup Texture.
  30006. * This allows special effects like sepia, black and white to sixties rendering style.
  30007. */
  30008. _this.cameraColorGradingTexture = null;
  30009. /**
  30010. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  30011. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  30012. * 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;
  30013. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  30014. */
  30015. _this.cameraColorCurves = null;
  30016. _this._renderTargets = new BABYLON.SmartArray(16);
  30017. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  30018. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  30019. _this._defines = new StandardMaterialDefines();
  30020. _this._cachedDefines = new StandardMaterialDefines();
  30021. _this._cachedDefines.BonesPerMesh = -1;
  30022. _this.getRenderTargetTextures = function () {
  30023. _this._renderTargets.reset();
  30024. if (_this.reflectionTexture && _this.reflectionTexture.isRenderTarget) {
  30025. _this._renderTargets.push(_this.reflectionTexture);
  30026. }
  30027. if (_this.refractionTexture && _this.refractionTexture.isRenderTarget) {
  30028. _this._renderTargets.push(_this.refractionTexture);
  30029. }
  30030. return _this._renderTargets;
  30031. };
  30032. return _this;
  30033. }
  30034. StandardMaterial.prototype.getClassName = function () {
  30035. return "StandardMaterial";
  30036. };
  30037. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  30038. get: function () {
  30039. return this._useLogarithmicDepth;
  30040. },
  30041. set: function (value) {
  30042. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  30043. },
  30044. enumerable: true,
  30045. configurable: true
  30046. });
  30047. StandardMaterial.prototype.needAlphaBlending = function () {
  30048. return (this.alpha < 1.0) || (this.opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled;
  30049. };
  30050. StandardMaterial.prototype.needAlphaTesting = function () {
  30051. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha;
  30052. };
  30053. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  30054. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha && this.useAlphaFromDiffuseTexture;
  30055. };
  30056. StandardMaterial.prototype.getAlphaTestTexture = function () {
  30057. return this.diffuseTexture;
  30058. };
  30059. // Methods
  30060. StandardMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  30061. if (!mesh) {
  30062. return true;
  30063. }
  30064. if (this._defines.INSTANCES !== useInstances) {
  30065. return false;
  30066. }
  30067. if (mesh._materialDefines && mesh._materialDefines.isEqual(this._defines)) {
  30068. return true;
  30069. }
  30070. return false;
  30071. };
  30072. StandardMaterial.prototype.isReady = function (mesh, useInstances) {
  30073. if (this.isFrozen) {
  30074. if (this._wasPreviouslyReady) {
  30075. return true;
  30076. }
  30077. }
  30078. var scene = this.getScene();
  30079. var engine = scene.getEngine();
  30080. var needUVs = false;
  30081. var needNormals = false;
  30082. this._defines.reset();
  30083. // Lights
  30084. if (scene.lightsEnabled && !this.disableLighting) {
  30085. needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, this._defines, this.maxSimultaneousLights);
  30086. }
  30087. if (!this.checkReadyOnEveryCall) {
  30088. if (this._renderId === scene.getRenderId()) {
  30089. if (this._checkCache(scene, mesh, useInstances)) {
  30090. return true;
  30091. }
  30092. }
  30093. }
  30094. // Textures
  30095. if (scene.texturesEnabled) {
  30096. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  30097. if (!this.diffuseTexture.isReady()) {
  30098. return false;
  30099. }
  30100. else {
  30101. needUVs = true;
  30102. this._defines.DIFFUSE = true;
  30103. }
  30104. }
  30105. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  30106. if (!this.ambientTexture.isReady()) {
  30107. return false;
  30108. }
  30109. else {
  30110. needUVs = true;
  30111. this._defines.AMBIENT = true;
  30112. }
  30113. }
  30114. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  30115. if (!this.opacityTexture.isReady()) {
  30116. return false;
  30117. }
  30118. else {
  30119. needUVs = true;
  30120. this._defines.OPACITY = true;
  30121. if (this.opacityTexture.getAlphaFromRGB) {
  30122. this._defines.OPACITYRGB = true;
  30123. }
  30124. }
  30125. }
  30126. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  30127. if (!this.reflectionTexture.isReady()) {
  30128. return false;
  30129. }
  30130. else {
  30131. needNormals = true;
  30132. this._defines.REFLECTION = true;
  30133. if (this.roughness > 0) {
  30134. this._defines.ROUGHNESS = true;
  30135. }
  30136. if (this.useReflectionOverAlpha) {
  30137. this._defines.REFLECTIONOVERALPHA = true;
  30138. }
  30139. if (this.reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  30140. this._defines.INVERTCUBICMAP = true;
  30141. }
  30142. this._defines.REFLECTIONMAP_3D = this.reflectionTexture.isCube;
  30143. switch (this.reflectionTexture.coordinatesMode) {
  30144. case BABYLON.Texture.CUBIC_MODE:
  30145. case BABYLON.Texture.INVCUBIC_MODE:
  30146. this._defines.REFLECTIONMAP_CUBIC = true;
  30147. break;
  30148. case BABYLON.Texture.EXPLICIT_MODE:
  30149. this._defines.REFLECTIONMAP_EXPLICIT = true;
  30150. break;
  30151. case BABYLON.Texture.PLANAR_MODE:
  30152. this._defines.REFLECTIONMAP_PLANAR = true;
  30153. break;
  30154. case BABYLON.Texture.PROJECTION_MODE:
  30155. this._defines.REFLECTIONMAP_PROJECTION = true;
  30156. break;
  30157. case BABYLON.Texture.SKYBOX_MODE:
  30158. this._defines.REFLECTIONMAP_SKYBOX = true;
  30159. break;
  30160. case BABYLON.Texture.SPHERICAL_MODE:
  30161. this._defines.REFLECTIONMAP_SPHERICAL = true;
  30162. break;
  30163. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  30164. this._defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  30165. break;
  30166. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  30167. this._defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  30168. break;
  30169. }
  30170. }
  30171. }
  30172. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  30173. if (!this.emissiveTexture.isReady()) {
  30174. return false;
  30175. }
  30176. else {
  30177. needUVs = true;
  30178. this._defines.EMISSIVE = true;
  30179. }
  30180. }
  30181. if (this.lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  30182. if (!this.lightmapTexture.isReady()) {
  30183. return false;
  30184. }
  30185. else {
  30186. needUVs = true;
  30187. this._defines.LIGHTMAP = true;
  30188. this._defines.USELIGHTMAPASSHADOWMAP = this.useLightmapAsShadowmap;
  30189. }
  30190. }
  30191. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  30192. if (!this.specularTexture.isReady()) {
  30193. return false;
  30194. }
  30195. else {
  30196. needUVs = true;
  30197. this._defines.SPECULAR = true;
  30198. this._defines.GLOSSINESS = this.useGlossinessFromSpecularMapAlpha;
  30199. }
  30200. }
  30201. if (scene.getEngine().getCaps().standardDerivatives && this.bumpTexture && StandardMaterial.BumpTextureEnabled) {
  30202. if (!this.bumpTexture.isReady()) {
  30203. return false;
  30204. }
  30205. else {
  30206. needUVs = true;
  30207. this._defines.BUMP = true;
  30208. if (this.useParallax) {
  30209. this._defines.PARALLAX = true;
  30210. if (this.useParallaxOcclusion) {
  30211. this._defines.PARALLAXOCCLUSION = true;
  30212. }
  30213. }
  30214. if (this.invertNormalMapX) {
  30215. this._defines.INVERTNORMALMAPX = true;
  30216. }
  30217. if (this.invertNormalMapY) {
  30218. this._defines.INVERTNORMALMAPY = true;
  30219. }
  30220. if (scene._mirroredCameraPosition) {
  30221. this._defines.INVERTNORMALMAPX = !this._defines.INVERTNORMALMAPX;
  30222. this._defines.INVERTNORMALMAPY = !this._defines.INVERTNORMALMAPY;
  30223. }
  30224. }
  30225. }
  30226. if (this.refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  30227. if (!this.refractionTexture.isReady()) {
  30228. return false;
  30229. }
  30230. else {
  30231. needUVs = true;
  30232. this._defines.REFRACTION = true;
  30233. this._defines.REFRACTIONMAP_3D = this.refractionTexture.isCube;
  30234. }
  30235. }
  30236. if (this.cameraColorGradingTexture && StandardMaterial.ColorGradingTextureEnabled) {
  30237. if (!this.cameraColorGradingTexture.isReady()) {
  30238. return false;
  30239. }
  30240. else {
  30241. this._defines.CAMERACOLORGRADING = true;
  30242. }
  30243. }
  30244. }
  30245. // Effect
  30246. if (scene.clipPlane) {
  30247. this._defines.CLIPPLANE = true;
  30248. }
  30249. if (engine.getAlphaTesting()) {
  30250. this._defines.ALPHATEST = true;
  30251. }
  30252. if (this._shouldUseAlphaFromDiffuseTexture()) {
  30253. this._defines.ALPHAFROMDIFFUSE = true;
  30254. }
  30255. if (this.useEmissiveAsIllumination) {
  30256. this._defines.EMISSIVEASILLUMINATION = true;
  30257. }
  30258. if (this.linkEmissiveWithDiffuse) {
  30259. this._defines.LINKEMISSIVEWITHDIFFUSE = true;
  30260. }
  30261. if (this.useLogarithmicDepth) {
  30262. this._defines.LOGARITHMICDEPTH = true;
  30263. }
  30264. if (this.cameraColorCurves) {
  30265. this._defines.CAMERACOLORCURVES = true;
  30266. }
  30267. // Point size
  30268. if (this.pointsCloud || scene.forcePointsCloud) {
  30269. this._defines.POINTSIZE = true;
  30270. }
  30271. // Fog
  30272. if (scene.fogEnabled && mesh && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  30273. this._defines.FOG = true;
  30274. }
  30275. if (StandardMaterial.FresnelEnabled) {
  30276. // Fresnel
  30277. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled ||
  30278. this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled ||
  30279. this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled ||
  30280. this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled ||
  30281. this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  30282. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  30283. this._defines.DIFFUSEFRESNEL = true;
  30284. }
  30285. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  30286. this._defines.OPACITYFRESNEL = true;
  30287. }
  30288. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  30289. this._defines.REFLECTIONFRESNEL = true;
  30290. if (this.useReflectionFresnelFromSpecular) {
  30291. this._defines.REFLECTIONFRESNELFROMSPECULAR = true;
  30292. }
  30293. }
  30294. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  30295. this._defines.REFRACTIONFRESNEL = true;
  30296. }
  30297. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  30298. this._defines.EMISSIVEFRESNEL = true;
  30299. }
  30300. needNormals = true;
  30301. this._defines.FRESNEL = true;
  30302. }
  30303. }
  30304. if (this._defines.SPECULARTERM && this.useSpecularOverAlpha) {
  30305. this._defines.SPECULAROVERALPHA = true;
  30306. }
  30307. // Attribs
  30308. if (mesh) {
  30309. if (needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  30310. this._defines.NORMAL = true;
  30311. }
  30312. if (needUVs) {
  30313. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  30314. this._defines.UV1 = true;
  30315. }
  30316. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  30317. this._defines.UV2 = true;
  30318. }
  30319. }
  30320. if (mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  30321. this._defines.VERTEXCOLOR = true;
  30322. if (mesh.hasVertexAlpha) {
  30323. this._defines.VERTEXALPHA = true;
  30324. }
  30325. }
  30326. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  30327. this._defines.NUM_BONE_INFLUENCERS = mesh.numBoneInfluencers;
  30328. this._defines.BonesPerMesh = (mesh.skeleton.bones.length + 1);
  30329. }
  30330. // Instances
  30331. if (useInstances) {
  30332. this._defines.INSTANCES = true;
  30333. }
  30334. }
  30335. // Get correct effect
  30336. if (!this._defines.isEqual(this._cachedDefines)) {
  30337. this._defines.cloneTo(this._cachedDefines);
  30338. scene.resetCachedMaterial();
  30339. // Fallbacks
  30340. var fallbacks = new BABYLON.EffectFallbacks();
  30341. if (this._defines.REFLECTION) {
  30342. fallbacks.addFallback(0, "REFLECTION");
  30343. }
  30344. if (this._defines.SPECULAR) {
  30345. fallbacks.addFallback(0, "SPECULAR");
  30346. }
  30347. if (this._defines.BUMP) {
  30348. fallbacks.addFallback(0, "BUMP");
  30349. }
  30350. if (this._defines.PARALLAX) {
  30351. fallbacks.addFallback(1, "PARALLAX");
  30352. }
  30353. if (this._defines.PARALLAXOCCLUSION) {
  30354. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  30355. }
  30356. if (this._defines.SPECULAROVERALPHA) {
  30357. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  30358. }
  30359. if (this._defines.FOG) {
  30360. fallbacks.addFallback(1, "FOG");
  30361. }
  30362. if (this._defines.POINTSIZE) {
  30363. fallbacks.addFallback(0, "POINTSIZE");
  30364. }
  30365. if (this._defines.LOGARITHMICDEPTH) {
  30366. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  30367. }
  30368. BABYLON.MaterialHelper.HandleFallbacksForShadows(this._defines, fallbacks, this.maxSimultaneousLights);
  30369. if (this._defines.SPECULARTERM) {
  30370. fallbacks.addFallback(0, "SPECULARTERM");
  30371. }
  30372. if (this._defines.DIFFUSEFRESNEL) {
  30373. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  30374. }
  30375. if (this._defines.OPACITYFRESNEL) {
  30376. fallbacks.addFallback(2, "OPACITYFRESNEL");
  30377. }
  30378. if (this._defines.REFLECTIONFRESNEL) {
  30379. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  30380. }
  30381. if (this._defines.EMISSIVEFRESNEL) {
  30382. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  30383. }
  30384. if (this._defines.FRESNEL) {
  30385. fallbacks.addFallback(4, "FRESNEL");
  30386. }
  30387. //Attributes
  30388. var attribs = [BABYLON.VertexBuffer.PositionKind];
  30389. if (this._defines.NORMAL) {
  30390. attribs.push(BABYLON.VertexBuffer.NormalKind);
  30391. }
  30392. if (this._defines.UV1) {
  30393. attribs.push(BABYLON.VertexBuffer.UVKind);
  30394. }
  30395. if (this._defines.UV2) {
  30396. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  30397. }
  30398. if (this._defines.VERTEXCOLOR) {
  30399. attribs.push(BABYLON.VertexBuffer.ColorKind);
  30400. }
  30401. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, this._defines, fallbacks);
  30402. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, this._defines);
  30403. var shaderName = "default";
  30404. var join = this._defines.toString();
  30405. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  30406. "vFogInfos", "vFogColor", "pointSize",
  30407. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  30408. "mBones",
  30409. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  30410. "depthValues",
  30411. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  30412. "logarithmicDepthConstant"
  30413. ];
  30414. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  30415. if (this._defines.CAMERACOLORCURVES) {
  30416. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  30417. }
  30418. if (this._defines.CAMERACOLORGRADING) {
  30419. BABYLON.ColorGradingTexture.PrepareUniformsAndSamplers(uniforms, samplers);
  30420. }
  30421. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList(uniforms, samplers, this._defines, this.maxSimultaneousLights);
  30422. this._effect = scene.getEngine().createEffect(shaderName, attribs, uniforms, samplers, join, fallbacks, this.onCompiled, this.onError, { maxSimultaneousLights: this.maxSimultaneousLights - 1 });
  30423. }
  30424. if (!this._effect.isReady()) {
  30425. return false;
  30426. }
  30427. this._renderId = scene.getRenderId();
  30428. this._wasPreviouslyReady = true;
  30429. if (mesh) {
  30430. if (!mesh._materialDefines) {
  30431. mesh._materialDefines = new StandardMaterialDefines();
  30432. }
  30433. this._defines.cloneTo(mesh._materialDefines);
  30434. }
  30435. return true;
  30436. };
  30437. StandardMaterial.prototype.unbind = function () {
  30438. if (this.reflectionTexture && this.reflectionTexture.isRenderTarget) {
  30439. this._effect.setTexture("reflection2DSampler", null);
  30440. }
  30441. if (this.refractionTexture && this.refractionTexture.isRenderTarget) {
  30442. this._effect.setTexture("refraction2DSampler", null);
  30443. }
  30444. _super.prototype.unbind.call(this);
  30445. };
  30446. StandardMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  30447. this._effect.setMatrix("world", world);
  30448. };
  30449. StandardMaterial.prototype.bind = function (world, mesh) {
  30450. var scene = this.getScene();
  30451. // Matrices
  30452. this.bindOnlyWorldMatrix(world);
  30453. // Bones
  30454. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  30455. if (scene.getCachedMaterial() !== this) {
  30456. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  30457. if (StandardMaterial.FresnelEnabled) {
  30458. // Fresnel
  30459. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  30460. this._effect.setColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  30461. this._effect.setColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  30462. }
  30463. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  30464. this._effect.setColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  30465. }
  30466. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  30467. this._effect.setColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  30468. this._effect.setColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  30469. }
  30470. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  30471. this._effect.setColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  30472. this._effect.setColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  30473. }
  30474. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  30475. this._effect.setColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  30476. this._effect.setColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  30477. }
  30478. }
  30479. // Textures
  30480. if (scene.texturesEnabled) {
  30481. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  30482. this._effect.setTexture("diffuseSampler", this.diffuseTexture);
  30483. this._effect.setFloat2("vDiffuseInfos", this.diffuseTexture.coordinatesIndex, this.diffuseTexture.level);
  30484. this._effect.setMatrix("diffuseMatrix", this.diffuseTexture.getTextureMatrix());
  30485. }
  30486. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  30487. this._effect.setTexture("ambientSampler", this.ambientTexture);
  30488. this._effect.setFloat2("vAmbientInfos", this.ambientTexture.coordinatesIndex, this.ambientTexture.level);
  30489. this._effect.setMatrix("ambientMatrix", this.ambientTexture.getTextureMatrix());
  30490. }
  30491. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  30492. this._effect.setTexture("opacitySampler", this.opacityTexture);
  30493. this._effect.setFloat2("vOpacityInfos", this.opacityTexture.coordinatesIndex, this.opacityTexture.level);
  30494. this._effect.setMatrix("opacityMatrix", this.opacityTexture.getTextureMatrix());
  30495. }
  30496. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  30497. if (this.reflectionTexture.isCube) {
  30498. this._effect.setTexture("reflectionCubeSampler", this.reflectionTexture);
  30499. }
  30500. else {
  30501. this._effect.setTexture("reflection2DSampler", this.reflectionTexture);
  30502. }
  30503. this._effect.setMatrix("reflectionMatrix", this.reflectionTexture.getReflectionTextureMatrix());
  30504. this._effect.setFloat2("vReflectionInfos", this.reflectionTexture.level, this.roughness);
  30505. }
  30506. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  30507. this._effect.setTexture("emissiveSampler", this.emissiveTexture);
  30508. this._effect.setFloat2("vEmissiveInfos", this.emissiveTexture.coordinatesIndex, this.emissiveTexture.level);
  30509. this._effect.setMatrix("emissiveMatrix", this.emissiveTexture.getTextureMatrix());
  30510. }
  30511. if (this.lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  30512. this._effect.setTexture("lightmapSampler", this.lightmapTexture);
  30513. this._effect.setFloat2("vLightmapInfos", this.lightmapTexture.coordinatesIndex, this.lightmapTexture.level);
  30514. this._effect.setMatrix("lightmapMatrix", this.lightmapTexture.getTextureMatrix());
  30515. }
  30516. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  30517. this._effect.setTexture("specularSampler", this.specularTexture);
  30518. this._effect.setFloat2("vSpecularInfos", this.specularTexture.coordinatesIndex, this.specularTexture.level);
  30519. this._effect.setMatrix("specularMatrix", this.specularTexture.getTextureMatrix());
  30520. }
  30521. if (this.bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  30522. this._effect.setTexture("bumpSampler", this.bumpTexture);
  30523. this._effect.setFloat3("vBumpInfos", this.bumpTexture.coordinatesIndex, 1.0 / this.bumpTexture.level, this.parallaxScaleBias);
  30524. this._effect.setMatrix("bumpMatrix", this.bumpTexture.getTextureMatrix());
  30525. }
  30526. if (this.refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  30527. var depth = 1.0;
  30528. if (this.refractionTexture.isCube) {
  30529. this._effect.setTexture("refractionCubeSampler", this.refractionTexture);
  30530. }
  30531. else {
  30532. this._effect.setTexture("refraction2DSampler", this.refractionTexture);
  30533. this._effect.setMatrix("refractionMatrix", this.refractionTexture.getReflectionTextureMatrix());
  30534. if (this.refractionTexture.depth) {
  30535. depth = this.refractionTexture.depth;
  30536. }
  30537. }
  30538. this._effect.setFloat4("vRefractionInfos", this.refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  30539. }
  30540. if (this.cameraColorGradingTexture && StandardMaterial.ColorGradingTextureEnabled) {
  30541. BABYLON.ColorGradingTexture.Bind(this.cameraColorGradingTexture, this._effect);
  30542. }
  30543. }
  30544. // Clip plane
  30545. BABYLON.MaterialHelper.BindClipPlane(this._effect, scene);
  30546. // Point size
  30547. if (this.pointsCloud) {
  30548. this._effect.setFloat("pointSize", this.pointSize);
  30549. }
  30550. // Colors
  30551. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  30552. this._effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.position);
  30553. this._effect.setColor3("vAmbientColor", this._globalAmbientColor);
  30554. if (this._defines.SPECULARTERM) {
  30555. this._effect.setColor4("vSpecularColor", this.specularColor, this.specularPower);
  30556. }
  30557. this._effect.setColor3("vEmissiveColor", this.emissiveColor);
  30558. }
  30559. if (scene.getCachedMaterial() !== this || !this.isFrozen) {
  30560. // Diffuse
  30561. this._effect.setColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  30562. // Lights
  30563. if (scene.lightsEnabled && !this.disableLighting) {
  30564. BABYLON.MaterialHelper.BindLights(scene, mesh, this._effect, this._defines, this.maxSimultaneousLights);
  30565. }
  30566. // View
  30567. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this.reflectionTexture || this.refractionTexture) {
  30568. this._effect.setMatrix("view", scene.getViewMatrix());
  30569. }
  30570. // Fog
  30571. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._effect);
  30572. // Log. depth
  30573. BABYLON.MaterialHelper.BindLogDepth(this._defines, this._effect, scene);
  30574. // Color Curves
  30575. if (this.cameraColorCurves) {
  30576. BABYLON.ColorCurves.Bind(this.cameraColorCurves, this._effect);
  30577. }
  30578. }
  30579. _super.prototype.bind.call(this, world, mesh);
  30580. };
  30581. StandardMaterial.prototype.getAnimatables = function () {
  30582. var results = [];
  30583. if (this.diffuseTexture && this.diffuseTexture.animations && this.diffuseTexture.animations.length > 0) {
  30584. results.push(this.diffuseTexture);
  30585. }
  30586. if (this.ambientTexture && this.ambientTexture.animations && this.ambientTexture.animations.length > 0) {
  30587. results.push(this.ambientTexture);
  30588. }
  30589. if (this.opacityTexture && this.opacityTexture.animations && this.opacityTexture.animations.length > 0) {
  30590. results.push(this.opacityTexture);
  30591. }
  30592. if (this.reflectionTexture && this.reflectionTexture.animations && this.reflectionTexture.animations.length > 0) {
  30593. results.push(this.reflectionTexture);
  30594. }
  30595. if (this.emissiveTexture && this.emissiveTexture.animations && this.emissiveTexture.animations.length > 0) {
  30596. results.push(this.emissiveTexture);
  30597. }
  30598. if (this.specularTexture && this.specularTexture.animations && this.specularTexture.animations.length > 0) {
  30599. results.push(this.specularTexture);
  30600. }
  30601. if (this.bumpTexture && this.bumpTexture.animations && this.bumpTexture.animations.length > 0) {
  30602. results.push(this.bumpTexture);
  30603. }
  30604. if (this.lightmapTexture && this.lightmapTexture.animations && this.lightmapTexture.animations.length > 0) {
  30605. results.push(this.lightmapTexture);
  30606. }
  30607. if (this.refractionTexture && this.refractionTexture.animations && this.refractionTexture.animations.length > 0) {
  30608. results.push(this.refractionTexture);
  30609. }
  30610. if (this.cameraColorGradingTexture && this.cameraColorGradingTexture.animations && this.cameraColorGradingTexture.animations.length > 0) {
  30611. results.push(this.cameraColorGradingTexture);
  30612. }
  30613. return results;
  30614. };
  30615. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  30616. if (forceDisposeTextures) {
  30617. if (this.diffuseTexture) {
  30618. this.diffuseTexture.dispose();
  30619. }
  30620. if (this.ambientTexture) {
  30621. this.ambientTexture.dispose();
  30622. }
  30623. if (this.opacityTexture) {
  30624. this.opacityTexture.dispose();
  30625. }
  30626. if (this.reflectionTexture) {
  30627. this.reflectionTexture.dispose();
  30628. }
  30629. if (this.emissiveTexture) {
  30630. this.emissiveTexture.dispose();
  30631. }
  30632. if (this.specularTexture) {
  30633. this.specularTexture.dispose();
  30634. }
  30635. if (this.bumpTexture) {
  30636. this.bumpTexture.dispose();
  30637. }
  30638. if (this.lightmapTexture) {
  30639. this.lightmapTexture.dispose();
  30640. }
  30641. if (this.refractionTexture) {
  30642. this.refractionTexture.dispose();
  30643. }
  30644. if (this.cameraColorGradingTexture) {
  30645. this.cameraColorGradingTexture.dispose();
  30646. }
  30647. }
  30648. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  30649. };
  30650. StandardMaterial.prototype.clone = function (name) {
  30651. var _this = this;
  30652. return BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  30653. };
  30654. StandardMaterial.prototype.serialize = function () {
  30655. return BABYLON.SerializationHelper.Serialize(this);
  30656. };
  30657. // Statics
  30658. StandardMaterial.Parse = function (source, scene, rootUrl) {
  30659. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  30660. };
  30661. return StandardMaterial;
  30662. }(BABYLON.Material));
  30663. // Flags used to enable or disable a type of texture for all Standard Materials
  30664. StandardMaterial.DiffuseTextureEnabled = true;
  30665. StandardMaterial.AmbientTextureEnabled = true;
  30666. StandardMaterial.OpacityTextureEnabled = true;
  30667. StandardMaterial.ReflectionTextureEnabled = true;
  30668. StandardMaterial.EmissiveTextureEnabled = true;
  30669. StandardMaterial.SpecularTextureEnabled = true;
  30670. StandardMaterial.BumpTextureEnabled = true;
  30671. StandardMaterial.FresnelEnabled = true;
  30672. StandardMaterial.LightmapTextureEnabled = true;
  30673. StandardMaterial.RefractionTextureEnabled = true;
  30674. StandardMaterial.ColorGradingTextureEnabled = true;
  30675. __decorate([
  30676. BABYLON.serializeAsTexture()
  30677. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  30678. __decorate([
  30679. BABYLON.serializeAsTexture()
  30680. ], StandardMaterial.prototype, "ambientTexture", void 0);
  30681. __decorate([
  30682. BABYLON.serializeAsTexture()
  30683. ], StandardMaterial.prototype, "opacityTexture", void 0);
  30684. __decorate([
  30685. BABYLON.serializeAsTexture()
  30686. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  30687. __decorate([
  30688. BABYLON.serializeAsTexture()
  30689. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  30690. __decorate([
  30691. BABYLON.serializeAsTexture()
  30692. ], StandardMaterial.prototype, "specularTexture", void 0);
  30693. __decorate([
  30694. BABYLON.serializeAsTexture()
  30695. ], StandardMaterial.prototype, "bumpTexture", void 0);
  30696. __decorate([
  30697. BABYLON.serializeAsTexture()
  30698. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  30699. __decorate([
  30700. BABYLON.serializeAsTexture()
  30701. ], StandardMaterial.prototype, "refractionTexture", void 0);
  30702. __decorate([
  30703. BABYLON.serializeAsColor3("ambient")
  30704. ], StandardMaterial.prototype, "ambientColor", void 0);
  30705. __decorate([
  30706. BABYLON.serializeAsColor3("diffuse")
  30707. ], StandardMaterial.prototype, "diffuseColor", void 0);
  30708. __decorate([
  30709. BABYLON.serializeAsColor3("specular")
  30710. ], StandardMaterial.prototype, "specularColor", void 0);
  30711. __decorate([
  30712. BABYLON.serializeAsColor3("emissive")
  30713. ], StandardMaterial.prototype, "emissiveColor", void 0);
  30714. __decorate([
  30715. BABYLON.serialize()
  30716. ], StandardMaterial.prototype, "specularPower", void 0);
  30717. __decorate([
  30718. BABYLON.serialize()
  30719. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  30720. __decorate([
  30721. BABYLON.serialize()
  30722. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  30723. __decorate([
  30724. BABYLON.serialize()
  30725. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  30726. __decorate([
  30727. BABYLON.serialize()
  30728. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  30729. __decorate([
  30730. BABYLON.serialize()
  30731. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  30732. __decorate([
  30733. BABYLON.serialize()
  30734. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  30735. __decorate([
  30736. BABYLON.serialize()
  30737. ], StandardMaterial.prototype, "disableLighting", void 0);
  30738. __decorate([
  30739. BABYLON.serialize()
  30740. ], StandardMaterial.prototype, "useParallax", void 0);
  30741. __decorate([
  30742. BABYLON.serialize()
  30743. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  30744. __decorate([
  30745. BABYLON.serialize()
  30746. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  30747. __decorate([
  30748. BABYLON.serialize()
  30749. ], StandardMaterial.prototype, "roughness", void 0);
  30750. __decorate([
  30751. BABYLON.serialize()
  30752. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  30753. __decorate([
  30754. BABYLON.serialize()
  30755. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  30756. __decorate([
  30757. BABYLON.serialize()
  30758. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  30759. __decorate([
  30760. BABYLON.serializeAsFresnelParameters()
  30761. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  30762. __decorate([
  30763. BABYLON.serializeAsFresnelParameters()
  30764. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  30765. __decorate([
  30766. BABYLON.serializeAsFresnelParameters()
  30767. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  30768. __decorate([
  30769. BABYLON.serializeAsFresnelParameters()
  30770. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  30771. __decorate([
  30772. BABYLON.serializeAsFresnelParameters()
  30773. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  30774. __decorate([
  30775. BABYLON.serialize()
  30776. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  30777. __decorate([
  30778. BABYLON.serialize()
  30779. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  30780. __decorate([
  30781. BABYLON.serialize()
  30782. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  30783. __decorate([
  30784. BABYLON.serialize()
  30785. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  30786. __decorate([
  30787. BABYLON.serializeAsTexture()
  30788. ], StandardMaterial.prototype, "cameraColorGradingTexture", void 0);
  30789. __decorate([
  30790. BABYLON.serializeAsColorCurves()
  30791. ], StandardMaterial.prototype, "cameraColorCurves", void 0);
  30792. __decorate([
  30793. BABYLON.serialize()
  30794. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  30795. BABYLON.StandardMaterial = StandardMaterial;
  30796. })(BABYLON || (BABYLON = {}));
  30797. //# sourceMappingURL=babylon.standardMaterial.js.map
  30798. var BABYLON;
  30799. (function (BABYLON) {
  30800. var MultiMaterial = (function (_super) {
  30801. __extends(MultiMaterial, _super);
  30802. function MultiMaterial(name, scene) {
  30803. var _this = _super.call(this, name, scene, true) || this;
  30804. _this.subMaterials = new Array();
  30805. scene.multiMaterials.push(_this);
  30806. return _this;
  30807. }
  30808. // Properties
  30809. MultiMaterial.prototype.getSubMaterial = function (index) {
  30810. if (index < 0 || index >= this.subMaterials.length) {
  30811. return this.getScene().defaultMaterial;
  30812. }
  30813. return this.subMaterials[index];
  30814. };
  30815. // Methods
  30816. MultiMaterial.prototype.getClassName = function () {
  30817. return "MultiMaterial";
  30818. };
  30819. MultiMaterial.prototype.isReady = function (mesh) {
  30820. for (var index = 0; index < this.subMaterials.length; index++) {
  30821. var subMaterial = this.subMaterials[index];
  30822. if (subMaterial) {
  30823. if (!this.subMaterials[index].isReady(mesh)) {
  30824. return false;
  30825. }
  30826. }
  30827. }
  30828. return true;
  30829. };
  30830. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  30831. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  30832. for (var index = 0; index < this.subMaterials.length; index++) {
  30833. var subMaterial = null;
  30834. if (cloneChildren) {
  30835. subMaterial = this.subMaterials[index].clone(name + "-" + this.subMaterials[index].name);
  30836. }
  30837. else {
  30838. subMaterial = this.subMaterials[index];
  30839. }
  30840. newMultiMaterial.subMaterials.push(subMaterial);
  30841. }
  30842. return newMultiMaterial;
  30843. };
  30844. MultiMaterial.prototype.serialize = function () {
  30845. var serializationObject = {};
  30846. serializationObject.name = this.name;
  30847. serializationObject.id = this.id;
  30848. serializationObject.tags = BABYLON.Tags.GetTags(this);
  30849. serializationObject.materials = [];
  30850. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  30851. var subMat = this.subMaterials[matIndex];
  30852. if (subMat) {
  30853. serializationObject.materials.push(subMat.id);
  30854. }
  30855. else {
  30856. serializationObject.materials.push(null);
  30857. }
  30858. }
  30859. return serializationObject;
  30860. };
  30861. return MultiMaterial;
  30862. }(BABYLON.Material));
  30863. BABYLON.MultiMaterial = MultiMaterial;
  30864. })(BABYLON || (BABYLON = {}));
  30865. //# sourceMappingURL=babylon.multiMaterial.js.map
  30866. var BABYLON;
  30867. (function (BABYLON) {
  30868. var SceneLoader = (function () {
  30869. function SceneLoader() {
  30870. }
  30871. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  30872. get: function () {
  30873. return 0;
  30874. },
  30875. enumerable: true,
  30876. configurable: true
  30877. });
  30878. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  30879. get: function () {
  30880. return 1;
  30881. },
  30882. enumerable: true,
  30883. configurable: true
  30884. });
  30885. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  30886. get: function () {
  30887. return 2;
  30888. },
  30889. enumerable: true,
  30890. configurable: true
  30891. });
  30892. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  30893. get: function () {
  30894. return 3;
  30895. },
  30896. enumerable: true,
  30897. configurable: true
  30898. });
  30899. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  30900. get: function () {
  30901. return SceneLoader._ForceFullSceneLoadingForIncremental;
  30902. },
  30903. set: function (value) {
  30904. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  30905. },
  30906. enumerable: true,
  30907. configurable: true
  30908. });
  30909. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  30910. get: function () {
  30911. return SceneLoader._ShowLoadingScreen;
  30912. },
  30913. set: function (value) {
  30914. SceneLoader._ShowLoadingScreen = value;
  30915. },
  30916. enumerable: true,
  30917. configurable: true
  30918. });
  30919. Object.defineProperty(SceneLoader, "loggingLevel", {
  30920. get: function () {
  30921. return SceneLoader._loggingLevel;
  30922. },
  30923. set: function (value) {
  30924. SceneLoader._loggingLevel = value;
  30925. },
  30926. enumerable: true,
  30927. configurable: true
  30928. });
  30929. SceneLoader._getDefaultPlugin = function () {
  30930. return SceneLoader._registeredPlugins[".babylon"];
  30931. };
  30932. SceneLoader._getPluginForExtension = function (extension) {
  30933. var registeredPlugin = SceneLoader._registeredPlugins[extension];
  30934. if (registeredPlugin) {
  30935. return registeredPlugin;
  30936. }
  30937. return SceneLoader._getDefaultPlugin();
  30938. };
  30939. SceneLoader._getPluginForFilename = function (sceneFilename) {
  30940. if (sceneFilename.name) {
  30941. sceneFilename = sceneFilename.name;
  30942. }
  30943. var dotPosition = sceneFilename.lastIndexOf(".");
  30944. var queryStringPosition = sceneFilename.indexOf("?");
  30945. if (queryStringPosition === -1) {
  30946. queryStringPosition = sceneFilename.length;
  30947. }
  30948. var extension = sceneFilename.substring(dotPosition, queryStringPosition).toLowerCase();
  30949. return SceneLoader._getPluginForExtension(extension);
  30950. };
  30951. // use babylon file loader directly if sceneFilename is prefixed with "data:"
  30952. SceneLoader._getDirectLoad = function (sceneFilename) {
  30953. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  30954. return sceneFilename.substr(5);
  30955. }
  30956. return null;
  30957. };
  30958. // Public functions
  30959. SceneLoader.GetPluginForExtension = function (extension) {
  30960. return SceneLoader._getPluginForExtension(extension).plugin;
  30961. };
  30962. SceneLoader.RegisterPlugin = function (plugin) {
  30963. if (typeof plugin.extensions === "string") {
  30964. var extension = plugin.extensions;
  30965. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  30966. plugin: plugin,
  30967. isBinary: false
  30968. };
  30969. }
  30970. else {
  30971. var extensions = plugin.extensions;
  30972. Object.keys(extensions).forEach(function (extension) {
  30973. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  30974. plugin: plugin,
  30975. isBinary: extensions[extension].isBinary
  30976. };
  30977. });
  30978. }
  30979. };
  30980. SceneLoader.ImportMesh = function (meshesNames, rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  30981. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  30982. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  30983. return;
  30984. }
  30985. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  30986. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  30987. return;
  30988. }
  30989. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  30990. var loadingToken = {};
  30991. scene._addPendingData(loadingToken);
  30992. var manifestChecked = function (success) {
  30993. scene.database = database;
  30994. var registeredPlugin = directLoad ? SceneLoader._getDefaultPlugin() : SceneLoader._getPluginForFilename(sceneFilename);
  30995. var plugin = registeredPlugin.plugin;
  30996. var useArrayBuffer = registeredPlugin.isBinary;
  30997. var importMeshFromData = function (data) {
  30998. var meshes = [];
  30999. var particleSystems = [];
  31000. var skeletons = [];
  31001. try {
  31002. if (plugin.importMesh) {
  31003. var syncedPlugin = plugin;
  31004. if (!syncedPlugin.importMesh(meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons)) {
  31005. if (onerror) {
  31006. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename);
  31007. }
  31008. scene._removePendingData(loadingToken);
  31009. return;
  31010. }
  31011. if (onsuccess) {
  31012. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  31013. onsuccess(meshes, particleSystems, skeletons);
  31014. scene._removePendingData(loadingToken);
  31015. }
  31016. }
  31017. else {
  31018. var asyncedPlugin = plugin;
  31019. asyncedPlugin.importMeshAsync(meshesNames, scene, data, rootUrl, function (meshes, particleSystems, skeletons) {
  31020. if (onsuccess) {
  31021. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  31022. onsuccess(meshes, particleSystems, skeletons);
  31023. scene._removePendingData(loadingToken);
  31024. }
  31025. }, function () {
  31026. if (onerror) {
  31027. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename);
  31028. }
  31029. scene._removePendingData(loadingToken);
  31030. });
  31031. }
  31032. }
  31033. catch (e) {
  31034. if (onerror) {
  31035. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename, e);
  31036. }
  31037. scene._removePendingData(loadingToken);
  31038. }
  31039. };
  31040. if (directLoad) {
  31041. importMeshFromData(directLoad);
  31042. return;
  31043. }
  31044. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, function (data) {
  31045. importMeshFromData(data);
  31046. }, progressCallBack, database, useArrayBuffer, function () {
  31047. if (onerror) {
  31048. onerror(scene, 'Unable to load file ' + rootUrl + sceneFilename);
  31049. }
  31050. });
  31051. };
  31052. if (scene.getEngine().enableOfflineSupport && !directLoad) {
  31053. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  31054. var database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  31055. }
  31056. else {
  31057. // If the scene is a data stream or offline support is not enabled, it's a direct load
  31058. manifestChecked(true);
  31059. }
  31060. };
  31061. /**
  31062. * Load a scene
  31063. * @param rootUrl a string that defines the root url for scene and resources
  31064. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  31065. * @param engine is the instance of BABYLON.Engine to use to create the scene
  31066. */
  31067. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onsuccess, progressCallBack, onerror) {
  31068. SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onsuccess, progressCallBack, onerror);
  31069. };
  31070. /**
  31071. * Append a scene
  31072. * @param rootUrl a string that defines the root url for scene and resources
  31073. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  31074. * @param scene is the instance of BABYLON.Scene to append to
  31075. */
  31076. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  31077. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  31078. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  31079. return;
  31080. }
  31081. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  31082. var registeredPlugin = directLoad ? SceneLoader._getDefaultPlugin() : SceneLoader._getPluginForFilename(sceneFilename);
  31083. var plugin = registeredPlugin.plugin;
  31084. var useArrayBuffer = registeredPlugin.isBinary;
  31085. var database;
  31086. var loadingToken = {};
  31087. scene._addPendingData(loadingToken);
  31088. if (SceneLoader.ShowLoadingScreen) {
  31089. scene.getEngine().displayLoadingUI();
  31090. }
  31091. var loadSceneFromData = function (data) {
  31092. scene.database = database;
  31093. if (plugin.load) {
  31094. var syncedPlugin = plugin;
  31095. if (!syncedPlugin.load(scene, data, rootUrl)) {
  31096. if (onerror) {
  31097. onerror(scene);
  31098. }
  31099. scene._removePendingData(loadingToken);
  31100. scene.getEngine().hideLoadingUI();
  31101. return;
  31102. }
  31103. if (onsuccess) {
  31104. onsuccess(scene);
  31105. }
  31106. scene._removePendingData(loadingToken);
  31107. }
  31108. else {
  31109. var asyncedPlugin = plugin;
  31110. asyncedPlugin.loadAsync(scene, data, rootUrl, function () {
  31111. if (onsuccess) {
  31112. onsuccess(scene);
  31113. }
  31114. scene._removePendingData(loadingToken);
  31115. }, function () {
  31116. if (onerror) {
  31117. onerror(scene);
  31118. }
  31119. scene._removePendingData(loadingToken);
  31120. scene.getEngine().hideLoadingUI();
  31121. });
  31122. }
  31123. if (SceneLoader.ShowLoadingScreen) {
  31124. scene.executeWhenReady(function () {
  31125. scene.getEngine().hideLoadingUI();
  31126. });
  31127. }
  31128. };
  31129. var manifestChecked = function (success) {
  31130. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, loadSceneFromData, progressCallBack, database, useArrayBuffer);
  31131. };
  31132. if (directLoad) {
  31133. loadSceneFromData(directLoad);
  31134. return;
  31135. }
  31136. if (rootUrl.indexOf("file:") === -1) {
  31137. if (scene.getEngine().enableOfflineSupport) {
  31138. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  31139. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  31140. }
  31141. else {
  31142. manifestChecked(true);
  31143. }
  31144. }
  31145. else {
  31146. BABYLON.Tools.ReadFile(sceneFilename, loadSceneFromData, progressCallBack, useArrayBuffer);
  31147. }
  31148. };
  31149. return SceneLoader;
  31150. }());
  31151. // Flags
  31152. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  31153. SceneLoader._ShowLoadingScreen = true;
  31154. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  31155. // Members
  31156. SceneLoader._registeredPlugins = {};
  31157. BABYLON.SceneLoader = SceneLoader;
  31158. ;
  31159. })(BABYLON || (BABYLON = {}));
  31160. //# sourceMappingURL=babylon.sceneLoader.js.map
  31161. var BABYLON;
  31162. (function (BABYLON) {
  31163. var Internals;
  31164. (function (Internals) {
  31165. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  31166. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  31167. var parsedMaterial = parsedData.materials[index];
  31168. if (parsedMaterial.id === id) {
  31169. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  31170. }
  31171. }
  31172. return null;
  31173. };
  31174. var isDescendantOf = function (mesh, names, hierarchyIds) {
  31175. names = (names instanceof Array) ? names : [names];
  31176. for (var i in names) {
  31177. if (mesh.name === names[i]) {
  31178. hierarchyIds.push(mesh.id);
  31179. return true;
  31180. }
  31181. }
  31182. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  31183. hierarchyIds.push(mesh.id);
  31184. return true;
  31185. }
  31186. return false;
  31187. };
  31188. var logOperation = function (operation, producer) {
  31189. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  31190. };
  31191. BABYLON.SceneLoader.RegisterPlugin({
  31192. extensions: ".babylon",
  31193. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
  31194. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  31195. // when SceneLoader.debugLogging = true (default), or exception encountered.
  31196. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  31197. // and avoid problems with multiple concurrent .babylon loads.
  31198. var log = "importMesh has failed JSON parse";
  31199. try {
  31200. var parsedData = JSON.parse(data);
  31201. log = "";
  31202. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  31203. var loadedSkeletonsIds = [];
  31204. var loadedMaterialsIds = [];
  31205. var hierarchyIds = [];
  31206. var index;
  31207. var cache;
  31208. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  31209. var parsedMesh = parsedData.meshes[index];
  31210. if (!meshesNames || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  31211. if (meshesNames instanceof Array) {
  31212. // Remove found mesh name from list.
  31213. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  31214. }
  31215. //Geometry?
  31216. if (parsedMesh.geometryId) {
  31217. //does the file contain geometries?
  31218. if (parsedData.geometries) {
  31219. //find the correct geometry and add it to the scene
  31220. var found = false;
  31221. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  31222. if (found || !parsedData.geometries[geometryType] || !(parsedData.geometries[geometryType] instanceof Array)) {
  31223. return;
  31224. }
  31225. else {
  31226. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  31227. if (parsedGeometryData.id === parsedMesh.geometryId) {
  31228. switch (geometryType) {
  31229. case "boxes":
  31230. BABYLON.Geometry.Primitives.Box.Parse(parsedGeometryData, scene);
  31231. break;
  31232. case "spheres":
  31233. BABYLON.Geometry.Primitives.Sphere.Parse(parsedGeometryData, scene);
  31234. break;
  31235. case "cylinders":
  31236. BABYLON.Geometry.Primitives.Cylinder.Parse(parsedGeometryData, scene);
  31237. break;
  31238. case "toruses":
  31239. BABYLON.Geometry.Primitives.Torus.Parse(parsedGeometryData, scene);
  31240. break;
  31241. case "grounds":
  31242. BABYLON.Geometry.Primitives.Ground.Parse(parsedGeometryData, scene);
  31243. break;
  31244. case "planes":
  31245. BABYLON.Geometry.Primitives.Plane.Parse(parsedGeometryData, scene);
  31246. break;
  31247. case "torusKnots":
  31248. BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedGeometryData, scene);
  31249. break;
  31250. case "vertexData":
  31251. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  31252. break;
  31253. }
  31254. found = true;
  31255. }
  31256. });
  31257. }
  31258. });
  31259. if (!found) {
  31260. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  31261. }
  31262. }
  31263. }
  31264. // Material ?
  31265. if (parsedMesh.materialId) {
  31266. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  31267. if (!materialFound && parsedData.multiMaterials) {
  31268. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  31269. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  31270. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  31271. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  31272. var subMatId = parsedMultiMaterial.materials[matIndex];
  31273. loadedMaterialsIds.push(subMatId);
  31274. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  31275. log += "\n\tMaterial " + mat.toString(fullDetails);
  31276. }
  31277. loadedMaterialsIds.push(parsedMultiMaterial.id);
  31278. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  31279. materialFound = true;
  31280. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  31281. break;
  31282. }
  31283. }
  31284. }
  31285. if (!materialFound) {
  31286. loadedMaterialsIds.push(parsedMesh.materialId);
  31287. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  31288. if (!mat) {
  31289. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  31290. }
  31291. else {
  31292. log += "\n\tMaterial " + mat.toString(fullDetails);
  31293. }
  31294. }
  31295. }
  31296. // Skeleton ?
  31297. if (parsedMesh.skeletonId > -1 && scene.skeletons) {
  31298. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  31299. if (!skeletonAlreadyLoaded) {
  31300. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  31301. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  31302. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  31303. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  31304. skeletons.push(skeleton);
  31305. loadedSkeletonsIds.push(parsedSkeleton.id);
  31306. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  31307. }
  31308. }
  31309. }
  31310. }
  31311. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  31312. meshes.push(mesh);
  31313. log += "\n\tMesh " + mesh.toString(fullDetails);
  31314. }
  31315. }
  31316. // Connecting parents
  31317. var currentMesh;
  31318. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  31319. currentMesh = scene.meshes[index];
  31320. if (currentMesh._waitingParentId) {
  31321. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  31322. currentMesh._waitingParentId = undefined;
  31323. }
  31324. }
  31325. // freeze and compute world matrix application
  31326. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  31327. currentMesh = scene.meshes[index];
  31328. if (currentMesh._waitingFreezeWorldMatrix) {
  31329. currentMesh.freezeWorldMatrix();
  31330. currentMesh._waitingFreezeWorldMatrix = undefined;
  31331. }
  31332. else {
  31333. currentMesh.computeWorldMatrix(true);
  31334. }
  31335. }
  31336. // Particles
  31337. if (parsedData.particleSystems) {
  31338. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  31339. var parsedParticleSystem = parsedData.particleSystems[index];
  31340. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  31341. particleSystems.push(BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl));
  31342. }
  31343. }
  31344. }
  31345. return true;
  31346. }
  31347. catch (err) {
  31348. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log);
  31349. log = null;
  31350. throw err;
  31351. }
  31352. finally {
  31353. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  31354. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  31355. }
  31356. }
  31357. },
  31358. load: function (scene, data, rootUrl) {
  31359. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  31360. // when SceneLoader.debugLogging = true (default), or exception encountered.
  31361. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  31362. // and avoid problems with multiple concurrent .babylon loads.
  31363. var log = "importScene has failed JSON parse";
  31364. try {
  31365. var parsedData = JSON.parse(data);
  31366. log = "";
  31367. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  31368. // Scene
  31369. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  31370. scene.autoClear = parsedData.autoClear;
  31371. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  31372. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  31373. if (parsedData.gravity) {
  31374. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  31375. }
  31376. // Fog
  31377. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  31378. scene.fogMode = parsedData.fogMode;
  31379. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  31380. scene.fogStart = parsedData.fogStart;
  31381. scene.fogEnd = parsedData.fogEnd;
  31382. scene.fogDensity = parsedData.fogDensity;
  31383. log += "\tFog mode for scene: ";
  31384. switch (scene.fogMode) {
  31385. // getters not compiling, so using hardcoded
  31386. case 1:
  31387. log += "exp\n";
  31388. break;
  31389. case 2:
  31390. log += "exp2\n";
  31391. break;
  31392. case 3:
  31393. log += "linear\n";
  31394. break;
  31395. }
  31396. }
  31397. //Physics
  31398. if (parsedData.physicsEnabled) {
  31399. var physicsPlugin;
  31400. if (parsedData.physicsEngine === "cannon") {
  31401. physicsPlugin = new BABYLON.CannonJSPlugin();
  31402. }
  31403. else if (parsedData.physicsEngine === "oimo") {
  31404. physicsPlugin = new BABYLON.OimoJSPlugin();
  31405. }
  31406. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  31407. //else - default engine, which is currently oimo
  31408. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  31409. scene.enablePhysics(physicsGravity, physicsPlugin);
  31410. }
  31411. // Metadata
  31412. if (parsedData.metadata !== undefined) {
  31413. scene.metadata = parsedData.metadata;
  31414. }
  31415. //collisions, if defined. otherwise, default is true
  31416. if (parsedData.collisionsEnabled != undefined) {
  31417. scene.collisionsEnabled = parsedData.collisionsEnabled;
  31418. }
  31419. scene.workerCollisions = !!parsedData.workerCollisions;
  31420. var index;
  31421. var cache;
  31422. // Lights
  31423. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  31424. var parsedLight = parsedData.lights[index];
  31425. var light = BABYLON.Light.Parse(parsedLight, scene);
  31426. log += (index === 0 ? "\n\tLights:" : "");
  31427. log += "\n\t\t" + light.toString(fullDetails);
  31428. }
  31429. // Animations
  31430. if (parsedData.animations) {
  31431. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  31432. var parsedAnimation = parsedData.animations[index];
  31433. var animation = BABYLON.Animation.Parse(parsedAnimation);
  31434. scene.animations.push(animation);
  31435. log += (index === 0 ? "\n\tAnimations:" : "");
  31436. log += "\n\t\t" + animation.toString(fullDetails);
  31437. }
  31438. }
  31439. if (parsedData.autoAnimate) {
  31440. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  31441. }
  31442. // Materials
  31443. if (parsedData.materials) {
  31444. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  31445. var parsedMaterial = parsedData.materials[index];
  31446. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  31447. log += (index === 0 ? "\n\tMaterials:" : "");
  31448. log += "\n\t\t" + mat.toString(fullDetails);
  31449. }
  31450. }
  31451. if (parsedData.multiMaterials) {
  31452. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  31453. var parsedMultiMaterial = parsedData.multiMaterials[index];
  31454. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  31455. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  31456. log += "\n\t\t" + mmat.toString(fullDetails);
  31457. }
  31458. }
  31459. // Skeletons
  31460. if (parsedData.skeletons) {
  31461. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  31462. var parsedSkeleton = parsedData.skeletons[index];
  31463. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  31464. log += (index === 0 ? "\n\tSkeletons:" : "");
  31465. log += "\n\t\t" + skeleton.toString(fullDetails);
  31466. }
  31467. }
  31468. // Geometries
  31469. var geometries = parsedData.geometries;
  31470. if (geometries) {
  31471. // Boxes
  31472. var boxes = geometries.boxes;
  31473. if (boxes) {
  31474. for (index = 0, cache = boxes.length; index < cache; index++) {
  31475. var parsedBox = boxes[index];
  31476. BABYLON.Geometry.Primitives.Box.Parse(parsedBox, scene);
  31477. }
  31478. }
  31479. // Spheres
  31480. var spheres = geometries.spheres;
  31481. if (spheres) {
  31482. for (index = 0, cache = spheres.length; index < cache; index++) {
  31483. var parsedSphere = spheres[index];
  31484. BABYLON.Geometry.Primitives.Sphere.Parse(parsedSphere, scene);
  31485. }
  31486. }
  31487. // Cylinders
  31488. var cylinders = geometries.cylinders;
  31489. if (cylinders) {
  31490. for (index = 0, cache = cylinders.length; index < cache; index++) {
  31491. var parsedCylinder = cylinders[index];
  31492. BABYLON.Geometry.Primitives.Cylinder.Parse(parsedCylinder, scene);
  31493. }
  31494. }
  31495. // Toruses
  31496. var toruses = geometries.toruses;
  31497. if (toruses) {
  31498. for (index = 0, cache = toruses.length; index < cache; index++) {
  31499. var parsedTorus = toruses[index];
  31500. BABYLON.Geometry.Primitives.Torus.Parse(parsedTorus, scene);
  31501. }
  31502. }
  31503. // Grounds
  31504. var grounds = geometries.grounds;
  31505. if (grounds) {
  31506. for (index = 0, cache = grounds.length; index < cache; index++) {
  31507. var parsedGround = grounds[index];
  31508. BABYLON.Geometry.Primitives.Ground.Parse(parsedGround, scene);
  31509. }
  31510. }
  31511. // Planes
  31512. var planes = geometries.planes;
  31513. if (planes) {
  31514. for (index = 0, cache = planes.length; index < cache; index++) {
  31515. var parsedPlane = planes[index];
  31516. BABYLON.Geometry.Primitives.Plane.Parse(parsedPlane, scene);
  31517. }
  31518. }
  31519. // TorusKnots
  31520. var torusKnots = geometries.torusKnots;
  31521. if (torusKnots) {
  31522. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  31523. var parsedTorusKnot = torusKnots[index];
  31524. BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedTorusKnot, scene);
  31525. }
  31526. }
  31527. // VertexData
  31528. var vertexData = geometries.vertexData;
  31529. if (vertexData) {
  31530. for (index = 0, cache = vertexData.length; index < cache; index++) {
  31531. var parsedVertexData = vertexData[index];
  31532. BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl);
  31533. }
  31534. }
  31535. }
  31536. // Meshes
  31537. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  31538. var parsedMesh = parsedData.meshes[index];
  31539. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  31540. log += (index === 0 ? "\n\tMeshes:" : "");
  31541. log += "\n\t\t" + mesh.toString(fullDetails);
  31542. }
  31543. // Cameras
  31544. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  31545. var parsedCamera = parsedData.cameras[index];
  31546. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  31547. log += (index === 0 ? "\n\tCameras:" : "");
  31548. log += "\n\t\t" + camera.toString(fullDetails);
  31549. }
  31550. if (parsedData.activeCameraID) {
  31551. scene.setActiveCameraByID(parsedData.activeCameraID);
  31552. }
  31553. // Browsing all the graph to connect the dots
  31554. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  31555. var camera = scene.cameras[index];
  31556. if (camera._waitingParentId) {
  31557. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  31558. camera._waitingParentId = undefined;
  31559. }
  31560. }
  31561. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  31562. var light = scene.lights[index];
  31563. if (light._waitingParentId) {
  31564. light.parent = scene.getLastEntryByID(light._waitingParentId);
  31565. light._waitingParentId = undefined;
  31566. }
  31567. }
  31568. // Sounds
  31569. var loadedSounds = [];
  31570. var loadedSound;
  31571. if (BABYLON.AudioEngine && parsedData.sounds) {
  31572. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  31573. var parsedSound = parsedData.sounds[index];
  31574. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  31575. if (!parsedSound.url)
  31576. parsedSound.url = parsedSound.name;
  31577. if (!loadedSounds[parsedSound.url]) {
  31578. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  31579. loadedSounds[parsedSound.url] = loadedSound;
  31580. }
  31581. else {
  31582. BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]);
  31583. }
  31584. }
  31585. else {
  31586. var emptySound = new BABYLON.Sound(parsedSound.name, null, scene);
  31587. }
  31588. }
  31589. }
  31590. loadedSounds = [];
  31591. // Connect parents & children and parse actions
  31592. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  31593. var mesh = scene.meshes[index];
  31594. if (mesh._waitingParentId) {
  31595. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  31596. mesh._waitingParentId = undefined;
  31597. }
  31598. if (mesh._waitingActions) {
  31599. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  31600. mesh._waitingActions = undefined;
  31601. }
  31602. }
  31603. // freeze world matrix application
  31604. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  31605. var currentMesh = scene.meshes[index];
  31606. if (currentMesh._waitingFreezeWorldMatrix) {
  31607. currentMesh.freezeWorldMatrix();
  31608. currentMesh._waitingFreezeWorldMatrix = undefined;
  31609. }
  31610. else {
  31611. currentMesh.computeWorldMatrix(true);
  31612. }
  31613. }
  31614. // Particles Systems
  31615. if (parsedData.particleSystems) {
  31616. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  31617. var parsedParticleSystem = parsedData.particleSystems[index];
  31618. BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  31619. }
  31620. }
  31621. // Lens flares
  31622. if (parsedData.lensFlareSystems) {
  31623. for (index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  31624. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  31625. BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  31626. }
  31627. }
  31628. // Shadows
  31629. if (parsedData.shadowGenerators) {
  31630. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  31631. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  31632. BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  31633. }
  31634. }
  31635. // Actions (scene)
  31636. if (parsedData.actions) {
  31637. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  31638. }
  31639. // Finish
  31640. return true;
  31641. }
  31642. catch (err) {
  31643. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log);
  31644. log = null;
  31645. throw err;
  31646. }
  31647. finally {
  31648. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  31649. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  31650. }
  31651. }
  31652. }
  31653. });
  31654. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  31655. })(BABYLON || (BABYLON = {}));
  31656. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  31657. var BABYLON;
  31658. (function (BABYLON) {
  31659. var SpriteManager = (function () {
  31660. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  31661. if (epsilon === void 0) { epsilon = 0.01; }
  31662. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  31663. this.name = name;
  31664. this.sprites = new Array();
  31665. this.renderingGroupId = 0;
  31666. this.layerMask = 0x0FFFFFFF;
  31667. this.fogEnabled = true;
  31668. this.isPickable = false;
  31669. /**
  31670. * An event triggered when the manager is disposed.
  31671. * @type {BABYLON.Observable}
  31672. */
  31673. this.onDisposeObservable = new BABYLON.Observable();
  31674. this._vertexBuffers = {};
  31675. this._capacity = capacity;
  31676. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  31677. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  31678. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  31679. if (cellSize.width && cellSize.height) {
  31680. this.cellWidth = cellSize.width;
  31681. this.cellHeight = cellSize.height;
  31682. }
  31683. else if (cellSize !== undefined) {
  31684. this.cellWidth = cellSize;
  31685. this.cellHeight = cellSize;
  31686. }
  31687. else {
  31688. return;
  31689. }
  31690. this._epsilon = epsilon;
  31691. this._scene = scene;
  31692. this._scene.spriteManagers.push(this);
  31693. var indices = [];
  31694. var index = 0;
  31695. for (var count = 0; count < capacity; count++) {
  31696. indices.push(index);
  31697. indices.push(index + 1);
  31698. indices.push(index + 2);
  31699. indices.push(index);
  31700. indices.push(index + 2);
  31701. indices.push(index + 3);
  31702. index += 4;
  31703. }
  31704. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  31705. // VBO
  31706. // 16 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color r, color g, color b, color a)
  31707. this._vertexData = new Float32Array(capacity * 16 * 4);
  31708. this._buffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 16);
  31709. var positions = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 4);
  31710. var options = this._buffer.createVertexBuffer("options", 4, 4);
  31711. var cellInfo = this._buffer.createVertexBuffer("cellInfo", 8, 4);
  31712. var colors = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 12, 4);
  31713. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  31714. this._vertexBuffers["options"] = options;
  31715. this._vertexBuffers["cellInfo"] = cellInfo;
  31716. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  31717. // Effects
  31718. this._effectBase = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  31719. this._effectFog = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  31720. }
  31721. Object.defineProperty(SpriteManager.prototype, "onDispose", {
  31722. set: function (callback) {
  31723. if (this._onDisposeObserver) {
  31724. this.onDisposeObservable.remove(this._onDisposeObserver);
  31725. }
  31726. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  31727. },
  31728. enumerable: true,
  31729. configurable: true
  31730. });
  31731. Object.defineProperty(SpriteManager.prototype, "texture", {
  31732. get: function () {
  31733. return this._spriteTexture;
  31734. },
  31735. set: function (value) {
  31736. this._spriteTexture = value;
  31737. },
  31738. enumerable: true,
  31739. configurable: true
  31740. });
  31741. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  31742. var arrayOffset = index * 16;
  31743. if (offsetX === 0)
  31744. offsetX = this._epsilon;
  31745. else if (offsetX === 1)
  31746. offsetX = 1 - this._epsilon;
  31747. if (offsetY === 0)
  31748. offsetY = this._epsilon;
  31749. else if (offsetY === 1)
  31750. offsetY = 1 - this._epsilon;
  31751. this._vertexData[arrayOffset] = sprite.position.x;
  31752. this._vertexData[arrayOffset + 1] = sprite.position.y;
  31753. this._vertexData[arrayOffset + 2] = sprite.position.z;
  31754. this._vertexData[arrayOffset + 3] = sprite.angle;
  31755. this._vertexData[arrayOffset + 4] = sprite.width;
  31756. this._vertexData[arrayOffset + 5] = sprite.height;
  31757. this._vertexData[arrayOffset + 6] = offsetX;
  31758. this._vertexData[arrayOffset + 7] = offsetY;
  31759. this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  31760. this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  31761. var offset = (sprite.cellIndex / rowSize) >> 0;
  31762. this._vertexData[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  31763. this._vertexData[arrayOffset + 11] = offset;
  31764. // Color
  31765. this._vertexData[arrayOffset + 12] = sprite.color.r;
  31766. this._vertexData[arrayOffset + 13] = sprite.color.g;
  31767. this._vertexData[arrayOffset + 14] = sprite.color.b;
  31768. this._vertexData[arrayOffset + 15] = sprite.color.a;
  31769. };
  31770. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  31771. var count = Math.min(this._capacity, this.sprites.length);
  31772. var min = BABYLON.Vector3.Zero();
  31773. var max = BABYLON.Vector3.Zero();
  31774. var distance = Number.MAX_VALUE;
  31775. var currentSprite;
  31776. var cameraSpacePosition = BABYLON.Vector3.Zero();
  31777. var cameraView = camera.getViewMatrix();
  31778. for (var index = 0; index < count; index++) {
  31779. var sprite = this.sprites[index];
  31780. if (!sprite) {
  31781. continue;
  31782. }
  31783. if (predicate) {
  31784. if (!predicate(sprite)) {
  31785. continue;
  31786. }
  31787. }
  31788. else if (!sprite.isPickable) {
  31789. continue;
  31790. }
  31791. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  31792. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  31793. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  31794. if (ray.intersectsBoxMinMax(min, max)) {
  31795. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  31796. if (distance > currentDistance) {
  31797. distance = currentDistance;
  31798. currentSprite = sprite;
  31799. if (fastCheck) {
  31800. break;
  31801. }
  31802. }
  31803. }
  31804. }
  31805. if (currentSprite) {
  31806. var result = new BABYLON.PickingInfo();
  31807. result.hit = true;
  31808. result.pickedSprite = currentSprite;
  31809. result.distance = distance;
  31810. return result;
  31811. }
  31812. return null;
  31813. };
  31814. SpriteManager.prototype.render = function () {
  31815. // Check
  31816. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  31817. return;
  31818. var engine = this._scene.getEngine();
  31819. var baseSize = this._spriteTexture.getBaseSize();
  31820. // Sprites
  31821. var deltaTime = engine.getDeltaTime();
  31822. var max = Math.min(this._capacity, this.sprites.length);
  31823. var rowSize = baseSize.width / this.cellWidth;
  31824. var offset = 0;
  31825. for (var index = 0; index < max; index++) {
  31826. var sprite = this.sprites[index];
  31827. if (!sprite) {
  31828. continue;
  31829. }
  31830. sprite._animate(deltaTime);
  31831. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  31832. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  31833. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  31834. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  31835. }
  31836. this._buffer.update(this._vertexData);
  31837. // Render
  31838. var effect = this._effectBase;
  31839. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  31840. effect = this._effectFog;
  31841. }
  31842. engine.enableEffect(effect);
  31843. var viewMatrix = this._scene.getViewMatrix();
  31844. effect.setTexture("diffuseSampler", this._spriteTexture);
  31845. effect.setMatrix("view", viewMatrix);
  31846. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  31847. effect.setFloat2("textureInfos", this.cellWidth / baseSize.width, this.cellHeight / baseSize.height);
  31848. // Fog
  31849. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  31850. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  31851. effect.setColor3("vFogColor", this._scene.fogColor);
  31852. }
  31853. // VBOs
  31854. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  31855. // Draw order
  31856. engine.setDepthFunctionToLessOrEqual();
  31857. effect.setBool("alphaTest", true);
  31858. engine.setColorWrite(false);
  31859. engine.draw(true, 0, max * 6);
  31860. engine.setColorWrite(true);
  31861. effect.setBool("alphaTest", false);
  31862. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  31863. engine.draw(true, 0, max * 6);
  31864. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  31865. };
  31866. SpriteManager.prototype.dispose = function () {
  31867. if (this._buffer) {
  31868. this._buffer.dispose();
  31869. this._buffer = null;
  31870. }
  31871. if (this._indexBuffer) {
  31872. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  31873. this._indexBuffer = null;
  31874. }
  31875. if (this._spriteTexture) {
  31876. this._spriteTexture.dispose();
  31877. this._spriteTexture = null;
  31878. }
  31879. // Remove from scene
  31880. var index = this._scene.spriteManagers.indexOf(this);
  31881. this._scene.spriteManagers.splice(index, 1);
  31882. // Callback
  31883. this.onDisposeObservable.notifyObservers(this);
  31884. this.onDisposeObservable.clear();
  31885. };
  31886. return SpriteManager;
  31887. }());
  31888. BABYLON.SpriteManager = SpriteManager;
  31889. })(BABYLON || (BABYLON = {}));
  31890. //# sourceMappingURL=babylon.spriteManager.js.map
  31891. var BABYLON;
  31892. (function (BABYLON) {
  31893. var Sprite = (function () {
  31894. function Sprite(name, manager) {
  31895. this.name = name;
  31896. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  31897. this.width = 1.0;
  31898. this.height = 1.0;
  31899. this.angle = 0;
  31900. this.cellIndex = 0;
  31901. this.invertU = 0;
  31902. this.invertV = 0;
  31903. this.animations = new Array();
  31904. this.isPickable = false;
  31905. this._animationStarted = false;
  31906. this._loopAnimation = false;
  31907. this._fromIndex = 0;
  31908. this._toIndex = 0;
  31909. this._delay = 0;
  31910. this._direction = 1;
  31911. this._frameCount = 0;
  31912. this._time = 0;
  31913. this._manager = manager;
  31914. this._manager.sprites.push(this);
  31915. this.position = BABYLON.Vector3.Zero();
  31916. }
  31917. Object.defineProperty(Sprite.prototype, "size", {
  31918. get: function () {
  31919. return this.width;
  31920. },
  31921. set: function (value) {
  31922. this.width = value;
  31923. this.height = value;
  31924. },
  31925. enumerable: true,
  31926. configurable: true
  31927. });
  31928. Sprite.prototype.playAnimation = function (from, to, loop, delay, onAnimationEnd) {
  31929. this._fromIndex = from;
  31930. this._toIndex = to;
  31931. this._loopAnimation = loop;
  31932. this._delay = delay;
  31933. this._animationStarted = true;
  31934. this._direction = from < to ? 1 : -1;
  31935. this.cellIndex = from;
  31936. this._time = 0;
  31937. this._onAnimationEnd = onAnimationEnd;
  31938. };
  31939. Sprite.prototype.stopAnimation = function () {
  31940. this._animationStarted = false;
  31941. };
  31942. Sprite.prototype._animate = function (deltaTime) {
  31943. if (!this._animationStarted)
  31944. return;
  31945. this._time += deltaTime;
  31946. if (this._time > this._delay) {
  31947. this._time = this._time % this._delay;
  31948. this.cellIndex += this._direction;
  31949. if (this.cellIndex === this._toIndex) {
  31950. if (this._loopAnimation) {
  31951. this.cellIndex = this._fromIndex;
  31952. }
  31953. else {
  31954. this._animationStarted = false;
  31955. if (this._onAnimationEnd) {
  31956. this._onAnimationEnd();
  31957. }
  31958. if (this.disposeWhenFinishedAnimating) {
  31959. this.dispose();
  31960. }
  31961. }
  31962. }
  31963. }
  31964. };
  31965. Sprite.prototype.dispose = function () {
  31966. for (var i = 0; i < this._manager.sprites.length; i++) {
  31967. if (this._manager.sprites[i] == this) {
  31968. this._manager.sprites.splice(i, 1);
  31969. }
  31970. }
  31971. };
  31972. return Sprite;
  31973. }());
  31974. BABYLON.Sprite = Sprite;
  31975. })(BABYLON || (BABYLON = {}));
  31976. //# sourceMappingURL=babylon.sprite.js.map
  31977. var BABYLON;
  31978. (function (BABYLON) {
  31979. var Layer = (function () {
  31980. function Layer(name, imgUrl, scene, isBackground, color) {
  31981. this.name = name;
  31982. this.scale = new BABYLON.Vector2(1, 1);
  31983. this.offset = new BABYLON.Vector2(0, 0);
  31984. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  31985. this._vertexBuffers = {};
  31986. // Events
  31987. /**
  31988. * An event triggered when the layer is disposed.
  31989. * @type {BABYLON.Observable}
  31990. */
  31991. this.onDisposeObservable = new BABYLON.Observable();
  31992. /**
  31993. * An event triggered before rendering the scene
  31994. * @type {BABYLON.Observable}
  31995. */
  31996. this.onBeforeRenderObservable = new BABYLON.Observable();
  31997. /**
  31998. * An event triggered after rendering the scene
  31999. * @type {BABYLON.Observable}
  32000. */
  32001. this.onAfterRenderObservable = new BABYLON.Observable();
  32002. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  32003. this.isBackground = isBackground === undefined ? true : isBackground;
  32004. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  32005. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  32006. this._scene.layers.push(this);
  32007. var engine = scene.getEngine();
  32008. // VBO
  32009. var vertices = [];
  32010. vertices.push(1, 1);
  32011. vertices.push(-1, 1);
  32012. vertices.push(-1, -1);
  32013. vertices.push(1, -1);
  32014. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  32015. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  32016. // Indices
  32017. var indices = [];
  32018. indices.push(0);
  32019. indices.push(1);
  32020. indices.push(2);
  32021. indices.push(0);
  32022. indices.push(2);
  32023. indices.push(3);
  32024. this._indexBuffer = engine.createIndexBuffer(indices);
  32025. // Effects
  32026. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  32027. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  32028. }
  32029. Object.defineProperty(Layer.prototype, "onDispose", {
  32030. set: function (callback) {
  32031. if (this._onDisposeObserver) {
  32032. this.onDisposeObservable.remove(this._onDisposeObserver);
  32033. }
  32034. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  32035. },
  32036. enumerable: true,
  32037. configurable: true
  32038. });
  32039. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  32040. set: function (callback) {
  32041. if (this._onBeforeRenderObserver) {
  32042. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  32043. }
  32044. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  32045. },
  32046. enumerable: true,
  32047. configurable: true
  32048. });
  32049. Object.defineProperty(Layer.prototype, "onAfterRender", {
  32050. set: function (callback) {
  32051. if (this._onAfterRenderObserver) {
  32052. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  32053. }
  32054. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  32055. },
  32056. enumerable: true,
  32057. configurable: true
  32058. });
  32059. Layer.prototype.render = function () {
  32060. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  32061. // Check
  32062. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  32063. return;
  32064. var engine = this._scene.getEngine();
  32065. this.onBeforeRenderObservable.notifyObservers(this);
  32066. // Render
  32067. engine.enableEffect(currentEffect);
  32068. engine.setState(false);
  32069. // Texture
  32070. currentEffect.setTexture("textureSampler", this.texture);
  32071. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  32072. // Color
  32073. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  32074. // Scale / offset
  32075. currentEffect.setVector2("offset", this.offset);
  32076. currentEffect.setVector2("scale", this.scale);
  32077. // VBOs
  32078. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  32079. // Draw order
  32080. if (!this.alphaTest) {
  32081. engine.setAlphaMode(this.alphaBlendingMode);
  32082. engine.draw(true, 0, 6);
  32083. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  32084. }
  32085. else {
  32086. engine.draw(true, 0, 6);
  32087. }
  32088. this.onAfterRenderObservable.notifyObservers(this);
  32089. };
  32090. Layer.prototype.dispose = function () {
  32091. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  32092. if (vertexBuffer) {
  32093. vertexBuffer.dispose();
  32094. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  32095. }
  32096. if (this._indexBuffer) {
  32097. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  32098. this._indexBuffer = null;
  32099. }
  32100. if (this.texture) {
  32101. this.texture.dispose();
  32102. this.texture = null;
  32103. }
  32104. // Remove from scene
  32105. var index = this._scene.layers.indexOf(this);
  32106. this._scene.layers.splice(index, 1);
  32107. // Callback
  32108. this.onDisposeObservable.notifyObservers(this);
  32109. this.onDisposeObservable.clear();
  32110. this.onAfterRenderObservable.clear();
  32111. this.onBeforeRenderObservable.clear();
  32112. };
  32113. return Layer;
  32114. }());
  32115. BABYLON.Layer = Layer;
  32116. })(BABYLON || (BABYLON = {}));
  32117. //# sourceMappingURL=babylon.layer.js.map
  32118. var BABYLON;
  32119. (function (BABYLON) {
  32120. var Particle = (function () {
  32121. function Particle() {
  32122. this.position = BABYLON.Vector3.Zero();
  32123. this.direction = BABYLON.Vector3.Zero();
  32124. this.color = new BABYLON.Color4(0, 0, 0, 0);
  32125. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  32126. this.lifeTime = 1.0;
  32127. this.age = 0;
  32128. this.size = 0;
  32129. this.angle = 0;
  32130. this.angularSpeed = 0;
  32131. }
  32132. Particle.prototype.copyTo = function (other) {
  32133. other.position.copyFrom(this.position);
  32134. other.direction.copyFrom(this.direction);
  32135. other.color.copyFrom(this.color);
  32136. other.colorStep.copyFrom(this.colorStep);
  32137. other.lifeTime = this.lifeTime;
  32138. other.age = this.age;
  32139. other.size = this.size;
  32140. other.angle = this.angle;
  32141. other.angularSpeed = this.angularSpeed;
  32142. };
  32143. return Particle;
  32144. }());
  32145. BABYLON.Particle = Particle;
  32146. })(BABYLON || (BABYLON = {}));
  32147. //# sourceMappingURL=babylon.particle.js.map
  32148. var BABYLON;
  32149. (function (BABYLON) {
  32150. var randomNumber = function (min, max) {
  32151. if (min === max) {
  32152. return (min);
  32153. }
  32154. var random = Math.random();
  32155. return ((random * (max - min)) + min);
  32156. };
  32157. var ParticleSystem = (function () {
  32158. function ParticleSystem(name, capacity, scene, customEffect) {
  32159. var _this = this;
  32160. this.name = name;
  32161. // Members
  32162. this.animations = [];
  32163. this.renderingGroupId = 0;
  32164. this.emitter = null;
  32165. this.emitRate = 10;
  32166. this.manualEmitCount = -1;
  32167. this.updateSpeed = 0.01;
  32168. this.targetStopDuration = 0;
  32169. this.disposeOnStop = false;
  32170. this.minEmitPower = 1;
  32171. this.maxEmitPower = 1;
  32172. this.minLifeTime = 1;
  32173. this.maxLifeTime = 1;
  32174. this.minSize = 1;
  32175. this.maxSize = 1;
  32176. this.minAngularSpeed = 0;
  32177. this.maxAngularSpeed = 0;
  32178. this.layerMask = 0x0FFFFFFF;
  32179. this.customShader = null;
  32180. this.preventAutoStart = false;
  32181. /**
  32182. * An event triggered when the system is disposed.
  32183. * @type {BABYLON.Observable}
  32184. */
  32185. this.onDisposeObservable = new BABYLON.Observable();
  32186. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  32187. this.forceDepthWrite = false;
  32188. this.gravity = BABYLON.Vector3.Zero();
  32189. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  32190. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  32191. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  32192. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  32193. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  32194. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  32195. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  32196. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  32197. this.particles = new Array();
  32198. this._stockParticles = new Array();
  32199. this._newPartsExcess = 0;
  32200. this._vertexBuffers = {};
  32201. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  32202. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  32203. this._scaledDirection = BABYLON.Vector3.Zero();
  32204. this._scaledGravity = BABYLON.Vector3.Zero();
  32205. this._currentRenderId = -1;
  32206. this._started = false;
  32207. this._stopped = false;
  32208. this._actualFrame = 0;
  32209. this.id = name;
  32210. this._capacity = capacity;
  32211. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  32212. this._customEffect = customEffect;
  32213. scene.particleSystems.push(this);
  32214. var indices = [];
  32215. var index = 0;
  32216. for (var count = 0; count < capacity; count++) {
  32217. indices.push(index);
  32218. indices.push(index + 1);
  32219. indices.push(index + 2);
  32220. indices.push(index);
  32221. indices.push(index + 2);
  32222. indices.push(index + 3);
  32223. index += 4;
  32224. }
  32225. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  32226. // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY) + 1 filler
  32227. this._vertexData = new Float32Array(capacity * 11 * 4);
  32228. this._vertexBuffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 11);
  32229. var positions = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 3);
  32230. var colors = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 3, 4);
  32231. var options = this._vertexBuffer.createVertexBuffer("options", 7, 4);
  32232. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  32233. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  32234. this._vertexBuffers["options"] = options;
  32235. // Default behaviors
  32236. this.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  32237. var randX = randomNumber(_this.direction1.x, _this.direction2.x);
  32238. var randY = randomNumber(_this.direction1.y, _this.direction2.y);
  32239. var randZ = randomNumber(_this.direction1.z, _this.direction2.z);
  32240. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  32241. };
  32242. this.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  32243. var randX = randomNumber(_this.minEmitBox.x, _this.maxEmitBox.x);
  32244. var randY = randomNumber(_this.minEmitBox.y, _this.maxEmitBox.y);
  32245. var randZ = randomNumber(_this.minEmitBox.z, _this.maxEmitBox.z);
  32246. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  32247. };
  32248. this.updateFunction = function (particles) {
  32249. for (var index = 0; index < particles.length; index++) {
  32250. var particle = particles[index];
  32251. particle.age += _this._scaledUpdateSpeed;
  32252. if (particle.age >= particle.lifeTime) {
  32253. _this.recycleParticle(particle);
  32254. index--;
  32255. continue;
  32256. }
  32257. else {
  32258. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  32259. particle.color.addInPlace(_this._scaledColorStep);
  32260. if (particle.color.a < 0)
  32261. particle.color.a = 0;
  32262. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  32263. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  32264. particle.position.addInPlace(_this._scaledDirection);
  32265. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  32266. particle.direction.addInPlace(_this._scaledGravity);
  32267. }
  32268. }
  32269. };
  32270. }
  32271. Object.defineProperty(ParticleSystem.prototype, "onDispose", {
  32272. set: function (callback) {
  32273. if (this._onDisposeObserver) {
  32274. this.onDisposeObservable.remove(this._onDisposeObserver);
  32275. }
  32276. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  32277. },
  32278. enumerable: true,
  32279. configurable: true
  32280. });
  32281. ParticleSystem.prototype.recycleParticle = function (particle) {
  32282. var lastParticle = this.particles.pop();
  32283. if (lastParticle !== particle) {
  32284. lastParticle.copyTo(particle);
  32285. this._stockParticles.push(lastParticle);
  32286. }
  32287. };
  32288. ParticleSystem.prototype.getCapacity = function () {
  32289. return this._capacity;
  32290. };
  32291. ParticleSystem.prototype.isAlive = function () {
  32292. return this._alive;
  32293. };
  32294. ParticleSystem.prototype.isStarted = function () {
  32295. return this._started;
  32296. };
  32297. ParticleSystem.prototype.start = function () {
  32298. this._started = true;
  32299. this._stopped = false;
  32300. this._actualFrame = 0;
  32301. };
  32302. ParticleSystem.prototype.stop = function () {
  32303. this._stopped = true;
  32304. };
  32305. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  32306. var offset = index * 11;
  32307. this._vertexData[offset] = particle.position.x;
  32308. this._vertexData[offset + 1] = particle.position.y;
  32309. this._vertexData[offset + 2] = particle.position.z;
  32310. this._vertexData[offset + 3] = particle.color.r;
  32311. this._vertexData[offset + 4] = particle.color.g;
  32312. this._vertexData[offset + 5] = particle.color.b;
  32313. this._vertexData[offset + 6] = particle.color.a;
  32314. this._vertexData[offset + 7] = particle.angle;
  32315. this._vertexData[offset + 8] = particle.size;
  32316. this._vertexData[offset + 9] = offsetX;
  32317. this._vertexData[offset + 10] = offsetY;
  32318. };
  32319. ParticleSystem.prototype._update = function (newParticles) {
  32320. // Update current
  32321. this._alive = this.particles.length > 0;
  32322. this.updateFunction(this.particles);
  32323. // Add new ones
  32324. var worldMatrix;
  32325. if (this.emitter.position) {
  32326. worldMatrix = this.emitter.getWorldMatrix();
  32327. }
  32328. else {
  32329. worldMatrix = BABYLON.Matrix.Translation(this.emitter.x, this.emitter.y, this.emitter.z);
  32330. }
  32331. var particle;
  32332. for (var index = 0; index < newParticles; index++) {
  32333. if (this.particles.length === this._capacity) {
  32334. break;
  32335. }
  32336. if (this._stockParticles.length !== 0) {
  32337. particle = this._stockParticles.pop();
  32338. particle.age = 0;
  32339. }
  32340. else {
  32341. particle = new BABYLON.Particle();
  32342. }
  32343. this.particles.push(particle);
  32344. var emitPower = randomNumber(this.minEmitPower, this.maxEmitPower);
  32345. this.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  32346. particle.lifeTime = randomNumber(this.minLifeTime, this.maxLifeTime);
  32347. particle.size = randomNumber(this.minSize, this.maxSize);
  32348. particle.angularSpeed = randomNumber(this.minAngularSpeed, this.maxAngularSpeed);
  32349. this.startPositionFunction(worldMatrix, particle.position, particle);
  32350. var step = randomNumber(0, 1.0);
  32351. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  32352. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  32353. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  32354. }
  32355. };
  32356. ParticleSystem.prototype._getEffect = function () {
  32357. if (this._customEffect) {
  32358. return this._customEffect;
  32359. }
  32360. ;
  32361. var defines = [];
  32362. if (this._scene.clipPlane) {
  32363. defines.push("#define CLIPPLANE");
  32364. }
  32365. // Effect
  32366. var join = defines.join("\n");
  32367. if (this._cachedDefines !== join) {
  32368. this._cachedDefines = join;
  32369. this._effect = this._scene.getEngine().createEffect("particles", [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options"], ["invView", "view", "projection", "vClipPlane", "textureMask"], ["diffuseSampler"], join);
  32370. }
  32371. return this._effect;
  32372. };
  32373. ParticleSystem.prototype.animate = function () {
  32374. if (!this._started)
  32375. return;
  32376. var effect = this._getEffect();
  32377. // Check
  32378. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  32379. return;
  32380. if (this._currentRenderId === this._scene.getRenderId()) {
  32381. return;
  32382. }
  32383. this._currentRenderId = this._scene.getRenderId();
  32384. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  32385. // determine the number of particles we need to create
  32386. var newParticles;
  32387. if (this.manualEmitCount > -1) {
  32388. newParticles = this.manualEmitCount;
  32389. this._newPartsExcess = 0;
  32390. this.manualEmitCount = 0;
  32391. }
  32392. else {
  32393. newParticles = ((this.emitRate * this._scaledUpdateSpeed) >> 0);
  32394. this._newPartsExcess += this.emitRate * this._scaledUpdateSpeed - newParticles;
  32395. }
  32396. if (this._newPartsExcess > 1.0) {
  32397. newParticles += this._newPartsExcess >> 0;
  32398. this._newPartsExcess -= this._newPartsExcess >> 0;
  32399. }
  32400. this._alive = false;
  32401. if (!this._stopped) {
  32402. this._actualFrame += this._scaledUpdateSpeed;
  32403. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  32404. this.stop();
  32405. }
  32406. else {
  32407. newParticles = 0;
  32408. }
  32409. this._update(newParticles);
  32410. // Stopped?
  32411. if (this._stopped) {
  32412. if (!this._alive) {
  32413. this._started = false;
  32414. if (this.disposeOnStop) {
  32415. this._scene._toBeDisposed.push(this);
  32416. }
  32417. }
  32418. }
  32419. // Update VBO
  32420. var offset = 0;
  32421. for (var index = 0; index < this.particles.length; index++) {
  32422. var particle = this.particles[index];
  32423. this._appendParticleVertex(offset++, particle, 0, 0);
  32424. this._appendParticleVertex(offset++, particle, 1, 0);
  32425. this._appendParticleVertex(offset++, particle, 1, 1);
  32426. this._appendParticleVertex(offset++, particle, 0, 1);
  32427. }
  32428. this._vertexBuffer.update(this._vertexData);
  32429. };
  32430. ParticleSystem.prototype.render = function () {
  32431. var effect = this._getEffect();
  32432. // Check
  32433. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this.particles.length)
  32434. return 0;
  32435. var engine = this._scene.getEngine();
  32436. // Render
  32437. engine.enableEffect(effect);
  32438. engine.setState(false);
  32439. var viewMatrix = this._scene.getViewMatrix();
  32440. effect.setTexture("diffuseSampler", this.particleTexture);
  32441. effect.setMatrix("view", viewMatrix);
  32442. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  32443. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  32444. if (this._scene.clipPlane) {
  32445. var clipPlane = this._scene.clipPlane;
  32446. var invView = viewMatrix.clone();
  32447. invView.invert();
  32448. effect.setMatrix("invView", invView);
  32449. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  32450. }
  32451. // VBOs
  32452. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  32453. // Draw order
  32454. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  32455. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  32456. }
  32457. else {
  32458. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  32459. }
  32460. if (this.forceDepthWrite) {
  32461. engine.setDepthWrite(true);
  32462. }
  32463. engine.draw(true, 0, this.particles.length * 6);
  32464. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  32465. return this.particles.length;
  32466. };
  32467. ParticleSystem.prototype.dispose = function () {
  32468. if (this._vertexBuffer) {
  32469. this._vertexBuffer.dispose();
  32470. this._vertexBuffer = null;
  32471. }
  32472. if (this._indexBuffer) {
  32473. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  32474. this._indexBuffer = null;
  32475. }
  32476. if (this.particleTexture) {
  32477. this.particleTexture.dispose();
  32478. this.particleTexture = null;
  32479. }
  32480. // Remove from scene
  32481. var index = this._scene.particleSystems.indexOf(this);
  32482. this._scene.particleSystems.splice(index, 1);
  32483. // Callback
  32484. this.onDisposeObservable.notifyObservers(this);
  32485. this.onDisposeObservable.clear();
  32486. };
  32487. // Clone
  32488. ParticleSystem.prototype.clone = function (name, newEmitter) {
  32489. var custom = null;
  32490. var program = null;
  32491. if (this.customShader != null) {
  32492. program = this.customShader;
  32493. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  32494. custom = this._scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  32495. }
  32496. var result = new ParticleSystem(name, this._capacity, this._scene, custom);
  32497. result.customShader = program;
  32498. BABYLON.Tools.DeepCopy(this, result, ["particles", "customShader"]);
  32499. if (newEmitter === undefined) {
  32500. newEmitter = this.emitter;
  32501. }
  32502. result.emitter = newEmitter;
  32503. if (this.particleTexture) {
  32504. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  32505. }
  32506. if (!this.preventAutoStart) {
  32507. result.start();
  32508. }
  32509. return result;
  32510. };
  32511. ParticleSystem.prototype.serialize = function () {
  32512. var serializationObject = {};
  32513. serializationObject.name = this.name;
  32514. serializationObject.id = this.id;
  32515. // Emitter
  32516. if (this.emitter.position) {
  32517. serializationObject.emitterId = this.emitter.id;
  32518. }
  32519. else {
  32520. serializationObject.emitter = this.emitter.asArray();
  32521. }
  32522. serializationObject.capacity = this.getCapacity();
  32523. if (this.particleTexture) {
  32524. serializationObject.textureName = this.particleTexture.name;
  32525. }
  32526. // Animations
  32527. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  32528. // Particle system
  32529. serializationObject.minAngularSpeed = this.minAngularSpeed;
  32530. serializationObject.maxAngularSpeed = this.maxAngularSpeed;
  32531. serializationObject.minSize = this.minSize;
  32532. serializationObject.maxSize = this.maxSize;
  32533. serializationObject.minEmitPower = this.minEmitPower;
  32534. serializationObject.maxEmitPower = this.maxEmitPower;
  32535. serializationObject.minLifeTime = this.minLifeTime;
  32536. serializationObject.maxLifeTime = this.maxLifeTime;
  32537. serializationObject.emitRate = this.emitRate;
  32538. serializationObject.minEmitBox = this.minEmitBox.asArray();
  32539. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  32540. serializationObject.gravity = this.gravity.asArray();
  32541. serializationObject.direction1 = this.direction1.asArray();
  32542. serializationObject.direction2 = this.direction2.asArray();
  32543. serializationObject.color1 = this.color1.asArray();
  32544. serializationObject.color2 = this.color2.asArray();
  32545. serializationObject.colorDead = this.colorDead.asArray();
  32546. serializationObject.updateSpeed = this.updateSpeed;
  32547. serializationObject.targetStopDuration = this.targetStopDuration;
  32548. serializationObject.textureMask = this.textureMask.asArray();
  32549. serializationObject.blendMode = this.blendMode;
  32550. serializationObject.customShader = this.customShader;
  32551. serializationObject.preventAutoStart = this.preventAutoStart;
  32552. return serializationObject;
  32553. };
  32554. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  32555. var name = parsedParticleSystem.name;
  32556. var custom = null;
  32557. var program = null;
  32558. if (parsedParticleSystem.customShader) {
  32559. program = parsedParticleSystem.customShader;
  32560. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  32561. custom = scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  32562. }
  32563. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene, custom);
  32564. particleSystem.customShader = program;
  32565. if (parsedParticleSystem.id) {
  32566. particleSystem.id = parsedParticleSystem.id;
  32567. }
  32568. // Auto start
  32569. if (parsedParticleSystem.preventAutoStart) {
  32570. particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;
  32571. }
  32572. // Texture
  32573. if (parsedParticleSystem.textureName) {
  32574. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  32575. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  32576. }
  32577. // Emitter
  32578. if (parsedParticleSystem.emitterId) {
  32579. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  32580. }
  32581. else {
  32582. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  32583. }
  32584. // Animations
  32585. if (parsedParticleSystem.animations) {
  32586. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  32587. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  32588. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  32589. }
  32590. }
  32591. if (parsedParticleSystem.autoAnimate) {
  32592. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  32593. }
  32594. // Particle system
  32595. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  32596. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  32597. particleSystem.minSize = parsedParticleSystem.minSize;
  32598. particleSystem.maxSize = parsedParticleSystem.maxSize;
  32599. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  32600. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  32601. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  32602. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  32603. particleSystem.emitRate = parsedParticleSystem.emitRate;
  32604. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  32605. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  32606. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  32607. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  32608. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  32609. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  32610. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  32611. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  32612. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  32613. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  32614. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  32615. particleSystem.blendMode = parsedParticleSystem.blendMode;
  32616. if (!particleSystem.preventAutoStart) {
  32617. particleSystem.start();
  32618. }
  32619. return particleSystem;
  32620. };
  32621. return ParticleSystem;
  32622. }());
  32623. // Statics
  32624. ParticleSystem.BLENDMODE_ONEONE = 0;
  32625. ParticleSystem.BLENDMODE_STANDARD = 1;
  32626. BABYLON.ParticleSystem = ParticleSystem;
  32627. })(BABYLON || (BABYLON = {}));
  32628. //# sourceMappingURL=babylon.particleSystem.js.map
  32629. var BABYLON;
  32630. (function (BABYLON) {
  32631. var AnimationRange = (function () {
  32632. function AnimationRange(name, from, to) {
  32633. this.name = name;
  32634. this.from = from;
  32635. this.to = to;
  32636. }
  32637. AnimationRange.prototype.clone = function () {
  32638. return new AnimationRange(this.name, this.from, this.to);
  32639. };
  32640. return AnimationRange;
  32641. }());
  32642. BABYLON.AnimationRange = AnimationRange;
  32643. /**
  32644. * Composed of a frame, and an action function
  32645. */
  32646. var AnimationEvent = (function () {
  32647. function AnimationEvent(frame, action, onlyOnce) {
  32648. this.frame = frame;
  32649. this.action = action;
  32650. this.onlyOnce = onlyOnce;
  32651. this.isDone = false;
  32652. }
  32653. return AnimationEvent;
  32654. }());
  32655. BABYLON.AnimationEvent = AnimationEvent;
  32656. var PathCursor = (function () {
  32657. function PathCursor(path) {
  32658. this.path = path;
  32659. this._onchange = new Array();
  32660. this.value = 0;
  32661. this.animations = new Array();
  32662. }
  32663. PathCursor.prototype.getPoint = function () {
  32664. var point = this.path.getPointAtLengthPosition(this.value);
  32665. return new BABYLON.Vector3(point.x, 0, point.y);
  32666. };
  32667. PathCursor.prototype.moveAhead = function (step) {
  32668. if (step === void 0) { step = 0.002; }
  32669. this.move(step);
  32670. return this;
  32671. };
  32672. PathCursor.prototype.moveBack = function (step) {
  32673. if (step === void 0) { step = 0.002; }
  32674. this.move(-step);
  32675. return this;
  32676. };
  32677. PathCursor.prototype.move = function (step) {
  32678. if (Math.abs(step) > 1) {
  32679. throw "step size should be less than 1.";
  32680. }
  32681. this.value += step;
  32682. this.ensureLimits();
  32683. this.raiseOnChange();
  32684. return this;
  32685. };
  32686. PathCursor.prototype.ensureLimits = function () {
  32687. while (this.value > 1) {
  32688. this.value -= 1;
  32689. }
  32690. while (this.value < 0) {
  32691. this.value += 1;
  32692. }
  32693. return this;
  32694. };
  32695. // used by animation engine
  32696. PathCursor.prototype.markAsDirty = function (propertyName) {
  32697. this.ensureLimits();
  32698. this.raiseOnChange();
  32699. return this;
  32700. };
  32701. PathCursor.prototype.raiseOnChange = function () {
  32702. var _this = this;
  32703. this._onchange.forEach(function (f) { return f(_this); });
  32704. return this;
  32705. };
  32706. PathCursor.prototype.onchange = function (f) {
  32707. this._onchange.push(f);
  32708. return this;
  32709. };
  32710. return PathCursor;
  32711. }());
  32712. BABYLON.PathCursor = PathCursor;
  32713. var Animation = (function () {
  32714. function Animation(name, targetProperty, framePerSecond, dataType, loopMode, enableBlending) {
  32715. this.name = name;
  32716. this.targetProperty = targetProperty;
  32717. this.framePerSecond = framePerSecond;
  32718. this.dataType = dataType;
  32719. this.loopMode = loopMode;
  32720. this.enableBlending = enableBlending;
  32721. this._offsetsCache = {};
  32722. this._highLimitsCache = {};
  32723. this._stopped = false;
  32724. this._blendingFactor = 0;
  32725. // The set of event that will be linked to this animation
  32726. this._events = new Array();
  32727. this.allowMatricesInterpolation = false;
  32728. this.blendingSpeed = 0.01;
  32729. this._ranges = {};
  32730. this.targetPropertyPath = targetProperty.split(".");
  32731. this.dataType = dataType;
  32732. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  32733. }
  32734. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  32735. var dataType = undefined;
  32736. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  32737. dataType = Animation.ANIMATIONTYPE_FLOAT;
  32738. }
  32739. else if (from instanceof BABYLON.Quaternion) {
  32740. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  32741. }
  32742. else if (from instanceof BABYLON.Vector3) {
  32743. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  32744. }
  32745. else if (from instanceof BABYLON.Vector2) {
  32746. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  32747. }
  32748. else if (from instanceof BABYLON.Color3) {
  32749. dataType = Animation.ANIMATIONTYPE_COLOR3;
  32750. }
  32751. else if (from instanceof BABYLON.Size) {
  32752. dataType = Animation.ANIMATIONTYPE_SIZE;
  32753. }
  32754. if (dataType == undefined) {
  32755. return null;
  32756. }
  32757. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  32758. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  32759. animation.setKeys(keys);
  32760. if (easingFunction !== undefined) {
  32761. animation.setEasingFunction(easingFunction);
  32762. }
  32763. return animation;
  32764. };
  32765. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  32766. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  32767. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  32768. };
  32769. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  32770. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  32771. node.animations.push(animation);
  32772. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  32773. };
  32774. // Methods
  32775. /**
  32776. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  32777. */
  32778. Animation.prototype.toString = function (fullDetails) {
  32779. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  32780. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  32781. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  32782. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  32783. if (fullDetails) {
  32784. ret += ", Ranges: {";
  32785. var first = true;
  32786. for (var name in this._ranges) {
  32787. if (first) {
  32788. ret += ", ";
  32789. first = false;
  32790. }
  32791. ret += name;
  32792. }
  32793. ret += "}";
  32794. }
  32795. return ret;
  32796. };
  32797. /**
  32798. * Add an event to this animation.
  32799. */
  32800. Animation.prototype.addEvent = function (event) {
  32801. this._events.push(event);
  32802. };
  32803. /**
  32804. * Remove all events found at the given frame
  32805. * @param frame
  32806. */
  32807. Animation.prototype.removeEvents = function (frame) {
  32808. for (var index = 0; index < this._events.length; index++) {
  32809. if (this._events[index].frame === frame) {
  32810. this._events.splice(index, 1);
  32811. index--;
  32812. }
  32813. }
  32814. };
  32815. Animation.prototype.createRange = function (name, from, to) {
  32816. // check name not already in use; could happen for bones after serialized
  32817. if (!this._ranges[name]) {
  32818. this._ranges[name] = new AnimationRange(name, from, to);
  32819. }
  32820. };
  32821. Animation.prototype.deleteRange = function (name, deleteFrames) {
  32822. if (deleteFrames === void 0) { deleteFrames = true; }
  32823. if (this._ranges[name]) {
  32824. if (deleteFrames) {
  32825. var from = this._ranges[name].from;
  32826. var to = this._ranges[name].to;
  32827. // this loop MUST go high to low for multiple splices to work
  32828. for (var key = this._keys.length - 1; key >= 0; key--) {
  32829. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  32830. this._keys.splice(key, 1);
  32831. }
  32832. }
  32833. }
  32834. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  32835. }
  32836. };
  32837. Animation.prototype.getRange = function (name) {
  32838. return this._ranges[name];
  32839. };
  32840. Animation.prototype.reset = function () {
  32841. this._offsetsCache = {};
  32842. this._highLimitsCache = {};
  32843. this.currentFrame = 0;
  32844. this._blendingFactor = 0;
  32845. this._originalBlendValue = null;
  32846. };
  32847. Animation.prototype.isStopped = function () {
  32848. return this._stopped;
  32849. };
  32850. Animation.prototype.getKeys = function () {
  32851. return this._keys;
  32852. };
  32853. Animation.prototype.getHighestFrame = function () {
  32854. var ret = 0;
  32855. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  32856. if (ret < this._keys[key].frame) {
  32857. ret = this._keys[key].frame;
  32858. }
  32859. }
  32860. return ret;
  32861. };
  32862. Animation.prototype.getEasingFunction = function () {
  32863. return this._easingFunction;
  32864. };
  32865. Animation.prototype.setEasingFunction = function (easingFunction) {
  32866. this._easingFunction = easingFunction;
  32867. };
  32868. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  32869. return startValue + (endValue - startValue) * gradient;
  32870. };
  32871. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  32872. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  32873. };
  32874. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  32875. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  32876. };
  32877. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  32878. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  32879. };
  32880. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  32881. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  32882. };
  32883. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  32884. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  32885. };
  32886. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  32887. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  32888. };
  32889. Animation.prototype.clone = function () {
  32890. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  32891. clone.enableBlending = this.enableBlending;
  32892. clone.blendingSpeed = this.blendingSpeed;
  32893. if (this._keys) {
  32894. clone.setKeys(this._keys);
  32895. }
  32896. if (this._ranges) {
  32897. clone._ranges = {};
  32898. for (var name in this._ranges) {
  32899. clone._ranges[name] = this._ranges[name].clone();
  32900. }
  32901. }
  32902. return clone;
  32903. };
  32904. Animation.prototype.setKeys = function (values) {
  32905. this._keys = values.slice(0);
  32906. this._offsetsCache = {};
  32907. this._highLimitsCache = {};
  32908. };
  32909. Animation.prototype._getKeyValue = function (value) {
  32910. if (typeof value === "function") {
  32911. return value();
  32912. }
  32913. return value;
  32914. };
  32915. Animation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  32916. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  32917. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  32918. }
  32919. this.currentFrame = currentFrame;
  32920. // Try to get a hash to find the right key
  32921. 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));
  32922. if (this._keys[startKey].frame >= currentFrame) {
  32923. while (startKey - 1 >= 0 && this._keys[startKey].frame >= currentFrame) {
  32924. startKey--;
  32925. }
  32926. }
  32927. for (var key = startKey; key < this._keys.length; key++) {
  32928. if (this._keys[key + 1].frame >= currentFrame) {
  32929. var startValue = this._getKeyValue(this._keys[key].value);
  32930. var endValue = this._getKeyValue(this._keys[key + 1].value);
  32931. // gradient : percent of currentFrame between the frame inf and the frame sup
  32932. var gradient = (currentFrame - this._keys[key].frame) / (this._keys[key + 1].frame - this._keys[key].frame);
  32933. // check for easingFunction and correction of gradient
  32934. if (this._easingFunction != null) {
  32935. gradient = this._easingFunction.ease(gradient);
  32936. }
  32937. switch (this.dataType) {
  32938. // Float
  32939. case Animation.ANIMATIONTYPE_FLOAT:
  32940. switch (loopMode) {
  32941. case Animation.ANIMATIONLOOPMODE_CYCLE:
  32942. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  32943. return this.floatInterpolateFunction(startValue, endValue, gradient);
  32944. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  32945. return offsetValue * repeatCount + this.floatInterpolateFunction(startValue, endValue, gradient);
  32946. }
  32947. break;
  32948. // Quaternion
  32949. case Animation.ANIMATIONTYPE_QUATERNION:
  32950. var quaternion = null;
  32951. switch (loopMode) {
  32952. case Animation.ANIMATIONLOOPMODE_CYCLE:
  32953. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  32954. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient);
  32955. break;
  32956. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  32957. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  32958. break;
  32959. }
  32960. return quaternion;
  32961. // Vector3
  32962. case Animation.ANIMATIONTYPE_VECTOR3:
  32963. switch (loopMode) {
  32964. case Animation.ANIMATIONLOOPMODE_CYCLE:
  32965. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  32966. return this.vector3InterpolateFunction(startValue, endValue, gradient);
  32967. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  32968. return this.vector3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  32969. }
  32970. // Vector2
  32971. case Animation.ANIMATIONTYPE_VECTOR2:
  32972. switch (loopMode) {
  32973. case Animation.ANIMATIONLOOPMODE_CYCLE:
  32974. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  32975. return this.vector2InterpolateFunction(startValue, endValue, gradient);
  32976. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  32977. return this.vector2InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  32978. }
  32979. // Size
  32980. case Animation.ANIMATIONTYPE_SIZE:
  32981. switch (loopMode) {
  32982. case Animation.ANIMATIONLOOPMODE_CYCLE:
  32983. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  32984. return this.sizeInterpolateFunction(startValue, endValue, gradient);
  32985. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  32986. return this.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  32987. }
  32988. // Color3
  32989. case Animation.ANIMATIONTYPE_COLOR3:
  32990. switch (loopMode) {
  32991. case Animation.ANIMATIONLOOPMODE_CYCLE:
  32992. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  32993. return this.color3InterpolateFunction(startValue, endValue, gradient);
  32994. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  32995. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  32996. }
  32997. // Matrix
  32998. case Animation.ANIMATIONTYPE_MATRIX:
  32999. switch (loopMode) {
  33000. case Animation.ANIMATIONLOOPMODE_CYCLE:
  33001. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  33002. if (this.allowMatricesInterpolation) {
  33003. return this.matrixInterpolateFunction(startValue, endValue, gradient);
  33004. }
  33005. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  33006. return startValue;
  33007. }
  33008. default:
  33009. break;
  33010. }
  33011. break;
  33012. }
  33013. }
  33014. return this._getKeyValue(this._keys[this._keys.length - 1].value);
  33015. };
  33016. Animation.prototype.setValue = function (currentValue, blend) {
  33017. if (blend === void 0) { blend = false; }
  33018. // Set value
  33019. var path;
  33020. var destination;
  33021. if (this.targetPropertyPath.length > 1) {
  33022. var property = this._target[this.targetPropertyPath[0]];
  33023. for (var index = 1; index < this.targetPropertyPath.length - 1; index++) {
  33024. property = property[this.targetPropertyPath[index]];
  33025. }
  33026. path = this.targetPropertyPath[this.targetPropertyPath.length - 1];
  33027. destination = property;
  33028. }
  33029. else {
  33030. path = this.targetPropertyPath[0];
  33031. destination = this._target;
  33032. }
  33033. // Blending
  33034. if (this.enableBlending && this._blendingFactor <= 1.0) {
  33035. if (!this._originalBlendValue) {
  33036. if (destination[path].clone) {
  33037. this._originalBlendValue = destination[path].clone();
  33038. }
  33039. else {
  33040. this._originalBlendValue = destination[path];
  33041. }
  33042. }
  33043. if (this._originalBlendValue.prototype) {
  33044. if (this._originalBlendValue.prototype.Lerp) {
  33045. destination[path] = this._originalBlendValue.construtor.prototype.Lerp(currentValue, this._originalBlendValue, this._blendingFactor);
  33046. }
  33047. else {
  33048. destination[path] = currentValue;
  33049. }
  33050. }
  33051. else if (this._originalBlendValue.m) {
  33052. destination[path] = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  33053. }
  33054. else {
  33055. destination[path] = this._originalBlendValue * (1.0 - this._blendingFactor) + this._blendingFactor * currentValue;
  33056. }
  33057. this._blendingFactor += this.blendingSpeed;
  33058. }
  33059. else {
  33060. destination[path] = currentValue;
  33061. }
  33062. if (this._target.markAsDirty) {
  33063. this._target.markAsDirty(this.targetProperty);
  33064. }
  33065. };
  33066. Animation.prototype.goToFrame = function (frame) {
  33067. if (frame < this._keys[0].frame) {
  33068. frame = this._keys[0].frame;
  33069. }
  33070. else if (frame > this._keys[this._keys.length - 1].frame) {
  33071. frame = this._keys[this._keys.length - 1].frame;
  33072. }
  33073. var currentValue = this._interpolate(frame, 0, this.loopMode);
  33074. this.setValue(currentValue);
  33075. };
  33076. Animation.prototype.animate = function (delay, from, to, loop, speedRatio, blend) {
  33077. if (blend === void 0) { blend = false; }
  33078. if (!this.targetPropertyPath || this.targetPropertyPath.length < 1) {
  33079. this._stopped = true;
  33080. return false;
  33081. }
  33082. var returnValue = true;
  33083. // Adding a start key at frame 0 if missing
  33084. if (this._keys[0].frame !== 0) {
  33085. var newKey = { frame: 0, value: this._keys[0].value };
  33086. this._keys.splice(0, 0, newKey);
  33087. }
  33088. // Check limits
  33089. if (from < this._keys[0].frame || from > this._keys[this._keys.length - 1].frame) {
  33090. from = this._keys[0].frame;
  33091. }
  33092. if (to < this._keys[0].frame || to > this._keys[this._keys.length - 1].frame) {
  33093. to = this._keys[this._keys.length - 1].frame;
  33094. }
  33095. //to and from cannot be the same key
  33096. if (from === to) {
  33097. from++;
  33098. }
  33099. // Compute ratio
  33100. var range = to - from;
  33101. var offsetValue;
  33102. // ratio represents the frame delta between from and to
  33103. var ratio = delay * (this.framePerSecond * speedRatio) / 1000.0;
  33104. var highLimitValue = 0;
  33105. if (ratio > range && !loop) {
  33106. returnValue = false;
  33107. highLimitValue = this._getKeyValue(this._keys[this._keys.length - 1].value);
  33108. }
  33109. else {
  33110. // Get max value if required
  33111. if (this.loopMode !== Animation.ANIMATIONLOOPMODE_CYCLE) {
  33112. var keyOffset = to.toString() + from.toString();
  33113. if (!this._offsetsCache[keyOffset]) {
  33114. var fromValue = this._interpolate(from, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  33115. var toValue = this._interpolate(to, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  33116. switch (this.dataType) {
  33117. // Float
  33118. case Animation.ANIMATIONTYPE_FLOAT:
  33119. this._offsetsCache[keyOffset] = toValue - fromValue;
  33120. break;
  33121. // Quaternion
  33122. case Animation.ANIMATIONTYPE_QUATERNION:
  33123. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  33124. break;
  33125. // Vector3
  33126. case Animation.ANIMATIONTYPE_VECTOR3:
  33127. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  33128. // Vector2
  33129. case Animation.ANIMATIONTYPE_VECTOR2:
  33130. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  33131. // Size
  33132. case Animation.ANIMATIONTYPE_SIZE:
  33133. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  33134. // Color3
  33135. case Animation.ANIMATIONTYPE_COLOR3:
  33136. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  33137. default:
  33138. break;
  33139. }
  33140. this._highLimitsCache[keyOffset] = toValue;
  33141. }
  33142. highLimitValue = this._highLimitsCache[keyOffset];
  33143. offsetValue = this._offsetsCache[keyOffset];
  33144. }
  33145. }
  33146. if (offsetValue === undefined) {
  33147. switch (this.dataType) {
  33148. // Float
  33149. case Animation.ANIMATIONTYPE_FLOAT:
  33150. offsetValue = 0;
  33151. break;
  33152. // Quaternion
  33153. case Animation.ANIMATIONTYPE_QUATERNION:
  33154. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  33155. break;
  33156. // Vector3
  33157. case Animation.ANIMATIONTYPE_VECTOR3:
  33158. offsetValue = BABYLON.Vector3.Zero();
  33159. break;
  33160. // Vector2
  33161. case Animation.ANIMATIONTYPE_VECTOR2:
  33162. offsetValue = BABYLON.Vector2.Zero();
  33163. break;
  33164. // Size
  33165. case Animation.ANIMATIONTYPE_SIZE:
  33166. offsetValue = BABYLON.Size.Zero();
  33167. break;
  33168. // Color3
  33169. case Animation.ANIMATIONTYPE_COLOR3:
  33170. offsetValue = BABYLON.Color3.Black();
  33171. }
  33172. }
  33173. // Compute value
  33174. var repeatCount = (ratio / range) >> 0;
  33175. var currentFrame = returnValue ? from + ratio % range : to;
  33176. var currentValue = this._interpolate(currentFrame, repeatCount, this.loopMode, offsetValue, highLimitValue);
  33177. // Set value
  33178. this.setValue(currentValue);
  33179. // Check events
  33180. for (var index = 0; index < this._events.length; index++) {
  33181. if (currentFrame >= this._events[index].frame) {
  33182. var event = this._events[index];
  33183. if (!event.isDone) {
  33184. // If event should be done only once, remove it.
  33185. if (event.onlyOnce) {
  33186. this._events.splice(index, 1);
  33187. index--;
  33188. }
  33189. event.isDone = true;
  33190. event.action();
  33191. } // Don't do anything if the event has already be done.
  33192. }
  33193. else if (this._events[index].isDone && !this._events[index].onlyOnce) {
  33194. // reset event, the animation is looping
  33195. this._events[index].isDone = false;
  33196. }
  33197. }
  33198. if (!returnValue) {
  33199. this._stopped = true;
  33200. }
  33201. return returnValue;
  33202. };
  33203. Animation.prototype.serialize = function () {
  33204. var serializationObject = {};
  33205. serializationObject.name = this.name;
  33206. serializationObject.property = this.targetProperty;
  33207. serializationObject.framePerSecond = this.framePerSecond;
  33208. serializationObject.dataType = this.dataType;
  33209. serializationObject.loopBehavior = this.loopMode;
  33210. serializationObject.enableBlending = this.enableBlending;
  33211. serializationObject.blendingSpeed = this.blendingSpeed;
  33212. var dataType = this.dataType;
  33213. serializationObject.keys = [];
  33214. var keys = this.getKeys();
  33215. for (var index = 0; index < keys.length; index++) {
  33216. var animationKey = keys[index];
  33217. var key = {};
  33218. key.frame = animationKey.frame;
  33219. switch (dataType) {
  33220. case Animation.ANIMATIONTYPE_FLOAT:
  33221. key.values = [animationKey.value];
  33222. break;
  33223. case Animation.ANIMATIONTYPE_QUATERNION:
  33224. case Animation.ANIMATIONTYPE_MATRIX:
  33225. case Animation.ANIMATIONTYPE_VECTOR3:
  33226. case Animation.ANIMATIONTYPE_COLOR3:
  33227. key.values = animationKey.value.asArray();
  33228. break;
  33229. }
  33230. serializationObject.keys.push(key);
  33231. }
  33232. serializationObject.ranges = [];
  33233. for (var name in this._ranges) {
  33234. var range = {};
  33235. range.name = name;
  33236. range.from = this._ranges[name].from;
  33237. range.to = this._ranges[name].to;
  33238. serializationObject.ranges.push(range);
  33239. }
  33240. return serializationObject;
  33241. };
  33242. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  33243. get: function () {
  33244. return Animation._ANIMATIONTYPE_FLOAT;
  33245. },
  33246. enumerable: true,
  33247. configurable: true
  33248. });
  33249. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  33250. get: function () {
  33251. return Animation._ANIMATIONTYPE_VECTOR3;
  33252. },
  33253. enumerable: true,
  33254. configurable: true
  33255. });
  33256. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  33257. get: function () {
  33258. return Animation._ANIMATIONTYPE_VECTOR2;
  33259. },
  33260. enumerable: true,
  33261. configurable: true
  33262. });
  33263. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  33264. get: function () {
  33265. return Animation._ANIMATIONTYPE_SIZE;
  33266. },
  33267. enumerable: true,
  33268. configurable: true
  33269. });
  33270. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  33271. get: function () {
  33272. return Animation._ANIMATIONTYPE_QUATERNION;
  33273. },
  33274. enumerable: true,
  33275. configurable: true
  33276. });
  33277. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  33278. get: function () {
  33279. return Animation._ANIMATIONTYPE_MATRIX;
  33280. },
  33281. enumerable: true,
  33282. configurable: true
  33283. });
  33284. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  33285. get: function () {
  33286. return Animation._ANIMATIONTYPE_COLOR3;
  33287. },
  33288. enumerable: true,
  33289. configurable: true
  33290. });
  33291. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  33292. get: function () {
  33293. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  33294. },
  33295. enumerable: true,
  33296. configurable: true
  33297. });
  33298. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  33299. get: function () {
  33300. return Animation._ANIMATIONLOOPMODE_CYCLE;
  33301. },
  33302. enumerable: true,
  33303. configurable: true
  33304. });
  33305. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  33306. get: function () {
  33307. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  33308. },
  33309. enumerable: true,
  33310. configurable: true
  33311. });
  33312. Animation.Parse = function (parsedAnimation) {
  33313. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  33314. var dataType = parsedAnimation.dataType;
  33315. var keys = [];
  33316. var data;
  33317. var index;
  33318. if (parsedAnimation.enableBlending) {
  33319. animation.enableBlending = parsedAnimation.enableBlending;
  33320. }
  33321. if (parsedAnimation.blendingSpeed) {
  33322. animation.blendingSpeed = parsedAnimation.blendingSpeed;
  33323. }
  33324. for (index = 0; index < parsedAnimation.keys.length; index++) {
  33325. var key = parsedAnimation.keys[index];
  33326. switch (dataType) {
  33327. case Animation.ANIMATIONTYPE_FLOAT:
  33328. data = key.values[0];
  33329. break;
  33330. case Animation.ANIMATIONTYPE_QUATERNION:
  33331. data = BABYLON.Quaternion.FromArray(key.values);
  33332. break;
  33333. case Animation.ANIMATIONTYPE_MATRIX:
  33334. data = BABYLON.Matrix.FromArray(key.values);
  33335. break;
  33336. case Animation.ANIMATIONTYPE_COLOR3:
  33337. data = BABYLON.Color3.FromArray(key.values);
  33338. break;
  33339. case Animation.ANIMATIONTYPE_VECTOR3:
  33340. default:
  33341. data = BABYLON.Vector3.FromArray(key.values);
  33342. break;
  33343. }
  33344. keys.push({
  33345. frame: key.frame,
  33346. value: data
  33347. });
  33348. }
  33349. animation.setKeys(keys);
  33350. if (parsedAnimation.ranges) {
  33351. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  33352. data = parsedAnimation.ranges[index];
  33353. animation.createRange(data.name, data.from, data.to);
  33354. }
  33355. }
  33356. return animation;
  33357. };
  33358. Animation.AppendSerializedAnimations = function (source, destination) {
  33359. if (source.animations) {
  33360. destination.animations = [];
  33361. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  33362. var animation = source.animations[animationIndex];
  33363. destination.animations.push(animation.serialize());
  33364. }
  33365. }
  33366. };
  33367. return Animation;
  33368. }());
  33369. // Statics
  33370. Animation._ANIMATIONTYPE_FLOAT = 0;
  33371. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  33372. Animation._ANIMATIONTYPE_QUATERNION = 2;
  33373. Animation._ANIMATIONTYPE_MATRIX = 3;
  33374. Animation._ANIMATIONTYPE_COLOR3 = 4;
  33375. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  33376. Animation._ANIMATIONTYPE_SIZE = 6;
  33377. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  33378. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  33379. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  33380. BABYLON.Animation = Animation;
  33381. })(BABYLON || (BABYLON = {}));
  33382. //# sourceMappingURL=babylon.animation.js.map
  33383. var BABYLON;
  33384. (function (BABYLON) {
  33385. var Animatable = (function () {
  33386. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  33387. if (fromFrame === void 0) { fromFrame = 0; }
  33388. if (toFrame === void 0) { toFrame = 100; }
  33389. if (loopAnimation === void 0) { loopAnimation = false; }
  33390. if (speedRatio === void 0) { speedRatio = 1.0; }
  33391. this.target = target;
  33392. this.fromFrame = fromFrame;
  33393. this.toFrame = toFrame;
  33394. this.loopAnimation = loopAnimation;
  33395. this.speedRatio = speedRatio;
  33396. this.onAnimationEnd = onAnimationEnd;
  33397. this._animations = new Array();
  33398. this._paused = false;
  33399. this.animationStarted = false;
  33400. if (animations) {
  33401. this.appendAnimations(target, animations);
  33402. }
  33403. this._scene = scene;
  33404. scene._activeAnimatables.push(this);
  33405. }
  33406. // Methods
  33407. Animatable.prototype.getAnimations = function () {
  33408. return this._animations;
  33409. };
  33410. Animatable.prototype.appendAnimations = function (target, animations) {
  33411. for (var index = 0; index < animations.length; index++) {
  33412. var animation = animations[index];
  33413. animation._target = target;
  33414. this._animations.push(animation);
  33415. }
  33416. };
  33417. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  33418. var animations = this._animations;
  33419. for (var index = 0; index < animations.length; index++) {
  33420. if (animations[index].targetProperty === property) {
  33421. return animations[index];
  33422. }
  33423. }
  33424. return null;
  33425. };
  33426. Animatable.prototype.reset = function () {
  33427. var animations = this._animations;
  33428. for (var index = 0; index < animations.length; index++) {
  33429. animations[index].reset();
  33430. }
  33431. this._localDelayOffset = null;
  33432. this._pausedDelay = null;
  33433. };
  33434. Animatable.prototype.enableBlending = function (blendingSpeed) {
  33435. var animations = this._animations;
  33436. for (var index = 0; index < animations.length; index++) {
  33437. animations[index].enableBlending = true;
  33438. animations[index].blendingSpeed = blendingSpeed;
  33439. }
  33440. };
  33441. Animatable.prototype.disableBlending = function () {
  33442. var animations = this._animations;
  33443. for (var index = 0; index < animations.length; index++) {
  33444. animations[index].enableBlending = false;
  33445. }
  33446. };
  33447. Animatable.prototype.goToFrame = function (frame) {
  33448. var animations = this._animations;
  33449. if (animations[0]) {
  33450. var fps = animations[0].framePerSecond;
  33451. var currentFrame = animations[0].currentFrame;
  33452. var adjustTime = frame - currentFrame;
  33453. var delay = adjustTime * 1000 / fps;
  33454. this._localDelayOffset -= delay;
  33455. }
  33456. for (var index = 0; index < animations.length; index++) {
  33457. animations[index].goToFrame(frame);
  33458. }
  33459. };
  33460. Animatable.prototype.pause = function () {
  33461. if (this._paused) {
  33462. return;
  33463. }
  33464. this._paused = true;
  33465. };
  33466. Animatable.prototype.restart = function () {
  33467. this._paused = false;
  33468. };
  33469. Animatable.prototype.stop = function (animationName) {
  33470. if (animationName) {
  33471. var idx = this._scene._activeAnimatables.indexOf(this);
  33472. if (idx > -1) {
  33473. var animations = this._animations;
  33474. for (var index = animations.length - 1; index >= 0; index--) {
  33475. if (typeof animationName === "string" && animations[index].name != animationName) {
  33476. continue;
  33477. }
  33478. animations[index].reset();
  33479. animations.splice(index, 1);
  33480. }
  33481. if (animations.length == 0) {
  33482. this._scene._activeAnimatables.splice(idx, 1);
  33483. if (this.onAnimationEnd) {
  33484. this.onAnimationEnd();
  33485. }
  33486. }
  33487. }
  33488. }
  33489. else {
  33490. var index = this._scene._activeAnimatables.indexOf(this);
  33491. if (index > -1) {
  33492. this._scene._activeAnimatables.splice(index, 1);
  33493. var animations = this._animations;
  33494. for (var index = 0; index < animations.length; index++) {
  33495. animations[index].reset();
  33496. }
  33497. if (this.onAnimationEnd) {
  33498. this.onAnimationEnd();
  33499. }
  33500. }
  33501. }
  33502. };
  33503. Animatable.prototype._animate = function (delay) {
  33504. if (this._paused) {
  33505. this.animationStarted = false;
  33506. if (!this._pausedDelay) {
  33507. this._pausedDelay = delay;
  33508. }
  33509. return true;
  33510. }
  33511. if (!this._localDelayOffset) {
  33512. this._localDelayOffset = delay;
  33513. }
  33514. else if (this._pausedDelay) {
  33515. this._localDelayOffset += delay - this._pausedDelay;
  33516. this._pausedDelay = null;
  33517. }
  33518. // Animating
  33519. var running = false;
  33520. var animations = this._animations;
  33521. var index;
  33522. for (index = 0; index < animations.length; index++) {
  33523. var animation = animations[index];
  33524. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this.speedRatio);
  33525. running = running || isRunning;
  33526. }
  33527. this.animationStarted = running;
  33528. if (!running) {
  33529. // Remove from active animatables
  33530. index = this._scene._activeAnimatables.indexOf(this);
  33531. this._scene._activeAnimatables.splice(index, 1);
  33532. }
  33533. if (!running && this.onAnimationEnd) {
  33534. this.onAnimationEnd();
  33535. this.onAnimationEnd = null;
  33536. }
  33537. return running;
  33538. };
  33539. return Animatable;
  33540. }());
  33541. BABYLON.Animatable = Animatable;
  33542. })(BABYLON || (BABYLON = {}));
  33543. //# sourceMappingURL=babylon.animatable.js.map
  33544. var BABYLON;
  33545. (function (BABYLON) {
  33546. var EasingFunction = (function () {
  33547. function EasingFunction() {
  33548. // Properties
  33549. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  33550. }
  33551. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  33552. get: function () {
  33553. return EasingFunction._EASINGMODE_EASEIN;
  33554. },
  33555. enumerable: true,
  33556. configurable: true
  33557. });
  33558. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  33559. get: function () {
  33560. return EasingFunction._EASINGMODE_EASEOUT;
  33561. },
  33562. enumerable: true,
  33563. configurable: true
  33564. });
  33565. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  33566. get: function () {
  33567. return EasingFunction._EASINGMODE_EASEINOUT;
  33568. },
  33569. enumerable: true,
  33570. configurable: true
  33571. });
  33572. EasingFunction.prototype.setEasingMode = function (easingMode) {
  33573. var n = Math.min(Math.max(easingMode, 0), 2);
  33574. this._easingMode = n;
  33575. };
  33576. EasingFunction.prototype.getEasingMode = function () {
  33577. return this._easingMode;
  33578. };
  33579. EasingFunction.prototype.easeInCore = function (gradient) {
  33580. throw new Error('You must implement this method');
  33581. };
  33582. EasingFunction.prototype.ease = function (gradient) {
  33583. switch (this._easingMode) {
  33584. case EasingFunction.EASINGMODE_EASEIN:
  33585. return this.easeInCore(gradient);
  33586. case EasingFunction.EASINGMODE_EASEOUT:
  33587. return (1 - this.easeInCore(1 - gradient));
  33588. }
  33589. if (gradient >= 0.5) {
  33590. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  33591. }
  33592. return (this.easeInCore(gradient * 2) * 0.5);
  33593. };
  33594. return EasingFunction;
  33595. }());
  33596. //Statics
  33597. EasingFunction._EASINGMODE_EASEIN = 0;
  33598. EasingFunction._EASINGMODE_EASEOUT = 1;
  33599. EasingFunction._EASINGMODE_EASEINOUT = 2;
  33600. BABYLON.EasingFunction = EasingFunction;
  33601. var CircleEase = (function (_super) {
  33602. __extends(CircleEase, _super);
  33603. function CircleEase() {
  33604. return _super.apply(this, arguments) || this;
  33605. }
  33606. CircleEase.prototype.easeInCore = function (gradient) {
  33607. gradient = Math.max(0, Math.min(1, gradient));
  33608. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  33609. };
  33610. return CircleEase;
  33611. }(EasingFunction));
  33612. BABYLON.CircleEase = CircleEase;
  33613. var BackEase = (function (_super) {
  33614. __extends(BackEase, _super);
  33615. function BackEase(amplitude) {
  33616. if (amplitude === void 0) { amplitude = 1; }
  33617. var _this = _super.call(this) || this;
  33618. _this.amplitude = amplitude;
  33619. return _this;
  33620. }
  33621. BackEase.prototype.easeInCore = function (gradient) {
  33622. var num = Math.max(0, this.amplitude);
  33623. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  33624. };
  33625. return BackEase;
  33626. }(EasingFunction));
  33627. BABYLON.BackEase = BackEase;
  33628. var BounceEase = (function (_super) {
  33629. __extends(BounceEase, _super);
  33630. function BounceEase(bounces, bounciness) {
  33631. if (bounces === void 0) { bounces = 3; }
  33632. if (bounciness === void 0) { bounciness = 2; }
  33633. var _this = _super.call(this) || this;
  33634. _this.bounces = bounces;
  33635. _this.bounciness = bounciness;
  33636. return _this;
  33637. }
  33638. BounceEase.prototype.easeInCore = function (gradient) {
  33639. var y = Math.max(0.0, this.bounces);
  33640. var bounciness = this.bounciness;
  33641. if (bounciness <= 1.0) {
  33642. bounciness = 1.001;
  33643. }
  33644. var num9 = Math.pow(bounciness, y);
  33645. var num5 = 1.0 - bounciness;
  33646. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  33647. var num15 = gradient * num4;
  33648. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  33649. var num3 = Math.floor(num65);
  33650. var num13 = num3 + 1.0;
  33651. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  33652. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  33653. var num7 = (num8 + num12) * 0.5;
  33654. var num6 = gradient - num7;
  33655. var num2 = num7 - num8;
  33656. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  33657. };
  33658. return BounceEase;
  33659. }(EasingFunction));
  33660. BABYLON.BounceEase = BounceEase;
  33661. var CubicEase = (function (_super) {
  33662. __extends(CubicEase, _super);
  33663. function CubicEase() {
  33664. return _super.apply(this, arguments) || this;
  33665. }
  33666. CubicEase.prototype.easeInCore = function (gradient) {
  33667. return (gradient * gradient * gradient);
  33668. };
  33669. return CubicEase;
  33670. }(EasingFunction));
  33671. BABYLON.CubicEase = CubicEase;
  33672. var ElasticEase = (function (_super) {
  33673. __extends(ElasticEase, _super);
  33674. function ElasticEase(oscillations, springiness) {
  33675. if (oscillations === void 0) { oscillations = 3; }
  33676. if (springiness === void 0) { springiness = 3; }
  33677. var _this = _super.call(this) || this;
  33678. _this.oscillations = oscillations;
  33679. _this.springiness = springiness;
  33680. return _this;
  33681. }
  33682. ElasticEase.prototype.easeInCore = function (gradient) {
  33683. var num2;
  33684. var num3 = Math.max(0.0, this.oscillations);
  33685. var num = Math.max(0.0, this.springiness);
  33686. if (num == 0) {
  33687. num2 = gradient;
  33688. }
  33689. else {
  33690. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  33691. }
  33692. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  33693. };
  33694. return ElasticEase;
  33695. }(EasingFunction));
  33696. BABYLON.ElasticEase = ElasticEase;
  33697. var ExponentialEase = (function (_super) {
  33698. __extends(ExponentialEase, _super);
  33699. function ExponentialEase(exponent) {
  33700. if (exponent === void 0) { exponent = 2; }
  33701. var _this = _super.call(this) || this;
  33702. _this.exponent = exponent;
  33703. return _this;
  33704. }
  33705. ExponentialEase.prototype.easeInCore = function (gradient) {
  33706. if (this.exponent <= 0) {
  33707. return gradient;
  33708. }
  33709. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  33710. };
  33711. return ExponentialEase;
  33712. }(EasingFunction));
  33713. BABYLON.ExponentialEase = ExponentialEase;
  33714. var PowerEase = (function (_super) {
  33715. __extends(PowerEase, _super);
  33716. function PowerEase(power) {
  33717. if (power === void 0) { power = 2; }
  33718. var _this = _super.call(this) || this;
  33719. _this.power = power;
  33720. return _this;
  33721. }
  33722. PowerEase.prototype.easeInCore = function (gradient) {
  33723. var y = Math.max(0.0, this.power);
  33724. return Math.pow(gradient, y);
  33725. };
  33726. return PowerEase;
  33727. }(EasingFunction));
  33728. BABYLON.PowerEase = PowerEase;
  33729. var QuadraticEase = (function (_super) {
  33730. __extends(QuadraticEase, _super);
  33731. function QuadraticEase() {
  33732. return _super.apply(this, arguments) || this;
  33733. }
  33734. QuadraticEase.prototype.easeInCore = function (gradient) {
  33735. return (gradient * gradient);
  33736. };
  33737. return QuadraticEase;
  33738. }(EasingFunction));
  33739. BABYLON.QuadraticEase = QuadraticEase;
  33740. var QuarticEase = (function (_super) {
  33741. __extends(QuarticEase, _super);
  33742. function QuarticEase() {
  33743. return _super.apply(this, arguments) || this;
  33744. }
  33745. QuarticEase.prototype.easeInCore = function (gradient) {
  33746. return (gradient * gradient * gradient * gradient);
  33747. };
  33748. return QuarticEase;
  33749. }(EasingFunction));
  33750. BABYLON.QuarticEase = QuarticEase;
  33751. var QuinticEase = (function (_super) {
  33752. __extends(QuinticEase, _super);
  33753. function QuinticEase() {
  33754. return _super.apply(this, arguments) || this;
  33755. }
  33756. QuinticEase.prototype.easeInCore = function (gradient) {
  33757. return (gradient * gradient * gradient * gradient * gradient);
  33758. };
  33759. return QuinticEase;
  33760. }(EasingFunction));
  33761. BABYLON.QuinticEase = QuinticEase;
  33762. var SineEase = (function (_super) {
  33763. __extends(SineEase, _super);
  33764. function SineEase() {
  33765. return _super.apply(this, arguments) || this;
  33766. }
  33767. SineEase.prototype.easeInCore = function (gradient) {
  33768. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  33769. };
  33770. return SineEase;
  33771. }(EasingFunction));
  33772. BABYLON.SineEase = SineEase;
  33773. var BezierCurveEase = (function (_super) {
  33774. __extends(BezierCurveEase, _super);
  33775. function BezierCurveEase(x1, y1, x2, y2) {
  33776. if (x1 === void 0) { x1 = 0; }
  33777. if (y1 === void 0) { y1 = 0; }
  33778. if (x2 === void 0) { x2 = 1; }
  33779. if (y2 === void 0) { y2 = 1; }
  33780. var _this = _super.call(this) || this;
  33781. _this.x1 = x1;
  33782. _this.y1 = y1;
  33783. _this.x2 = x2;
  33784. _this.y2 = y2;
  33785. return _this;
  33786. }
  33787. BezierCurveEase.prototype.easeInCore = function (gradient) {
  33788. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  33789. };
  33790. return BezierCurveEase;
  33791. }(EasingFunction));
  33792. BABYLON.BezierCurveEase = BezierCurveEase;
  33793. })(BABYLON || (BABYLON = {}));
  33794. //# sourceMappingURL=babylon.easing.js.map
  33795. /// <reference path="..\babylon.node.ts" />
  33796. var BABYLON;
  33797. (function (BABYLON) {
  33798. var Bone = (function (_super) {
  33799. __extends(Bone, _super);
  33800. function Bone(name, skeleton, parentBone, matrix, restPose) {
  33801. var _this = _super.call(this, name, skeleton.getScene()) || this;
  33802. _this.name = name;
  33803. _this.children = new Array();
  33804. _this.animations = new Array();
  33805. _this._worldTransform = new BABYLON.Matrix();
  33806. _this._absoluteTransform = new BABYLON.Matrix();
  33807. _this._invertedAbsoluteTransform = new BABYLON.Matrix();
  33808. _this._scaleMatrix = BABYLON.Matrix.Identity();
  33809. _this._scaleVector = new BABYLON.Vector3(1, 1, 1);
  33810. _this._negateScaleChildren = new BABYLON.Vector3(1, 1, 1);
  33811. _this._scalingDeterminant = 1;
  33812. _this._skeleton = skeleton;
  33813. _this._localMatrix = matrix;
  33814. _this._baseMatrix = matrix.clone();
  33815. _this._restPose = restPose ? restPose : matrix.clone();
  33816. skeleton.bones.push(_this);
  33817. if (parentBone) {
  33818. _this._parent = parentBone;
  33819. parentBone.children.push(_this);
  33820. }
  33821. else {
  33822. _this._parent = null;
  33823. }
  33824. _this._updateDifferenceMatrix();
  33825. if (_this.getAbsoluteTransform().determinant() < 0) {
  33826. _this._scalingDeterminant *= -1;
  33827. }
  33828. return _this;
  33829. }
  33830. Object.defineProperty(Bone.prototype, "_matrix", {
  33831. get: function () {
  33832. return this._localMatrix;
  33833. },
  33834. set: function (val) {
  33835. if (this._localMatrix) {
  33836. this._localMatrix.copyFrom(val);
  33837. }
  33838. else {
  33839. this._localMatrix = val;
  33840. }
  33841. },
  33842. enumerable: true,
  33843. configurable: true
  33844. });
  33845. // Members
  33846. Bone.prototype.getParent = function () {
  33847. return this._parent;
  33848. };
  33849. Bone.prototype.getLocalMatrix = function () {
  33850. return this._localMatrix;
  33851. };
  33852. Bone.prototype.getBaseMatrix = function () {
  33853. return this._baseMatrix;
  33854. };
  33855. Bone.prototype.getRestPose = function () {
  33856. return this._restPose;
  33857. };
  33858. Bone.prototype.returnToRest = function () {
  33859. this.updateMatrix(this._restPose.clone());
  33860. };
  33861. Bone.prototype.getWorldMatrix = function () {
  33862. return this._worldTransform;
  33863. };
  33864. Bone.prototype.getInvertedAbsoluteTransform = function () {
  33865. return this._invertedAbsoluteTransform;
  33866. };
  33867. Bone.prototype.getAbsoluteTransform = function () {
  33868. return this._absoluteTransform;
  33869. };
  33870. // Methods
  33871. Bone.prototype.updateMatrix = function (matrix, updateDifferenceMatrix) {
  33872. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  33873. this._baseMatrix = matrix.clone();
  33874. this._localMatrix = matrix.clone();
  33875. this._skeleton._markAsDirty();
  33876. if (updateDifferenceMatrix) {
  33877. this._updateDifferenceMatrix();
  33878. }
  33879. };
  33880. Bone.prototype._updateDifferenceMatrix = function (rootMatrix) {
  33881. if (!rootMatrix) {
  33882. rootMatrix = this._baseMatrix;
  33883. }
  33884. if (this._parent) {
  33885. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  33886. }
  33887. else {
  33888. this._absoluteTransform.copyFrom(rootMatrix);
  33889. }
  33890. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  33891. for (var index = 0; index < this.children.length; index++) {
  33892. this.children[index]._updateDifferenceMatrix();
  33893. }
  33894. };
  33895. Bone.prototype.markAsDirty = function () {
  33896. this._currentRenderId++;
  33897. this._skeleton._markAsDirty();
  33898. };
  33899. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) {
  33900. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  33901. if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; }
  33902. // all animation may be coming from a library skeleton, so may need to create animation
  33903. if (this.animations.length === 0) {
  33904. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  33905. this.animations[0].setKeys([]);
  33906. }
  33907. // get animation info / verify there is such a range from the source bone
  33908. var sourceRange = source.animations[0].getRange(rangeName);
  33909. if (!sourceRange) {
  33910. return false;
  33911. }
  33912. var from = sourceRange.from;
  33913. var to = sourceRange.to;
  33914. var sourceKeys = source.animations[0].getKeys();
  33915. // rescaling prep
  33916. var sourceBoneLength = source.length;
  33917. var sourceParent = source.getParent();
  33918. var parent = this.getParent();
  33919. var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  33920. var parentRatio = parentScalingReqd ? parent.length / sourceParent.length : null;
  33921. var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);
  33922. var destKeys = this.animations[0].getKeys();
  33923. // loop vars declaration
  33924. var orig;
  33925. var origTranslation;
  33926. var mat;
  33927. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  33928. orig = sourceKeys[key];
  33929. if (orig.frame >= from && orig.frame <= to) {
  33930. if (rescaleAsRequired) {
  33931. mat = orig.value.clone();
  33932. // scale based on parent ratio, when bone has parent
  33933. if (parentScalingReqd) {
  33934. origTranslation = mat.getTranslation();
  33935. mat.setTranslation(origTranslation.scaleInPlace(parentRatio));
  33936. }
  33937. else if (dimensionsScalingReqd) {
  33938. origTranslation = mat.getTranslation();
  33939. mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));
  33940. }
  33941. else {
  33942. mat = orig.value;
  33943. }
  33944. }
  33945. else {
  33946. mat = orig.value;
  33947. }
  33948. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  33949. }
  33950. }
  33951. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  33952. return true;
  33953. };
  33954. /**
  33955. * Translate the bone in local or world space.
  33956. * @param vec The amount to translate the bone.
  33957. * @param space The space that the translation is in.
  33958. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  33959. */
  33960. Bone.prototype.translate = function (vec, space, mesh) {
  33961. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  33962. var lm = this.getLocalMatrix();
  33963. if (space == BABYLON.Space.LOCAL) {
  33964. lm.m[12] += vec.x;
  33965. lm.m[13] += vec.y;
  33966. lm.m[14] += vec.z;
  33967. }
  33968. else {
  33969. var wm;
  33970. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  33971. if (mesh) {
  33972. wm = mesh.getWorldMatrix();
  33973. }
  33974. this._skeleton.computeAbsoluteTransforms();
  33975. var tmat = BABYLON.Tmp.Matrix[0];
  33976. var tvec = BABYLON.Tmp.Vector3[0];
  33977. if (mesh) {
  33978. tmat.copyFrom(this._parent.getAbsoluteTransform());
  33979. tmat.multiplyToRef(wm, tmat);
  33980. }
  33981. else {
  33982. tmat.copyFrom(this._parent.getAbsoluteTransform());
  33983. }
  33984. tmat.m[12] = 0;
  33985. tmat.m[13] = 0;
  33986. tmat.m[14] = 0;
  33987. tmat.invert();
  33988. BABYLON.Vector3.TransformCoordinatesToRef(vec, tmat, tvec);
  33989. lm.m[12] += tvec.x;
  33990. lm.m[13] += tvec.y;
  33991. lm.m[14] += tvec.z;
  33992. }
  33993. this.markAsDirty();
  33994. };
  33995. /**
  33996. * Set the postion of the bone in local or world space.
  33997. * @param position The position to set the bone.
  33998. * @param space The space that the position is in.
  33999. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  34000. */
  34001. Bone.prototype.setPosition = function (position, space, mesh) {
  34002. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  34003. var lm = this.getLocalMatrix();
  34004. if (space == BABYLON.Space.LOCAL) {
  34005. lm.m[12] = position.x;
  34006. lm.m[13] = position.y;
  34007. lm.m[14] = position.z;
  34008. }
  34009. else {
  34010. var wm;
  34011. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  34012. if (mesh) {
  34013. wm = mesh.getWorldMatrix();
  34014. }
  34015. this._skeleton.computeAbsoluteTransforms();
  34016. var tmat = BABYLON.Tmp.Matrix[0];
  34017. var vec = BABYLON.Tmp.Vector3[0];
  34018. if (mesh) {
  34019. tmat.copyFrom(this._parent.getAbsoluteTransform());
  34020. tmat.multiplyToRef(wm, tmat);
  34021. }
  34022. else {
  34023. tmat.copyFrom(this._parent.getAbsoluteTransform());
  34024. }
  34025. tmat.invert();
  34026. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, vec);
  34027. lm.m[12] = vec.x;
  34028. lm.m[13] = vec.y;
  34029. lm.m[14] = vec.z;
  34030. }
  34031. this.markAsDirty();
  34032. };
  34033. /**
  34034. * Set the absolute postion of the bone (world space).
  34035. * @param position The position to set the bone.
  34036. * @param mesh The mesh that this bone is attached to.
  34037. */
  34038. Bone.prototype.setAbsolutePosition = function (position, mesh) {
  34039. this.setPosition(position, BABYLON.Space.WORLD, mesh);
  34040. };
  34041. /**
  34042. * Set the scale of the bone on the x, y and z axes.
  34043. * @param x The scale of the bone on the x axis.
  34044. * @param x The scale of the bone on the y axis.
  34045. * @param z The scale of the bone on the z axis.
  34046. * @param scaleChildren Set this to true if children of the bone should be scaled.
  34047. */
  34048. Bone.prototype.setScale = function (x, y, z, scaleChildren) {
  34049. if (scaleChildren === void 0) { scaleChildren = false; }
  34050. if (this.animations[0] && !this.animations[0].isStopped()) {
  34051. if (!scaleChildren) {
  34052. this._negateScaleChildren.x = 1 / x;
  34053. this._negateScaleChildren.y = 1 / y;
  34054. this._negateScaleChildren.z = 1 / z;
  34055. }
  34056. this._syncScaleVector();
  34057. }
  34058. this.scale(x / this._scaleVector.x, y / this._scaleVector.y, z / this._scaleVector.z, scaleChildren);
  34059. };
  34060. /**
  34061. * Scale the bone on the x, y and z axes.
  34062. * @param x The amount to scale the bone on the x axis.
  34063. * @param x The amount to scale the bone on the y axis.
  34064. * @param z The amount to scale the bone on the z axis.
  34065. * @param scaleChildren Set this to true if children of the bone should be scaled.
  34066. */
  34067. Bone.prototype.scale = function (x, y, z, scaleChildren) {
  34068. if (scaleChildren === void 0) { scaleChildren = false; }
  34069. var locMat = this.getLocalMatrix();
  34070. var origLocMat = BABYLON.Tmp.Matrix[0];
  34071. origLocMat.copyFrom(locMat);
  34072. var origLocMatInv = BABYLON.Tmp.Matrix[1];
  34073. origLocMatInv.copyFrom(origLocMat);
  34074. origLocMatInv.invert();
  34075. var scaleMat = BABYLON.Tmp.Matrix[2];
  34076. BABYLON.Matrix.FromValuesToRef(x, 0, 0, 0, 0, y, 0, 0, 0, 0, z, 0, 0, 0, 0, 1, scaleMat);
  34077. this._scaleMatrix.multiplyToRef(scaleMat, this._scaleMatrix);
  34078. this._scaleVector.x *= x;
  34079. this._scaleVector.y *= y;
  34080. this._scaleVector.z *= z;
  34081. locMat.multiplyToRef(origLocMatInv, locMat);
  34082. locMat.multiplyToRef(scaleMat, locMat);
  34083. locMat.multiplyToRef(origLocMat, locMat);
  34084. var parent = this.getParent();
  34085. if (parent) {
  34086. locMat.multiplyToRef(parent.getAbsoluteTransform(), this.getAbsoluteTransform());
  34087. }
  34088. else {
  34089. this.getAbsoluteTransform().copyFrom(locMat);
  34090. }
  34091. var len = this.children.length;
  34092. scaleMat.invert();
  34093. for (var i = 0; i < len; i++) {
  34094. var child = this.children[i];
  34095. var cm = child.getLocalMatrix();
  34096. cm.multiplyToRef(scaleMat, cm);
  34097. var lm = child.getLocalMatrix();
  34098. lm.m[12] *= x;
  34099. lm.m[13] *= y;
  34100. lm.m[14] *= z;
  34101. }
  34102. this.computeAbsoluteTransforms();
  34103. if (scaleChildren) {
  34104. for (var i = 0; i < len; i++) {
  34105. this.children[i].scale(x, y, z, scaleChildren);
  34106. }
  34107. }
  34108. this.markAsDirty();
  34109. };
  34110. /**
  34111. * Set the yaw, pitch, and roll of the bone in local or world space.
  34112. * @param yaw The rotation of the bone on the y axis.
  34113. * @param pitch The rotation of the bone on the x axis.
  34114. * @param roll The rotation of the bone on the z axis.
  34115. * @param space The space that the axes of rotation are in.
  34116. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  34117. */
  34118. Bone.prototype.setYawPitchRoll = function (yaw, pitch, roll, space, mesh) {
  34119. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  34120. var rotMat = BABYLON.Tmp.Matrix[0];
  34121. BABYLON.Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, rotMat);
  34122. var rotMatInv = BABYLON.Tmp.Matrix[1];
  34123. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  34124. rotMatInv.multiplyToRef(rotMat, rotMat);
  34125. this._rotateWithMatrix(rotMat, space, mesh);
  34126. };
  34127. /**
  34128. * Rotate the bone on an axis in local or world space.
  34129. * @param axis The axis to rotate the bone on.
  34130. * @param amount The amount to rotate the bone.
  34131. * @param space The space that the axis is in.
  34132. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  34133. */
  34134. Bone.prototype.rotate = function (axis, amount, space, mesh) {
  34135. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  34136. var rmat = BABYLON.Tmp.Matrix[0];
  34137. rmat.m[12] = 0;
  34138. rmat.m[13] = 0;
  34139. rmat.m[14] = 0;
  34140. BABYLON.Matrix.RotationAxisToRef(axis, amount, rmat);
  34141. this._rotateWithMatrix(rmat, space, mesh);
  34142. };
  34143. /**
  34144. * Set the rotation of the bone to a particular axis angle in local or world space.
  34145. * @param axis The axis to rotate the bone on.
  34146. * @param angle The angle that the bone should be rotated to.
  34147. * @param space The space that the axis is in.
  34148. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  34149. */
  34150. Bone.prototype.setAxisAngle = function (axis, angle, space, mesh) {
  34151. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  34152. var rotMat = BABYLON.Tmp.Matrix[0];
  34153. BABYLON.Matrix.RotationAxisToRef(axis, angle, rotMat);
  34154. var rotMatInv = BABYLON.Tmp.Matrix[1];
  34155. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  34156. rotMatInv.multiplyToRef(rotMat, rotMat);
  34157. this._rotateWithMatrix(rotMat, space, mesh);
  34158. };
  34159. /**
  34160. * Set the euler rotation of the bone in local of world space.
  34161. * @param rotation The euler rotation that the bone should be set to.
  34162. * @param space The space that the rotation is in.
  34163. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  34164. */
  34165. Bone.prototype.setRotation = function (rotation, space, mesh) {
  34166. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  34167. this.setYawPitchRoll(rotation.y, rotation.x, rotation.z, space, mesh);
  34168. };
  34169. /**
  34170. * Set the quaternion rotation of the bone in local of world space.
  34171. * @param quat The quaternion rotation that the bone should be set to.
  34172. * @param space The space that the rotation is in.
  34173. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  34174. */
  34175. Bone.prototype.setRotationQuaternion = function (quat, space, mesh) {
  34176. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  34177. var rotMatInv = BABYLON.Tmp.Matrix[0];
  34178. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  34179. var rotMat = BABYLON.Tmp.Matrix[1];
  34180. BABYLON.Matrix.FromQuaternionToRef(quat, rotMat);
  34181. rotMatInv.multiplyToRef(rotMat, rotMat);
  34182. this._rotateWithMatrix(rotMat, space, mesh);
  34183. };
  34184. /**
  34185. * Set the rotation matrix of the bone in local of world space.
  34186. * @param rotMat The rotation matrix that the bone should be set to.
  34187. * @param space The space that the rotation is in.
  34188. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  34189. */
  34190. Bone.prototype.setRotationMatrix = function (rotMat, space, mesh) {
  34191. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  34192. var rotMatInv = BABYLON.Tmp.Matrix[0];
  34193. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  34194. var rotMat2 = BABYLON.Tmp.Matrix[1];
  34195. rotMat2.copyFrom(rotMat);
  34196. rotMatInv.multiplyToRef(rotMat, rotMat2);
  34197. this._rotateWithMatrix(rotMat2, space, mesh);
  34198. };
  34199. Bone.prototype._rotateWithMatrix = function (rmat, space, mesh) {
  34200. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  34201. var lmat = this.getLocalMatrix();
  34202. var lx = lmat.m[12];
  34203. var ly = lmat.m[13];
  34204. var lz = lmat.m[14];
  34205. var parent = this.getParent();
  34206. var parentScale = BABYLON.Tmp.Matrix[3];
  34207. var parentScaleInv = BABYLON.Tmp.Matrix[4];
  34208. if (parent) {
  34209. if (space == BABYLON.Space.WORLD) {
  34210. if (mesh) {
  34211. parentScale.copyFrom(mesh.getWorldMatrix());
  34212. parent.getAbsoluteTransform().multiplyToRef(parentScale, parentScale);
  34213. }
  34214. else {
  34215. parentScale.copyFrom(parent.getAbsoluteTransform());
  34216. }
  34217. }
  34218. else {
  34219. parentScale = parent._scaleMatrix;
  34220. }
  34221. parentScaleInv.copyFrom(parentScale);
  34222. parentScaleInv.invert();
  34223. lmat.multiplyToRef(parentScale, lmat);
  34224. lmat.multiplyToRef(rmat, lmat);
  34225. lmat.multiplyToRef(parentScaleInv, lmat);
  34226. }
  34227. else {
  34228. if (space == BABYLON.Space.WORLD && mesh) {
  34229. parentScale.copyFrom(mesh.getWorldMatrix());
  34230. parentScaleInv.copyFrom(parentScale);
  34231. parentScaleInv.invert();
  34232. lmat.multiplyToRef(parentScale, lmat);
  34233. lmat.multiplyToRef(rmat, lmat);
  34234. lmat.multiplyToRef(parentScaleInv, lmat);
  34235. }
  34236. else {
  34237. lmat.multiplyToRef(rmat, lmat);
  34238. }
  34239. }
  34240. lmat.m[12] = lx;
  34241. lmat.m[13] = ly;
  34242. lmat.m[14] = lz;
  34243. this.computeAbsoluteTransforms();
  34244. this.markAsDirty();
  34245. };
  34246. Bone.prototype._getNegativeRotationToRef = function (rotMatInv, space, mesh) {
  34247. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  34248. if (space == BABYLON.Space.WORLD) {
  34249. var scaleMatrix = BABYLON.Tmp.Matrix[2];
  34250. scaleMatrix.copyFrom(this._scaleMatrix);
  34251. rotMatInv.copyFrom(this.getAbsoluteTransform());
  34252. if (mesh) {
  34253. rotMatInv.multiplyToRef(mesh.getWorldMatrix(), rotMatInv);
  34254. var meshScale = BABYLON.Tmp.Matrix[3];
  34255. BABYLON.Matrix.ScalingToRef(mesh.scaling.x, mesh.scaling.y, mesh.scaling.z, meshScale);
  34256. scaleMatrix.multiplyToRef(meshScale, scaleMatrix);
  34257. }
  34258. rotMatInv.invert();
  34259. scaleMatrix.m[0] *= this._scalingDeterminant;
  34260. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  34261. }
  34262. else {
  34263. rotMatInv.copyFrom(this.getLocalMatrix());
  34264. rotMatInv.invert();
  34265. var scaleMatrix = BABYLON.Tmp.Matrix[2];
  34266. scaleMatrix.copyFrom(this._scaleMatrix);
  34267. if (this._parent) {
  34268. var pscaleMatrix = BABYLON.Tmp.Matrix[3];
  34269. pscaleMatrix.copyFrom(this._parent._scaleMatrix);
  34270. pscaleMatrix.invert();
  34271. pscaleMatrix.multiplyToRef(rotMatInv, rotMatInv);
  34272. }
  34273. else {
  34274. scaleMatrix.m[0] *= this._scalingDeterminant;
  34275. }
  34276. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  34277. }
  34278. };
  34279. /**
  34280. * Get the scale of the bone
  34281. * @returns the scale of the bone
  34282. */
  34283. Bone.prototype.getScale = function () {
  34284. return this._scaleVector.clone();
  34285. };
  34286. /**
  34287. * Copy the scale of the bone to a vector3.
  34288. * @param result The vector3 to copy the scale to
  34289. */
  34290. Bone.prototype.getScaleToRef = function (result) {
  34291. result.copyFrom(this._scaleVector);
  34292. };
  34293. /**
  34294. * Get the position of the bone in local or world space.
  34295. * @param space The space that the returned position is in.
  34296. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  34297. * @returns The position of the bone
  34298. */
  34299. Bone.prototype.getPosition = function (space, mesh) {
  34300. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  34301. var pos = BABYLON.Vector3.Zero();
  34302. this.getPositionToRef(space, mesh, pos);
  34303. return pos;
  34304. };
  34305. /**
  34306. * Copy the position of the bone to a vector3 in local or world space.
  34307. * @param space The space that the returned position is in.
  34308. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  34309. * @param result The vector3 to copy the position to.
  34310. */
  34311. Bone.prototype.getPositionToRef = function (space, mesh, result) {
  34312. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  34313. if (space == BABYLON.Space.LOCAL) {
  34314. var lm = this.getLocalMatrix();
  34315. result.x = lm.m[12];
  34316. result.y = lm.m[13];
  34317. result.z = lm.m[14];
  34318. }
  34319. else {
  34320. var wm;
  34321. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  34322. if (mesh) {
  34323. wm = mesh.getWorldMatrix();
  34324. }
  34325. this._skeleton.computeAbsoluteTransforms();
  34326. var tmat = BABYLON.Tmp.Matrix[0];
  34327. if (mesh) {
  34328. tmat.copyFrom(this.getAbsoluteTransform());
  34329. tmat.multiplyToRef(wm, tmat);
  34330. }
  34331. else {
  34332. tmat = this.getAbsoluteTransform();
  34333. }
  34334. result.x = tmat.m[12];
  34335. result.y = tmat.m[13];
  34336. result.z = tmat.m[14];
  34337. }
  34338. };
  34339. /**
  34340. * Get the absolute position of the bone (world space).
  34341. * @param mesh The mesh that this bone is attached to.
  34342. * @returns The absolute position of the bone
  34343. */
  34344. Bone.prototype.getAbsolutePosition = function (mesh) {
  34345. var pos = BABYLON.Vector3.Zero();
  34346. this.getPositionToRef(BABYLON.Space.WORLD, mesh, pos);
  34347. return pos;
  34348. };
  34349. /**
  34350. * Copy the absolute position of the bone (world space) to the result param.
  34351. * @param mesh The mesh that this bone is attached to.
  34352. * @param result The vector3 to copy the absolute position to.
  34353. */
  34354. Bone.prototype.getAbsolutePositionToRef = function (mesh, result) {
  34355. this.getPositionToRef(BABYLON.Space.WORLD, mesh, result);
  34356. };
  34357. /**
  34358. * Compute the absolute transforms of this bone and its children.
  34359. */
  34360. Bone.prototype.computeAbsoluteTransforms = function () {
  34361. if (this._parent) {
  34362. this._localMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  34363. }
  34364. else {
  34365. this._absoluteTransform.copyFrom(this._localMatrix);
  34366. var poseMatrix = this._skeleton.getPoseMatrix();
  34367. if (poseMatrix) {
  34368. this._absoluteTransform.multiplyToRef(poseMatrix, this._absoluteTransform);
  34369. }
  34370. }
  34371. var children = this.children;
  34372. var len = children.length;
  34373. for (var i = 0; i < len; i++) {
  34374. children[i].computeAbsoluteTransforms();
  34375. }
  34376. };
  34377. Bone.prototype._syncScaleVector = function () {
  34378. var lm = this.getLocalMatrix();
  34379. var xsq = (lm.m[0] * lm.m[0] + lm.m[1] * lm.m[1] + lm.m[2] * lm.m[2]);
  34380. var ysq = (lm.m[4] * lm.m[4] + lm.m[5] * lm.m[5] + lm.m[6] * lm.m[6]);
  34381. var zsq = (lm.m[8] * lm.m[8] + lm.m[9] * lm.m[9] + lm.m[10] * lm.m[10]);
  34382. var xs = lm.m[0] * lm.m[1] * lm.m[2] * lm.m[3] < 0 ? -1 : 1;
  34383. var ys = lm.m[4] * lm.m[5] * lm.m[6] * lm.m[7] < 0 ? -1 : 1;
  34384. var zs = lm.m[8] * lm.m[9] * lm.m[10] * lm.m[11] < 0 ? -1 : 1;
  34385. this._scaleVector.x = xs * Math.sqrt(xsq);
  34386. this._scaleVector.y = ys * Math.sqrt(ysq);
  34387. this._scaleVector.z = zs * Math.sqrt(zsq);
  34388. if (this._parent) {
  34389. this._scaleVector.x /= this._parent._negateScaleChildren.x;
  34390. this._scaleVector.y /= this._parent._negateScaleChildren.y;
  34391. this._scaleVector.z /= this._parent._negateScaleChildren.z;
  34392. }
  34393. 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);
  34394. };
  34395. /**
  34396. * Get the world direction from an axis that is in the local space of the bone.
  34397. * @param localAxis The local direction that is used to compute the world direction.
  34398. * @param mesh The mesh that this bone is attached to.
  34399. * @returns The world direction
  34400. */
  34401. Bone.prototype.getDirection = function (localAxis, mesh) {
  34402. var result = BABYLON.Vector3.Zero();
  34403. this.getDirectionToRef(localAxis, mesh, result);
  34404. return result;
  34405. };
  34406. /**
  34407. * Copy the world direction to a vector3 from an axis that is in the local space of the bone.
  34408. * @param localAxis The local direction that is used to compute the world direction.
  34409. * @param mesh The mesh that this bone is attached to.
  34410. * @param result The vector3 that the world direction will be copied to.
  34411. */
  34412. Bone.prototype.getDirectionToRef = function (localAxis, mesh, result) {
  34413. var wm;
  34414. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  34415. if (mesh) {
  34416. wm = mesh.getWorldMatrix();
  34417. }
  34418. this._skeleton.computeAbsoluteTransforms();
  34419. var mat = BABYLON.Tmp.Matrix[0];
  34420. mat.copyFrom(this.getAbsoluteTransform());
  34421. if (mesh) {
  34422. mat.multiplyToRef(wm, mat);
  34423. }
  34424. BABYLON.Vector3.TransformNormalToRef(localAxis, mat, result);
  34425. result.normalize();
  34426. };
  34427. /**
  34428. * Get the euler rotation of the bone in local or world space.
  34429. * @param space The space that the rotation should be in.
  34430. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  34431. * @returns The euler rotation
  34432. */
  34433. Bone.prototype.getRotation = function (space, mesh) {
  34434. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  34435. var result = BABYLON.Vector3.Zero();
  34436. this.getRotationToRef(space, mesh, result);
  34437. return result;
  34438. };
  34439. /**
  34440. * Copy the euler rotation of the bone to a vector3. The rotation can be in either local or world space.
  34441. * @param space The space that the rotation should be in.
  34442. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  34443. * @param result The vector3 that the rotation should be copied to.
  34444. */
  34445. Bone.prototype.getRotationToRef = function (space, mesh, result) {
  34446. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  34447. var quat = BABYLON.Tmp.Quaternion[0];
  34448. this.getRotationQuaternionToRef(space, mesh, quat);
  34449. quat.toEulerAnglesToRef(result);
  34450. };
  34451. /**
  34452. * Get the quaternion rotation of the bone in either local or world space.
  34453. * @param space The space that the rotation should be in.
  34454. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  34455. * @returns The quaternion rotation
  34456. */
  34457. Bone.prototype.getRotationQuaternion = function (space, mesh) {
  34458. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  34459. var result = BABYLON.Quaternion.Identity();
  34460. this.getRotationQuaternionToRef(space, mesh, result);
  34461. return result;
  34462. };
  34463. /**
  34464. * Copy the quaternion rotation of the bone to a quaternion. The rotation can be in either local or world space.
  34465. * @param space The space that the rotation should be in.
  34466. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  34467. * @param result The quaternion that the rotation should be copied to.
  34468. */
  34469. Bone.prototype.getRotationQuaternionToRef = function (space, mesh, result) {
  34470. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  34471. if (space == BABYLON.Space.LOCAL) {
  34472. this.getLocalMatrix().decompose(BABYLON.Tmp.Vector3[0], result, BABYLON.Tmp.Vector3[1]);
  34473. }
  34474. else {
  34475. var mat = BABYLON.Tmp.Matrix[0];
  34476. var amat = this.getAbsoluteTransform();
  34477. if (mesh) {
  34478. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  34479. }
  34480. else {
  34481. mat.copyFrom(amat);
  34482. }
  34483. mat.m[0] *= this._scalingDeterminant;
  34484. mat.m[1] *= this._scalingDeterminant;
  34485. mat.m[2] *= this._scalingDeterminant;
  34486. mat.decompose(BABYLON.Tmp.Vector3[0], result, BABYLON.Tmp.Vector3[1]);
  34487. }
  34488. };
  34489. /**
  34490. * Get the rotation matrix of the bone in local or world space.
  34491. * @param space The space that the rotation should be in.
  34492. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  34493. * @returns The rotation matrix
  34494. */
  34495. Bone.prototype.getRotationMatrix = function (space, mesh) {
  34496. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  34497. var result = BABYLON.Matrix.Identity();
  34498. this.getRotationMatrixToRef(space, mesh, result);
  34499. return result;
  34500. };
  34501. /**
  34502. * Copy the rotation matrix of the bone to a matrix. The rotation can be in either local or world space.
  34503. * @param space The space that the rotation should be in.
  34504. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  34505. * @param result The quaternion that the rotation should be copied to.
  34506. */
  34507. Bone.prototype.getRotationMatrixToRef = function (space, mesh, result) {
  34508. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  34509. if (space == BABYLON.Space.LOCAL) {
  34510. this.getLocalMatrix().getRotationMatrixToRef(result);
  34511. }
  34512. else {
  34513. var mat = BABYLON.Tmp.Matrix[0];
  34514. var amat = this.getAbsoluteTransform();
  34515. if (mesh) {
  34516. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  34517. }
  34518. else {
  34519. mat.copyFrom(amat);
  34520. }
  34521. mat.m[0] *= this._scalingDeterminant;
  34522. mat.m[1] *= this._scalingDeterminant;
  34523. mat.m[2] *= this._scalingDeterminant;
  34524. mat.getRotationMatrixToRef(result);
  34525. }
  34526. };
  34527. /**
  34528. * Get the world position of a point that is in the local space of the bone.
  34529. * @param position The local position
  34530. * @param mesh The mesh that this bone is attached to.
  34531. * @returns The world position
  34532. */
  34533. Bone.prototype.getAbsolutePositionFromLocal = function (position, mesh) {
  34534. var result = BABYLON.Vector3.Zero();
  34535. this.getAbsolutePositionFromLocalToRef(position, mesh, result);
  34536. return result;
  34537. };
  34538. /**
  34539. * Get the world position of a point that is in the local space of the bone and copy it to the result param.
  34540. * @param position The local position
  34541. * @param mesh The mesh that this bone is attached to.
  34542. * @param result The vector3 that the world position should be copied to.
  34543. */
  34544. Bone.prototype.getAbsolutePositionFromLocalToRef = function (position, mesh, result) {
  34545. var wm;
  34546. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  34547. if (mesh) {
  34548. wm = mesh.getWorldMatrix();
  34549. }
  34550. this._skeleton.computeAbsoluteTransforms();
  34551. var tmat = BABYLON.Tmp.Matrix[0];
  34552. if (mesh) {
  34553. tmat.copyFrom(this.getAbsoluteTransform());
  34554. tmat.multiplyToRef(wm, tmat);
  34555. }
  34556. else {
  34557. tmat = this.getAbsoluteTransform();
  34558. }
  34559. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  34560. };
  34561. /**
  34562. * Get the local position of a point that is in world space.
  34563. * @param position The world position
  34564. * @param mesh The mesh that this bone is attached to.
  34565. * @returns The local position
  34566. */
  34567. Bone.prototype.getLocalPositionFromAbsolute = function (position, mesh) {
  34568. var result = BABYLON.Vector3.Zero();
  34569. this.getLocalPositionFromAbsoluteToRef(position, mesh, result);
  34570. return result;
  34571. };
  34572. /**
  34573. * Get the local position of a point that is in world space and copy it to the result param.
  34574. * @param position The world position
  34575. * @param mesh The mesh that this bone is attached to.
  34576. * @param result The vector3 that the local position should be copied to.
  34577. */
  34578. Bone.prototype.getLocalPositionFromAbsoluteToRef = function (position, mesh, result) {
  34579. var wm;
  34580. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  34581. if (mesh) {
  34582. wm = mesh.getWorldMatrix();
  34583. }
  34584. this._skeleton.computeAbsoluteTransforms();
  34585. var tmat = BABYLON.Tmp.Matrix[0];
  34586. tmat.copyFrom(this.getAbsoluteTransform());
  34587. if (mesh) {
  34588. tmat.multiplyToRef(wm, tmat);
  34589. }
  34590. tmat.invert();
  34591. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  34592. };
  34593. return Bone;
  34594. }(BABYLON.Node));
  34595. BABYLON.Bone = Bone;
  34596. })(BABYLON || (BABYLON = {}));
  34597. //# sourceMappingURL=babylon.bone.js.map
  34598. var BABYLON;
  34599. (function (BABYLON) {
  34600. var BoneIKController = (function () {
  34601. function BoneIKController(mesh, bone, options) {
  34602. this.targetPosition = BABYLON.Vector3.Zero();
  34603. this.poleTargetPosition = BABYLON.Vector3.Zero();
  34604. this.poleTargetLocalOffset = BABYLON.Vector3.Zero();
  34605. this.poleAngle = 0;
  34606. this.slerpAmount = 1;
  34607. this._bone1Quat = BABYLON.Quaternion.Identity();
  34608. this._bone1Mat = BABYLON.Matrix.Identity();
  34609. this._bone2Ang = Math.PI;
  34610. this._maxAngle = Math.PI;
  34611. this._rightHandedSystem = false;
  34612. this._bendAxis = BABYLON.Vector3.Right();
  34613. this._slerping = false;
  34614. this._adjustRoll = 0;
  34615. this._bone2 = bone;
  34616. this._bone1 = bone.getParent();
  34617. this.mesh = mesh;
  34618. var bonePos = bone.getPosition();
  34619. if (bone.getAbsoluteTransform().determinant() > 0) {
  34620. this._rightHandedSystem = true;
  34621. this._bendAxis.x = 0;
  34622. this._bendAxis.y = 0;
  34623. this._bendAxis.z = -1;
  34624. if (bonePos.x > bonePos.y && bonePos.x > bonePos.z) {
  34625. this._adjustRoll = Math.PI * .5;
  34626. this._bendAxis.z = 1;
  34627. }
  34628. }
  34629. if (this._bone1.length) {
  34630. var boneScale1 = this._bone1.getScale();
  34631. var boneScale2 = this._bone2.getScale();
  34632. this._bone1Length = this._bone1.length * boneScale1.y * this.mesh.scaling.y;
  34633. this._bone2Length = this._bone2.length * boneScale2.y * this.mesh.scaling.y;
  34634. }
  34635. else if (this._bone1.children[0]) {
  34636. mesh.computeWorldMatrix(true);
  34637. var pos1 = this._bone2.children[0].getAbsolutePosition(mesh);
  34638. var pos2 = this._bone2.getAbsolutePosition(mesh);
  34639. var pos3 = this._bone1.getAbsolutePosition(mesh);
  34640. this._bone1Length = BABYLON.Vector3.Distance(pos1, pos2);
  34641. this._bone2Length = BABYLON.Vector3.Distance(pos2, pos3);
  34642. }
  34643. this._bone1.getRotationMatrixToRef(BABYLON.Space.WORLD, mesh, this._bone1Mat);
  34644. this.maxAngle = Math.PI;
  34645. if (options) {
  34646. if (options.targetMesh) {
  34647. this.targetMesh = options.targetMesh;
  34648. this.targetMesh.computeWorldMatrix(true);
  34649. }
  34650. if (options.poleTargetMesh) {
  34651. this.poleTargetMesh = options.poleTargetMesh;
  34652. this.poleTargetMesh.computeWorldMatrix(true);
  34653. }
  34654. else if (options.poleTargetBone) {
  34655. this.poleTargetBone = options.poleTargetBone;
  34656. }
  34657. else if (this._bone1.getParent()) {
  34658. this.poleTargetBone = this._bone1.getParent();
  34659. }
  34660. if (options.poleTargetLocalOffset) {
  34661. this.poleTargetLocalOffset.copyFrom(options.poleTargetLocalOffset);
  34662. }
  34663. if (options.poleAngle) {
  34664. this.poleAngle = options.poleAngle;
  34665. }
  34666. if (options.bendAxis) {
  34667. this._bendAxis.copyFrom(options.bendAxis);
  34668. }
  34669. if (options.maxAngle) {
  34670. this.maxAngle = options.maxAngle;
  34671. }
  34672. if (options.slerpAmount) {
  34673. this.slerpAmount = options.slerpAmount;
  34674. }
  34675. }
  34676. }
  34677. Object.defineProperty(BoneIKController.prototype, "maxAngle", {
  34678. get: function () {
  34679. return this._maxAngle;
  34680. },
  34681. set: function (value) {
  34682. this._setMaxAngle(value);
  34683. },
  34684. enumerable: true,
  34685. configurable: true
  34686. });
  34687. BoneIKController.prototype._setMaxAngle = function (ang) {
  34688. if (ang < 0) {
  34689. ang = 0;
  34690. }
  34691. if (ang > Math.PI || ang == undefined) {
  34692. ang = Math.PI;
  34693. }
  34694. this._maxAngle = ang;
  34695. var a = this._bone1Length;
  34696. var b = this._bone2Length;
  34697. this._maxReach = Math.sqrt(a * a + b * b - 2 * a * b * Math.cos(ang));
  34698. };
  34699. BoneIKController.prototype.update = function () {
  34700. var bone1 = this._bone1;
  34701. var target = this.targetPosition;
  34702. var poleTarget = this.poleTargetPosition;
  34703. var mat1 = BoneIKController._tmpMats[0];
  34704. var mat2 = BoneIKController._tmpMats[1];
  34705. if (this.targetMesh) {
  34706. target.copyFrom(this.targetMesh.getAbsolutePosition());
  34707. }
  34708. if (this.poleTargetBone) {
  34709. this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset, this.mesh, poleTarget);
  34710. }
  34711. else if (this.poleTargetMesh) {
  34712. BABYLON.Vector3.TransformCoordinatesToRef(this.poleTargetLocalOffset, this.poleTargetMesh.getWorldMatrix(), poleTarget);
  34713. }
  34714. var bonePos = BoneIKController._tmpVecs[0];
  34715. var zaxis = BoneIKController._tmpVecs[1];
  34716. var xaxis = BoneIKController._tmpVecs[2];
  34717. var yaxis = BoneIKController._tmpVecs[3];
  34718. var upAxis = BoneIKController._tmpVecs[4];
  34719. var _tmpQuat = BoneIKController._tmpQuat;
  34720. bone1.getAbsolutePositionToRef(this.mesh, bonePos);
  34721. poleTarget.subtractToRef(bonePos, upAxis);
  34722. if (upAxis.x == 0 && upAxis.y == 0 && upAxis.z == 0) {
  34723. upAxis.y = 1;
  34724. }
  34725. else {
  34726. upAxis.normalize();
  34727. }
  34728. target.subtractToRef(bonePos, yaxis);
  34729. yaxis.normalize();
  34730. BABYLON.Vector3.CrossToRef(yaxis, upAxis, zaxis);
  34731. zaxis.normalize();
  34732. BABYLON.Vector3.CrossToRef(yaxis, zaxis, xaxis);
  34733. xaxis.normalize();
  34734. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1);
  34735. var a = this._bone1Length;
  34736. var b = this._bone2Length;
  34737. var c = BABYLON.Vector3.Distance(bonePos, target);
  34738. if (this._maxReach > 0) {
  34739. c = Math.min(this._maxReach, c);
  34740. }
  34741. var acosa = (b * b + c * c - a * a) / (2 * b * c);
  34742. var acosb = (c * c + a * a - b * b) / (2 * c * a);
  34743. if (acosa > 1) {
  34744. acosa = 1;
  34745. }
  34746. if (acosb > 1) {
  34747. acosb = 1;
  34748. }
  34749. if (acosa < -1) {
  34750. acosa = -1;
  34751. }
  34752. if (acosb < -1) {
  34753. acosb = -1;
  34754. }
  34755. var angA = Math.acos(acosa);
  34756. var angB = Math.acos(acosb);
  34757. var angC = -angA - angB;
  34758. if (this._rightHandedSystem) {
  34759. BABYLON.Matrix.RotationYawPitchRollToRef(0, 0, this._adjustRoll, mat2);
  34760. mat2.multiplyToRef(mat1, mat1);
  34761. BABYLON.Matrix.RotationAxisToRef(this._bendAxis, angB, mat2);
  34762. mat2.multiplyToRef(mat1, mat1);
  34763. }
  34764. else {
  34765. var _tmpVec = BoneIKController._tmpVecs[5];
  34766. _tmpVec.copyFrom(this._bendAxis);
  34767. _tmpVec.x *= -1;
  34768. BABYLON.Matrix.RotationAxisToRef(_tmpVec, -angB, mat2);
  34769. mat2.multiplyToRef(mat1, mat1);
  34770. }
  34771. if (this.poleAngle) {
  34772. BABYLON.Matrix.RotationAxisToRef(yaxis, this.poleAngle, mat2);
  34773. mat1.multiplyToRef(mat2, mat1);
  34774. }
  34775. if (this.slerpAmount < 1) {
  34776. if (!this._slerping) {
  34777. BABYLON.Quaternion.FromRotationMatrixToRef(this._bone1Mat, this._bone1Quat);
  34778. }
  34779. BABYLON.Quaternion.FromRotationMatrixToRef(mat1, _tmpQuat);
  34780. BABYLON.Quaternion.SlerpToRef(this._bone1Quat, _tmpQuat, this.slerpAmount, this._bone1Quat);
  34781. angC = this._bone2Ang * (1.0 - this.slerpAmount) + angC * this.slerpAmount;
  34782. this._bone1.setRotationQuaternion(this._bone1Quat, BABYLON.Space.WORLD, this.mesh);
  34783. this._slerping = true;
  34784. }
  34785. else {
  34786. this._bone1.setRotationMatrix(mat1, BABYLON.Space.WORLD, this.mesh);
  34787. this._bone1Mat.copyFrom(mat1);
  34788. this._slerping = false;
  34789. }
  34790. this._bone2.setAxisAngle(this._bendAxis, angC, BABYLON.Space.LOCAL);
  34791. this._bone2Ang = angC;
  34792. };
  34793. return BoneIKController;
  34794. }());
  34795. BoneIKController._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  34796. BoneIKController._tmpQuat = BABYLON.Quaternion.Identity();
  34797. BoneIKController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  34798. BABYLON.BoneIKController = BoneIKController;
  34799. })(BABYLON || (BABYLON = {}));
  34800. //# sourceMappingURL=babylon.boneIKController.js.map
  34801. var BABYLON;
  34802. (function (BABYLON) {
  34803. var BoneLookController = (function () {
  34804. /**
  34805. * Create a BoneLookController
  34806. * @param mesh the mesh that the bone belongs to
  34807. * @param bone the bone that will be looking to the target
  34808. * @param target the target Vector3 to look at
  34809. * @param settings optional settings:
  34810. * - maxYaw: the maximum angle the bone will yaw to
  34811. * - minYaw: the minimum angle the bone will yaw to
  34812. * - maxPitch: the maximum angle the bone will pitch to
  34813. * - minPitch: the minimum angle the bone will yaw to
  34814. * - slerpAmount: set the between 0 and 1 to make the bone slerp to the target.
  34815. * - upAxis: the up axis of the coordinate system
  34816. * - upAxisSpace: the space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  34817. * - yawAxis: set yawAxis if the bone does not yaw on the y axis
  34818. * - pitchAxis: set pitchAxis if the bone does not pitch on the x axis
  34819. * - adjustYaw: used to make an adjustment to the yaw of the bone
  34820. * - adjustPitch: used to make an adjustment to the pitch of the bone
  34821. * - adjustRoll: used to make an adjustment to the roll of the bone
  34822. **/
  34823. function BoneLookController(mesh, bone, target, options) {
  34824. /**
  34825. * The up axis of the coordinate system that is used when the bone is rotated.
  34826. */
  34827. this.upAxis = BABYLON.Vector3.Up();
  34828. /**
  34829. * The space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  34830. */
  34831. this.upAxisSpace = BABYLON.Space.LOCAL;
  34832. /**
  34833. * Used to make an adjustment to the yaw of the bone.
  34834. */
  34835. this.adjustYaw = 0;
  34836. /**
  34837. * Used to make an adjustment to the pitch of the bone.
  34838. */
  34839. this.adjustPitch = 0;
  34840. /**
  34841. * Used to make an adjustment to the roll of the bone.
  34842. */
  34843. this.adjustRoll = 0;
  34844. /**
  34845. * The amount to slerp (spherical linear interpolation) to the target. Set this to a value between 0 and 1 (a value of 1 disables slerp).
  34846. */
  34847. this.slerpAmount = 1;
  34848. this._boneQuat = BABYLON.Quaternion.Identity();
  34849. this._slerping = false;
  34850. this._firstFrameSkipped = false;
  34851. this._fowardAxis = BABYLON.Vector3.Forward();
  34852. this.mesh = mesh;
  34853. this.bone = bone;
  34854. this.target = target;
  34855. if (options) {
  34856. if (options.adjustYaw) {
  34857. this.adjustYaw = options.adjustYaw;
  34858. }
  34859. if (options.adjustPitch) {
  34860. this.adjustPitch = options.adjustPitch;
  34861. }
  34862. if (options.adjustRoll) {
  34863. this.adjustRoll = options.adjustRoll;
  34864. }
  34865. if (options.maxYaw != null) {
  34866. this.maxYaw = options.maxYaw;
  34867. }
  34868. else {
  34869. this.maxYaw = Math.PI;
  34870. }
  34871. if (options.minYaw != null) {
  34872. this.minYaw = options.minYaw;
  34873. }
  34874. else {
  34875. this.minYaw = -Math.PI;
  34876. }
  34877. if (options.maxPitch != null) {
  34878. this.maxPitch = options.maxPitch;
  34879. }
  34880. else {
  34881. this.maxPitch = Math.PI;
  34882. }
  34883. if (options.minPitch != null) {
  34884. this.minPitch = options.minPitch;
  34885. }
  34886. else {
  34887. this.minPitch = -Math.PI;
  34888. }
  34889. if (options.slerpAmount != null) {
  34890. this.slerpAmount = options.slerpAmount;
  34891. }
  34892. if (options.upAxis != null) {
  34893. this.upAxis = options.upAxis;
  34894. }
  34895. if (options.upAxisSpace != null) {
  34896. this.upAxisSpace = options.upAxisSpace;
  34897. }
  34898. if (options.yawAxis != null || options.pitchAxis != null) {
  34899. var newYawAxis = BABYLON.Axis.Y;
  34900. var newPitchAxis = BABYLON.Axis.X;
  34901. if (options.yawAxis != null) {
  34902. newYawAxis = options.yawAxis.clone();
  34903. newYawAxis.normalize();
  34904. }
  34905. if (options.pitchAxis != null) {
  34906. newPitchAxis = options.pitchAxis.clone();
  34907. newPitchAxis.normalize();
  34908. }
  34909. var newRollAxis = BABYLON.Vector3.Cross(newPitchAxis, newYawAxis);
  34910. this._transformYawPitch = BABYLON.Matrix.Identity();
  34911. BABYLON.Matrix.FromXYZAxesToRef(newPitchAxis, newYawAxis, newRollAxis, this._transformYawPitch);
  34912. this._transformYawPitchInv = this._transformYawPitch.clone();
  34913. this._transformYawPitch.invert();
  34914. }
  34915. }
  34916. if (!bone.getParent() && this.upAxisSpace == BABYLON.Space.BONE) {
  34917. this.upAxisSpace = BABYLON.Space.LOCAL;
  34918. }
  34919. }
  34920. Object.defineProperty(BoneLookController.prototype, "minYaw", {
  34921. /**
  34922. * Get/set the minimum yaw angle that the bone can look to.
  34923. */
  34924. get: function () {
  34925. return this._minYaw;
  34926. },
  34927. set: function (value) {
  34928. this._minYaw = value;
  34929. this._minYawSin = Math.sin(value);
  34930. this._minYawCos = Math.cos(value);
  34931. if (this._maxYaw != null) {
  34932. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  34933. this._yawRange = this._maxYaw - this._minYaw;
  34934. }
  34935. },
  34936. enumerable: true,
  34937. configurable: true
  34938. });
  34939. Object.defineProperty(BoneLookController.prototype, "maxYaw", {
  34940. /**
  34941. * Get/set the maximum yaw angle that the bone can look to.
  34942. */
  34943. get: function () {
  34944. return this._maxYaw;
  34945. },
  34946. set: function (value) {
  34947. this._maxYaw = value;
  34948. this._maxYawSin = Math.sin(value);
  34949. this._maxYawCos = Math.cos(value);
  34950. if (this._minYaw != null) {
  34951. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  34952. this._yawRange = this._maxYaw - this._minYaw;
  34953. }
  34954. },
  34955. enumerable: true,
  34956. configurable: true
  34957. });
  34958. Object.defineProperty(BoneLookController.prototype, "minPitch", {
  34959. /**
  34960. * Get/set the minimum pitch angle that the bone can look to.
  34961. */
  34962. get: function () {
  34963. return this._minPitch;
  34964. },
  34965. set: function (value) {
  34966. this._minPitch = value;
  34967. this._minPitchTan = Math.tan(value);
  34968. },
  34969. enumerable: true,
  34970. configurable: true
  34971. });
  34972. Object.defineProperty(BoneLookController.prototype, "maxPitch", {
  34973. /**
  34974. * Get/set the maximum pitch angle that the bone can look to.
  34975. */
  34976. get: function () {
  34977. return this._maxPitch;
  34978. },
  34979. set: function (value) {
  34980. this._maxPitch = value;
  34981. this._maxPitchTan = Math.tan(value);
  34982. },
  34983. enumerable: true,
  34984. configurable: true
  34985. });
  34986. /**
  34987. * Update the bone to look at the target. This should be called before the scene is rendered (use scene.registerBeforeRender()).
  34988. */
  34989. BoneLookController.prototype.update = function () {
  34990. //skip the first frame when slerping so that the mesh rotation is correct
  34991. if (this.slerpAmount < 1 && !this._firstFrameSkipped) {
  34992. this._firstFrameSkipped = true;
  34993. return;
  34994. }
  34995. var bone = this.bone;
  34996. var bonePos = BoneLookController._tmpVecs[0];
  34997. bone.getAbsolutePositionToRef(this.mesh, bonePos);
  34998. var target = this.target;
  34999. var _tmpMat1 = BoneLookController._tmpMats[0];
  35000. var _tmpMat2 = BoneLookController._tmpMats[1];
  35001. var mesh = this.mesh;
  35002. var parentBone = bone.getParent();
  35003. var upAxis = BoneLookController._tmpVecs[1];
  35004. upAxis.copyFrom(this.upAxis);
  35005. if (this.upAxisSpace == BABYLON.Space.BONE) {
  35006. if (this._transformYawPitch) {
  35007. BABYLON.Vector3.TransformCoordinatesToRef(upAxis, this._transformYawPitchInv, upAxis);
  35008. }
  35009. parentBone.getDirectionToRef(upAxis, this.mesh, upAxis);
  35010. }
  35011. else if (this.upAxisSpace == BABYLON.Space.LOCAL) {
  35012. mesh.getDirectionToRef(upAxis, upAxis);
  35013. if (mesh.scaling.x != 1 || mesh.scaling.y != 1 || mesh.scaling.z != 1) {
  35014. upAxis.normalize();
  35015. }
  35016. }
  35017. var checkYaw = false;
  35018. var checkPitch = false;
  35019. if (this._maxYaw != Math.PI || this._minYaw != -Math.PI) {
  35020. checkYaw = true;
  35021. }
  35022. if (this._maxPitch != Math.PI || this._minPitch != -Math.PI) {
  35023. checkPitch = true;
  35024. }
  35025. if (checkYaw || checkPitch) {
  35026. var spaceMat = BoneLookController._tmpMats[2];
  35027. var spaceMatInv = BoneLookController._tmpMats[3];
  35028. if (this.upAxisSpace == BABYLON.Space.BONE && upAxis.y == 1) {
  35029. parentBone.getRotationMatrixToRef(BABYLON.Space.WORLD, this.mesh, spaceMat);
  35030. }
  35031. else if (this.upAxisSpace == BABYLON.Space.LOCAL && upAxis.y == 1 && !parentBone) {
  35032. spaceMat.copyFrom(mesh.getWorldMatrix());
  35033. }
  35034. else {
  35035. var forwardAxis = BoneLookController._tmpVecs[2];
  35036. forwardAxis.copyFrom(this._fowardAxis);
  35037. if (this._transformYawPitch) {
  35038. BABYLON.Vector3.TransformCoordinatesToRef(forwardAxis, this._transformYawPitchInv, forwardAxis);
  35039. }
  35040. if (parentBone) {
  35041. parentBone.getDirectionToRef(forwardAxis, this.mesh, forwardAxis);
  35042. }
  35043. else {
  35044. mesh.getDirectionToRef(forwardAxis, forwardAxis);
  35045. }
  35046. var rightAxis = BABYLON.Vector3.Cross(upAxis, forwardAxis);
  35047. rightAxis.normalize();
  35048. var forwardAxis = BABYLON.Vector3.Cross(rightAxis, upAxis);
  35049. BABYLON.Matrix.FromXYZAxesToRef(rightAxis, upAxis, forwardAxis, spaceMat);
  35050. }
  35051. spaceMat.invertToRef(spaceMatInv);
  35052. var xzlen;
  35053. if (checkPitch) {
  35054. var localTarget = BoneLookController._tmpVecs[3];
  35055. target.subtractToRef(bonePos, localTarget);
  35056. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  35057. var xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  35058. var pitch = Math.atan2(localTarget.y, xzlen);
  35059. var newPitch = pitch;
  35060. if (pitch > this._maxPitch) {
  35061. localTarget.y = this._maxPitchTan * xzlen;
  35062. newPitch = this._maxPitch;
  35063. }
  35064. else if (pitch < this._minPitch) {
  35065. localTarget.y = this._minPitchTan * xzlen;
  35066. newPitch = this._minPitch;
  35067. }
  35068. if (pitch != newPitch) {
  35069. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  35070. localTarget.addInPlace(bonePos);
  35071. target = localTarget;
  35072. }
  35073. }
  35074. if (checkYaw) {
  35075. var localTarget = BoneLookController._tmpVecs[4];
  35076. target.subtractToRef(bonePos, localTarget);
  35077. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  35078. var yaw = Math.atan2(localTarget.x, localTarget.z);
  35079. var newYaw = yaw;
  35080. if (yaw > this._maxYaw || yaw < this._minYaw) {
  35081. if (xzlen == null) {
  35082. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  35083. }
  35084. if (this._yawRange > Math.PI) {
  35085. if (this._isAngleBetween(yaw, this._maxYaw, this._midYawConstraint)) {
  35086. localTarget.z = this._maxYawCos * xzlen;
  35087. localTarget.x = this._maxYawSin * xzlen;
  35088. newYaw = this._maxYaw;
  35089. }
  35090. else if (this._isAngleBetween(yaw, this._midYawConstraint, this._minYaw)) {
  35091. localTarget.z = this._minYawCos * xzlen;
  35092. localTarget.x = this._minYawSin * xzlen;
  35093. newYaw = this._minYaw;
  35094. }
  35095. }
  35096. else {
  35097. if (yaw > this._maxYaw) {
  35098. localTarget.z = this._maxYawCos * xzlen;
  35099. localTarget.x = this._maxYawSin * xzlen;
  35100. newYaw = this._maxYaw;
  35101. }
  35102. else if (yaw < this._minYaw) {
  35103. localTarget.z = this._minYawCos * xzlen;
  35104. localTarget.x = this._minYawSin * xzlen;
  35105. newYaw = this._minYaw;
  35106. }
  35107. }
  35108. }
  35109. if (this._slerping && this._yawRange > Math.PI) {
  35110. //are we going to be crossing into the min/max region?
  35111. var boneFwd = BoneLookController._tmpVecs[8];
  35112. boneFwd.copyFrom(BABYLON.Axis.Z);
  35113. if (this._transformYawPitch) {
  35114. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, this._transformYawPitchInv, boneFwd);
  35115. }
  35116. var boneRotMat = BABYLON.BoneLookController._tmpMats[4];
  35117. this._boneQuat.toRotationMatrix(boneRotMat);
  35118. this.mesh.getWorldMatrix().multiplyToRef(boneRotMat, boneRotMat);
  35119. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, boneRotMat, boneFwd);
  35120. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, spaceMatInv, boneFwd);
  35121. var boneYaw = Math.atan2(boneFwd.x, boneFwd.z);
  35122. var angBtwTar = this._getAngleBetween(boneYaw, yaw);
  35123. var angBtwMidYaw = this._getAngleBetween(boneYaw, this._midYawConstraint);
  35124. if (angBtwTar > angBtwMidYaw) {
  35125. if (xzlen == null) {
  35126. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  35127. }
  35128. var angBtwMax = this._getAngleBetween(boneYaw, this._maxYaw);
  35129. var angBtwMin = this._getAngleBetween(boneYaw, this._minYaw);
  35130. if (angBtwMin < angBtwMax) {
  35131. newYaw = boneYaw + Math.PI * .75;
  35132. localTarget.z = Math.cos(newYaw) * xzlen;
  35133. localTarget.x = Math.sin(newYaw) * xzlen;
  35134. }
  35135. else {
  35136. newYaw = boneYaw - Math.PI * .75;
  35137. localTarget.z = Math.cos(newYaw) * xzlen;
  35138. localTarget.x = Math.sin(newYaw) * xzlen;
  35139. }
  35140. }
  35141. }
  35142. if (yaw != newYaw) {
  35143. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  35144. localTarget.addInPlace(bonePos);
  35145. target = localTarget;
  35146. }
  35147. }
  35148. }
  35149. var zaxis = BoneLookController._tmpVecs[5];
  35150. var xaxis = BoneLookController._tmpVecs[6];
  35151. var yaxis = BoneLookController._tmpVecs[7];
  35152. var _tmpQuat = BoneLookController._tmpQuat;
  35153. target.subtractToRef(bonePos, zaxis);
  35154. zaxis.normalize();
  35155. BABYLON.Vector3.CrossToRef(upAxis, zaxis, xaxis);
  35156. xaxis.normalize();
  35157. BABYLON.Vector3.CrossToRef(zaxis, xaxis, yaxis);
  35158. yaxis.normalize();
  35159. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, _tmpMat1);
  35160. if (xaxis.x === 0 && xaxis.y === 0 && xaxis.z === 0) {
  35161. return;
  35162. }
  35163. if (yaxis.x === 0 && yaxis.y === 0 && yaxis.z === 0) {
  35164. return;
  35165. }
  35166. if (zaxis.x === 0 && zaxis.y === 0 && zaxis.z === 0) {
  35167. return;
  35168. }
  35169. if (this.adjustYaw || this.adjustPitch || this.adjustRoll) {
  35170. BABYLON.Matrix.RotationYawPitchRollToRef(this.adjustYaw, this.adjustPitch, this.adjustRoll, _tmpMat2);
  35171. _tmpMat2.multiplyToRef(_tmpMat1, _tmpMat1);
  35172. }
  35173. if (this.slerpAmount < 1) {
  35174. if (!this._slerping) {
  35175. this.bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, this.mesh, this._boneQuat);
  35176. }
  35177. if (this._transformYawPitch) {
  35178. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  35179. }
  35180. BABYLON.Quaternion.FromRotationMatrixToRef(_tmpMat1, _tmpQuat);
  35181. BABYLON.Quaternion.SlerpToRef(this._boneQuat, _tmpQuat, this.slerpAmount, this._boneQuat);
  35182. this.bone.setRotationQuaternion(this._boneQuat, BABYLON.Space.WORLD, this.mesh);
  35183. this._slerping = true;
  35184. }
  35185. else {
  35186. if (this._transformYawPitch) {
  35187. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  35188. }
  35189. this.bone.setRotationMatrix(_tmpMat1, BABYLON.Space.WORLD, this.mesh);
  35190. this._slerping = false;
  35191. }
  35192. };
  35193. BoneLookController.prototype._getAngleDiff = function (ang1, ang2) {
  35194. var angDiff = ang2 - ang1;
  35195. angDiff %= Math.PI * 2;
  35196. if (angDiff > Math.PI) {
  35197. angDiff -= Math.PI * 2;
  35198. }
  35199. else if (angDiff < -Math.PI) {
  35200. angDiff += Math.PI * 2;
  35201. }
  35202. return angDiff;
  35203. };
  35204. BoneLookController.prototype._getAngleBetween = function (ang1, ang2) {
  35205. ang1 %= (2 * Math.PI);
  35206. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  35207. ang2 %= (2 * Math.PI);
  35208. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  35209. var ab = 0;
  35210. if (ang1 < ang2) {
  35211. ab = ang2 - ang1;
  35212. }
  35213. else {
  35214. ab = ang1 - ang2;
  35215. }
  35216. if (ab > Math.PI) {
  35217. ab = Math.PI * 2 - ab;
  35218. }
  35219. return ab;
  35220. };
  35221. BoneLookController.prototype._isAngleBetween = function (ang, ang1, ang2) {
  35222. ang %= (2 * Math.PI);
  35223. ang = (ang < 0) ? ang + (2 * Math.PI) : ang;
  35224. ang1 %= (2 * Math.PI);
  35225. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  35226. ang2 %= (2 * Math.PI);
  35227. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  35228. if (ang1 < ang2) {
  35229. if (ang > ang1 && ang < ang2) {
  35230. return true;
  35231. }
  35232. }
  35233. else {
  35234. if (ang > ang2 && ang < ang1) {
  35235. return true;
  35236. }
  35237. }
  35238. return false;
  35239. };
  35240. return BoneLookController;
  35241. }());
  35242. BoneLookController._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  35243. BoneLookController._tmpQuat = BABYLON.Quaternion.Identity();
  35244. BoneLookController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  35245. BABYLON.BoneLookController = BoneLookController;
  35246. })(BABYLON || (BABYLON = {}));
  35247. //# sourceMappingURL=babylon.boneLookController.js.map
  35248. var BABYLON;
  35249. (function (BABYLON) {
  35250. var Skeleton = (function () {
  35251. function Skeleton(name, id, scene) {
  35252. this.name = name;
  35253. this.id = id;
  35254. this.bones = new Array();
  35255. this.needInitialSkinMatrix = false;
  35256. this._isDirty = true;
  35257. this._meshesWithPoseMatrix = new Array();
  35258. this._identity = BABYLON.Matrix.Identity();
  35259. this._ranges = {};
  35260. this._lastAbsoluteTransformsUpdateId = -1;
  35261. // Events
  35262. /**
  35263. * An event triggered before computing the skeleton's matrices
  35264. * @type {BABYLON.Observable}
  35265. */
  35266. this.onBeforeComputeObservable = new BABYLON.Observable();
  35267. this.bones = [];
  35268. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  35269. scene.skeletons.push(this);
  35270. //make sure it will recalculate the matrix next time prepare is called.
  35271. this._isDirty = true;
  35272. }
  35273. // Members
  35274. Skeleton.prototype.getTransformMatrices = function (mesh) {
  35275. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  35276. return mesh._bonesTransformMatrices;
  35277. }
  35278. if (!this._transformMatrices) {
  35279. this.prepare();
  35280. }
  35281. return this._transformMatrices;
  35282. };
  35283. Skeleton.prototype.getScene = function () {
  35284. return this._scene;
  35285. };
  35286. // Methods
  35287. /**
  35288. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  35289. */
  35290. Skeleton.prototype.toString = function (fullDetails) {
  35291. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  35292. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  35293. if (fullDetails) {
  35294. ret += ", Ranges: {";
  35295. var first = true;
  35296. for (var name_1 in this._ranges) {
  35297. if (first) {
  35298. ret += ", ";
  35299. first = false;
  35300. }
  35301. ret += name_1;
  35302. }
  35303. ret += "}";
  35304. }
  35305. return ret;
  35306. };
  35307. /**
  35308. * Get bone's index searching by name
  35309. * @param {string} name is bone's name to search for
  35310. * @return {number} Indice of the bone. Returns -1 if not found
  35311. */
  35312. Skeleton.prototype.getBoneIndexByName = function (name) {
  35313. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  35314. if (this.bones[boneIndex].name === name) {
  35315. return boneIndex;
  35316. }
  35317. }
  35318. return -1;
  35319. };
  35320. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  35321. // check name not already in use
  35322. if (!this._ranges[name]) {
  35323. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  35324. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  35325. if (this.bones[i].animations[0]) {
  35326. this.bones[i].animations[0].createRange(name, from, to);
  35327. }
  35328. }
  35329. }
  35330. };
  35331. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  35332. if (deleteFrames === void 0) { deleteFrames = true; }
  35333. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  35334. if (this.bones[i].animations[0]) {
  35335. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  35336. }
  35337. }
  35338. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  35339. };
  35340. Skeleton.prototype.getAnimationRange = function (name) {
  35341. return this._ranges[name];
  35342. };
  35343. /**
  35344. * Returns as an Array, all AnimationRanges defined on this skeleton
  35345. */
  35346. Skeleton.prototype.getAnimationRanges = function () {
  35347. var animationRanges = [];
  35348. var name;
  35349. var i = 0;
  35350. for (name in this._ranges) {
  35351. animationRanges[i] = this._ranges[name];
  35352. i++;
  35353. }
  35354. return animationRanges;
  35355. };
  35356. /**
  35357. * note: This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  35358. */
  35359. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  35360. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  35361. if (this._ranges[name] || !source.getAnimationRange(name)) {
  35362. return false;
  35363. }
  35364. var ret = true;
  35365. var frameOffset = this._getHighestAnimationFrame() + 1;
  35366. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  35367. var boneDict = {};
  35368. var sourceBones = source.bones;
  35369. var nBones;
  35370. var i;
  35371. for (i = 0, nBones = sourceBones.length; i < nBones; i++) {
  35372. boneDict[sourceBones[i].name] = sourceBones[i];
  35373. }
  35374. if (this.bones.length !== sourceBones.length) {
  35375. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  35376. ret = false;
  35377. }
  35378. var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;
  35379. for (i = 0, nBones = this.bones.length; i < nBones; i++) {
  35380. var boneName = this.bones[i].name;
  35381. var sourceBone = boneDict[boneName];
  35382. if (sourceBone) {
  35383. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio);
  35384. }
  35385. else {
  35386. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  35387. ret = false;
  35388. }
  35389. }
  35390. // do not call createAnimationRange(), since it also is done to bones, which was already done
  35391. var range = source.getAnimationRange(name);
  35392. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  35393. return ret;
  35394. };
  35395. Skeleton.prototype.returnToRest = function () {
  35396. for (var index = 0; index < this.bones.length; index++) {
  35397. this.bones[index].returnToRest();
  35398. }
  35399. };
  35400. Skeleton.prototype._getHighestAnimationFrame = function () {
  35401. var ret = 0;
  35402. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  35403. if (this.bones[i].animations[0]) {
  35404. var highest = this.bones[i].animations[0].getHighestFrame();
  35405. if (ret < highest) {
  35406. ret = highest;
  35407. }
  35408. }
  35409. }
  35410. return ret;
  35411. };
  35412. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  35413. var range = this.getAnimationRange(name);
  35414. if (!range) {
  35415. return null;
  35416. }
  35417. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  35418. };
  35419. Skeleton.prototype._markAsDirty = function () {
  35420. this._isDirty = true;
  35421. };
  35422. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  35423. this._meshesWithPoseMatrix.push(mesh);
  35424. };
  35425. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  35426. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  35427. if (index > -1) {
  35428. this._meshesWithPoseMatrix.splice(index, 1);
  35429. }
  35430. };
  35431. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  35432. this.onBeforeComputeObservable.notifyObservers(this);
  35433. for (var index = 0; index < this.bones.length; index++) {
  35434. var bone = this.bones[index];
  35435. var parentBone = bone.getParent();
  35436. if (parentBone) {
  35437. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  35438. }
  35439. else {
  35440. if (initialSkinMatrix) {
  35441. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  35442. }
  35443. else {
  35444. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  35445. }
  35446. }
  35447. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, index * 16);
  35448. }
  35449. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  35450. };
  35451. Skeleton.prototype.prepare = function () {
  35452. if (!this._isDirty) {
  35453. return;
  35454. }
  35455. if (this.needInitialSkinMatrix) {
  35456. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  35457. var mesh = this._meshesWithPoseMatrix[index];
  35458. var poseMatrix = mesh.getPoseMatrix();
  35459. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  35460. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  35461. }
  35462. if (this._synchronizedWithMesh !== mesh) {
  35463. this._synchronizedWithMesh = mesh;
  35464. // Prepare bones
  35465. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  35466. var bone = this.bones[boneIndex];
  35467. if (!bone.getParent()) {
  35468. var matrix = bone.getBaseMatrix();
  35469. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[1]);
  35470. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[1]);
  35471. }
  35472. }
  35473. }
  35474. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  35475. }
  35476. }
  35477. else {
  35478. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  35479. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  35480. }
  35481. this._computeTransformMatrices(this._transformMatrices, null);
  35482. }
  35483. this._isDirty = false;
  35484. this._scene._activeBones.addCount(this.bones.length, false);
  35485. };
  35486. Skeleton.prototype.getAnimatables = function () {
  35487. if (!this._animatables || this._animatables.length !== this.bones.length) {
  35488. this._animatables = [];
  35489. for (var index = 0; index < this.bones.length; index++) {
  35490. this._animatables.push(this.bones[index]);
  35491. }
  35492. }
  35493. return this._animatables;
  35494. };
  35495. Skeleton.prototype.clone = function (name, id) {
  35496. var result = new Skeleton(name, id || name, this._scene);
  35497. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  35498. for (var index = 0; index < this.bones.length; index++) {
  35499. var source = this.bones[index];
  35500. var parentBone = null;
  35501. if (source.getParent()) {
  35502. var parentIndex = this.bones.indexOf(source.getParent());
  35503. parentBone = result.bones[parentIndex];
  35504. }
  35505. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  35506. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  35507. }
  35508. if (this._ranges) {
  35509. result._ranges = {};
  35510. for (var rangeName in this._ranges) {
  35511. result._ranges[rangeName] = this._ranges[rangeName].clone();
  35512. }
  35513. }
  35514. this._isDirty = true;
  35515. return result;
  35516. };
  35517. Skeleton.prototype.enableBlending = function (blendingSpeed) {
  35518. if (blendingSpeed === void 0) { blendingSpeed = 0.01; }
  35519. this.bones.forEach(function (bone) {
  35520. bone.animations.forEach(function (animation) {
  35521. animation.enableBlending = true;
  35522. animation.blendingSpeed = blendingSpeed;
  35523. });
  35524. });
  35525. };
  35526. Skeleton.prototype.dispose = function () {
  35527. this._meshesWithPoseMatrix = [];
  35528. // Animations
  35529. this.getScene().stopAnimation(this);
  35530. // Remove from scene
  35531. this.getScene().removeSkeleton(this);
  35532. };
  35533. Skeleton.prototype.serialize = function () {
  35534. var serializationObject = {};
  35535. serializationObject.name = this.name;
  35536. serializationObject.id = this.id;
  35537. serializationObject.dimensionsAtRest = this.dimensionsAtRest;
  35538. serializationObject.bones = [];
  35539. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  35540. for (var index = 0; index < this.bones.length; index++) {
  35541. var bone = this.bones[index];
  35542. var serializedBone = {
  35543. parentBoneIndex: bone.getParent() ? this.bones.indexOf(bone.getParent()) : -1,
  35544. name: bone.name,
  35545. matrix: bone.getBaseMatrix().toArray(),
  35546. rest: bone.getRestPose().toArray()
  35547. };
  35548. serializationObject.bones.push(serializedBone);
  35549. if (bone.length) {
  35550. serializedBone.length = bone.length;
  35551. }
  35552. if (bone.animations && bone.animations.length > 0) {
  35553. serializedBone.animation = bone.animations[0].serialize();
  35554. }
  35555. serializationObject.ranges = [];
  35556. for (var name in this._ranges) {
  35557. var range = {};
  35558. range.name = name;
  35559. range.from = this._ranges[name].from;
  35560. range.to = this._ranges[name].to;
  35561. serializationObject.ranges.push(range);
  35562. }
  35563. }
  35564. return serializationObject;
  35565. };
  35566. Skeleton.Parse = function (parsedSkeleton, scene) {
  35567. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  35568. if (parsedSkeleton.dimensionsAtRest) {
  35569. skeleton.dimensionsAtRest = BABYLON.Vector3.FromArray(parsedSkeleton.dimensionsAtRest);
  35570. }
  35571. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  35572. var index;
  35573. for (index = 0; index < parsedSkeleton.bones.length; index++) {
  35574. var parsedBone = parsedSkeleton.bones[index];
  35575. var parentBone = null;
  35576. if (parsedBone.parentBoneIndex > -1) {
  35577. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  35578. }
  35579. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  35580. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  35581. if (parsedBone.length) {
  35582. bone.length = parsedBone.length;
  35583. }
  35584. if (parsedBone.animation) {
  35585. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  35586. }
  35587. }
  35588. // placed after bones, so createAnimationRange can cascade down
  35589. if (parsedSkeleton.ranges) {
  35590. for (index = 0; index < parsedSkeleton.ranges.length; index++) {
  35591. var data = parsedSkeleton.ranges[index];
  35592. skeleton.createAnimationRange(data.name, data.from, data.to);
  35593. }
  35594. }
  35595. return skeleton;
  35596. };
  35597. Skeleton.prototype.computeAbsoluteTransforms = function (forceUpdate) {
  35598. if (forceUpdate === void 0) { forceUpdate = false; }
  35599. var renderId = this._scene.getRenderId();
  35600. if (this._lastAbsoluteTransformsUpdateId != renderId || forceUpdate) {
  35601. this.bones[0].computeAbsoluteTransforms();
  35602. this._lastAbsoluteTransformsUpdateId = renderId;
  35603. }
  35604. };
  35605. Skeleton.prototype.getPoseMatrix = function () {
  35606. var poseMatrix;
  35607. if (this._meshesWithPoseMatrix.length > 0) {
  35608. poseMatrix = this._meshesWithPoseMatrix[0].getPoseMatrix();
  35609. }
  35610. return poseMatrix;
  35611. };
  35612. return Skeleton;
  35613. }());
  35614. BABYLON.Skeleton = Skeleton;
  35615. })(BABYLON || (BABYLON = {}));
  35616. //# sourceMappingURL=babylon.skeleton.js.map
  35617. var BABYLON;
  35618. (function (BABYLON) {
  35619. var PostProcess = (function () {
  35620. function PostProcess(name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType) {
  35621. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  35622. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  35623. this.name = name;
  35624. this.width = -1;
  35625. this.height = -1;
  35626. /*
  35627. Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  35628. Can only be used on a single postprocess or on the last one of a chain.
  35629. */
  35630. this.enablePixelPerfectMode = false;
  35631. this.samples = 1;
  35632. this._reusable = false;
  35633. this._textures = new BABYLON.SmartArray(2);
  35634. this._currentRenderTextureInd = 0;
  35635. this._scaleRatio = new BABYLON.Vector2(1, 1);
  35636. // Events
  35637. /**
  35638. * An event triggered when the postprocess is activated.
  35639. * @type {BABYLON.Observable}
  35640. */
  35641. this.onActivateObservable = new BABYLON.Observable();
  35642. /**
  35643. * An event triggered when the postprocess changes its size.
  35644. * @type {BABYLON.Observable}
  35645. */
  35646. this.onSizeChangedObservable = new BABYLON.Observable();
  35647. /**
  35648. * An event triggered when the postprocess applies its effect.
  35649. * @type {BABYLON.Observable}
  35650. */
  35651. this.onApplyObservable = new BABYLON.Observable();
  35652. /**
  35653. * An event triggered before rendering the postprocess
  35654. * @type {BABYLON.Observable}
  35655. */
  35656. this.onBeforeRenderObservable = new BABYLON.Observable();
  35657. /**
  35658. * An event triggered after rendering the postprocess
  35659. * @type {BABYLON.Observable}
  35660. */
  35661. this.onAfterRenderObservable = new BABYLON.Observable();
  35662. if (camera != null) {
  35663. this._camera = camera;
  35664. this._scene = camera.getScene();
  35665. camera.attachPostProcess(this);
  35666. this._engine = this._scene.getEngine();
  35667. }
  35668. else {
  35669. this._engine = engine;
  35670. }
  35671. this._options = options;
  35672. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  35673. this._reusable = reusable || false;
  35674. this._textureType = textureType;
  35675. this._samplers = samplers || [];
  35676. this._samplers.push("textureSampler");
  35677. this._fragmentUrl = fragmentUrl;
  35678. this._parameters = parameters || [];
  35679. this._parameters.push("scale");
  35680. this.updateEffect(defines);
  35681. }
  35682. Object.defineProperty(PostProcess.prototype, "onActivate", {
  35683. set: function (callback) {
  35684. if (this._onActivateObserver) {
  35685. this.onActivateObservable.remove(this._onActivateObserver);
  35686. }
  35687. this._onActivateObserver = this.onActivateObservable.add(callback);
  35688. },
  35689. enumerable: true,
  35690. configurable: true
  35691. });
  35692. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  35693. set: function (callback) {
  35694. if (this._onSizeChangedObserver) {
  35695. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  35696. }
  35697. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  35698. },
  35699. enumerable: true,
  35700. configurable: true
  35701. });
  35702. Object.defineProperty(PostProcess.prototype, "onApply", {
  35703. set: function (callback) {
  35704. if (this._onApplyObserver) {
  35705. this.onApplyObservable.remove(this._onApplyObserver);
  35706. }
  35707. this._onApplyObserver = this.onApplyObservable.add(callback);
  35708. },
  35709. enumerable: true,
  35710. configurable: true
  35711. });
  35712. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  35713. set: function (callback) {
  35714. if (this._onBeforeRenderObserver) {
  35715. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  35716. }
  35717. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  35718. },
  35719. enumerable: true,
  35720. configurable: true
  35721. });
  35722. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  35723. set: function (callback) {
  35724. if (this._onAfterRenderObserver) {
  35725. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  35726. }
  35727. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  35728. },
  35729. enumerable: true,
  35730. configurable: true
  35731. });
  35732. PostProcess.prototype.updateEffect = function (defines) {
  35733. this._effect = this._engine.createEffect({ vertex: "postprocess", fragment: this._fragmentUrl }, ["position"], this._parameters, this._samplers, defines !== undefined ? defines : "");
  35734. };
  35735. PostProcess.prototype.isReusable = function () {
  35736. return this._reusable;
  35737. };
  35738. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  35739. PostProcess.prototype.markTextureDirty = function () {
  35740. this.width = -1;
  35741. };
  35742. PostProcess.prototype.activate = function (camera, sourceTexture) {
  35743. var _this = this;
  35744. camera = camera || this._camera;
  35745. var scene = camera.getScene();
  35746. var maxSize = camera.getEngine().getCaps().maxTextureSize;
  35747. var requiredWidth = ((sourceTexture ? sourceTexture._width : this._engine.getRenderingCanvas().width) * this._options) | 0;
  35748. var requiredHeight = ((sourceTexture ? sourceTexture._height : this._engine.getRenderingCanvas().height) * this._options) | 0;
  35749. var desiredWidth = this._options.width || requiredWidth;
  35750. var desiredHeight = this._options.height || requiredHeight;
  35751. if (this.renderTargetSamplingMode !== BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  35752. if (!this._options.width) {
  35753. desiredWidth = BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize);
  35754. }
  35755. if (!this._options.height) {
  35756. desiredHeight = BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize);
  35757. }
  35758. }
  35759. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  35760. if (this._textures.length > 0) {
  35761. for (var i = 0; i < this._textures.length; i++) {
  35762. this._engine._releaseTexture(this._textures.data[i]);
  35763. }
  35764. this._textures.reset();
  35765. }
  35766. this.width = desiredWidth;
  35767. this.height = desiredHeight;
  35768. var textureSize = { width: this.width, height: this.height };
  35769. var textureOptions = {
  35770. generateMipMaps: false,
  35771. generateDepthBuffer: camera._postProcesses.indexOf(this) === 0,
  35772. generateStencilBuffer: camera._postProcesses.indexOf(this) === 0 && this._engine.isStencilEnable,
  35773. samplingMode: this.renderTargetSamplingMode,
  35774. type: this._textureType
  35775. };
  35776. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  35777. if (this._reusable) {
  35778. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  35779. }
  35780. this.onSizeChangedObservable.notifyObservers(this);
  35781. }
  35782. this._textures.forEach(function (texture) {
  35783. if (texture.samples !== _this.samples) {
  35784. _this._engine.updateRenderTargetTextureSampleCount(texture, _this.samples);
  35785. }
  35786. });
  35787. if (this.enablePixelPerfectMode) {
  35788. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  35789. this._engine.bindFramebuffer(this._textures.data[this._currentRenderTextureInd], 0, requiredWidth, requiredHeight);
  35790. }
  35791. else {
  35792. this._scaleRatio.copyFromFloats(1, 1);
  35793. this._engine.bindFramebuffer(this._textures.data[this._currentRenderTextureInd]);
  35794. }
  35795. this.onActivateObservable.notifyObservers(camera);
  35796. // Clear
  35797. if (this.clearColor) {
  35798. this._engine.clear(this.clearColor, true, true, true);
  35799. }
  35800. else {
  35801. this._engine.clear(scene.clearColor, scene.autoClear || scene.forceWireframe, true, true);
  35802. }
  35803. if (this._reusable) {
  35804. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  35805. }
  35806. };
  35807. Object.defineProperty(PostProcess.prototype, "isSupported", {
  35808. get: function () {
  35809. return this._effect.isSupported;
  35810. },
  35811. enumerable: true,
  35812. configurable: true
  35813. });
  35814. PostProcess.prototype.apply = function () {
  35815. // Check
  35816. if (!this._effect.isReady())
  35817. return null;
  35818. // States
  35819. this._engine.enableEffect(this._effect);
  35820. this._engine.setState(false);
  35821. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  35822. this._engine.setDepthBuffer(false);
  35823. this._engine.setDepthWrite(false);
  35824. // Texture
  35825. this._effect._bindTexture("textureSampler", this._textures.data[this._currentRenderTextureInd]);
  35826. // Parameters
  35827. this._effect.setVector2("scale", this._scaleRatio);
  35828. this.onApplyObservable.notifyObservers(this._effect);
  35829. return this._effect;
  35830. };
  35831. PostProcess.prototype.dispose = function (camera) {
  35832. camera = camera || this._camera;
  35833. if (this._textures.length > 0) {
  35834. for (var i = 0; i < this._textures.length; i++) {
  35835. this._engine._releaseTexture(this._textures.data[i]);
  35836. }
  35837. }
  35838. this._textures.dispose();
  35839. if (!camera) {
  35840. return;
  35841. }
  35842. camera.detachPostProcess(this);
  35843. var index = camera._postProcesses.indexOf(this);
  35844. if (index === 0 && camera._postProcesses.length > 0) {
  35845. this._camera._postProcesses[0].markTextureDirty();
  35846. }
  35847. this.onActivateObservable.clear();
  35848. this.onAfterRenderObservable.clear();
  35849. this.onApplyObservable.clear();
  35850. this.onBeforeRenderObservable.clear();
  35851. this.onSizeChangedObservable.clear();
  35852. };
  35853. return PostProcess;
  35854. }());
  35855. BABYLON.PostProcess = PostProcess;
  35856. })(BABYLON || (BABYLON = {}));
  35857. //# sourceMappingURL=babylon.postProcess.js.map
  35858. var BABYLON;
  35859. (function (BABYLON) {
  35860. var PostProcessManager = (function () {
  35861. function PostProcessManager(scene) {
  35862. this._vertexBuffers = {};
  35863. this._scene = scene;
  35864. }
  35865. PostProcessManager.prototype._prepareBuffers = function () {
  35866. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  35867. return;
  35868. }
  35869. // VBO
  35870. var vertices = [];
  35871. vertices.push(1, 1);
  35872. vertices.push(-1, 1);
  35873. vertices.push(-1, -1);
  35874. vertices.push(1, -1);
  35875. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  35876. // Indices
  35877. var indices = [];
  35878. indices.push(0);
  35879. indices.push(1);
  35880. indices.push(2);
  35881. indices.push(0);
  35882. indices.push(2);
  35883. indices.push(3);
  35884. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  35885. };
  35886. // Methods
  35887. PostProcessManager.prototype._prepareFrame = function (sourceTexture) {
  35888. var postProcesses = this._scene.activeCamera._postProcesses;
  35889. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  35890. return false;
  35891. }
  35892. postProcesses[0].activate(this._scene.activeCamera, sourceTexture);
  35893. return true;
  35894. };
  35895. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture) {
  35896. var engine = this._scene.getEngine();
  35897. for (var index = 0; index < postProcesses.length; index++) {
  35898. if (index < postProcesses.length - 1) {
  35899. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  35900. }
  35901. else {
  35902. if (targetTexture) {
  35903. engine.bindFramebuffer(targetTexture);
  35904. }
  35905. else {
  35906. engine.restoreDefaultFramebuffer();
  35907. }
  35908. }
  35909. var pp = postProcesses[index];
  35910. var effect = pp.apply();
  35911. if (effect) {
  35912. pp.onBeforeRenderObservable.notifyObservers(effect);
  35913. // VBOs
  35914. this._prepareBuffers();
  35915. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  35916. // Draw order
  35917. engine.draw(true, 0, 6);
  35918. pp.onAfterRenderObservable.notifyObservers(effect);
  35919. }
  35920. }
  35921. // Restore depth buffer
  35922. engine.setDepthBuffer(true);
  35923. engine.setDepthWrite(true);
  35924. };
  35925. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses) {
  35926. postProcesses = postProcesses || this._scene.activeCamera._postProcesses;
  35927. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  35928. return;
  35929. }
  35930. var engine = this._scene.getEngine();
  35931. for (var index = 0, len = postProcesses.length; index < len; index++) {
  35932. if (index < len - 1) {
  35933. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  35934. }
  35935. else {
  35936. if (targetTexture) {
  35937. engine.bindFramebuffer(targetTexture, faceIndex);
  35938. }
  35939. else {
  35940. engine.restoreDefaultFramebuffer();
  35941. }
  35942. }
  35943. if (doNotPresent) {
  35944. break;
  35945. }
  35946. var pp = postProcesses[index];
  35947. var effect = pp.apply();
  35948. if (effect) {
  35949. pp.onBeforeRenderObservable.notifyObservers(effect);
  35950. // VBOs
  35951. this._prepareBuffers();
  35952. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  35953. // Draw order
  35954. engine.draw(true, 0, 6);
  35955. pp.onAfterRenderObservable.notifyObservers(effect);
  35956. }
  35957. }
  35958. // Restore depth buffer
  35959. engine.setDepthBuffer(true);
  35960. engine.setDepthWrite(true);
  35961. };
  35962. PostProcessManager.prototype.dispose = function () {
  35963. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  35964. if (buffer) {
  35965. buffer.dispose();
  35966. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  35967. }
  35968. if (this._indexBuffer) {
  35969. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  35970. this._indexBuffer = null;
  35971. }
  35972. };
  35973. return PostProcessManager;
  35974. }());
  35975. BABYLON.PostProcessManager = PostProcessManager;
  35976. })(BABYLON || (BABYLON = {}));
  35977. //# sourceMappingURL=babylon.postProcessManager.js.map
  35978. var BABYLON;
  35979. (function (BABYLON) {
  35980. var PassPostProcess = (function (_super) {
  35981. __extends(PassPostProcess, _super);
  35982. function PassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  35983. return _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable) || this;
  35984. }
  35985. return PassPostProcess;
  35986. }(BABYLON.PostProcess));
  35987. BABYLON.PassPostProcess = PassPostProcess;
  35988. })(BABYLON || (BABYLON = {}));
  35989. //# sourceMappingURL=babylon.passPostProcess.js.map
  35990. var BABYLON;
  35991. (function (BABYLON) {
  35992. /**
  35993. * This is a holder class for the physics joint created by the physics plugin.
  35994. * It holds a set of functions to control the underlying joint.
  35995. */
  35996. var PhysicsJoint = (function () {
  35997. function PhysicsJoint(type, jointData) {
  35998. this.type = type;
  35999. this.jointData = jointData;
  36000. jointData.nativeParams = jointData.nativeParams || {};
  36001. }
  36002. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  36003. get: function () {
  36004. return this._physicsJoint;
  36005. },
  36006. set: function (newJoint) {
  36007. if (this._physicsJoint) {
  36008. }
  36009. this._physicsJoint = newJoint;
  36010. },
  36011. enumerable: true,
  36012. configurable: true
  36013. });
  36014. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  36015. set: function (physicsPlugin) {
  36016. this._physicsPlugin = physicsPlugin;
  36017. },
  36018. enumerable: true,
  36019. configurable: true
  36020. });
  36021. /**
  36022. * Execute a function that is physics-plugin specific.
  36023. * @param {Function} func the function that will be executed.
  36024. * It accepts two parameters: the physics world and the physics joint.
  36025. */
  36026. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  36027. func(this._physicsPlugin.world, this._physicsJoint);
  36028. };
  36029. return PhysicsJoint;
  36030. }());
  36031. //TODO check if the native joints are the same
  36032. //Joint Types
  36033. PhysicsJoint.DistanceJoint = 0;
  36034. PhysicsJoint.HingeJoint = 1;
  36035. PhysicsJoint.BallAndSocketJoint = 2;
  36036. PhysicsJoint.WheelJoint = 3;
  36037. PhysicsJoint.SliderJoint = 4;
  36038. //OIMO
  36039. PhysicsJoint.PrismaticJoint = 5;
  36040. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  36041. PhysicsJoint.UniversalJoint = 6;
  36042. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  36043. //Cannon
  36044. //Similar to a Ball-Joint. Different in params
  36045. PhysicsJoint.PointToPointJoint = 8;
  36046. //Cannon only at the moment
  36047. PhysicsJoint.SpringJoint = 9;
  36048. PhysicsJoint.LockJoint = 10;
  36049. BABYLON.PhysicsJoint = PhysicsJoint;
  36050. /**
  36051. * A class representing a physics distance joint.
  36052. */
  36053. var DistanceJoint = (function (_super) {
  36054. __extends(DistanceJoint, _super);
  36055. function DistanceJoint(jointData) {
  36056. return _super.call(this, PhysicsJoint.DistanceJoint, jointData) || this;
  36057. }
  36058. /**
  36059. * Update the predefined distance.
  36060. */
  36061. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  36062. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  36063. };
  36064. return DistanceJoint;
  36065. }(PhysicsJoint));
  36066. BABYLON.DistanceJoint = DistanceJoint;
  36067. var MotorEnabledJoint = (function (_super) {
  36068. __extends(MotorEnabledJoint, _super);
  36069. function MotorEnabledJoint(type, jointData) {
  36070. return _super.call(this, type, jointData) || this;
  36071. }
  36072. /**
  36073. * Set the motor values.
  36074. * Attention, this function is plugin specific. Engines won't react 100% the same.
  36075. * @param {number} force the force to apply
  36076. * @param {number} maxForce max force for this motor.
  36077. */
  36078. MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
  36079. this._physicsPlugin.setMotor(this, force, maxForce);
  36080. };
  36081. /**
  36082. * Set the motor's limits.
  36083. * Attention, this function is plugin specific. Engines won't react 100% the same.
  36084. */
  36085. MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  36086. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  36087. };
  36088. return MotorEnabledJoint;
  36089. }(PhysicsJoint));
  36090. BABYLON.MotorEnabledJoint = MotorEnabledJoint;
  36091. /**
  36092. * This class represents a single hinge physics joint
  36093. */
  36094. var HingeJoint = (function (_super) {
  36095. __extends(HingeJoint, _super);
  36096. function HingeJoint(jointData) {
  36097. return _super.call(this, PhysicsJoint.HingeJoint, jointData) || this;
  36098. }
  36099. /**
  36100. * Set the motor values.
  36101. * Attention, this function is plugin specific. Engines won't react 100% the same.
  36102. * @param {number} force the force to apply
  36103. * @param {number} maxForce max force for this motor.
  36104. */
  36105. HingeJoint.prototype.setMotor = function (force, maxForce) {
  36106. this._physicsPlugin.setMotor(this, force, maxForce);
  36107. };
  36108. /**
  36109. * Set the motor's limits.
  36110. * Attention, this function is plugin specific. Engines won't react 100% the same.
  36111. */
  36112. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  36113. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  36114. };
  36115. return HingeJoint;
  36116. }(MotorEnabledJoint));
  36117. BABYLON.HingeJoint = HingeJoint;
  36118. /**
  36119. * This class represents a dual hinge physics joint (same as wheel joint)
  36120. */
  36121. var Hinge2Joint = (function (_super) {
  36122. __extends(Hinge2Joint, _super);
  36123. function Hinge2Joint(jointData) {
  36124. return _super.call(this, PhysicsJoint.Hinge2Joint, jointData) || this;
  36125. }
  36126. /**
  36127. * Set the motor values.
  36128. * Attention, this function is plugin specific. Engines won't react 100% the same.
  36129. * @param {number} force the force to apply
  36130. * @param {number} maxForce max force for this motor.
  36131. * @param {motorIndex} the motor's index, 0 or 1.
  36132. */
  36133. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  36134. if (motorIndex === void 0) { motorIndex = 0; }
  36135. this._physicsPlugin.setMotor(this, force, maxForce, motorIndex);
  36136. };
  36137. /**
  36138. * Set the motor limits.
  36139. * Attention, this function is plugin specific. Engines won't react 100% the same.
  36140. * @param {number} upperLimit the upper limit
  36141. * @param {number} lowerLimit lower limit
  36142. * @param {motorIndex} the motor's index, 0 or 1.
  36143. */
  36144. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  36145. if (motorIndex === void 0) { motorIndex = 0; }
  36146. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  36147. };
  36148. return Hinge2Joint;
  36149. }(MotorEnabledJoint));
  36150. BABYLON.Hinge2Joint = Hinge2Joint;
  36151. })(BABYLON || (BABYLON = {}));
  36152. //# sourceMappingURL=babylon.physicsJoint.js.map
  36153. var BABYLON;
  36154. (function (BABYLON) {
  36155. var PhysicsImpostor = (function () {
  36156. function PhysicsImpostor(object, type, _options, _scene) {
  36157. if (_options === void 0) { _options = { mass: 0 }; }
  36158. var _this = this;
  36159. this.object = object;
  36160. this.type = type;
  36161. this._options = _options;
  36162. this._scene = _scene;
  36163. this._bodyUpdateRequired = false;
  36164. this._onBeforePhysicsStepCallbacks = new Array();
  36165. this._onAfterPhysicsStepCallbacks = new Array();
  36166. this._onPhysicsCollideCallbacks = [];
  36167. this._deltaPosition = BABYLON.Vector3.Zero();
  36168. this._tmpPositionWithDelta = BABYLON.Vector3.Zero();
  36169. this._tmpRotationWithDelta = new BABYLON.Quaternion();
  36170. /**
  36171. * this function is executed by the physics engine.
  36172. */
  36173. this.beforeStep = function () {
  36174. _this.object.position.subtractToRef(_this._deltaPosition, _this._tmpPositionWithDelta);
  36175. //conjugate deltaRotation
  36176. if (_this._deltaRotationConjugated) {
  36177. _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this._tmpRotationWithDelta);
  36178. }
  36179. else {
  36180. _this._tmpRotationWithDelta.copyFrom(_this.object.rotationQuaternion);
  36181. }
  36182. _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, _this._tmpPositionWithDelta, _this._tmpRotationWithDelta);
  36183. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  36184. func(_this);
  36185. });
  36186. };
  36187. /**
  36188. * this function is executed by the physics engine.
  36189. */
  36190. this.afterStep = function () {
  36191. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  36192. func(_this);
  36193. });
  36194. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  36195. _this.object.position.addInPlace(_this._deltaPosition);
  36196. if (_this._deltaRotation) {
  36197. _this.object.rotationQuaternion.multiplyInPlace(_this._deltaRotation);
  36198. }
  36199. };
  36200. /**
  36201. * Legacy collision detection event support
  36202. */
  36203. this.onCollideEvent = null;
  36204. //event and body object due to cannon's event-based architecture.
  36205. this.onCollide = function (e) {
  36206. if (!_this._onPhysicsCollideCallbacks.length && !_this.onCollideEvent)
  36207. return;
  36208. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  36209. if (otherImpostor) {
  36210. // Legacy collision detection event support
  36211. if (_this.onCollideEvent) {
  36212. _this.onCollideEvent(_this, otherImpostor);
  36213. }
  36214. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  36215. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  36216. }).forEach(function (obj) {
  36217. obj.callback(_this, otherImpostor);
  36218. });
  36219. }
  36220. };
  36221. //sanity check!
  36222. if (!this.object) {
  36223. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  36224. return;
  36225. }
  36226. //legacy support for old syntax.
  36227. if (!this._scene && object.getScene) {
  36228. this._scene = object.getScene();
  36229. }
  36230. this._physicsEngine = this._scene.getPhysicsEngine();
  36231. if (!this._physicsEngine) {
  36232. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  36233. }
  36234. else {
  36235. //set the object's quaternion, if not set
  36236. if (!this.object.rotationQuaternion) {
  36237. if (this.object.rotation) {
  36238. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  36239. }
  36240. else {
  36241. this.object.rotationQuaternion = new BABYLON.Quaternion();
  36242. }
  36243. }
  36244. //default options params
  36245. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  36246. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  36247. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  36248. this._joints = [];
  36249. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  36250. if (!this.object.parent) {
  36251. this._init();
  36252. }
  36253. }
  36254. }
  36255. /**
  36256. * This function will completly initialize this impostor.
  36257. * It will create a new body - but only if this mesh has no parent.
  36258. * If it has, this impostor will not be used other than to define the impostor
  36259. * of the child mesh.
  36260. */
  36261. PhysicsImpostor.prototype._init = function () {
  36262. this._physicsEngine.removeImpostor(this);
  36263. this.physicsBody = null;
  36264. this._parent = this._parent || this._getPhysicsParent();
  36265. if (!this.parent) {
  36266. this._physicsEngine.addImpostor(this);
  36267. }
  36268. };
  36269. PhysicsImpostor.prototype._getPhysicsParent = function () {
  36270. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  36271. var parentMesh = this.object.parent;
  36272. return parentMesh.physicsImpostor;
  36273. }
  36274. return;
  36275. };
  36276. /**
  36277. * Should a new body be generated.
  36278. */
  36279. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  36280. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  36281. };
  36282. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  36283. this.forceUpdate();
  36284. };
  36285. /**
  36286. * Force a regeneration of this or the parent's impostor's body.
  36287. * Use under cautious - This will remove all joints already implemented.
  36288. */
  36289. PhysicsImpostor.prototype.forceUpdate = function () {
  36290. this._init();
  36291. if (this.parent) {
  36292. this.parent.forceUpdate();
  36293. }
  36294. };
  36295. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  36296. /*public get mesh(): AbstractMesh {
  36297. return this._mesh;
  36298. }*/
  36299. /**
  36300. * Gets the body that holds this impostor. Either its own, or its parent.
  36301. */
  36302. get: function () {
  36303. return this._parent ? this._parent.physicsBody : this._physicsBody;
  36304. },
  36305. /**
  36306. * Set the physics body. Used mainly by the physics engine/plugin
  36307. */
  36308. set: function (physicsBody) {
  36309. if (this._physicsBody) {
  36310. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  36311. }
  36312. this._physicsBody = physicsBody;
  36313. this.resetUpdateFlags();
  36314. },
  36315. enumerable: true,
  36316. configurable: true
  36317. });
  36318. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  36319. get: function () {
  36320. return this._parent;
  36321. },
  36322. set: function (value) {
  36323. this._parent = value;
  36324. },
  36325. enumerable: true,
  36326. configurable: true
  36327. });
  36328. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  36329. this._bodyUpdateRequired = false;
  36330. };
  36331. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  36332. if (this.object.getBoundingInfo) {
  36333. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  36334. return this.object.getBoundingInfo().boundingBox.extendSizeWorld.scale(2).multiply(this.object.scaling);
  36335. }
  36336. else {
  36337. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  36338. }
  36339. };
  36340. PhysicsImpostor.prototype.getObjectCenter = function () {
  36341. if (this.object.getBoundingInfo) {
  36342. return this.object.getBoundingInfo().boundingBox.centerWorld;
  36343. }
  36344. else {
  36345. return this.object.position;
  36346. }
  36347. };
  36348. /**
  36349. * Get a specific parametes from the options parameter.
  36350. */
  36351. PhysicsImpostor.prototype.getParam = function (paramName) {
  36352. return this._options[paramName];
  36353. };
  36354. /**
  36355. * Sets a specific parameter in the options given to the physics plugin
  36356. */
  36357. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  36358. this._options[paramName] = value;
  36359. this._bodyUpdateRequired = true;
  36360. };
  36361. /**
  36362. * Specifically change the body's mass option. Won't recreate the physics body object
  36363. */
  36364. PhysicsImpostor.prototype.setMass = function (mass) {
  36365. if (this.getParam("mass") !== mass) {
  36366. this.setParam("mass", mass);
  36367. }
  36368. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  36369. };
  36370. PhysicsImpostor.prototype.getLinearVelocity = function () {
  36371. return this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this);
  36372. };
  36373. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  36374. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  36375. };
  36376. PhysicsImpostor.prototype.getAngularVelocity = function () {
  36377. return this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this);
  36378. };
  36379. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  36380. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  36381. };
  36382. /**
  36383. * Execute a function with the physics plugin native code.
  36384. * Provide a function the will have two variables - the world object and the physics body object.
  36385. */
  36386. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  36387. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  36388. };
  36389. /**
  36390. * Register a function that will be executed before the physics world is stepping forward.
  36391. */
  36392. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  36393. this._onBeforePhysicsStepCallbacks.push(func);
  36394. };
  36395. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  36396. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  36397. if (index > -1) {
  36398. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  36399. }
  36400. else {
  36401. BABYLON.Tools.Warn("Function to remove was not found");
  36402. }
  36403. };
  36404. /**
  36405. * Register a function that will be executed after the physics step
  36406. */
  36407. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  36408. this._onAfterPhysicsStepCallbacks.push(func);
  36409. };
  36410. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  36411. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  36412. if (index > -1) {
  36413. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  36414. }
  36415. else {
  36416. BABYLON.Tools.Warn("Function to remove was not found");
  36417. }
  36418. };
  36419. /**
  36420. * register a function that will be executed when this impostor collides against a different body.
  36421. */
  36422. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  36423. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  36424. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  36425. };
  36426. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  36427. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  36428. var index = this._onPhysicsCollideCallbacks.indexOf({ callback: func, otherImpostors: collidedAgainstList });
  36429. if (index > -1) {
  36430. this._onPhysicsCollideCallbacks.splice(index, 1);
  36431. }
  36432. else {
  36433. BABYLON.Tools.Warn("Function to remove was not found");
  36434. }
  36435. };
  36436. /**
  36437. * Apply a force
  36438. */
  36439. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  36440. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  36441. };
  36442. /**
  36443. * Apply an impulse
  36444. */
  36445. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  36446. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  36447. };
  36448. /**
  36449. * A help function to create a joint.
  36450. */
  36451. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  36452. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  36453. this.addJoint(otherImpostor, joint);
  36454. };
  36455. /**
  36456. * Add a joint to this impostor with a different impostor.
  36457. */
  36458. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  36459. this._joints.push({
  36460. otherImpostor: otherImpostor,
  36461. joint: joint
  36462. });
  36463. this._physicsEngine.addJoint(this, otherImpostor, joint);
  36464. };
  36465. /**
  36466. * Will keep this body still, in a sleep mode.
  36467. */
  36468. PhysicsImpostor.prototype.sleep = function () {
  36469. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  36470. };
  36471. /**
  36472. * Wake the body up.
  36473. */
  36474. PhysicsImpostor.prototype.wakeUp = function () {
  36475. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  36476. };
  36477. PhysicsImpostor.prototype.clone = function (newObject) {
  36478. if (!newObject)
  36479. return null;
  36480. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  36481. };
  36482. PhysicsImpostor.prototype.dispose = function () {
  36483. var _this = this;
  36484. //no dispose if no physics engine is available.
  36485. if (!this._physicsEngine) {
  36486. return;
  36487. }
  36488. this._joints.forEach(function (j) {
  36489. _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
  36490. });
  36491. //dispose the physics body
  36492. this._physicsEngine.removeImpostor(this);
  36493. if (this.parent) {
  36494. this.parent.forceUpdate();
  36495. }
  36496. else {
  36497. }
  36498. };
  36499. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  36500. this._deltaPosition.copyFrom(position);
  36501. };
  36502. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  36503. if (!this._deltaRotation) {
  36504. this._deltaRotation = new BABYLON.Quaternion();
  36505. }
  36506. this._deltaRotation.copyFrom(rotation);
  36507. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  36508. };
  36509. return PhysicsImpostor;
  36510. }());
  36511. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  36512. //Impostor types
  36513. PhysicsImpostor.NoImpostor = 0;
  36514. PhysicsImpostor.SphereImpostor = 1;
  36515. PhysicsImpostor.BoxImpostor = 2;
  36516. PhysicsImpostor.PlaneImpostor = 3;
  36517. PhysicsImpostor.MeshImpostor = 4;
  36518. PhysicsImpostor.CylinderImpostor = 7;
  36519. PhysicsImpostor.ParticleImpostor = 8;
  36520. PhysicsImpostor.HeightmapImpostor = 9;
  36521. BABYLON.PhysicsImpostor = PhysicsImpostor;
  36522. })(BABYLON || (BABYLON = {}));
  36523. //# sourceMappingURL=babylon.physicsImpostor.js.map
  36524. var BABYLON;
  36525. (function (BABYLON) {
  36526. var PhysicsEngine = (function () {
  36527. function PhysicsEngine(gravity, _physicsPlugin) {
  36528. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  36529. this._physicsPlugin = _physicsPlugin;
  36530. //new methods and parameters
  36531. this._impostors = [];
  36532. this._joints = [];
  36533. if (!this._physicsPlugin.isSupported()) {
  36534. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  36535. + "Please make sure it is included.");
  36536. }
  36537. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  36538. this.setGravity(gravity);
  36539. this.setTimeStep();
  36540. }
  36541. PhysicsEngine.prototype.setGravity = function (gravity) {
  36542. this.gravity = gravity;
  36543. this._physicsPlugin.setGravity(this.gravity);
  36544. };
  36545. /**
  36546. * Set the time step of the physics engine.
  36547. * default is 1/60.
  36548. * To slow it down, enter 1/600 for example.
  36549. * To speed it up, 1/30
  36550. * @param {number} newTimeStep the new timestep to apply to this world.
  36551. */
  36552. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  36553. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  36554. this._physicsPlugin.setTimeStep(newTimeStep);
  36555. };
  36556. PhysicsEngine.prototype.dispose = function () {
  36557. this._impostors.forEach(function (impostor) {
  36558. impostor.dispose();
  36559. });
  36560. this._physicsPlugin.dispose();
  36561. };
  36562. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  36563. return this._physicsPlugin.name;
  36564. };
  36565. /**
  36566. * Adding a new impostor for the impostor tracking.
  36567. * This will be done by the impostor itself.
  36568. * @param {PhysicsImpostor} impostor the impostor to add
  36569. */
  36570. PhysicsEngine.prototype.addImpostor = function (impostor) {
  36571. impostor.uniqueId = this._impostors.push(impostor);
  36572. //if no parent, generate the body
  36573. if (!impostor.parent) {
  36574. this._physicsPlugin.generatePhysicsBody(impostor);
  36575. }
  36576. };
  36577. /**
  36578. * Remove an impostor from the engine.
  36579. * This impostor and its mesh will not longer be updated by the physics engine.
  36580. * @param {PhysicsImpostor} impostor the impostor to remove
  36581. */
  36582. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  36583. var index = this._impostors.indexOf(impostor);
  36584. if (index > -1) {
  36585. var removed = this._impostors.splice(index, 1);
  36586. //Is it needed?
  36587. if (removed.length) {
  36588. //this will also remove it from the world.
  36589. removed[0].physicsBody = null;
  36590. }
  36591. }
  36592. };
  36593. /**
  36594. * Add a joint to the physics engine
  36595. * @param {PhysicsImpostor} mainImpostor the main impostor to which the joint is added.
  36596. * @param {PhysicsImpostor} connectedImpostor the impostor that is connected to the main impostor using this joint
  36597. * @param {PhysicsJoint} the joint that will connect both impostors.
  36598. */
  36599. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  36600. var impostorJoint = {
  36601. mainImpostor: mainImpostor,
  36602. connectedImpostor: connectedImpostor,
  36603. joint: joint
  36604. };
  36605. joint.physicsPlugin = this._physicsPlugin;
  36606. this._joints.push(impostorJoint);
  36607. this._physicsPlugin.generateJoint(impostorJoint);
  36608. };
  36609. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  36610. var matchingJoints = this._joints.filter(function (impostorJoint) {
  36611. return (impostorJoint.connectedImpostor === connectedImpostor
  36612. && impostorJoint.joint === joint
  36613. && impostorJoint.mainImpostor === mainImpostor);
  36614. });
  36615. if (matchingJoints.length) {
  36616. this._physicsPlugin.removeJoint(matchingJoints[0]);
  36617. }
  36618. };
  36619. /**
  36620. * Called by the scene. no need to call it.
  36621. */
  36622. PhysicsEngine.prototype._step = function (delta) {
  36623. var _this = this;
  36624. //check if any mesh has no body / requires an update
  36625. this._impostors.forEach(function (impostor) {
  36626. if (impostor.isBodyInitRequired()) {
  36627. _this._physicsPlugin.generatePhysicsBody(impostor);
  36628. }
  36629. });
  36630. if (delta > 0.1) {
  36631. delta = 0.1;
  36632. }
  36633. else if (delta <= 0) {
  36634. delta = 1.0 / 60.0;
  36635. }
  36636. this._physicsPlugin.executeStep(delta, this._impostors);
  36637. };
  36638. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  36639. return this._physicsPlugin;
  36640. };
  36641. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  36642. for (var i = 0; i < this._impostors.length; ++i) {
  36643. if (this._impostors[i].object === object) {
  36644. return this._impostors[i];
  36645. }
  36646. }
  36647. };
  36648. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  36649. for (var i = 0; i < this._impostors.length; ++i) {
  36650. if (this._impostors[i].physicsBody === body) {
  36651. return this._impostors[i];
  36652. }
  36653. }
  36654. };
  36655. return PhysicsEngine;
  36656. }());
  36657. // Statics
  36658. PhysicsEngine.Epsilon = 0.001;
  36659. BABYLON.PhysicsEngine = PhysicsEngine;
  36660. })(BABYLON || (BABYLON = {}));
  36661. //# sourceMappingURL=babylon.physicsEngine.js.map
  36662. var BABYLON;
  36663. (function (BABYLON) {
  36664. var VertexData = (function () {
  36665. function VertexData() {
  36666. }
  36667. VertexData.prototype.set = function (data, kind) {
  36668. switch (kind) {
  36669. case BABYLON.VertexBuffer.PositionKind:
  36670. this.positions = data;
  36671. break;
  36672. case BABYLON.VertexBuffer.NormalKind:
  36673. this.normals = data;
  36674. break;
  36675. case BABYLON.VertexBuffer.TangentKind:
  36676. this.tangents = data;
  36677. break;
  36678. case BABYLON.VertexBuffer.UVKind:
  36679. this.uvs = data;
  36680. break;
  36681. case BABYLON.VertexBuffer.UV2Kind:
  36682. this.uvs2 = data;
  36683. break;
  36684. case BABYLON.VertexBuffer.UV3Kind:
  36685. this.uvs3 = data;
  36686. break;
  36687. case BABYLON.VertexBuffer.UV4Kind:
  36688. this.uvs4 = data;
  36689. break;
  36690. case BABYLON.VertexBuffer.UV5Kind:
  36691. this.uvs5 = data;
  36692. break;
  36693. case BABYLON.VertexBuffer.UV6Kind:
  36694. this.uvs6 = data;
  36695. break;
  36696. case BABYLON.VertexBuffer.ColorKind:
  36697. this.colors = data;
  36698. break;
  36699. case BABYLON.VertexBuffer.MatricesIndicesKind:
  36700. this.matricesIndices = data;
  36701. break;
  36702. case BABYLON.VertexBuffer.MatricesWeightsKind:
  36703. this.matricesWeights = data;
  36704. break;
  36705. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  36706. this.matricesIndicesExtra = data;
  36707. break;
  36708. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  36709. this.matricesWeightsExtra = data;
  36710. break;
  36711. }
  36712. };
  36713. /**
  36714. * Associates the vertexData to the passed Mesh.
  36715. * Sets it as updatable or not (default `false`).
  36716. * Returns the VertexData.
  36717. */
  36718. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  36719. this._applyTo(mesh, updatable);
  36720. return this;
  36721. };
  36722. /**
  36723. * Associates the vertexData to the passed Geometry.
  36724. * Sets it as updatable or not (default `false`).
  36725. * Returns the VertexData.
  36726. */
  36727. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  36728. this._applyTo(geometry, updatable);
  36729. return this;
  36730. };
  36731. /**
  36732. * Updates the associated mesh.
  36733. * Returns the VertexData.
  36734. */
  36735. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  36736. this._update(mesh);
  36737. return this;
  36738. };
  36739. /**
  36740. * Updates the associated geometry.
  36741. * Returns the VertexData.
  36742. */
  36743. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  36744. this._update(geometry);
  36745. return this;
  36746. };
  36747. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  36748. if (this.positions) {
  36749. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  36750. }
  36751. if (this.normals) {
  36752. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  36753. }
  36754. if (this.tangents) {
  36755. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updatable);
  36756. }
  36757. if (this.uvs) {
  36758. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  36759. }
  36760. if (this.uvs2) {
  36761. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  36762. }
  36763. if (this.uvs3) {
  36764. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  36765. }
  36766. if (this.uvs4) {
  36767. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  36768. }
  36769. if (this.uvs5) {
  36770. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  36771. }
  36772. if (this.uvs6) {
  36773. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  36774. }
  36775. if (this.colors) {
  36776. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  36777. }
  36778. if (this.matricesIndices) {
  36779. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  36780. }
  36781. if (this.matricesWeights) {
  36782. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  36783. }
  36784. if (this.matricesIndicesExtra) {
  36785. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  36786. }
  36787. if (this.matricesWeightsExtra) {
  36788. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  36789. }
  36790. if (this.indices) {
  36791. meshOrGeometry.setIndices(this.indices);
  36792. }
  36793. return this;
  36794. };
  36795. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  36796. if (this.positions) {
  36797. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  36798. }
  36799. if (this.normals) {
  36800. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  36801. }
  36802. if (this.tangents) {
  36803. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updateExtends, makeItUnique);
  36804. }
  36805. if (this.uvs) {
  36806. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  36807. }
  36808. if (this.uvs2) {
  36809. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  36810. }
  36811. if (this.uvs3) {
  36812. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  36813. }
  36814. if (this.uvs4) {
  36815. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  36816. }
  36817. if (this.uvs5) {
  36818. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  36819. }
  36820. if (this.uvs6) {
  36821. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  36822. }
  36823. if (this.colors) {
  36824. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  36825. }
  36826. if (this.matricesIndices) {
  36827. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  36828. }
  36829. if (this.matricesWeights) {
  36830. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  36831. }
  36832. if (this.matricesIndicesExtra) {
  36833. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  36834. }
  36835. if (this.matricesWeightsExtra) {
  36836. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  36837. }
  36838. if (this.indices) {
  36839. meshOrGeometry.setIndices(this.indices);
  36840. }
  36841. return this;
  36842. };
  36843. /**
  36844. * Transforms each position and each normal of the vertexData according to the passed Matrix.
  36845. * Returns the VertexData.
  36846. */
  36847. VertexData.prototype.transform = function (matrix) {
  36848. var transformed = BABYLON.Vector3.Zero();
  36849. var index;
  36850. if (this.positions) {
  36851. var position = BABYLON.Vector3.Zero();
  36852. for (index = 0; index < this.positions.length; index += 3) {
  36853. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  36854. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  36855. this.positions[index] = transformed.x;
  36856. this.positions[index + 1] = transformed.y;
  36857. this.positions[index + 2] = transformed.z;
  36858. }
  36859. }
  36860. if (this.normals) {
  36861. var normal = BABYLON.Vector3.Zero();
  36862. for (index = 0; index < this.normals.length; index += 3) {
  36863. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  36864. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  36865. this.normals[index] = transformed.x;
  36866. this.normals[index + 1] = transformed.y;
  36867. this.normals[index + 2] = transformed.z;
  36868. }
  36869. }
  36870. if (this.tangents) {
  36871. var tangent = BABYLON.Vector4.Zero();
  36872. var tangentTransformed = BABYLON.Vector4.Zero();
  36873. for (index = 0; index < this.tangents.length; index += 4) {
  36874. BABYLON.Vector4.FromArrayToRef(this.tangents, index, tangent);
  36875. BABYLON.Vector4.TransformNormalToRef(tangent, matrix, tangentTransformed);
  36876. this.tangents[index] = tangentTransformed.x;
  36877. this.tangents[index + 1] = tangentTransformed.y;
  36878. this.tangents[index + 2] = tangentTransformed.z;
  36879. this.tangents[index + 3] = tangentTransformed.w;
  36880. }
  36881. }
  36882. return this;
  36883. };
  36884. /**
  36885. * Merges the passed VertexData into the current one.
  36886. * Returns the modified VertexData.
  36887. */
  36888. VertexData.prototype.merge = function (other) {
  36889. if (other.indices) {
  36890. if (!this.indices) {
  36891. this.indices = [];
  36892. }
  36893. var offset = this.positions ? this.positions.length / 3 : 0;
  36894. for (var index = 0; index < other.indices.length; index++) {
  36895. //TODO check type - if Int32Array | Uint32Array | Uint16Array!
  36896. this.indices.push(other.indices[index] + offset);
  36897. }
  36898. }
  36899. this.positions = this._mergeElement(this.positions, other.positions);
  36900. this.normals = this._mergeElement(this.normals, other.normals);
  36901. this.tangents = this._mergeElement(this.tangents, other.tangents);
  36902. this.uvs = this._mergeElement(this.uvs, other.uvs);
  36903. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);
  36904. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);
  36905. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);
  36906. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);
  36907. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);
  36908. this.colors = this._mergeElement(this.colors, other.colors);
  36909. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);
  36910. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);
  36911. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);
  36912. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);
  36913. return this;
  36914. };
  36915. VertexData.prototype._mergeElement = function (source, other) {
  36916. if (!other)
  36917. return source;
  36918. if (!source)
  36919. return other;
  36920. var len = other.length + source.length;
  36921. var isSrcTypedArray = source instanceof Float32Array;
  36922. var isOthTypedArray = other instanceof Float32Array;
  36923. // use non-loop method when the source is Float32Array
  36924. if (isSrcTypedArray) {
  36925. var ret32 = new Float32Array(len);
  36926. ret32.set(source);
  36927. ret32.set(other, source.length);
  36928. return ret32;
  36929. }
  36930. else if (!isOthTypedArray) {
  36931. return source.concat(other);
  36932. }
  36933. else {
  36934. var ret = source.slice(0); // copy source to a separate array
  36935. for (var i = 0, len = other.length; i < len; i++) {
  36936. ret.push(other[i]);
  36937. }
  36938. return ret;
  36939. }
  36940. };
  36941. /**
  36942. * Serializes the VertexData.
  36943. * Returns a serialized object.
  36944. */
  36945. VertexData.prototype.serialize = function () {
  36946. var serializationObject = this.serialize();
  36947. if (this.positions) {
  36948. serializationObject.positions = this.positions;
  36949. }
  36950. if (this.normals) {
  36951. serializationObject.normals = this.normals;
  36952. }
  36953. if (this.tangents) {
  36954. serializationObject.tangents = this.tangents;
  36955. }
  36956. if (this.uvs) {
  36957. serializationObject.uvs = this.uvs;
  36958. }
  36959. if (this.uvs2) {
  36960. serializationObject.uvs2 = this.uvs2;
  36961. }
  36962. if (this.uvs3) {
  36963. serializationObject.uvs3 = this.uvs3;
  36964. }
  36965. if (this.uvs4) {
  36966. serializationObject.uvs4 = this.uvs4;
  36967. }
  36968. if (this.uvs5) {
  36969. serializationObject.uvs5 = this.uvs5;
  36970. }
  36971. if (this.uvs6) {
  36972. serializationObject.uvs6 = this.uvs6;
  36973. }
  36974. if (this.colors) {
  36975. serializationObject.colors = this.colors;
  36976. }
  36977. if (this.matricesIndices) {
  36978. serializationObject.matricesIndices = this.matricesIndices;
  36979. serializationObject.matricesIndices._isExpanded = true;
  36980. }
  36981. if (this.matricesWeights) {
  36982. serializationObject.matricesWeights = this.matricesWeights;
  36983. }
  36984. if (this.matricesIndicesExtra) {
  36985. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  36986. serializationObject.matricesIndicesExtra._isExpanded = true;
  36987. }
  36988. if (this.matricesWeightsExtra) {
  36989. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  36990. }
  36991. serializationObject.indices = this.indices;
  36992. return serializationObject;
  36993. };
  36994. // Statics
  36995. /**
  36996. * Returns the object VertexData associated to the passed mesh.
  36997. */
  36998. VertexData.ExtractFromMesh = function (mesh, copyWhenShared) {
  36999. return VertexData._ExtractFrom(mesh, copyWhenShared);
  37000. };
  37001. /**
  37002. * Returns the object VertexData associated to the passed geometry.
  37003. */
  37004. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared) {
  37005. return VertexData._ExtractFrom(geometry, copyWhenShared);
  37006. };
  37007. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared) {
  37008. var result = new VertexData();
  37009. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  37010. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared);
  37011. }
  37012. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  37013. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared);
  37014. }
  37015. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  37016. result.tangents = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.TangentKind, copyWhenShared);
  37017. }
  37018. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  37019. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared);
  37020. }
  37021. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  37022. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared);
  37023. }
  37024. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  37025. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared);
  37026. }
  37027. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  37028. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared);
  37029. }
  37030. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  37031. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared);
  37032. }
  37033. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  37034. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared);
  37035. }
  37036. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  37037. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared);
  37038. }
  37039. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  37040. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared);
  37041. }
  37042. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  37043. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared);
  37044. }
  37045. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  37046. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared);
  37047. }
  37048. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  37049. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared);
  37050. }
  37051. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  37052. return result;
  37053. };
  37054. /**
  37055. * Creates the vertexData of the Ribbon.
  37056. */
  37057. VertexData.CreateRibbon = function (options) {
  37058. var pathArray = options.pathArray;
  37059. var closeArray = options.closeArray || false;
  37060. var closePath = options.closePath || false;
  37061. var invertUV = options.invertUV || false;
  37062. var defaultOffset = Math.floor(pathArray[0].length / 2);
  37063. var offset = options.offset || defaultOffset;
  37064. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  37065. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37066. var customUV = options.uvs;
  37067. var customColors = options.colors;
  37068. var positions = [];
  37069. var indices = [];
  37070. var normals = [];
  37071. var uvs = [];
  37072. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  37073. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  37074. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  37075. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  37076. var minlg; // minimal length among all paths from pathArray
  37077. var lg = []; // array of path lengths : nb of vertex per path
  37078. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  37079. var p; // path iterator
  37080. var i; // point iterator
  37081. var j; // point iterator
  37082. // if single path in pathArray
  37083. if (pathArray.length < 2) {
  37084. var ar1 = [];
  37085. var ar2 = [];
  37086. for (i = 0; i < pathArray[0].length - offset; i++) {
  37087. ar1.push(pathArray[0][i]);
  37088. ar2.push(pathArray[0][i + offset]);
  37089. }
  37090. pathArray = [ar1, ar2];
  37091. }
  37092. // positions and horizontal distances (u)
  37093. var idc = 0;
  37094. var closePathCorr = (closePath) ? 1 : 0; // the final index will be +1 if closePath
  37095. var path;
  37096. var l;
  37097. minlg = pathArray[0].length;
  37098. var vectlg;
  37099. var dist;
  37100. for (p = 0; p < pathArray.length; p++) {
  37101. uTotalDistance[p] = 0;
  37102. us[p] = [0];
  37103. path = pathArray[p];
  37104. l = path.length;
  37105. minlg = (minlg < l) ? minlg : l;
  37106. j = 0;
  37107. while (j < l) {
  37108. positions.push(path[j].x, path[j].y, path[j].z);
  37109. if (j > 0) {
  37110. vectlg = path[j].subtract(path[j - 1]).length();
  37111. dist = vectlg + uTotalDistance[p];
  37112. us[p].push(dist);
  37113. uTotalDistance[p] = dist;
  37114. }
  37115. j++;
  37116. }
  37117. if (closePath) {
  37118. j--;
  37119. positions.push(path[0].x, path[0].y, path[0].z);
  37120. vectlg = path[j].subtract(path[0]).length();
  37121. dist = vectlg + uTotalDistance[p];
  37122. us[p].push(dist);
  37123. uTotalDistance[p] = dist;
  37124. }
  37125. lg[p] = l + closePathCorr;
  37126. idx[p] = idc;
  37127. idc += (l + closePathCorr);
  37128. }
  37129. // vertical distances (v)
  37130. var path1;
  37131. var path2;
  37132. var vertex1;
  37133. var vertex2;
  37134. for (i = 0; i < minlg + closePathCorr; i++) {
  37135. vTotalDistance[i] = 0;
  37136. vs[i] = [0];
  37137. for (p = 0; p < pathArray.length - 1; p++) {
  37138. path1 = pathArray[p];
  37139. path2 = pathArray[p + 1];
  37140. if (i === minlg) {
  37141. vertex1 = path1[0];
  37142. vertex2 = path2[0];
  37143. }
  37144. else {
  37145. vertex1 = path1[i];
  37146. vertex2 = path2[i];
  37147. }
  37148. vectlg = vertex2.subtract(vertex1).length();
  37149. dist = vectlg + vTotalDistance[i];
  37150. vs[i].push(dist);
  37151. vTotalDistance[i] = dist;
  37152. }
  37153. if (closeArray) {
  37154. path1 = pathArray[p];
  37155. path2 = pathArray[0];
  37156. if (i === minlg) {
  37157. vertex2 = path2[0];
  37158. }
  37159. vectlg = vertex2.subtract(vertex1).length();
  37160. dist = vectlg + vTotalDistance[i];
  37161. vTotalDistance[i] = dist;
  37162. }
  37163. }
  37164. // uvs
  37165. var u;
  37166. var v;
  37167. if (customUV) {
  37168. for (p = 0; p < customUV.length; p++) {
  37169. uvs.push(customUV[p].x, customUV[p].y);
  37170. }
  37171. }
  37172. else {
  37173. for (p = 0; p < pathArray.length; p++) {
  37174. for (i = 0; i < minlg + closePathCorr; i++) {
  37175. u = (uTotalDistance[p] != 0.0) ? us[p][i] / uTotalDistance[p] : 0.0;
  37176. v = (vTotalDistance[i] != 0.0) ? vs[i][p] / vTotalDistance[i] : 0.0;
  37177. if (invertUV) {
  37178. uvs.push(v, u);
  37179. }
  37180. else {
  37181. uvs.push(u, v);
  37182. }
  37183. }
  37184. }
  37185. }
  37186. // indices
  37187. p = 0; // path index
  37188. var pi = 0; // positions array index
  37189. var l1 = lg[p] - 1; // path1 length
  37190. var l2 = lg[p + 1] - 1; // path2 length
  37191. var min = (l1 < l2) ? l1 : l2; // current path stop index
  37192. var shft = idx[1] - idx[0]; // shift
  37193. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  37194. while (pi <= min && p < path1nb) {
  37195. // 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
  37196. indices.push(pi, pi + shft, pi + 1);
  37197. indices.push(pi + shft + 1, pi + 1, pi + shft);
  37198. pi += 1;
  37199. if (pi === min) {
  37200. p++;
  37201. if (p === lg.length - 1) {
  37202. shft = idx[0] - idx[p];
  37203. l1 = lg[p] - 1;
  37204. l2 = lg[0] - 1;
  37205. }
  37206. else {
  37207. shft = idx[p + 1] - idx[p];
  37208. l1 = lg[p] - 1;
  37209. l2 = lg[p + 1] - 1;
  37210. }
  37211. pi = idx[p];
  37212. min = (l1 < l2) ? l1 + pi : l2 + pi;
  37213. }
  37214. }
  37215. // normals
  37216. VertexData.ComputeNormals(positions, indices, normals);
  37217. if (closePath) {
  37218. var indexFirst = 0;
  37219. var indexLast = 0;
  37220. for (p = 0; p < pathArray.length; p++) {
  37221. indexFirst = idx[p] * 3;
  37222. if (p + 1 < pathArray.length) {
  37223. indexLast = (idx[p + 1] - 1) * 3;
  37224. }
  37225. else {
  37226. indexLast = normals.length - 3;
  37227. }
  37228. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  37229. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  37230. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  37231. normals[indexLast] = normals[indexFirst];
  37232. normals[indexLast + 1] = normals[indexFirst + 1];
  37233. normals[indexLast + 2] = normals[indexFirst + 2];
  37234. }
  37235. }
  37236. // sides
  37237. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  37238. // Colors
  37239. if (customColors) {
  37240. var colors = new Float32Array(customColors.length * 4);
  37241. for (var c = 0; c < customColors.length; c++) {
  37242. colors[c * 4] = customColors[c].r;
  37243. colors[c * 4 + 1] = customColors[c].g;
  37244. colors[c * 4 + 2] = customColors[c].b;
  37245. colors[c * 4 + 3] = customColors[c].a;
  37246. }
  37247. }
  37248. // Result
  37249. var vertexData = new VertexData();
  37250. vertexData.indices = indices;
  37251. vertexData.positions = positions;
  37252. vertexData.normals = normals;
  37253. vertexData.uvs = uvs;
  37254. if (customColors) {
  37255. vertexData.set(colors, BABYLON.VertexBuffer.ColorKind);
  37256. }
  37257. if (closePath) {
  37258. vertexData._idx = idx;
  37259. }
  37260. return vertexData;
  37261. };
  37262. /**
  37263. * Creates the VertexData of the Box.
  37264. */
  37265. VertexData.CreateBox = function (options) {
  37266. var normalsSource = [
  37267. new BABYLON.Vector3(0, 0, 1),
  37268. new BABYLON.Vector3(0, 0, -1),
  37269. new BABYLON.Vector3(1, 0, 0),
  37270. new BABYLON.Vector3(-1, 0, 0),
  37271. new BABYLON.Vector3(0, 1, 0),
  37272. new BABYLON.Vector3(0, -1, 0)
  37273. ];
  37274. var indices = [];
  37275. var positions = [];
  37276. var normals = [];
  37277. var uvs = [];
  37278. var width = options.width || options.size || 1;
  37279. var height = options.height || options.size || 1;
  37280. var depth = options.depth || options.size || 1;
  37281. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37282. var faceUV = options.faceUV || new Array(6);
  37283. var faceColors = options.faceColors;
  37284. var colors = [];
  37285. // default face colors and UV if undefined
  37286. for (var f = 0; f < 6; f++) {
  37287. if (faceUV[f] === undefined) {
  37288. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  37289. }
  37290. if (faceColors && faceColors[f] === undefined) {
  37291. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  37292. }
  37293. }
  37294. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  37295. // Create each face in turn.
  37296. for (var index = 0; index < normalsSource.length; index++) {
  37297. var normal = normalsSource[index];
  37298. // Get two vectors perpendicular to the face normal and to each other.
  37299. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  37300. var side2 = BABYLON.Vector3.Cross(normal, side1);
  37301. // Six indices (two triangles) per face.
  37302. var verticesLength = positions.length / 3;
  37303. indices.push(verticesLength);
  37304. indices.push(verticesLength + 1);
  37305. indices.push(verticesLength + 2);
  37306. indices.push(verticesLength);
  37307. indices.push(verticesLength + 2);
  37308. indices.push(verticesLength + 3);
  37309. // Four vertices per face.
  37310. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  37311. positions.push(vertex.x, vertex.y, vertex.z);
  37312. normals.push(normal.x, normal.y, normal.z);
  37313. uvs.push(faceUV[index].z, faceUV[index].w);
  37314. if (faceColors) {
  37315. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  37316. }
  37317. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  37318. positions.push(vertex.x, vertex.y, vertex.z);
  37319. normals.push(normal.x, normal.y, normal.z);
  37320. uvs.push(faceUV[index].x, faceUV[index].w);
  37321. if (faceColors) {
  37322. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  37323. }
  37324. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  37325. positions.push(vertex.x, vertex.y, vertex.z);
  37326. normals.push(normal.x, normal.y, normal.z);
  37327. uvs.push(faceUV[index].x, faceUV[index].y);
  37328. if (faceColors) {
  37329. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  37330. }
  37331. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  37332. positions.push(vertex.x, vertex.y, vertex.z);
  37333. normals.push(normal.x, normal.y, normal.z);
  37334. uvs.push(faceUV[index].z, faceUV[index].y);
  37335. if (faceColors) {
  37336. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  37337. }
  37338. }
  37339. // sides
  37340. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  37341. // Result
  37342. var vertexData = new VertexData();
  37343. vertexData.indices = indices;
  37344. vertexData.positions = positions;
  37345. vertexData.normals = normals;
  37346. vertexData.uvs = uvs;
  37347. if (faceColors) {
  37348. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  37349. vertexData.colors = totalColors;
  37350. }
  37351. return vertexData;
  37352. };
  37353. /**
  37354. * Creates the VertexData of the Sphere.
  37355. */
  37356. VertexData.CreateSphere = function (options) {
  37357. var segments = options.segments || 32;
  37358. var diameterX = options.diameterX || options.diameter || 1;
  37359. var diameterY = options.diameterY || options.diameter || 1;
  37360. var diameterZ = options.diameterZ || options.diameter || 1;
  37361. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  37362. var slice = (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  37363. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37364. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  37365. var totalZRotationSteps = 2 + segments;
  37366. var totalYRotationSteps = 2 * totalZRotationSteps;
  37367. var indices = [];
  37368. var positions = [];
  37369. var normals = [];
  37370. var uvs = [];
  37371. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  37372. var normalizedZ = zRotationStep / totalZRotationSteps;
  37373. var angleZ = normalizedZ * Math.PI * slice;
  37374. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  37375. var normalizedY = yRotationStep / totalYRotationSteps;
  37376. var angleY = normalizedY * Math.PI * 2 * arc;
  37377. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  37378. var rotationY = BABYLON.Matrix.RotationY(angleY);
  37379. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  37380. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  37381. var vertex = complete.multiply(radius);
  37382. var normal = complete.divide(radius).normalize();
  37383. positions.push(vertex.x, vertex.y, vertex.z);
  37384. normals.push(normal.x, normal.y, normal.z);
  37385. uvs.push(normalizedY, normalizedZ);
  37386. }
  37387. if (zRotationStep > 0) {
  37388. var verticesCount = positions.length / 3;
  37389. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  37390. indices.push((firstIndex));
  37391. indices.push((firstIndex + 1));
  37392. indices.push(firstIndex + totalYRotationSteps + 1);
  37393. indices.push((firstIndex + totalYRotationSteps + 1));
  37394. indices.push((firstIndex + 1));
  37395. indices.push((firstIndex + totalYRotationSteps + 2));
  37396. }
  37397. }
  37398. }
  37399. // Sides
  37400. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  37401. // Result
  37402. var vertexData = new VertexData();
  37403. vertexData.indices = indices;
  37404. vertexData.positions = positions;
  37405. vertexData.normals = normals;
  37406. vertexData.uvs = uvs;
  37407. return vertexData;
  37408. };
  37409. /**
  37410. * Creates the VertexData of the Cylinder or Cone.
  37411. */
  37412. VertexData.CreateCylinder = function (options) {
  37413. var height = options.height || 2;
  37414. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  37415. var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;
  37416. var tessellation = options.tessellation || 24;
  37417. var subdivisions = options.subdivisions || 1;
  37418. var hasRings = options.hasRings;
  37419. var enclose = options.enclose;
  37420. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  37421. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37422. var faceUV = options.faceUV || new Array(3);
  37423. var faceColors = options.faceColors;
  37424. // default face colors and UV if undefined
  37425. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  37426. var ringNb = (hasRings) ? subdivisions : 1;
  37427. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  37428. var f;
  37429. for (f = 0; f < surfaceNb; f++) {
  37430. if (faceColors && faceColors[f] === undefined) {
  37431. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  37432. }
  37433. }
  37434. for (f = 0; f < surfaceNb; f++) {
  37435. if (faceUV && faceUV[f] === undefined) {
  37436. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  37437. }
  37438. }
  37439. var indices = [];
  37440. var positions = [];
  37441. var normals = [];
  37442. var uvs = [];
  37443. var colors = [];
  37444. var angle_step = Math.PI * 2 * arc / tessellation;
  37445. var angle;
  37446. var h;
  37447. var radius;
  37448. var tan = (diameterBottom - diameterTop) / 2 / height;
  37449. var ringVertex = BABYLON.Vector3.Zero();
  37450. var ringNormal = BABYLON.Vector3.Zero();
  37451. var ringFirstVertex = BABYLON.Vector3.Zero();
  37452. var ringFirstNormal = BABYLON.Vector3.Zero();
  37453. var quadNormal = BABYLON.Vector3.Zero();
  37454. var Y = BABYLON.Axis.Y;
  37455. // positions, normals, uvs
  37456. var i;
  37457. var j;
  37458. var r;
  37459. var ringIdx = 1;
  37460. var s = 1; // surface index
  37461. var cs = 0;
  37462. var v = 0;
  37463. for (i = 0; i <= subdivisions; i++) {
  37464. h = i / subdivisions;
  37465. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  37466. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  37467. for (r = 0; r < ringIdx; r++) {
  37468. if (hasRings) {
  37469. s += r;
  37470. }
  37471. if (enclose) {
  37472. s += 2 * r;
  37473. }
  37474. for (j = 0; j <= tessellation; j++) {
  37475. angle = j * angle_step;
  37476. // position
  37477. ringVertex.x = Math.cos(-angle) * radius;
  37478. ringVertex.y = -height / 2 + h * height;
  37479. ringVertex.z = Math.sin(-angle) * radius;
  37480. // normal
  37481. if (diameterTop === 0 && i === subdivisions) {
  37482. // if no top cap, reuse former normals
  37483. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  37484. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  37485. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  37486. }
  37487. else {
  37488. ringNormal.x = ringVertex.x;
  37489. ringNormal.z = ringVertex.z;
  37490. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  37491. ringNormal.normalize();
  37492. }
  37493. // keep first ring vertex values for enclose
  37494. if (j === 0) {
  37495. ringFirstVertex.copyFrom(ringVertex);
  37496. ringFirstNormal.copyFrom(ringNormal);
  37497. }
  37498. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  37499. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  37500. if (hasRings) {
  37501. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  37502. }
  37503. else {
  37504. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  37505. }
  37506. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  37507. if (faceColors) {
  37508. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  37509. }
  37510. }
  37511. // if enclose, add four vertices and their dedicated normals
  37512. if (arc !== 1 && enclose) {
  37513. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  37514. positions.push(0, ringVertex.y, 0);
  37515. positions.push(0, ringVertex.y, 0);
  37516. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  37517. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  37518. quadNormal.normalize();
  37519. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  37520. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  37521. quadNormal.normalize();
  37522. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  37523. if (hasRings) {
  37524. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  37525. }
  37526. else {
  37527. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  37528. }
  37529. uvs.push(faceUV[s + 1].x, v);
  37530. uvs.push(faceUV[s + 1].z, v);
  37531. if (hasRings) {
  37532. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  37533. }
  37534. else {
  37535. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  37536. }
  37537. uvs.push(faceUV[s + 2].x, v);
  37538. uvs.push(faceUV[s + 2].z, v);
  37539. if (faceColors) {
  37540. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  37541. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  37542. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  37543. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  37544. }
  37545. }
  37546. if (cs !== s) {
  37547. cs = s;
  37548. }
  37549. }
  37550. }
  37551. // indices
  37552. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  37553. var s;
  37554. i = 0;
  37555. for (s = 0; s < subdivisions; s++) {
  37556. for (j = 0; j < tessellation; j++) {
  37557. var i0 = i * (e + 1) + j;
  37558. var i1 = (i + 1) * (e + 1) + j;
  37559. var i2 = i * (e + 1) + (j + 1);
  37560. var i3 = (i + 1) * (e + 1) + (j + 1);
  37561. indices.push(i0, i1, i2);
  37562. indices.push(i3, i2, i1);
  37563. }
  37564. if (arc !== 1 && enclose) {
  37565. indices.push(i0 + 2, i1 + 2, i2 + 2);
  37566. indices.push(i3 + 2, i2 + 2, i1 + 2);
  37567. indices.push(i0 + 4, i1 + 4, i2 + 4);
  37568. indices.push(i3 + 4, i2 + 4, i1 + 4);
  37569. }
  37570. i = (hasRings) ? (i + 2) : (i + 1);
  37571. }
  37572. // Caps
  37573. var createCylinderCap = function (isTop) {
  37574. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  37575. if (radius === 0) {
  37576. return;
  37577. }
  37578. // Cap positions, normals & uvs
  37579. var angle;
  37580. var circleVector;
  37581. var i;
  37582. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  37583. var c;
  37584. if (faceColors) {
  37585. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  37586. }
  37587. // cap center
  37588. var vbase = positions.length / 3;
  37589. var offset = isTop ? height / 2 : -height / 2;
  37590. var center = new BABYLON.Vector3(0, offset, 0);
  37591. positions.push(center.x, center.y, center.z);
  37592. normals.push(0, isTop ? 1 : -1, 0);
  37593. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  37594. if (faceColors) {
  37595. colors.push(c.r, c.g, c.b, c.a);
  37596. }
  37597. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  37598. for (i = 0; i <= tessellation; i++) {
  37599. angle = Math.PI * 2 * i * arc / tessellation;
  37600. var cos = Math.cos(-angle);
  37601. var sin = Math.sin(-angle);
  37602. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  37603. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  37604. positions.push(circleVector.x, circleVector.y, circleVector.z);
  37605. normals.push(0, isTop ? 1 : -1, 0);
  37606. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  37607. if (faceColors) {
  37608. colors.push(c.r, c.g, c.b, c.a);
  37609. }
  37610. }
  37611. // Cap indices
  37612. for (i = 0; i < tessellation; i++) {
  37613. if (!isTop) {
  37614. indices.push(vbase);
  37615. indices.push(vbase + (i + 1));
  37616. indices.push(vbase + (i + 2));
  37617. }
  37618. else {
  37619. indices.push(vbase);
  37620. indices.push(vbase + (i + 2));
  37621. indices.push(vbase + (i + 1));
  37622. }
  37623. }
  37624. };
  37625. // add caps to geometry
  37626. createCylinderCap(false);
  37627. createCylinderCap(true);
  37628. // Sides
  37629. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  37630. var vertexData = new VertexData();
  37631. vertexData.indices = indices;
  37632. vertexData.positions = positions;
  37633. vertexData.normals = normals;
  37634. vertexData.uvs = uvs;
  37635. if (faceColors) {
  37636. vertexData.colors = colors;
  37637. }
  37638. return vertexData;
  37639. };
  37640. /**
  37641. * Creates the VertexData of the Torus.
  37642. */
  37643. VertexData.CreateTorus = function (options) {
  37644. var indices = [];
  37645. var positions = [];
  37646. var normals = [];
  37647. var uvs = [];
  37648. var diameter = options.diameter || 1;
  37649. var thickness = options.thickness || 0.5;
  37650. var tessellation = options.tessellation || 16;
  37651. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37652. var stride = tessellation + 1;
  37653. for (var i = 0; i <= tessellation; i++) {
  37654. var u = i / tessellation;
  37655. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  37656. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  37657. for (var j = 0; j <= tessellation; j++) {
  37658. var v = 1 - j / tessellation;
  37659. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  37660. var dx = Math.cos(innerAngle);
  37661. var dy = Math.sin(innerAngle);
  37662. // Create a vertex.
  37663. var normal = new BABYLON.Vector3(dx, dy, 0);
  37664. var position = normal.scale(thickness / 2);
  37665. var textureCoordinate = new BABYLON.Vector2(u, v);
  37666. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  37667. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  37668. positions.push(position.x, position.y, position.z);
  37669. normals.push(normal.x, normal.y, normal.z);
  37670. uvs.push(textureCoordinate.x, textureCoordinate.y);
  37671. // And create indices for two triangles.
  37672. var nextI = (i + 1) % stride;
  37673. var nextJ = (j + 1) % stride;
  37674. indices.push(i * stride + j);
  37675. indices.push(i * stride + nextJ);
  37676. indices.push(nextI * stride + j);
  37677. indices.push(i * stride + nextJ);
  37678. indices.push(nextI * stride + nextJ);
  37679. indices.push(nextI * stride + j);
  37680. }
  37681. }
  37682. // Sides
  37683. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  37684. // Result
  37685. var vertexData = new VertexData();
  37686. vertexData.indices = indices;
  37687. vertexData.positions = positions;
  37688. vertexData.normals = normals;
  37689. vertexData.uvs = uvs;
  37690. return vertexData;
  37691. };
  37692. /**
  37693. * Creates the VertexData of the LineSystem.
  37694. */
  37695. VertexData.CreateLineSystem = function (options) {
  37696. var indices = [];
  37697. var positions = [];
  37698. var lines = options.lines;
  37699. var idx = 0;
  37700. for (var l = 0; l < lines.length; l++) {
  37701. var points = lines[l];
  37702. for (var index = 0; index < points.length; index++) {
  37703. positions.push(points[index].x, points[index].y, points[index].z);
  37704. if (index > 0) {
  37705. indices.push(idx - 1);
  37706. indices.push(idx);
  37707. }
  37708. idx++;
  37709. }
  37710. }
  37711. var vertexData = new VertexData();
  37712. vertexData.indices = indices;
  37713. vertexData.positions = positions;
  37714. return vertexData;
  37715. };
  37716. /**
  37717. * Create the VertexData of the DashedLines.
  37718. */
  37719. VertexData.CreateDashedLines = function (options) {
  37720. var dashSize = options.dashSize || 3;
  37721. var gapSize = options.gapSize || 1;
  37722. var dashNb = options.dashNb || 200;
  37723. var points = options.points;
  37724. var positions = new Array();
  37725. var indices = new Array();
  37726. var curvect = BABYLON.Vector3.Zero();
  37727. var lg = 0;
  37728. var nb = 0;
  37729. var shft = 0;
  37730. var dashshft = 0;
  37731. var curshft = 0;
  37732. var idx = 0;
  37733. var i = 0;
  37734. for (i = 0; i < points.length - 1; i++) {
  37735. points[i + 1].subtractToRef(points[i], curvect);
  37736. lg += curvect.length();
  37737. }
  37738. shft = lg / dashNb;
  37739. dashshft = dashSize * shft / (dashSize + gapSize);
  37740. for (i = 0; i < points.length - 1; i++) {
  37741. points[i + 1].subtractToRef(points[i], curvect);
  37742. nb = Math.floor(curvect.length() / shft);
  37743. curvect.normalize();
  37744. for (var j = 0; j < nb; j++) {
  37745. curshft = shft * j;
  37746. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  37747. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  37748. indices.push(idx, idx + 1);
  37749. idx += 2;
  37750. }
  37751. }
  37752. // Result
  37753. var vertexData = new VertexData();
  37754. vertexData.positions = positions;
  37755. vertexData.indices = indices;
  37756. return vertexData;
  37757. };
  37758. /**
  37759. * Creates the VertexData of the Ground.
  37760. */
  37761. VertexData.CreateGround = function (options) {
  37762. var indices = [];
  37763. var positions = [];
  37764. var normals = [];
  37765. var uvs = [];
  37766. var row, col;
  37767. var width = options.width || 1;
  37768. var height = options.height || 1;
  37769. var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  37770. var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  37771. for (row = 0; row <= subdivisionsY; row++) {
  37772. for (col = 0; col <= subdivisionsX; col++) {
  37773. var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
  37774. var normal = new BABYLON.Vector3(0, 1.0, 0);
  37775. positions.push(position.x, position.y, position.z);
  37776. normals.push(normal.x, normal.y, normal.z);
  37777. uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsY);
  37778. }
  37779. }
  37780. for (row = 0; row < subdivisionsY; row++) {
  37781. for (col = 0; col < subdivisionsX; col++) {
  37782. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  37783. indices.push(col + 1 + row * (subdivisionsX + 1));
  37784. indices.push(col + row * (subdivisionsX + 1));
  37785. indices.push(col + (row + 1) * (subdivisionsX + 1));
  37786. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  37787. indices.push(col + row * (subdivisionsX + 1));
  37788. }
  37789. }
  37790. // Result
  37791. var vertexData = new VertexData();
  37792. vertexData.indices = indices;
  37793. vertexData.positions = positions;
  37794. vertexData.normals = normals;
  37795. vertexData.uvs = uvs;
  37796. return vertexData;
  37797. };
  37798. /**
  37799. * Creates the VertexData of the TiledGround.
  37800. */
  37801. VertexData.CreateTiledGround = function (options) {
  37802. var xmin = options.xmin || -1.0;
  37803. var zmin = options.zmin || -1.0;
  37804. var xmax = options.xmax || 1.0;
  37805. var zmax = options.zmax || 1.0;
  37806. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  37807. var precision = options.precision || { w: 1, h: 1 };
  37808. var indices = [];
  37809. var positions = [];
  37810. var normals = [];
  37811. var uvs = [];
  37812. var row, col, tileRow, tileCol;
  37813. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  37814. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  37815. precision.w = (precision.w < 1) ? 1 : precision.w;
  37816. precision.h = (precision.h < 1) ? 1 : precision.h;
  37817. var tileSize = {
  37818. 'w': (xmax - xmin) / subdivisions.w,
  37819. 'h': (zmax - zmin) / subdivisions.h
  37820. };
  37821. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  37822. // Indices
  37823. var base = positions.length / 3;
  37824. var rowLength = precision.w + 1;
  37825. for (row = 0; row < precision.h; row++) {
  37826. for (col = 0; col < precision.w; col++) {
  37827. var square = [
  37828. base + col + row * rowLength,
  37829. base + (col + 1) + row * rowLength,
  37830. base + (col + 1) + (row + 1) * rowLength,
  37831. base + col + (row + 1) * rowLength
  37832. ];
  37833. indices.push(square[1]);
  37834. indices.push(square[2]);
  37835. indices.push(square[3]);
  37836. indices.push(square[0]);
  37837. indices.push(square[1]);
  37838. indices.push(square[3]);
  37839. }
  37840. }
  37841. // Position, normals and uvs
  37842. var position = BABYLON.Vector3.Zero();
  37843. var normal = new BABYLON.Vector3(0, 1.0, 0);
  37844. for (row = 0; row <= precision.h; row++) {
  37845. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  37846. for (col = 0; col <= precision.w; col++) {
  37847. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  37848. position.y = 0;
  37849. positions.push(position.x, position.y, position.z);
  37850. normals.push(normal.x, normal.y, normal.z);
  37851. uvs.push(col / precision.w, row / precision.h);
  37852. }
  37853. }
  37854. }
  37855. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  37856. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  37857. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  37858. }
  37859. }
  37860. // Result
  37861. var vertexData = new VertexData();
  37862. vertexData.indices = indices;
  37863. vertexData.positions = positions;
  37864. vertexData.normals = normals;
  37865. vertexData.uvs = uvs;
  37866. return vertexData;
  37867. };
  37868. /**
  37869. * Creates the VertexData of the Ground designed from a heightmap.
  37870. */
  37871. VertexData.CreateGroundFromHeightMap = function (options) {
  37872. var indices = [];
  37873. var positions = [];
  37874. var normals = [];
  37875. var uvs = [];
  37876. var row, col;
  37877. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  37878. // Vertices
  37879. for (row = 0; row <= options.subdivisions; row++) {
  37880. for (col = 0; col <= options.subdivisions; col++) {
  37881. 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));
  37882. // Compute height
  37883. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  37884. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  37885. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  37886. var r = options.buffer[pos] / 255.0;
  37887. var g = options.buffer[pos + 1] / 255.0;
  37888. var b = options.buffer[pos + 2] / 255.0;
  37889. var gradient = r * filter.r + g * filter.g + b * filter.b;
  37890. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  37891. // Add vertex
  37892. positions.push(position.x, position.y, position.z);
  37893. normals.push(0, 0, 0);
  37894. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  37895. }
  37896. }
  37897. // Indices
  37898. for (row = 0; row < options.subdivisions; row++) {
  37899. for (col = 0; col < options.subdivisions; col++) {
  37900. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  37901. indices.push(col + 1 + row * (options.subdivisions + 1));
  37902. indices.push(col + row * (options.subdivisions + 1));
  37903. indices.push(col + (row + 1) * (options.subdivisions + 1));
  37904. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  37905. indices.push(col + row * (options.subdivisions + 1));
  37906. }
  37907. }
  37908. // Normals
  37909. VertexData.ComputeNormals(positions, indices, normals);
  37910. // Result
  37911. var vertexData = new VertexData();
  37912. vertexData.indices = indices;
  37913. vertexData.positions = positions;
  37914. vertexData.normals = normals;
  37915. vertexData.uvs = uvs;
  37916. return vertexData;
  37917. };
  37918. /**
  37919. * Creates the VertexData of the Plane.
  37920. */
  37921. VertexData.CreatePlane = function (options) {
  37922. var indices = [];
  37923. var positions = [];
  37924. var normals = [];
  37925. var uvs = [];
  37926. var width = options.width || options.size || 1;
  37927. var height = options.height || options.size || 1;
  37928. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37929. // Vertices
  37930. var halfWidth = width / 2.0;
  37931. var halfHeight = height / 2.0;
  37932. positions.push(-halfWidth, -halfHeight, 0);
  37933. normals.push(0, 0, -1.0);
  37934. uvs.push(0.0, 0.0);
  37935. positions.push(halfWidth, -halfHeight, 0);
  37936. normals.push(0, 0, -1.0);
  37937. uvs.push(1.0, 0.0);
  37938. positions.push(halfWidth, halfHeight, 0);
  37939. normals.push(0, 0, -1.0);
  37940. uvs.push(1.0, 1.0);
  37941. positions.push(-halfWidth, halfHeight, 0);
  37942. normals.push(0, 0, -1.0);
  37943. uvs.push(0.0, 1.0);
  37944. // Indices
  37945. indices.push(0);
  37946. indices.push(1);
  37947. indices.push(2);
  37948. indices.push(0);
  37949. indices.push(2);
  37950. indices.push(3);
  37951. // Sides
  37952. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  37953. // Result
  37954. var vertexData = new VertexData();
  37955. vertexData.indices = indices;
  37956. vertexData.positions = positions;
  37957. vertexData.normals = normals;
  37958. vertexData.uvs = uvs;
  37959. return vertexData;
  37960. };
  37961. /**
  37962. * Creates the VertexData of the Disc or regular Polygon.
  37963. */
  37964. VertexData.CreateDisc = function (options) {
  37965. var positions = [];
  37966. var indices = [];
  37967. var normals = [];
  37968. var uvs = [];
  37969. var radius = options.radius || 0.5;
  37970. var tessellation = options.tessellation || 64;
  37971. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  37972. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37973. // positions and uvs
  37974. positions.push(0, 0, 0); // disc center first
  37975. uvs.push(0.5, 0.5);
  37976. var theta = Math.PI * 2 * arc;
  37977. var step = theta / tessellation;
  37978. for (var a = 0; a < theta; a += step) {
  37979. var x = Math.cos(a);
  37980. var y = Math.sin(a);
  37981. var u = (x + 1) / 2;
  37982. var v = (1 - y) / 2;
  37983. positions.push(radius * x, radius * y, 0);
  37984. uvs.push(u, v);
  37985. }
  37986. if (arc === 1) {
  37987. positions.push(positions[3], positions[4], positions[5]); // close the circle
  37988. uvs.push(uvs[2], uvs[3]);
  37989. }
  37990. //indices
  37991. var vertexNb = positions.length / 3;
  37992. for (var i = 1; i < vertexNb - 1; i++) {
  37993. indices.push(i + 1, 0, i);
  37994. }
  37995. // result
  37996. VertexData.ComputeNormals(positions, indices, normals);
  37997. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  37998. var vertexData = new VertexData();
  37999. vertexData.indices = indices;
  38000. vertexData.positions = positions;
  38001. vertexData.normals = normals;
  38002. vertexData.uvs = uvs;
  38003. return vertexData;
  38004. };
  38005. /**
  38006. * Creates the VertexData of the IcoSphere.
  38007. */
  38008. VertexData.CreateIcoSphere = function (options) {
  38009. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38010. var radius = options.radius || 1;
  38011. var flat = (options.flat === undefined) ? true : options.flat;
  38012. var subdivisions = options.subdivisions || 4;
  38013. var radiusX = options.radiusX || radius;
  38014. var radiusY = options.radiusY || radius;
  38015. var radiusZ = options.radiusZ || radius;
  38016. var t = (1 + Math.sqrt(5)) / 2;
  38017. // 12 vertex x,y,z
  38018. var ico_vertices = [
  38019. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  38020. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  38021. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  38022. ];
  38023. // index of 3 vertex makes a face of icopshere
  38024. var ico_indices = [
  38025. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  38026. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  38027. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  38028. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  38029. ];
  38030. // vertex for uv have aliased position, not for UV
  38031. var vertices_unalias_id = [
  38032. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  38033. // vertex alias
  38034. 0,
  38035. 2,
  38036. 3,
  38037. 3,
  38038. 3,
  38039. 4,
  38040. 7,
  38041. 8,
  38042. 9,
  38043. 9,
  38044. 10,
  38045. 11 // 23: B + 12
  38046. ];
  38047. // uv as integer step (not pixels !)
  38048. var ico_vertexuv = [
  38049. 5, 1, 3, 1, 6, 4, 0, 0,
  38050. 5, 3, 4, 2, 2, 2, 4, 0,
  38051. 2, 0, 1, 1, 6, 0, 6, 2,
  38052. // vertex alias (for same vertex on different faces)
  38053. 0, 4,
  38054. 3, 3,
  38055. 4, 4,
  38056. 3, 1,
  38057. 4, 2,
  38058. 4, 4,
  38059. 0, 2,
  38060. 1, 1,
  38061. 2, 2,
  38062. 3, 3,
  38063. 1, 3,
  38064. 2, 4 // 23: B + 12
  38065. ];
  38066. // Vertices[0, 1, ...9, A, B] : position on UV plane
  38067. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  38068. // First island of uv mapping
  38069. // v = 4h 3+ 2
  38070. // v = 3h 9+ 4
  38071. // v = 2h 9+ 5 B
  38072. // v = 1h 9 1 0
  38073. // v = 0h 3 8 7 A
  38074. // u = 0 1 2 3 4 5 6 *a
  38075. // Second island of uv mapping
  38076. // v = 4h 0+ B+ 4+
  38077. // v = 3h A+ 2+
  38078. // v = 2h 7+ 6 3+
  38079. // v = 1h 8+ 3+
  38080. // v = 0h
  38081. // u = 0 1 2 3 4 5 6 *a
  38082. // Face layout on texture UV mapping
  38083. // ============
  38084. // \ 4 /\ 16 / ======
  38085. // \ / \ / /\ 11 /
  38086. // \/ 7 \/ / \ /
  38087. // ======= / 10 \/
  38088. // /\ 17 /\ =======
  38089. // / \ / \ \ 15 /\
  38090. // / 8 \/ 12 \ \ / \
  38091. // ============ \/ 6 \
  38092. // \ 18 /\ ============
  38093. // \ / \ \ 5 /\ 0 /
  38094. // \/ 13 \ \ / \ /
  38095. // ======= \/ 1 \/
  38096. // =============
  38097. // /\ 19 /\ 2 /\
  38098. // / \ / \ / \
  38099. // / 14 \/ 9 \/ 3 \
  38100. // ===================
  38101. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  38102. var ustep = 138 / 1024;
  38103. var vstep = 239 / 1024;
  38104. var uoffset = 60 / 1024;
  38105. var voffset = 26 / 1024;
  38106. // Second island should have margin, not to touch the first island
  38107. // avoid any borderline artefact in pixel rounding
  38108. var island_u_offset = -40 / 1024;
  38109. var island_v_offset = +20 / 1024;
  38110. // face is either island 0 or 1 :
  38111. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  38112. var island = [
  38113. 0, 0, 0, 0, 1,
  38114. 0, 0, 1, 1, 0,
  38115. 0, 0, 1, 1, 0,
  38116. 0, 1, 1, 1, 0 // 15 - 19
  38117. ];
  38118. var indices = [];
  38119. var positions = [];
  38120. var normals = [];
  38121. var uvs = [];
  38122. var current_indice = 0;
  38123. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  38124. var face_vertex_pos = new Array(3);
  38125. var face_vertex_uv = new Array(3);
  38126. var v012;
  38127. for (v012 = 0; v012 < 3; v012++) {
  38128. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  38129. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  38130. }
  38131. // create all with normals
  38132. for (var face = 0; face < 20; face++) {
  38133. // 3 vertex per face
  38134. for (v012 = 0; v012 < 3; v012++) {
  38135. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  38136. var v_id = ico_indices[3 * face + v012];
  38137. // vertex have 3D position (x,y,z)
  38138. 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]);
  38139. // Normalize to get normal, then scale to radius
  38140. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  38141. // uv Coordinates from vertex ID
  38142. 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);
  38143. }
  38144. // Subdivide the face (interpolate pos, norm, uv)
  38145. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  38146. // - norm is linear interpolation of vertex corner normal
  38147. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  38148. // - uv is linear interpolation
  38149. //
  38150. // Topology is as below for sub-divide by 2
  38151. // vertex shown as v0,v1,v2
  38152. // interp index is i1 to progress in range [v0,v1[
  38153. // interp index is i2 to progress in range [v0,v2[
  38154. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  38155. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  38156. //
  38157. //
  38158. // i2 v2
  38159. // ^ ^
  38160. // / / \
  38161. // / / \
  38162. // / / \
  38163. // / / (0,1) \
  38164. // / #---------\
  38165. // / / \ (0,0)'/ \
  38166. // / / \ / \
  38167. // / / \ / \
  38168. // / / (0,0) \ / (1,0) \
  38169. // / #---------#---------\
  38170. // v0 v1
  38171. //
  38172. // --------------------> i1
  38173. //
  38174. // interp of (i1,i2):
  38175. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  38176. // along i1 : lerp(x0,x1, i1/(S-i2))
  38177. //
  38178. // centroid of triangle is needed to get help normal computation
  38179. // (c1,c2) are used for centroid location
  38180. var interp_vertex = function (i1, i2, c1, c2) {
  38181. // vertex is interpolated from
  38182. // - face_vertex_pos[0..2]
  38183. // - face_vertex_uv[0..2]
  38184. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  38185. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  38186. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  38187. pos_interp.normalize();
  38188. var vertex_normal;
  38189. if (flat) {
  38190. // in flat mode, recalculate normal as face centroid normal
  38191. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  38192. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  38193. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  38194. }
  38195. else {
  38196. // in smooth mode, recalculate normal from each single vertex position
  38197. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  38198. }
  38199. // Vertex normal need correction due to X,Y,Z radius scaling
  38200. vertex_normal.x /= radiusX;
  38201. vertex_normal.y /= radiusY;
  38202. vertex_normal.z /= radiusZ;
  38203. vertex_normal.normalize();
  38204. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  38205. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  38206. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  38207. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  38208. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  38209. uvs.push(uv_interp.x, uv_interp.y);
  38210. // push each vertex has member of a face
  38211. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  38212. indices.push(current_indice);
  38213. current_indice++;
  38214. };
  38215. for (var i2 = 0; i2 < subdivisions; i2++) {
  38216. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  38217. // face : (i1,i2) for /\ :
  38218. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  38219. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  38220. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  38221. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  38222. if (i1 + i2 + 1 < subdivisions) {
  38223. // face : (i1,i2)' for \/ :
  38224. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  38225. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  38226. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  38227. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  38228. }
  38229. }
  38230. }
  38231. }
  38232. // Sides
  38233. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  38234. // Result
  38235. var vertexData = new VertexData();
  38236. vertexData.indices = indices;
  38237. vertexData.positions = positions;
  38238. vertexData.normals = normals;
  38239. vertexData.uvs = uvs;
  38240. return vertexData;
  38241. };
  38242. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  38243. /**
  38244. * Creates the VertexData of the Polyhedron.
  38245. */
  38246. VertexData.CreatePolyhedron = function (options) {
  38247. // provided polyhedron types :
  38248. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  38249. // 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)
  38250. var polyhedra = [];
  38251. 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]] };
  38252. 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]] };
  38253. polyhedra[2] = {
  38254. 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]],
  38255. 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]]
  38256. };
  38257. polyhedra[3] = {
  38258. 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]],
  38259. 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]]
  38260. };
  38261. polyhedra[4] = {
  38262. 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]],
  38263. 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]]
  38264. };
  38265. 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]] };
  38266. 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]] };
  38267. 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]] };
  38268. 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]] };
  38269. 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]] };
  38270. 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]] };
  38271. 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]] };
  38272. 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]] };
  38273. 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]] };
  38274. polyhedra[14] = {
  38275. 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]],
  38276. 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]]
  38277. };
  38278. var type = (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  38279. var size = options.size;
  38280. var sizeX = options.sizeX || size || 1;
  38281. var sizeY = options.sizeY || size || 1;
  38282. var sizeZ = options.sizeZ || size || 1;
  38283. var data = options.custom || polyhedra[type];
  38284. var nbfaces = data.face.length;
  38285. var faceUV = options.faceUV || new Array(nbfaces);
  38286. var faceColors = options.faceColors;
  38287. var flat = (options.flat === undefined) ? true : options.flat;
  38288. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38289. var positions = [];
  38290. var indices = [];
  38291. var normals = [];
  38292. var uvs = [];
  38293. var colors = [];
  38294. var index = 0;
  38295. var faceIdx = 0; // face cursor in the array "indexes"
  38296. var indexes = [];
  38297. var i = 0;
  38298. var f = 0;
  38299. var u, v, ang, x, y, tmp;
  38300. // default face colors and UV if undefined
  38301. if (flat) {
  38302. for (f = 0; f < nbfaces; f++) {
  38303. if (faceColors && faceColors[f] === undefined) {
  38304. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  38305. }
  38306. if (faceUV && faceUV[f] === undefined) {
  38307. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  38308. }
  38309. }
  38310. }
  38311. if (!flat) {
  38312. for (i = 0; i < data.vertex.length; i++) {
  38313. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  38314. uvs.push(0, 0);
  38315. }
  38316. for (f = 0; f < nbfaces; f++) {
  38317. for (i = 0; i < data.face[f].length - 2; i++) {
  38318. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  38319. }
  38320. }
  38321. }
  38322. else {
  38323. for (f = 0; f < nbfaces; f++) {
  38324. var fl = data.face[f].length; // number of vertices of the current face
  38325. ang = 2 * Math.PI / fl;
  38326. x = 0.5 * Math.tan(ang / 2);
  38327. y = 0.5;
  38328. // positions, uvs, colors
  38329. for (i = 0; i < fl; i++) {
  38330. // positions
  38331. 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);
  38332. indexes.push(index);
  38333. index++;
  38334. // uvs
  38335. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  38336. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  38337. uvs.push(u, v);
  38338. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  38339. y = x * Math.sin(ang) + y * Math.cos(ang);
  38340. x = tmp;
  38341. // colors
  38342. if (faceColors) {
  38343. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  38344. }
  38345. }
  38346. // indices from indexes
  38347. for (i = 0; i < fl - 2; i++) {
  38348. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  38349. }
  38350. faceIdx += fl;
  38351. }
  38352. }
  38353. VertexData.ComputeNormals(positions, indices, normals);
  38354. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  38355. var vertexData = new VertexData();
  38356. vertexData.positions = positions;
  38357. vertexData.indices = indices;
  38358. vertexData.normals = normals;
  38359. vertexData.uvs = uvs;
  38360. if (faceColors && flat) {
  38361. vertexData.colors = colors;
  38362. }
  38363. return vertexData;
  38364. };
  38365. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  38366. /**
  38367. * Creates the VertexData of the Torus Knot.
  38368. */
  38369. VertexData.CreateTorusKnot = function (options) {
  38370. var indices = [];
  38371. var positions = [];
  38372. var normals = [];
  38373. var uvs = [];
  38374. var radius = options.radius || 2;
  38375. var tube = options.tube || 0.5;
  38376. var radialSegments = options.radialSegments || 32;
  38377. var tubularSegments = options.tubularSegments || 32;
  38378. var p = options.p || 2;
  38379. var q = options.q || 3;
  38380. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38381. // Helper
  38382. var getPos = function (angle) {
  38383. var cu = Math.cos(angle);
  38384. var su = Math.sin(angle);
  38385. var quOverP = q / p * angle;
  38386. var cs = Math.cos(quOverP);
  38387. var tx = radius * (2 + cs) * 0.5 * cu;
  38388. var ty = radius * (2 + cs) * su * 0.5;
  38389. var tz = radius * Math.sin(quOverP) * 0.5;
  38390. return new BABYLON.Vector3(tx, ty, tz);
  38391. };
  38392. // Vertices
  38393. var i;
  38394. var j;
  38395. for (i = 0; i <= radialSegments; i++) {
  38396. var modI = i % radialSegments;
  38397. var u = modI / radialSegments * 2 * p * Math.PI;
  38398. var p1 = getPos(u);
  38399. var p2 = getPos(u + 0.01);
  38400. var tang = p2.subtract(p1);
  38401. var n = p2.add(p1);
  38402. var bitan = BABYLON.Vector3.Cross(tang, n);
  38403. n = BABYLON.Vector3.Cross(bitan, tang);
  38404. bitan.normalize();
  38405. n.normalize();
  38406. for (j = 0; j < tubularSegments; j++) {
  38407. var modJ = j % tubularSegments;
  38408. var v = modJ / tubularSegments * 2 * Math.PI;
  38409. var cx = -tube * Math.cos(v);
  38410. var cy = tube * Math.sin(v);
  38411. positions.push(p1.x + cx * n.x + cy * bitan.x);
  38412. positions.push(p1.y + cx * n.y + cy * bitan.y);
  38413. positions.push(p1.z + cx * n.z + cy * bitan.z);
  38414. uvs.push(i / radialSegments);
  38415. uvs.push(j / tubularSegments);
  38416. }
  38417. }
  38418. for (i = 0; i < radialSegments; i++) {
  38419. for (j = 0; j < tubularSegments; j++) {
  38420. var jNext = (j + 1) % tubularSegments;
  38421. var a = i * tubularSegments + j;
  38422. var b = (i + 1) * tubularSegments + j;
  38423. var c = (i + 1) * tubularSegments + jNext;
  38424. var d = i * tubularSegments + jNext;
  38425. indices.push(d);
  38426. indices.push(b);
  38427. indices.push(a);
  38428. indices.push(d);
  38429. indices.push(c);
  38430. indices.push(b);
  38431. }
  38432. }
  38433. // Normals
  38434. VertexData.ComputeNormals(positions, indices, normals);
  38435. // Sides
  38436. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  38437. // Result
  38438. var vertexData = new VertexData();
  38439. vertexData.indices = indices;
  38440. vertexData.positions = positions;
  38441. vertexData.normals = normals;
  38442. vertexData.uvs = uvs;
  38443. return vertexData;
  38444. };
  38445. // Tools
  38446. /**
  38447. * @param {any} - positions (number[] or Float32Array)
  38448. * @param {any} - indices (number[] or Uint16Array)
  38449. * @param {any} - normals (number[] or Float32Array)
  38450. * options (optional) :
  38451. * facetPositions : optional array of facet positions (vector3)
  38452. * facetNormals : optional array of facet normals (vector3)
  38453. * facetPartitioning : optional partitioning array. facetPositions is required for facetPartitioning computation
  38454. * subDiv : optional partitioning data about subdivsions on each axis (int), required for facetPartitioning computation
  38455. * ratio : optional partitioning ratio / bounding box, required for facetPartitioning computation
  38456. * bbSize : optional bounding box size data, required for facetPartitioning computation
  38457. * bInfo : optional bounding info, required for facetPartitioning computation
  38458. */
  38459. VertexData.ComputeNormals = function (positions, indices, normals, options) {
  38460. // temporary scalar variables
  38461. var index = 0; // facet index
  38462. var p1p2x = 0.0; // p1p2 vector x coordinate
  38463. var p1p2y = 0.0; // p1p2 vector y coordinate
  38464. var p1p2z = 0.0; // p1p2 vector z coordinate
  38465. var p3p2x = 0.0; // p3p2 vector x coordinate
  38466. var p3p2y = 0.0; // p3p2 vector y coordinate
  38467. var p3p2z = 0.0; // p3p2 vector z coordinate
  38468. var faceNormalx = 0.0; // facet normal x coordinate
  38469. var faceNormaly = 0.0; // facet normal y coordinate
  38470. var faceNormalz = 0.0; // facet normal z coordinate
  38471. var length = 0.0; // facet normal length before normalization
  38472. var v1x = 0; // vector1 x index in the positions array
  38473. var v1y = 0; // vector1 y index in the positions array
  38474. var v1z = 0; // vector1 z index in the positions array
  38475. var v2x = 0; // vector2 x index in the positions array
  38476. var v2y = 0; // vector2 y index in the positions array
  38477. var v2z = 0; // vector2 z index in the positions array
  38478. var v3x = 0; // vector3 x index in the positions array
  38479. var v3y = 0; // vector3 y index in the positions array
  38480. var v3z = 0; // vector3 z index in the positions array
  38481. var computeFacetNormals = false;
  38482. var computeFacetPositions = false;
  38483. var computeFacetPartitioning = false;
  38484. if (options) {
  38485. computeFacetNormals = (options.facetNormals) ? true : false;
  38486. computeFacetPositions = (options.facetPositions) ? true : false;
  38487. computeFacetPartitioning = (options.facetPartitioning) ? true : false;
  38488. }
  38489. // facetPartitioning reinit if needed
  38490. if (computeFacetPartitioning) {
  38491. var ox = 0; // X partitioning index for facet position
  38492. var oy = 0; // Y partinioning index for facet position
  38493. var oz = 0; // Z partinioning index for facet position
  38494. var b1x = 0; // X partitioning index for facet v1 vertex
  38495. var b1y = 0; // Y partitioning index for facet v1 vertex
  38496. var b1z = 0; // z partitioning index for facet v1 vertex
  38497. var b2x = 0; // X partitioning index for facet v2 vertex
  38498. var b2y = 0; // Y partitioning index for facet v2 vertex
  38499. var b2z = 0; // Z partitioning index for facet v2 vertex
  38500. var b3x = 0; // X partitioning index for facet v3 vertex
  38501. var b3y = 0; // Y partitioning index for facet v3 vertex
  38502. var b3z = 0; // Z partitioning index for facet v3 vertex
  38503. var block_idx_o = 0; // facet barycenter block index
  38504. var block_idx_v1 = 0; // v1 vertex block index
  38505. var block_idx_v2 = 0; // v2 vertex block index
  38506. var block_idx_v3 = 0; // v3 vertex block index
  38507. var bbSizeMax = (options.bbSize.x > options.bbSize.y) ? options.bbSize.x : options.bbSize.y;
  38508. bbSizeMax = (bbSizeMax > options.bbSize.z) ? bbSizeMax : options.bbSize.z;
  38509. var xSubRatio = options.subDiv.X * options.ratio / options.bbSize.x;
  38510. var ySubRatio = options.subDiv.Y * options.ratio / options.bbSize.y;
  38511. var zSubRatio = options.subDiv.Z * options.ratio / options.bbSize.z;
  38512. var subSq = options.subDiv.max * options.subDiv.max;
  38513. options.facetPartitioning.length = 0;
  38514. }
  38515. // reset the normals
  38516. for (index = 0; index < positions.length; index++) {
  38517. normals[index] = 0.0;
  38518. }
  38519. // Loop : 1 indice triplet = 1 facet
  38520. var nbFaces = indices.length / 3;
  38521. for (index = 0; index < nbFaces; index++) {
  38522. // get the indexes of the coordinates of each vertex of the facet
  38523. v1x = indices[index * 3] * 3;
  38524. v1y = v1x + 1;
  38525. v1z = v1x + 2;
  38526. v2x = indices[index * 3 + 1] * 3;
  38527. v2y = v2x + 1;
  38528. v2z = v2x + 2;
  38529. v3x = indices[index * 3 + 2] * 3;
  38530. v3y = v3x + 1;
  38531. v3z = v3x + 2;
  38532. p1p2x = positions[v1x] - positions[v2x]; // compute two vectors per facet : p1p2 and p3p2
  38533. p1p2y = positions[v1y] - positions[v2y];
  38534. p1p2z = positions[v1z] - positions[v2z];
  38535. p3p2x = positions[v3x] - positions[v2x];
  38536. p3p2y = positions[v3y] - positions[v2y];
  38537. p3p2z = positions[v3z] - positions[v2z];
  38538. // compute the face normal with the cross product
  38539. faceNormalx = p1p2y * p3p2z - p1p2z * p3p2y;
  38540. faceNormaly = p1p2z * p3p2x - p1p2x * p3p2z;
  38541. faceNormalz = p1p2x * p3p2y - p1p2y * p3p2x;
  38542. // normalize this normal and store it in the array facetData
  38543. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  38544. length = (length === 0) ? 1.0 : length;
  38545. faceNormalx /= length;
  38546. faceNormaly /= length;
  38547. faceNormalz /= length;
  38548. if (computeFacetNormals) {
  38549. options.facetNormals[index].x = faceNormalx;
  38550. options.facetNormals[index].y = faceNormaly;
  38551. options.facetNormals[index].z = faceNormalz;
  38552. }
  38553. if (computeFacetPositions) {
  38554. // compute and the facet barycenter coordinates in the array facetPositions
  38555. options.facetPositions[index].x = (positions[v1x] + positions[v2x] + positions[v3x]) / 3.0;
  38556. options.facetPositions[index].y = (positions[v1y] + positions[v2y] + positions[v3y]) / 3.0;
  38557. options.facetPositions[index].z = (positions[v1z] + positions[v2z] + positions[v3z]) / 3.0;
  38558. }
  38559. if (computeFacetPartitioning) {
  38560. // store the facet indexes in arrays in the main facetPartitioning array :
  38561. // compute each facet vertex (+ facet barycenter) index in the partiniong array
  38562. ox = Math.floor((options.facetPositions[index].x - options.bInfo.minimum.x * options.ratio) * xSubRatio);
  38563. oy = Math.floor((options.facetPositions[index].y - options.bInfo.minimum.y * options.ratio) * ySubRatio);
  38564. oz = Math.floor((options.facetPositions[index].z - options.bInfo.minimum.z * options.ratio) * zSubRatio);
  38565. b1x = Math.floor((positions[v1x] - options.bInfo.minimum.x * options.ratio) * xSubRatio);
  38566. b1y = Math.floor((positions[v1y] - options.bInfo.minimum.y * options.ratio) * ySubRatio);
  38567. b1z = Math.floor((positions[v1z] - options.bInfo.minimum.z * options.ratio) * zSubRatio);
  38568. b2x = Math.floor((positions[v2x] - options.bInfo.minimum.x * options.ratio) * xSubRatio);
  38569. b2y = Math.floor((positions[v2y] - options.bInfo.minimum.y * options.ratio) * ySubRatio);
  38570. b2z = Math.floor((positions[v2z] - options.bInfo.minimum.z * options.ratio) * zSubRatio);
  38571. b3x = Math.floor((positions[v3x] - options.bInfo.minimum.x * options.ratio) * xSubRatio);
  38572. b3y = Math.floor((positions[v3y] - options.bInfo.minimum.y * options.ratio) * ySubRatio);
  38573. b3z = Math.floor((positions[v3z] - options.bInfo.minimum.z * options.ratio) * zSubRatio);
  38574. block_idx_v1 = b1x + options.subDiv.max * b1y + subSq * b1z;
  38575. block_idx_v2 = b2x + options.subDiv.max * b2y + subSq * b2z;
  38576. block_idx_v3 = b3x + options.subDiv.max * b3y + subSq * b3z;
  38577. block_idx_o = ox + options.subDiv.max * oy + subSq * oz;
  38578. options.facetPartitioning[block_idx_o] = options.facetPartitioning[block_idx_o] ? options.facetPartitioning[block_idx_o] : new Array();
  38579. options.facetPartitioning[block_idx_v1] = options.facetPartitioning[block_idx_v1] ? options.facetPartitioning[block_idx_v1] : new Array();
  38580. options.facetPartitioning[block_idx_v2] = options.facetPartitioning[block_idx_v2] ? options.facetPartitioning[block_idx_v2] : new Array();
  38581. options.facetPartitioning[block_idx_v3] = options.facetPartitioning[block_idx_v3] ? options.facetPartitioning[block_idx_v3] : new Array();
  38582. // push each facet index in each block containing the vertex
  38583. options.facetPartitioning[block_idx_v1].push(index);
  38584. if (block_idx_v2 != block_idx_v1) {
  38585. options.facetPartitioning[block_idx_v2].push(index);
  38586. }
  38587. if (!(block_idx_v3 == block_idx_v2 || block_idx_v3 == block_idx_v1)) {
  38588. options.facetPartitioning[block_idx_v3].push(index);
  38589. }
  38590. if (!(block_idx_o == block_idx_v1 || block_idx_o == block_idx_v2 || block_idx_o == block_idx_v3)) {
  38591. options.facetPartitioning[block_idx_o].push(index);
  38592. }
  38593. }
  38594. // compute the normals anyway
  38595. normals[v1x] += faceNormalx; // accumulate all the normals per face
  38596. normals[v1y] += faceNormaly;
  38597. normals[v1z] += faceNormalz;
  38598. normals[v2x] += faceNormalx;
  38599. normals[v2y] += faceNormaly;
  38600. normals[v2z] += faceNormalz;
  38601. normals[v3x] += faceNormalx;
  38602. normals[v3y] += faceNormaly;
  38603. normals[v3z] += faceNormalz;
  38604. }
  38605. // last normalization of each normal
  38606. for (index = 0; index < normals.length / 3; index++) {
  38607. faceNormalx = normals[index * 3];
  38608. faceNormaly = normals[index * 3 + 1];
  38609. faceNormalz = normals[index * 3 + 2];
  38610. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  38611. length = (length === 0) ? 1.0 : length;
  38612. faceNormalx /= length;
  38613. faceNormaly /= length;
  38614. faceNormalz /= length;
  38615. normals[index * 3] = faceNormalx;
  38616. normals[index * 3 + 1] = faceNormaly;
  38617. normals[index * 3 + 2] = faceNormalz;
  38618. }
  38619. };
  38620. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs) {
  38621. var li = indices.length;
  38622. var ln = normals.length;
  38623. var i;
  38624. var n;
  38625. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38626. switch (sideOrientation) {
  38627. case BABYLON.Mesh.FRONTSIDE:
  38628. // nothing changed
  38629. break;
  38630. case BABYLON.Mesh.BACKSIDE:
  38631. var tmp;
  38632. // indices
  38633. for (i = 0; i < li; i += 3) {
  38634. tmp = indices[i];
  38635. indices[i] = indices[i + 2];
  38636. indices[i + 2] = tmp;
  38637. }
  38638. // normals
  38639. for (n = 0; n < ln; n++) {
  38640. normals[n] = -normals[n];
  38641. }
  38642. break;
  38643. case BABYLON.Mesh.DOUBLESIDE:
  38644. // positions
  38645. var lp = positions.length;
  38646. var l = lp / 3;
  38647. for (var p = 0; p < lp; p++) {
  38648. positions[lp + p] = positions[p];
  38649. }
  38650. // indices
  38651. for (i = 0; i < li; i += 3) {
  38652. indices[i + li] = indices[i + 2] + l;
  38653. indices[i + 1 + li] = indices[i + 1] + l;
  38654. indices[i + 2 + li] = indices[i] + l;
  38655. }
  38656. // normals
  38657. for (n = 0; n < ln; n++) {
  38658. normals[ln + n] = -normals[n];
  38659. }
  38660. // uvs
  38661. var lu = uvs.length;
  38662. for (var u = 0; u < lu; u++) {
  38663. uvs[u + lu] = uvs[u];
  38664. }
  38665. break;
  38666. }
  38667. };
  38668. /**
  38669. * Creates a new VertexData from the imported parameters.
  38670. */
  38671. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  38672. var vertexData = new VertexData();
  38673. // positions
  38674. var positions = parsedVertexData.positions;
  38675. if (positions) {
  38676. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  38677. }
  38678. // normals
  38679. var normals = parsedVertexData.normals;
  38680. if (normals) {
  38681. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  38682. }
  38683. // tangents
  38684. var tangents = parsedVertexData.tangents;
  38685. if (tangents) {
  38686. vertexData.set(tangents, BABYLON.VertexBuffer.TangentKind);
  38687. }
  38688. // uvs
  38689. var uvs = parsedVertexData.uvs;
  38690. if (uvs) {
  38691. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  38692. }
  38693. // uv2s
  38694. var uv2s = parsedVertexData.uv2s;
  38695. if (uv2s) {
  38696. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  38697. }
  38698. // uv3s
  38699. var uv3s = parsedVertexData.uv3s;
  38700. if (uv3s) {
  38701. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  38702. }
  38703. // uv4s
  38704. var uv4s = parsedVertexData.uv4s;
  38705. if (uv4s) {
  38706. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  38707. }
  38708. // uv5s
  38709. var uv5s = parsedVertexData.uv5s;
  38710. if (uv5s) {
  38711. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  38712. }
  38713. // uv6s
  38714. var uv6s = parsedVertexData.uv6s;
  38715. if (uv6s) {
  38716. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  38717. }
  38718. // colors
  38719. var colors = parsedVertexData.colors;
  38720. if (colors) {
  38721. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  38722. }
  38723. // matricesIndices
  38724. var matricesIndices = parsedVertexData.matricesIndices;
  38725. if (matricesIndices) {
  38726. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  38727. }
  38728. // matricesWeights
  38729. var matricesWeights = parsedVertexData.matricesWeights;
  38730. if (matricesWeights) {
  38731. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  38732. }
  38733. // indices
  38734. var indices = parsedVertexData.indices;
  38735. if (indices) {
  38736. vertexData.indices = indices;
  38737. }
  38738. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  38739. };
  38740. return VertexData;
  38741. }());
  38742. BABYLON.VertexData = VertexData;
  38743. })(BABYLON || (BABYLON = {}));
  38744. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  38745. var BABYLON;
  38746. (function (BABYLON) {
  38747. var Tags = (function () {
  38748. function Tags() {
  38749. }
  38750. Tags.EnableFor = function (obj) {
  38751. obj._tags = obj._tags || {};
  38752. obj.hasTags = function () {
  38753. return Tags.HasTags(obj);
  38754. };
  38755. obj.addTags = function (tagsString) {
  38756. return Tags.AddTagsTo(obj, tagsString);
  38757. };
  38758. obj.removeTags = function (tagsString) {
  38759. return Tags.RemoveTagsFrom(obj, tagsString);
  38760. };
  38761. obj.matchesTagsQuery = function (tagsQuery) {
  38762. return Tags.MatchesQuery(obj, tagsQuery);
  38763. };
  38764. };
  38765. Tags.DisableFor = function (obj) {
  38766. delete obj._tags;
  38767. delete obj.hasTags;
  38768. delete obj.addTags;
  38769. delete obj.removeTags;
  38770. delete obj.matchesTagsQuery;
  38771. };
  38772. Tags.HasTags = function (obj) {
  38773. if (!obj._tags) {
  38774. return false;
  38775. }
  38776. return !BABYLON.Tools.IsEmpty(obj._tags);
  38777. };
  38778. Tags.GetTags = function (obj, asString) {
  38779. if (asString === void 0) { asString = true; }
  38780. if (!obj._tags) {
  38781. return null;
  38782. }
  38783. if (asString) {
  38784. var tagsArray = [];
  38785. for (var tag in obj._tags) {
  38786. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  38787. tagsArray.push(tag);
  38788. }
  38789. }
  38790. return tagsArray.join(" ");
  38791. }
  38792. else {
  38793. return obj._tags;
  38794. }
  38795. };
  38796. // the tags 'true' and 'false' are reserved and cannot be used as tags
  38797. // a tag cannot start with '||', '&&', and '!'
  38798. // it cannot contain whitespaces
  38799. Tags.AddTagsTo = function (obj, tagsString) {
  38800. if (!tagsString) {
  38801. return;
  38802. }
  38803. if (typeof tagsString !== "string") {
  38804. return;
  38805. }
  38806. var tags = tagsString.split(" ");
  38807. tags.forEach(function (tag, index, array) {
  38808. Tags._AddTagTo(obj, tag);
  38809. });
  38810. };
  38811. Tags._AddTagTo = function (obj, tag) {
  38812. tag = tag.trim();
  38813. if (tag === "" || tag === "true" || tag === "false") {
  38814. return;
  38815. }
  38816. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  38817. return;
  38818. }
  38819. Tags.EnableFor(obj);
  38820. obj._tags[tag] = true;
  38821. };
  38822. Tags.RemoveTagsFrom = function (obj, tagsString) {
  38823. if (!Tags.HasTags(obj)) {
  38824. return;
  38825. }
  38826. var tags = tagsString.split(" ");
  38827. for (var t in tags) {
  38828. Tags._RemoveTagFrom(obj, tags[t]);
  38829. }
  38830. };
  38831. Tags._RemoveTagFrom = function (obj, tag) {
  38832. delete obj._tags[tag];
  38833. };
  38834. Tags.MatchesQuery = function (obj, tagsQuery) {
  38835. if (tagsQuery === undefined) {
  38836. return true;
  38837. }
  38838. if (tagsQuery === "") {
  38839. return Tags.HasTags(obj);
  38840. }
  38841. return BABYLON.Internals.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  38842. };
  38843. return Tags;
  38844. }());
  38845. BABYLON.Tags = Tags;
  38846. })(BABYLON || (BABYLON = {}));
  38847. //# sourceMappingURL=babylon.tags.js.map
  38848. var BABYLON;
  38849. (function (BABYLON) {
  38850. var Internals;
  38851. (function (Internals) {
  38852. var AndOrNotEvaluator = (function () {
  38853. function AndOrNotEvaluator() {
  38854. }
  38855. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  38856. if (!query.match(/\([^\(\)]*\)/g)) {
  38857. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  38858. }
  38859. else {
  38860. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  38861. // remove parenthesis
  38862. r = r.slice(1, r.length - 1);
  38863. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  38864. });
  38865. }
  38866. if (query === "true") {
  38867. return true;
  38868. }
  38869. if (query === "false") {
  38870. return false;
  38871. }
  38872. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  38873. };
  38874. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  38875. evaluateCallback = evaluateCallback || (function (r) {
  38876. return r === "true" ? true : false;
  38877. });
  38878. var result;
  38879. var or = parenthesisContent.split("||");
  38880. for (var i in or) {
  38881. if (or.hasOwnProperty(i)) {
  38882. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  38883. var and = ori.split("&&");
  38884. if (and.length > 1) {
  38885. for (var j = 0; j < and.length; ++j) {
  38886. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  38887. if (andj !== "true" && andj !== "false") {
  38888. if (andj[0] === "!") {
  38889. result = !evaluateCallback(andj.substring(1));
  38890. }
  38891. else {
  38892. result = evaluateCallback(andj);
  38893. }
  38894. }
  38895. else {
  38896. result = andj === "true" ? true : false;
  38897. }
  38898. if (!result) {
  38899. ori = "false";
  38900. break;
  38901. }
  38902. }
  38903. }
  38904. if (result || ori === "true") {
  38905. result = true;
  38906. break;
  38907. }
  38908. // result equals false (or undefined)
  38909. if (ori !== "true" && ori !== "false") {
  38910. if (ori[0] === "!") {
  38911. result = !evaluateCallback(ori.substring(1));
  38912. }
  38913. else {
  38914. result = evaluateCallback(ori);
  38915. }
  38916. }
  38917. else {
  38918. result = ori === "true" ? true : false;
  38919. }
  38920. }
  38921. }
  38922. // the whole parenthesis scope is replaced by 'true' or 'false'
  38923. return result ? "true" : "false";
  38924. };
  38925. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  38926. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  38927. // remove whitespaces
  38928. r = r.replace(/[\s]/g, function () { return ""; });
  38929. return r.length % 2 ? "!" : "";
  38930. });
  38931. booleanString = booleanString.trim();
  38932. if (booleanString === "!true") {
  38933. booleanString = "false";
  38934. }
  38935. else if (booleanString === "!false") {
  38936. booleanString = "true";
  38937. }
  38938. return booleanString;
  38939. };
  38940. return AndOrNotEvaluator;
  38941. }());
  38942. Internals.AndOrNotEvaluator = AndOrNotEvaluator;
  38943. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  38944. })(BABYLON || (BABYLON = {}));
  38945. //# sourceMappingURL=babylon.andOrNotEvaluator.js.map
  38946. var BABYLON;
  38947. (function (BABYLON) {
  38948. var PostProcessRenderPass = (function () {
  38949. function PostProcessRenderPass(scene, name, size, renderList, beforeRender, afterRender) {
  38950. this._enabled = true;
  38951. this._refCount = 0;
  38952. this._name = name;
  38953. this._renderTexture = new BABYLON.RenderTargetTexture(name, size, scene);
  38954. this.setRenderList(renderList);
  38955. this._renderTexture.onBeforeRenderObservable.add(beforeRender);
  38956. this._renderTexture.onAfterRenderObservable.add(afterRender);
  38957. this._scene = scene;
  38958. this._renderList = renderList;
  38959. }
  38960. // private
  38961. PostProcessRenderPass.prototype._incRefCount = function () {
  38962. if (this._refCount === 0) {
  38963. this._scene.customRenderTargets.push(this._renderTexture);
  38964. }
  38965. return ++this._refCount;
  38966. };
  38967. PostProcessRenderPass.prototype._decRefCount = function () {
  38968. this._refCount--;
  38969. if (this._refCount <= 0) {
  38970. this._scene.customRenderTargets.splice(this._scene.customRenderTargets.indexOf(this._renderTexture), 1);
  38971. }
  38972. return this._refCount;
  38973. };
  38974. PostProcessRenderPass.prototype._update = function () {
  38975. this.setRenderList(this._renderList);
  38976. };
  38977. // public
  38978. PostProcessRenderPass.prototype.setRenderList = function (renderList) {
  38979. this._renderTexture.renderList = renderList;
  38980. };
  38981. PostProcessRenderPass.prototype.getRenderTexture = function () {
  38982. return this._renderTexture;
  38983. };
  38984. return PostProcessRenderPass;
  38985. }());
  38986. BABYLON.PostProcessRenderPass = PostProcessRenderPass;
  38987. })(BABYLON || (BABYLON = {}));
  38988. //# sourceMappingURL=babylon.postProcessRenderPass.js.map
  38989. var BABYLON;
  38990. (function (BABYLON) {
  38991. var PostProcessRenderEffect = (function () {
  38992. function PostProcessRenderEffect(engine, name, getPostProcess, singleInstance) {
  38993. this._engine = engine;
  38994. this._name = name;
  38995. this._singleInstance = singleInstance || true;
  38996. this._getPostProcess = getPostProcess;
  38997. this._cameras = [];
  38998. this._indicesForCamera = [];
  38999. this._postProcesses = {};
  39000. this._renderPasses = {};
  39001. this._renderEffectAsPasses = {};
  39002. }
  39003. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  39004. get: function () {
  39005. for (var index in this._postProcesses) {
  39006. if (!this._postProcesses[index].isSupported) {
  39007. return false;
  39008. }
  39009. }
  39010. return true;
  39011. },
  39012. enumerable: true,
  39013. configurable: true
  39014. });
  39015. PostProcessRenderEffect.prototype._update = function () {
  39016. for (var renderPassName in this._renderPasses) {
  39017. this._renderPasses[renderPassName]._update();
  39018. }
  39019. };
  39020. PostProcessRenderEffect.prototype.addPass = function (renderPass) {
  39021. this._renderPasses[renderPass._name] = renderPass;
  39022. this._linkParameters();
  39023. };
  39024. PostProcessRenderEffect.prototype.removePass = function (renderPass) {
  39025. delete this._renderPasses[renderPass._name];
  39026. this._linkParameters();
  39027. };
  39028. PostProcessRenderEffect.prototype.addRenderEffectAsPass = function (renderEffect) {
  39029. this._renderEffectAsPasses[renderEffect._name] = renderEffect;
  39030. this._linkParameters();
  39031. };
  39032. PostProcessRenderEffect.prototype.getPass = function (passName) {
  39033. for (var renderPassName in this._renderPasses) {
  39034. if (renderPassName === passName) {
  39035. return this._renderPasses[passName];
  39036. }
  39037. }
  39038. };
  39039. PostProcessRenderEffect.prototype.emptyPasses = function () {
  39040. this._renderPasses = {};
  39041. this._linkParameters();
  39042. };
  39043. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  39044. var cameraKey;
  39045. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  39046. for (var i = 0; i < _cam.length; i++) {
  39047. var camera = _cam[i];
  39048. var cameraName = camera.name;
  39049. if (this._singleInstance) {
  39050. cameraKey = 0;
  39051. }
  39052. else {
  39053. cameraKey = cameraName;
  39054. }
  39055. this._postProcesses[cameraKey] = this._postProcesses[cameraKey] || this._getPostProcess();
  39056. var index = camera.attachPostProcess(this._postProcesses[cameraKey]);
  39057. if (!this._indicesForCamera[cameraName]) {
  39058. this._indicesForCamera[cameraName] = [];
  39059. }
  39060. this._indicesForCamera[cameraName].push(index);
  39061. if (this._cameras.indexOf(camera) === -1) {
  39062. this._cameras[cameraName] = camera;
  39063. }
  39064. for (var passName in this._renderPasses) {
  39065. this._renderPasses[passName]._incRefCount();
  39066. }
  39067. }
  39068. this._linkParameters();
  39069. };
  39070. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  39071. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  39072. for (var i = 0; i < _cam.length; i++) {
  39073. var camera = _cam[i];
  39074. var cameraName = camera.name;
  39075. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  39076. var index = this._cameras.indexOf(cameraName);
  39077. this._indicesForCamera.splice(index, 1);
  39078. this._cameras.splice(index, 1);
  39079. for (var passName in this._renderPasses) {
  39080. this._renderPasses[passName]._decRefCount();
  39081. }
  39082. }
  39083. };
  39084. PostProcessRenderEffect.prototype._enable = function (cameras) {
  39085. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  39086. for (var i = 0; i < _cam.length; i++) {
  39087. var camera = _cam[i];
  39088. var cameraName = camera.name;
  39089. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  39090. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
  39091. cameras[i].attachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName][j]);
  39092. }
  39093. }
  39094. for (var passName in this._renderPasses) {
  39095. this._renderPasses[passName]._incRefCount();
  39096. }
  39097. }
  39098. };
  39099. PostProcessRenderEffect.prototype._disable = function (cameras) {
  39100. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  39101. for (var i = 0; i < _cam.length; i++) {
  39102. var camera = _cam[i];
  39103. var cameraName = camera.Name;
  39104. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  39105. for (var passName in this._renderPasses) {
  39106. this._renderPasses[passName]._decRefCount();
  39107. }
  39108. }
  39109. };
  39110. PostProcessRenderEffect.prototype.getPostProcess = function (camera) {
  39111. if (this._singleInstance) {
  39112. return this._postProcesses[0];
  39113. }
  39114. else {
  39115. return this._postProcesses[camera.name];
  39116. }
  39117. };
  39118. PostProcessRenderEffect.prototype._linkParameters = function () {
  39119. var _this = this;
  39120. for (var index in this._postProcesses) {
  39121. if (this.applyParameters) {
  39122. this.applyParameters(this._postProcesses[index]);
  39123. }
  39124. this._postProcesses[index].onBeforeRenderObservable.add(function (effect) {
  39125. _this._linkTextures(effect);
  39126. });
  39127. }
  39128. };
  39129. PostProcessRenderEffect.prototype._linkTextures = function (effect) {
  39130. for (var renderPassName in this._renderPasses) {
  39131. effect.setTexture(renderPassName, this._renderPasses[renderPassName].getRenderTexture());
  39132. }
  39133. for (var renderEffectName in this._renderEffectAsPasses) {
  39134. effect.setTextureFromPostProcess(renderEffectName + "Sampler", this._renderEffectAsPasses[renderEffectName].getPostProcess());
  39135. }
  39136. };
  39137. return PostProcessRenderEffect;
  39138. }());
  39139. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  39140. })(BABYLON || (BABYLON = {}));
  39141. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  39142. var BABYLON;
  39143. (function (BABYLON) {
  39144. var PostProcessRenderPipeline = (function () {
  39145. function PostProcessRenderPipeline(engine, name) {
  39146. this._engine = engine;
  39147. this._name = name;
  39148. this._renderEffects = {};
  39149. this._renderEffectsForIsolatedPass = {};
  39150. this._cameras = [];
  39151. }
  39152. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  39153. get: function () {
  39154. for (var renderEffectName in this._renderEffects) {
  39155. if (!this._renderEffects[renderEffectName].isSupported) {
  39156. return false;
  39157. }
  39158. }
  39159. return true;
  39160. },
  39161. enumerable: true,
  39162. configurable: true
  39163. });
  39164. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  39165. this._renderEffects[renderEffect._name] = renderEffect;
  39166. };
  39167. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  39168. var renderEffects = this._renderEffects[renderEffectName];
  39169. if (!renderEffects) {
  39170. return;
  39171. }
  39172. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  39173. };
  39174. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  39175. var renderEffects = this._renderEffects[renderEffectName];
  39176. if (!renderEffects) {
  39177. return;
  39178. }
  39179. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  39180. };
  39181. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  39182. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  39183. var indicesToDelete = [];
  39184. var i;
  39185. for (i = 0; i < _cam.length; i++) {
  39186. var camera = _cam[i];
  39187. var cameraName = camera.name;
  39188. if (this._cameras.indexOf(camera) === -1) {
  39189. this._cameras[cameraName] = camera;
  39190. }
  39191. else if (unique) {
  39192. indicesToDelete.push(i);
  39193. }
  39194. }
  39195. for (i = 0; i < indicesToDelete.length; i++) {
  39196. cameras.splice(indicesToDelete[i], 1);
  39197. }
  39198. for (var renderEffectName in this._renderEffects) {
  39199. this._renderEffects[renderEffectName]._attachCameras(_cam);
  39200. }
  39201. };
  39202. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  39203. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  39204. for (var renderEffectName in this._renderEffects) {
  39205. this._renderEffects[renderEffectName]._detachCameras(_cam);
  39206. }
  39207. for (var i = 0; i < _cam.length; i++) {
  39208. this._cameras.splice(this._cameras.indexOf(_cam[i]), 1);
  39209. }
  39210. };
  39211. PostProcessRenderPipeline.prototype._enableDisplayOnlyPass = function (passName, cameras) {
  39212. var _this = this;
  39213. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  39214. var pass = null;
  39215. var renderEffectName;
  39216. for (renderEffectName in this._renderEffects) {
  39217. pass = this._renderEffects[renderEffectName].getPass(passName);
  39218. if (pass != null) {
  39219. break;
  39220. }
  39221. }
  39222. if (pass === null) {
  39223. return;
  39224. }
  39225. for (renderEffectName in this._renderEffects) {
  39226. this._renderEffects[renderEffectName]._disable(_cam);
  39227. }
  39228. pass._name = PostProcessRenderPipeline.PASS_SAMPLER_NAME;
  39229. for (var i = 0; i < _cam.length; i++) {
  39230. var camera = _cam[i];
  39231. var cameraName = camera.name;
  39232. 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); });
  39233. this._renderEffectsForIsolatedPass[cameraName].emptyPasses();
  39234. this._renderEffectsForIsolatedPass[cameraName].addPass(pass);
  39235. this._renderEffectsForIsolatedPass[cameraName]._attachCameras(camera);
  39236. }
  39237. };
  39238. PostProcessRenderPipeline.prototype._disableDisplayOnlyPass = function (cameras) {
  39239. var _this = this;
  39240. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  39241. for (var i = 0; i < _cam.length; i++) {
  39242. var camera = _cam[i];
  39243. var cameraName = camera.name;
  39244. 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); });
  39245. this._renderEffectsForIsolatedPass[cameraName]._disable(camera);
  39246. }
  39247. for (var renderEffectName in this._renderEffects) {
  39248. this._renderEffects[renderEffectName]._enable(_cam);
  39249. }
  39250. };
  39251. PostProcessRenderPipeline.prototype._update = function () {
  39252. for (var renderEffectName in this._renderEffects) {
  39253. this._renderEffects[renderEffectName]._update();
  39254. }
  39255. for (var i = 0; i < this._cameras.length; i++) {
  39256. var cameraName = this._cameras[i].name;
  39257. if (this._renderEffectsForIsolatedPass[cameraName]) {
  39258. this._renderEffectsForIsolatedPass[cameraName]._update();
  39259. }
  39260. }
  39261. };
  39262. PostProcessRenderPipeline.prototype.dispose = function () {
  39263. // Must be implemented by children
  39264. };
  39265. return PostProcessRenderPipeline;
  39266. }());
  39267. PostProcessRenderPipeline.PASS_EFFECT_NAME = "passEffect";
  39268. PostProcessRenderPipeline.PASS_SAMPLER_NAME = "passSampler";
  39269. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  39270. })(BABYLON || (BABYLON = {}));
  39271. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  39272. var BABYLON;
  39273. (function (BABYLON) {
  39274. var PostProcessRenderPipelineManager = (function () {
  39275. function PostProcessRenderPipelineManager() {
  39276. this._renderPipelines = {};
  39277. }
  39278. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  39279. this._renderPipelines[renderPipeline._name] = renderPipeline;
  39280. };
  39281. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  39282. var renderPipeline = this._renderPipelines[renderPipelineName];
  39283. if (!renderPipeline) {
  39284. return;
  39285. }
  39286. renderPipeline._attachCameras(cameras, unique);
  39287. };
  39288. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  39289. var renderPipeline = this._renderPipelines[renderPipelineName];
  39290. if (!renderPipeline) {
  39291. return;
  39292. }
  39293. renderPipeline._detachCameras(cameras);
  39294. };
  39295. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  39296. var renderPipeline = this._renderPipelines[renderPipelineName];
  39297. if (!renderPipeline) {
  39298. return;
  39299. }
  39300. renderPipeline._enableEffect(renderEffectName, cameras);
  39301. };
  39302. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  39303. var renderPipeline = this._renderPipelines[renderPipelineName];
  39304. if (!renderPipeline) {
  39305. return;
  39306. }
  39307. renderPipeline._disableEffect(renderEffectName, cameras);
  39308. };
  39309. PostProcessRenderPipelineManager.prototype.enableDisplayOnlyPassInPipeline = function (renderPipelineName, passName, cameras) {
  39310. var renderPipeline = this._renderPipelines[renderPipelineName];
  39311. if (!renderPipeline) {
  39312. return;
  39313. }
  39314. renderPipeline._enableDisplayOnlyPass(passName, cameras);
  39315. };
  39316. PostProcessRenderPipelineManager.prototype.disableDisplayOnlyPassInPipeline = function (renderPipelineName, cameras) {
  39317. var renderPipeline = this._renderPipelines[renderPipelineName];
  39318. if (!renderPipeline) {
  39319. return;
  39320. }
  39321. renderPipeline._disableDisplayOnlyPass(cameras);
  39322. };
  39323. PostProcessRenderPipelineManager.prototype.update = function () {
  39324. for (var renderPipelineName in this._renderPipelines) {
  39325. var pipeline = this._renderPipelines[renderPipelineName];
  39326. if (!pipeline.isSupported) {
  39327. pipeline.dispose();
  39328. delete this._renderPipelines[renderPipelineName];
  39329. }
  39330. else {
  39331. pipeline._update();
  39332. }
  39333. }
  39334. };
  39335. return PostProcessRenderPipelineManager;
  39336. }());
  39337. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  39338. })(BABYLON || (BABYLON = {}));
  39339. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  39340. var BABYLON;
  39341. (function (BABYLON) {
  39342. var BoundingBoxRenderer = (function () {
  39343. function BoundingBoxRenderer(scene) {
  39344. this.frontColor = new BABYLON.Color3(1, 1, 1);
  39345. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  39346. this.showBackLines = true;
  39347. this.renderList = new BABYLON.SmartArray(32);
  39348. this._vertexBuffers = {};
  39349. this._scene = scene;
  39350. }
  39351. BoundingBoxRenderer.prototype._prepareRessources = function () {
  39352. if (this._colorShader) {
  39353. return;
  39354. }
  39355. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  39356. attributes: [BABYLON.VertexBuffer.PositionKind],
  39357. uniforms: ["worldViewProjection", "color"]
  39358. });
  39359. var engine = this._scene.getEngine();
  39360. var boxdata = BABYLON.VertexData.CreateBox(1.0);
  39361. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  39362. 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]);
  39363. };
  39364. BoundingBoxRenderer.prototype.reset = function () {
  39365. this.renderList.reset();
  39366. };
  39367. BoundingBoxRenderer.prototype.render = function () {
  39368. if (this.renderList.length === 0) {
  39369. return;
  39370. }
  39371. this._prepareRessources();
  39372. if (!this._colorShader.isReady()) {
  39373. return;
  39374. }
  39375. var engine = this._scene.getEngine();
  39376. engine.setDepthWrite(false);
  39377. this._colorShader._preBind();
  39378. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  39379. var boundingBox = this.renderList.data[boundingBoxIndex];
  39380. var min = boundingBox.minimum;
  39381. var max = boundingBox.maximum;
  39382. var diff = max.subtract(min);
  39383. var median = min.add(diff.scale(0.5));
  39384. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  39385. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  39386. .multiply(boundingBox.getWorldMatrix());
  39387. // VBOs
  39388. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  39389. if (this.showBackLines) {
  39390. // Back
  39391. engine.setDepthFunctionToGreaterOrEqual();
  39392. this._scene.resetCachedMaterial();
  39393. this._colorShader.setColor4("color", this.backColor.toColor4());
  39394. this._colorShader.bind(worldMatrix);
  39395. // Draw order
  39396. engine.draw(false, 0, 24);
  39397. }
  39398. // Front
  39399. engine.setDepthFunctionToLess();
  39400. this._scene.resetCachedMaterial();
  39401. this._colorShader.setColor4("color", this.frontColor.toColor4());
  39402. this._colorShader.bind(worldMatrix);
  39403. // Draw order
  39404. engine.draw(false, 0, 24);
  39405. }
  39406. this._colorShader.unbind();
  39407. engine.setDepthFunctionToLessOrEqual();
  39408. engine.setDepthWrite(true);
  39409. };
  39410. BoundingBoxRenderer.prototype.dispose = function () {
  39411. if (!this._colorShader) {
  39412. return;
  39413. }
  39414. this.renderList.dispose();
  39415. this._colorShader.dispose();
  39416. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  39417. if (buffer) {
  39418. buffer.dispose();
  39419. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  39420. }
  39421. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  39422. };
  39423. return BoundingBoxRenderer;
  39424. }());
  39425. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  39426. })(BABYLON || (BABYLON = {}));
  39427. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  39428. var BABYLON;
  39429. (function (BABYLON) {
  39430. var Condition = (function () {
  39431. function Condition(actionManager) {
  39432. this._actionManager = actionManager;
  39433. }
  39434. Condition.prototype.isValid = function () {
  39435. return true;
  39436. };
  39437. Condition.prototype._getProperty = function (propertyPath) {
  39438. return this._actionManager._getProperty(propertyPath);
  39439. };
  39440. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  39441. return this._actionManager._getEffectiveTarget(target, propertyPath);
  39442. };
  39443. Condition.prototype.serialize = function () {
  39444. };
  39445. Condition.prototype._serialize = function (serializedCondition) {
  39446. return {
  39447. type: 2,
  39448. children: [],
  39449. name: serializedCondition.name,
  39450. properties: serializedCondition.properties
  39451. };
  39452. };
  39453. return Condition;
  39454. }());
  39455. BABYLON.Condition = Condition;
  39456. var ValueCondition = (function (_super) {
  39457. __extends(ValueCondition, _super);
  39458. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  39459. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  39460. var _this = _super.call(this, actionManager) || this;
  39461. _this.propertyPath = propertyPath;
  39462. _this.value = value;
  39463. _this.operator = operator;
  39464. _this._target = target;
  39465. _this._effectiveTarget = _this._getEffectiveTarget(target, _this.propertyPath);
  39466. _this._property = _this._getProperty(_this.propertyPath);
  39467. return _this;
  39468. }
  39469. Object.defineProperty(ValueCondition, "IsEqual", {
  39470. get: function () {
  39471. return ValueCondition._IsEqual;
  39472. },
  39473. enumerable: true,
  39474. configurable: true
  39475. });
  39476. Object.defineProperty(ValueCondition, "IsDifferent", {
  39477. get: function () {
  39478. return ValueCondition._IsDifferent;
  39479. },
  39480. enumerable: true,
  39481. configurable: true
  39482. });
  39483. Object.defineProperty(ValueCondition, "IsGreater", {
  39484. get: function () {
  39485. return ValueCondition._IsGreater;
  39486. },
  39487. enumerable: true,
  39488. configurable: true
  39489. });
  39490. Object.defineProperty(ValueCondition, "IsLesser", {
  39491. get: function () {
  39492. return ValueCondition._IsLesser;
  39493. },
  39494. enumerable: true,
  39495. configurable: true
  39496. });
  39497. // Methods
  39498. ValueCondition.prototype.isValid = function () {
  39499. switch (this.operator) {
  39500. case ValueCondition.IsGreater:
  39501. return this._effectiveTarget[this._property] > this.value;
  39502. case ValueCondition.IsLesser:
  39503. return this._effectiveTarget[this._property] < this.value;
  39504. case ValueCondition.IsEqual:
  39505. case ValueCondition.IsDifferent:
  39506. var check;
  39507. if (this.value.equals) {
  39508. check = this.value.equals(this._effectiveTarget[this._property]);
  39509. }
  39510. else {
  39511. check = this.value === this._effectiveTarget[this._property];
  39512. }
  39513. return this.operator === ValueCondition.IsEqual ? check : !check;
  39514. }
  39515. return false;
  39516. };
  39517. ValueCondition.prototype.serialize = function () {
  39518. return this._serialize({
  39519. name: "ValueCondition",
  39520. properties: [
  39521. BABYLON.Action._GetTargetProperty(this._target),
  39522. { name: "propertyPath", value: this.propertyPath },
  39523. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  39524. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  39525. ]
  39526. });
  39527. };
  39528. ValueCondition.GetOperatorName = function (operator) {
  39529. switch (operator) {
  39530. case ValueCondition._IsEqual: return "IsEqual";
  39531. case ValueCondition._IsDifferent: return "IsDifferent";
  39532. case ValueCondition._IsGreater: return "IsGreater";
  39533. case ValueCondition._IsLesser: return "IsLesser";
  39534. default: return "";
  39535. }
  39536. };
  39537. return ValueCondition;
  39538. }(Condition));
  39539. // Statics
  39540. ValueCondition._IsEqual = 0;
  39541. ValueCondition._IsDifferent = 1;
  39542. ValueCondition._IsGreater = 2;
  39543. ValueCondition._IsLesser = 3;
  39544. BABYLON.ValueCondition = ValueCondition;
  39545. var PredicateCondition = (function (_super) {
  39546. __extends(PredicateCondition, _super);
  39547. function PredicateCondition(actionManager, predicate) {
  39548. var _this = _super.call(this, actionManager) || this;
  39549. _this.predicate = predicate;
  39550. return _this;
  39551. }
  39552. PredicateCondition.prototype.isValid = function () {
  39553. return this.predicate();
  39554. };
  39555. return PredicateCondition;
  39556. }(Condition));
  39557. BABYLON.PredicateCondition = PredicateCondition;
  39558. var StateCondition = (function (_super) {
  39559. __extends(StateCondition, _super);
  39560. function StateCondition(actionManager, target, value) {
  39561. var _this = _super.call(this, actionManager) || this;
  39562. _this.value = value;
  39563. _this._target = target;
  39564. return _this;
  39565. }
  39566. // Methods
  39567. StateCondition.prototype.isValid = function () {
  39568. return this._target.state === this.value;
  39569. };
  39570. StateCondition.prototype.serialize = function () {
  39571. return this._serialize({
  39572. name: "StateCondition",
  39573. properties: [
  39574. BABYLON.Action._GetTargetProperty(this._target),
  39575. { name: "value", value: this.value }
  39576. ]
  39577. });
  39578. };
  39579. return StateCondition;
  39580. }(Condition));
  39581. BABYLON.StateCondition = StateCondition;
  39582. })(BABYLON || (BABYLON = {}));
  39583. //# sourceMappingURL=babylon.condition.js.map
  39584. var BABYLON;
  39585. (function (BABYLON) {
  39586. var Action = (function () {
  39587. function Action(triggerOptions, condition) {
  39588. this.triggerOptions = triggerOptions;
  39589. if (triggerOptions.parameter) {
  39590. this.trigger = triggerOptions.trigger;
  39591. this._triggerParameter = triggerOptions.parameter;
  39592. }
  39593. else {
  39594. this.trigger = triggerOptions;
  39595. }
  39596. this._nextActiveAction = this;
  39597. this._condition = condition;
  39598. }
  39599. // Methods
  39600. Action.prototype._prepare = function () {
  39601. };
  39602. Action.prototype.getTriggerParameter = function () {
  39603. return this._triggerParameter;
  39604. };
  39605. Action.prototype._executeCurrent = function (evt) {
  39606. if (this._nextActiveAction._condition) {
  39607. var condition = this._nextActiveAction._condition;
  39608. var currentRenderId = this._actionManager.getScene().getRenderId();
  39609. // We cache the current evaluation for the current frame
  39610. if (condition._evaluationId === currentRenderId) {
  39611. if (!condition._currentResult) {
  39612. return;
  39613. }
  39614. }
  39615. else {
  39616. condition._evaluationId = currentRenderId;
  39617. if (!condition.isValid()) {
  39618. condition._currentResult = false;
  39619. return;
  39620. }
  39621. condition._currentResult = true;
  39622. }
  39623. }
  39624. this._nextActiveAction.execute(evt);
  39625. this.skipToNextActiveAction();
  39626. };
  39627. Action.prototype.execute = function (evt) {
  39628. };
  39629. Action.prototype.skipToNextActiveAction = function () {
  39630. if (this._nextActiveAction._child) {
  39631. if (!this._nextActiveAction._child._actionManager) {
  39632. this._nextActiveAction._child._actionManager = this._actionManager;
  39633. }
  39634. this._nextActiveAction = this._nextActiveAction._child;
  39635. }
  39636. else {
  39637. this._nextActiveAction = this;
  39638. }
  39639. };
  39640. Action.prototype.then = function (action) {
  39641. this._child = action;
  39642. action._actionManager = this._actionManager;
  39643. action._prepare();
  39644. return action;
  39645. };
  39646. Action.prototype._getProperty = function (propertyPath) {
  39647. return this._actionManager._getProperty(propertyPath);
  39648. };
  39649. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  39650. return this._actionManager._getEffectiveTarget(target, propertyPath);
  39651. };
  39652. Action.prototype.serialize = function (parent) {
  39653. };
  39654. // Called by BABYLON.Action objects in serialize(...). Internal use
  39655. Action.prototype._serialize = function (serializedAction, parent) {
  39656. var serializationObject = {
  39657. type: 1,
  39658. children: [],
  39659. name: serializedAction.name,
  39660. properties: serializedAction.properties || []
  39661. };
  39662. // Serialize child
  39663. if (this._child) {
  39664. this._child.serialize(serializationObject);
  39665. }
  39666. // Check if "this" has a condition
  39667. if (this._condition) {
  39668. var serializedCondition = this._condition.serialize();
  39669. serializedCondition.children.push(serializationObject);
  39670. if (parent) {
  39671. parent.children.push(serializedCondition);
  39672. }
  39673. return serializedCondition;
  39674. }
  39675. if (parent) {
  39676. parent.children.push(serializationObject);
  39677. }
  39678. return serializationObject;
  39679. };
  39680. return Action;
  39681. }());
  39682. Action._SerializeValueAsString = function (value) {
  39683. if (typeof value === "number") {
  39684. return value.toString();
  39685. }
  39686. if (typeof value === "boolean") {
  39687. return value ? "true" : "false";
  39688. }
  39689. if (value instanceof BABYLON.Vector2) {
  39690. return value.x + ", " + value.y;
  39691. }
  39692. if (value instanceof BABYLON.Vector3) {
  39693. return value.x + ", " + value.y + ", " + value.z;
  39694. }
  39695. if (value instanceof BABYLON.Color3) {
  39696. return value.r + ", " + value.g + ", " + value.b;
  39697. }
  39698. if (value instanceof BABYLON.Color4) {
  39699. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  39700. }
  39701. return value; // string
  39702. };
  39703. Action._GetTargetProperty = function (target) {
  39704. return {
  39705. name: "target",
  39706. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  39707. : target instanceof BABYLON.Light ? "LightProperties"
  39708. : target instanceof BABYLON.Camera ? "CameraProperties"
  39709. : "SceneProperties",
  39710. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  39711. };
  39712. };
  39713. BABYLON.Action = Action;
  39714. })(BABYLON || (BABYLON = {}));
  39715. //# sourceMappingURL=babylon.action.js.map
  39716. var BABYLON;
  39717. (function (BABYLON) {
  39718. /**
  39719. * ActionEvent is the event beint sent when an action is triggered.
  39720. */
  39721. var ActionEvent = (function () {
  39722. /**
  39723. * @constructor
  39724. * @param source The mesh or sprite that triggered the action.
  39725. * @param pointerX The X mouse cursor position at the time of the event
  39726. * @param pointerY The Y mouse cursor position at the time of the event
  39727. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  39728. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  39729. */
  39730. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent, additionalData) {
  39731. this.source = source;
  39732. this.pointerX = pointerX;
  39733. this.pointerY = pointerY;
  39734. this.meshUnderPointer = meshUnderPointer;
  39735. this.sourceEvent = sourceEvent;
  39736. this.additionalData = additionalData;
  39737. }
  39738. /**
  39739. * Helper function to auto-create an ActionEvent from a source mesh.
  39740. * @param source The source mesh that triggered the event
  39741. * @param evt {Event} The original (browser) event
  39742. */
  39743. ActionEvent.CreateNew = function (source, evt, additionalData) {
  39744. var scene = source.getScene();
  39745. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  39746. };
  39747. /**
  39748. * Helper function to auto-create an ActionEvent from a source mesh.
  39749. * @param source The source sprite that triggered the event
  39750. * @param scene Scene associated with the sprite
  39751. * @param evt {Event} The original (browser) event
  39752. */
  39753. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  39754. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  39755. };
  39756. /**
  39757. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  39758. * @param scene the scene where the event occurred
  39759. * @param evt {Event} The original (browser) event
  39760. */
  39761. ActionEvent.CreateNewFromScene = function (scene, evt) {
  39762. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  39763. };
  39764. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  39765. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  39766. };
  39767. return ActionEvent;
  39768. }());
  39769. BABYLON.ActionEvent = ActionEvent;
  39770. /**
  39771. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  39772. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  39773. */
  39774. var ActionManager = (function () {
  39775. function ActionManager(scene) {
  39776. // Members
  39777. this.actions = new Array();
  39778. this.hoverCursor = '';
  39779. this._scene = scene;
  39780. scene._actionManagers.push(this);
  39781. }
  39782. Object.defineProperty(ActionManager, "NothingTrigger", {
  39783. get: function () {
  39784. return ActionManager._NothingTrigger;
  39785. },
  39786. enumerable: true,
  39787. configurable: true
  39788. });
  39789. Object.defineProperty(ActionManager, "OnPickTrigger", {
  39790. get: function () {
  39791. return ActionManager._OnPickTrigger;
  39792. },
  39793. enumerable: true,
  39794. configurable: true
  39795. });
  39796. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  39797. get: function () {
  39798. return ActionManager._OnLeftPickTrigger;
  39799. },
  39800. enumerable: true,
  39801. configurable: true
  39802. });
  39803. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  39804. get: function () {
  39805. return ActionManager._OnRightPickTrigger;
  39806. },
  39807. enumerable: true,
  39808. configurable: true
  39809. });
  39810. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  39811. get: function () {
  39812. return ActionManager._OnCenterPickTrigger;
  39813. },
  39814. enumerable: true,
  39815. configurable: true
  39816. });
  39817. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  39818. get: function () {
  39819. return ActionManager._OnPickDownTrigger;
  39820. },
  39821. enumerable: true,
  39822. configurable: true
  39823. });
  39824. Object.defineProperty(ActionManager, "OnDoublePickTrigger", {
  39825. get: function () {
  39826. return ActionManager._OnDoublePickTrigger;
  39827. },
  39828. enumerable: true,
  39829. configurable: true
  39830. });
  39831. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  39832. get: function () {
  39833. return ActionManager._OnPickUpTrigger;
  39834. },
  39835. enumerable: true,
  39836. configurable: true
  39837. });
  39838. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  39839. /// This trigger will only be raised if you also declared a OnPickDown
  39840. get: function () {
  39841. return ActionManager._OnPickOutTrigger;
  39842. },
  39843. enumerable: true,
  39844. configurable: true
  39845. });
  39846. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  39847. get: function () {
  39848. return ActionManager._OnLongPressTrigger;
  39849. },
  39850. enumerable: true,
  39851. configurable: true
  39852. });
  39853. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  39854. get: function () {
  39855. return ActionManager._OnPointerOverTrigger;
  39856. },
  39857. enumerable: true,
  39858. configurable: true
  39859. });
  39860. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  39861. get: function () {
  39862. return ActionManager._OnPointerOutTrigger;
  39863. },
  39864. enumerable: true,
  39865. configurable: true
  39866. });
  39867. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  39868. get: function () {
  39869. return ActionManager._OnEveryFrameTrigger;
  39870. },
  39871. enumerable: true,
  39872. configurable: true
  39873. });
  39874. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  39875. get: function () {
  39876. return ActionManager._OnIntersectionEnterTrigger;
  39877. },
  39878. enumerable: true,
  39879. configurable: true
  39880. });
  39881. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  39882. get: function () {
  39883. return ActionManager._OnIntersectionExitTrigger;
  39884. },
  39885. enumerable: true,
  39886. configurable: true
  39887. });
  39888. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  39889. get: function () {
  39890. return ActionManager._OnKeyDownTrigger;
  39891. },
  39892. enumerable: true,
  39893. configurable: true
  39894. });
  39895. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  39896. get: function () {
  39897. return ActionManager._OnKeyUpTrigger;
  39898. },
  39899. enumerable: true,
  39900. configurable: true
  39901. });
  39902. // Methods
  39903. ActionManager.prototype.dispose = function () {
  39904. var index = this._scene._actionManagers.indexOf(this);
  39905. for (var i = 0; i < this.actions.length; i++) {
  39906. var action = this.actions[i];
  39907. ActionManager.Triggers[action.trigger]--;
  39908. if (ActionManager.Triggers[action.trigger] === 0) {
  39909. delete ActionManager.Triggers[action.trigger];
  39910. }
  39911. }
  39912. if (index > -1) {
  39913. this._scene._actionManagers.splice(index, 1);
  39914. }
  39915. };
  39916. ActionManager.prototype.getScene = function () {
  39917. return this._scene;
  39918. };
  39919. /**
  39920. * Does this action manager handles actions of any of the given triggers
  39921. * @param {number[]} triggers - the triggers to be tested
  39922. * @return {boolean} whether one (or more) of the triggers is handeled
  39923. */
  39924. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  39925. for (var index = 0; index < this.actions.length; index++) {
  39926. var action = this.actions[index];
  39927. if (triggers.indexOf(action.trigger) > -1) {
  39928. return true;
  39929. }
  39930. }
  39931. return false;
  39932. };
  39933. /**
  39934. * Does this action manager handles actions of a given trigger
  39935. * @param {number} trigger - the trigger to be tested
  39936. * @return {boolean} whether the trigger is handeled
  39937. */
  39938. ActionManager.prototype.hasSpecificTrigger = function (trigger) {
  39939. for (var index = 0; index < this.actions.length; index++) {
  39940. var action = this.actions[index];
  39941. if (action.trigger === trigger) {
  39942. return true;
  39943. }
  39944. }
  39945. return false;
  39946. };
  39947. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  39948. /**
  39949. * Does this action manager has pointer triggers
  39950. * @return {boolean} whether or not it has pointer triggers
  39951. */
  39952. get: function () {
  39953. for (var index = 0; index < this.actions.length; index++) {
  39954. var action = this.actions[index];
  39955. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  39956. return true;
  39957. }
  39958. }
  39959. return false;
  39960. },
  39961. enumerable: true,
  39962. configurable: true
  39963. });
  39964. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  39965. /**
  39966. * Does this action manager has pick triggers
  39967. * @return {boolean} whether or not it has pick triggers
  39968. */
  39969. get: function () {
  39970. for (var index = 0; index < this.actions.length; index++) {
  39971. var action = this.actions[index];
  39972. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  39973. return true;
  39974. }
  39975. }
  39976. return false;
  39977. },
  39978. enumerable: true,
  39979. configurable: true
  39980. });
  39981. Object.defineProperty(ActionManager, "HasTriggers", {
  39982. /**
  39983. * Does exist one action manager with at least one trigger
  39984. * @return {boolean} whether or not it exists one action manager with one trigger
  39985. **/
  39986. get: function () {
  39987. for (var t in ActionManager.Triggers) {
  39988. if (ActionManager.Triggers.hasOwnProperty(t)) {
  39989. return true;
  39990. }
  39991. }
  39992. return false;
  39993. },
  39994. enumerable: true,
  39995. configurable: true
  39996. });
  39997. Object.defineProperty(ActionManager, "HasPickTriggers", {
  39998. /**
  39999. * Does exist one action manager with at least one pick trigger
  40000. * @return {boolean} whether or not it exists one action manager with one pick trigger
  40001. **/
  40002. get: function () {
  40003. for (var t in ActionManager.Triggers) {
  40004. if (ActionManager.Triggers.hasOwnProperty(t)) {
  40005. var t_int = parseInt(t);
  40006. if (t_int >= ActionManager._OnPickTrigger && t_int <= ActionManager._OnPickUpTrigger) {
  40007. return true;
  40008. }
  40009. }
  40010. }
  40011. return false;
  40012. },
  40013. enumerable: true,
  40014. configurable: true
  40015. });
  40016. /**
  40017. * Does exist one action manager that handles actions of a given trigger
  40018. * @param {number} trigger - the trigger to be tested
  40019. * @return {boolean} whether the trigger is handeled by at least one action manager
  40020. **/
  40021. ActionManager.HasSpecificTrigger = function (trigger) {
  40022. for (var t in ActionManager.Triggers) {
  40023. if (ActionManager.Triggers.hasOwnProperty(t)) {
  40024. var t_int = parseInt(t);
  40025. if (t_int === trigger) {
  40026. return true;
  40027. }
  40028. }
  40029. }
  40030. return false;
  40031. };
  40032. /**
  40033. * Registers an action to this action manager
  40034. * @param {BABYLON.Action} action - the action to be registered
  40035. * @return {BABYLON.Action} the action amended (prepared) after registration
  40036. */
  40037. ActionManager.prototype.registerAction = function (action) {
  40038. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  40039. if (this.getScene().actionManager !== this) {
  40040. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  40041. return null;
  40042. }
  40043. }
  40044. this.actions.push(action);
  40045. if (ActionManager.Triggers[action.trigger]) {
  40046. ActionManager.Triggers[action.trigger]++;
  40047. }
  40048. else {
  40049. ActionManager.Triggers[action.trigger] = 1;
  40050. }
  40051. action._actionManager = this;
  40052. action._prepare();
  40053. return action;
  40054. };
  40055. /**
  40056. * Process a specific trigger
  40057. * @param {number} trigger - the trigger to process
  40058. * @param evt {BABYLON.ActionEvent} the event details to be processed
  40059. */
  40060. ActionManager.prototype.processTrigger = function (trigger, evt) {
  40061. for (var index = 0; index < this.actions.length; index++) {
  40062. var action = this.actions[index];
  40063. if (action.trigger === trigger) {
  40064. if (trigger === ActionManager.OnKeyUpTrigger
  40065. || trigger === ActionManager.OnKeyDownTrigger) {
  40066. var parameter = action.getTriggerParameter();
  40067. if (parameter && parameter !== evt.sourceEvent.keyCode) {
  40068. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  40069. var actualkey = String.fromCharCode(unicode).toLowerCase();
  40070. if (actualkey !== parameter.toLowerCase()) {
  40071. continue;
  40072. }
  40073. }
  40074. }
  40075. action._executeCurrent(evt);
  40076. }
  40077. }
  40078. };
  40079. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  40080. var properties = propertyPath.split(".");
  40081. for (var index = 0; index < properties.length - 1; index++) {
  40082. target = target[properties[index]];
  40083. }
  40084. return target;
  40085. };
  40086. ActionManager.prototype._getProperty = function (propertyPath) {
  40087. var properties = propertyPath.split(".");
  40088. return properties[properties.length - 1];
  40089. };
  40090. ActionManager.prototype.serialize = function (name) {
  40091. var root = {
  40092. children: [],
  40093. name: name,
  40094. type: 3,
  40095. properties: [] // Empty for root but required
  40096. };
  40097. for (var i = 0; i < this.actions.length; i++) {
  40098. var triggerObject = {
  40099. type: 0,
  40100. children: [],
  40101. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  40102. properties: []
  40103. };
  40104. var triggerOptions = this.actions[i].triggerOptions;
  40105. if (triggerOptions && typeof triggerOptions !== "number") {
  40106. if (triggerOptions.parameter instanceof BABYLON.Node) {
  40107. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  40108. }
  40109. else {
  40110. var parameter = {};
  40111. BABYLON.Tools.DeepCopy(triggerOptions.parameter, parameter, ["mesh"]);
  40112. if (triggerOptions.parameter.mesh) {
  40113. parameter._meshId = triggerOptions.parameter.mesh.id;
  40114. }
  40115. triggerObject.properties.push({ name: "parameter", targetType: null, value: parameter });
  40116. }
  40117. }
  40118. // Serialize child action, recursively
  40119. this.actions[i].serialize(triggerObject);
  40120. // Add serialized trigger
  40121. root.children.push(triggerObject);
  40122. }
  40123. return root;
  40124. };
  40125. ActionManager.Parse = function (parsedActions, object, scene) {
  40126. var actionManager = new BABYLON.ActionManager(scene);
  40127. if (object === null)
  40128. scene.actionManager = actionManager;
  40129. else
  40130. object.actionManager = actionManager;
  40131. // instanciate a new object
  40132. var instanciate = function (name, params) {
  40133. var newInstance = Object.create(BABYLON[name].prototype);
  40134. newInstance.constructor.apply(newInstance, params);
  40135. return newInstance;
  40136. };
  40137. var parseParameter = function (name, value, target, propertyPath) {
  40138. if (propertyPath === null) {
  40139. // String, boolean or float
  40140. var floatValue = parseFloat(value);
  40141. if (value === "true" || value === "false")
  40142. return value === "true";
  40143. else
  40144. return isNaN(floatValue) ? value : floatValue;
  40145. }
  40146. var effectiveTarget = propertyPath.split(".");
  40147. var values = value.split(",");
  40148. // Get effective Target
  40149. for (var i = 0; i < effectiveTarget.length; i++) {
  40150. target = target[effectiveTarget[i]];
  40151. }
  40152. // Return appropriate value with its type
  40153. if (typeof (target) === "boolean")
  40154. return values[0] === "true";
  40155. if (typeof (target) === "string")
  40156. return values[0];
  40157. // Parameters with multiple values such as Vector3 etc.
  40158. var split = new Array();
  40159. for (var i = 0; i < values.length; i++)
  40160. split.push(parseFloat(values[i]));
  40161. if (target instanceof BABYLON.Vector3)
  40162. return BABYLON.Vector3.FromArray(split);
  40163. if (target instanceof BABYLON.Vector4)
  40164. return BABYLON.Vector4.FromArray(split);
  40165. if (target instanceof BABYLON.Color3)
  40166. return BABYLON.Color3.FromArray(split);
  40167. if (target instanceof BABYLON.Color4)
  40168. return BABYLON.Color4.FromArray(split);
  40169. return parseFloat(values[0]);
  40170. };
  40171. // traverse graph per trigger
  40172. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  40173. if (combineArray === void 0) { combineArray = null; }
  40174. if (parsedAction.detached)
  40175. return;
  40176. var parameters = new Array();
  40177. var target = null;
  40178. var propertyPath = null;
  40179. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  40180. // Parameters
  40181. if (parsedAction.type === 2)
  40182. parameters.push(actionManager);
  40183. else
  40184. parameters.push(trigger);
  40185. if (combine) {
  40186. var actions = new Array();
  40187. for (var j = 0; j < parsedAction.combine.length; j++) {
  40188. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  40189. }
  40190. parameters.push(actions);
  40191. }
  40192. else {
  40193. for (var i = 0; i < parsedAction.properties.length; i++) {
  40194. var value = parsedAction.properties[i].value;
  40195. var name = parsedAction.properties[i].name;
  40196. var targetType = parsedAction.properties[i].targetType;
  40197. if (name === "target")
  40198. if (targetType !== null && targetType === "SceneProperties")
  40199. value = target = scene;
  40200. else
  40201. value = target = scene.getNodeByName(value);
  40202. else if (name === "parent")
  40203. value = scene.getNodeByName(value);
  40204. else if (name === "sound")
  40205. value = scene.getSoundByName(value);
  40206. else if (name !== "propertyPath") {
  40207. if (parsedAction.type === 2 && name === "operator")
  40208. value = BABYLON.ValueCondition[value];
  40209. else
  40210. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  40211. }
  40212. else {
  40213. propertyPath = value;
  40214. }
  40215. parameters.push(value);
  40216. }
  40217. }
  40218. if (combineArray === null) {
  40219. parameters.push(condition);
  40220. }
  40221. else {
  40222. parameters.push(null);
  40223. }
  40224. // If interpolate value action
  40225. if (parsedAction.name === "InterpolateValueAction") {
  40226. var param = parameters[parameters.length - 2];
  40227. parameters[parameters.length - 1] = param;
  40228. parameters[parameters.length - 2] = condition;
  40229. }
  40230. // Action or condition(s) and not CombineAction
  40231. var newAction = instanciate(parsedAction.name, parameters);
  40232. if (newAction instanceof BABYLON.Condition && condition !== null) {
  40233. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  40234. if (action)
  40235. action.then(nothing);
  40236. else
  40237. actionManager.registerAction(nothing);
  40238. action = nothing;
  40239. }
  40240. if (combineArray === null) {
  40241. if (newAction instanceof BABYLON.Condition) {
  40242. condition = newAction;
  40243. newAction = action;
  40244. }
  40245. else {
  40246. condition = null;
  40247. if (action)
  40248. action.then(newAction);
  40249. else
  40250. actionManager.registerAction(newAction);
  40251. }
  40252. }
  40253. else {
  40254. combineArray.push(newAction);
  40255. }
  40256. for (var i = 0; i < parsedAction.children.length; i++)
  40257. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  40258. };
  40259. // triggers
  40260. for (var i = 0; i < parsedActions.children.length; i++) {
  40261. var triggerParams;
  40262. var trigger = parsedActions.children[i];
  40263. if (trigger.properties.length > 0) {
  40264. var param = trigger.properties[0].value;
  40265. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  40266. if (value._meshId) {
  40267. value.mesh = scene.getMeshByID(value._meshId);
  40268. }
  40269. triggerParams = { trigger: BABYLON.ActionManager[trigger.name], parameter: value };
  40270. }
  40271. else
  40272. triggerParams = BABYLON.ActionManager[trigger.name];
  40273. for (var j = 0; j < trigger.children.length; j++) {
  40274. if (!trigger.detached)
  40275. traverse(trigger.children[j], triggerParams, null, null);
  40276. }
  40277. }
  40278. };
  40279. ActionManager.GetTriggerName = function (trigger) {
  40280. switch (trigger) {
  40281. case 0: return "NothingTrigger";
  40282. case 1: return "OnPickTrigger";
  40283. case 2: return "OnLeftPickTrigger";
  40284. case 3: return "OnRightPickTrigger";
  40285. case 4: return "OnCenterPickTrigger";
  40286. case 5: return "OnPickDownTrigger";
  40287. case 6: return "OnPickUpTrigger";
  40288. case 7: return "OnLongPressTrigger";
  40289. case 8: return "OnPointerOverTrigger";
  40290. case 9: return "OnPointerOutTrigger";
  40291. case 10: return "OnEveryFrameTrigger";
  40292. case 11: return "OnIntersectionEnterTrigger";
  40293. case 12: return "OnIntersectionExitTrigger";
  40294. case 13: return "OnKeyDownTrigger";
  40295. case 14: return "OnKeyUpTrigger";
  40296. case 15: return "OnPickOutTrigger";
  40297. default: return "";
  40298. }
  40299. };
  40300. return ActionManager;
  40301. }());
  40302. // Statics
  40303. ActionManager._NothingTrigger = 0;
  40304. ActionManager._OnPickTrigger = 1;
  40305. ActionManager._OnLeftPickTrigger = 2;
  40306. ActionManager._OnRightPickTrigger = 3;
  40307. ActionManager._OnCenterPickTrigger = 4;
  40308. ActionManager._OnPickDownTrigger = 5;
  40309. ActionManager._OnDoublePickTrigger = 6;
  40310. ActionManager._OnPickUpTrigger = 7;
  40311. ActionManager._OnLongPressTrigger = 8;
  40312. ActionManager._OnPointerOverTrigger = 9;
  40313. ActionManager._OnPointerOutTrigger = 10;
  40314. ActionManager._OnEveryFrameTrigger = 11;
  40315. ActionManager._OnIntersectionEnterTrigger = 12;
  40316. ActionManager._OnIntersectionExitTrigger = 13;
  40317. ActionManager._OnKeyDownTrigger = 14;
  40318. ActionManager._OnKeyUpTrigger = 15;
  40319. ActionManager._OnPickOutTrigger = 16;
  40320. ActionManager.Triggers = {};
  40321. BABYLON.ActionManager = ActionManager;
  40322. })(BABYLON || (BABYLON = {}));
  40323. //# sourceMappingURL=babylon.actionManager.js.map
  40324. var BABYLON;
  40325. (function (BABYLON) {
  40326. var InterpolateValueAction = (function (_super) {
  40327. __extends(InterpolateValueAction, _super);
  40328. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  40329. if (duration === void 0) { duration = 1000; }
  40330. var _this = _super.call(this, triggerOptions, condition) || this;
  40331. _this.propertyPath = propertyPath;
  40332. _this.value = value;
  40333. _this.duration = duration;
  40334. _this.stopOtherAnimations = stopOtherAnimations;
  40335. _this.onInterpolationDone = onInterpolationDone;
  40336. _this._target = _this._effectiveTarget = target;
  40337. return _this;
  40338. }
  40339. InterpolateValueAction.prototype._prepare = function () {
  40340. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  40341. this._property = this._getProperty(this.propertyPath);
  40342. };
  40343. InterpolateValueAction.prototype.execute = function () {
  40344. var scene = this._actionManager.getScene();
  40345. var keys = [
  40346. {
  40347. frame: 0,
  40348. value: this._effectiveTarget[this._property]
  40349. }, {
  40350. frame: 100,
  40351. value: this.value
  40352. }
  40353. ];
  40354. var dataType;
  40355. if (typeof this.value === "number") {
  40356. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  40357. }
  40358. else if (this.value instanceof BABYLON.Color3) {
  40359. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  40360. }
  40361. else if (this.value instanceof BABYLON.Vector3) {
  40362. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  40363. }
  40364. else if (this.value instanceof BABYLON.Matrix) {
  40365. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  40366. }
  40367. else if (this.value instanceof BABYLON.Quaternion) {
  40368. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  40369. }
  40370. else {
  40371. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  40372. return;
  40373. }
  40374. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  40375. animation.setKeys(keys);
  40376. if (this.stopOtherAnimations) {
  40377. scene.stopAnimation(this._effectiveTarget);
  40378. }
  40379. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, this.onInterpolationDone);
  40380. };
  40381. InterpolateValueAction.prototype.serialize = function (parent) {
  40382. return _super.prototype._serialize.call(this, {
  40383. name: "InterpolateValueAction",
  40384. properties: [
  40385. BABYLON.Action._GetTargetProperty(this._target),
  40386. { name: "propertyPath", value: this.propertyPath },
  40387. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  40388. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  40389. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  40390. ]
  40391. }, parent);
  40392. };
  40393. return InterpolateValueAction;
  40394. }(BABYLON.Action));
  40395. BABYLON.InterpolateValueAction = InterpolateValueAction;
  40396. })(BABYLON || (BABYLON = {}));
  40397. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  40398. var BABYLON;
  40399. (function (BABYLON) {
  40400. var SwitchBooleanAction = (function (_super) {
  40401. __extends(SwitchBooleanAction, _super);
  40402. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  40403. var _this = _super.call(this, triggerOptions, condition) || this;
  40404. _this.propertyPath = propertyPath;
  40405. _this._target = _this._effectiveTarget = target;
  40406. return _this;
  40407. }
  40408. SwitchBooleanAction.prototype._prepare = function () {
  40409. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  40410. this._property = this._getProperty(this.propertyPath);
  40411. };
  40412. SwitchBooleanAction.prototype.execute = function () {
  40413. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  40414. };
  40415. SwitchBooleanAction.prototype.serialize = function (parent) {
  40416. return _super.prototype._serialize.call(this, {
  40417. name: "SwitchBooleanAction",
  40418. properties: [
  40419. BABYLON.Action._GetTargetProperty(this._target),
  40420. { name: "propertyPath", value: this.propertyPath }
  40421. ]
  40422. }, parent);
  40423. };
  40424. return SwitchBooleanAction;
  40425. }(BABYLON.Action));
  40426. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  40427. var SetStateAction = (function (_super) {
  40428. __extends(SetStateAction, _super);
  40429. function SetStateAction(triggerOptions, target, value, condition) {
  40430. var _this = _super.call(this, triggerOptions, condition) || this;
  40431. _this.value = value;
  40432. _this._target = target;
  40433. return _this;
  40434. }
  40435. SetStateAction.prototype.execute = function () {
  40436. this._target.state = this.value;
  40437. };
  40438. SetStateAction.prototype.serialize = function (parent) {
  40439. return _super.prototype._serialize.call(this, {
  40440. name: "SetStateAction",
  40441. properties: [
  40442. BABYLON.Action._GetTargetProperty(this._target),
  40443. { name: "value", value: this.value }
  40444. ]
  40445. }, parent);
  40446. };
  40447. return SetStateAction;
  40448. }(BABYLON.Action));
  40449. BABYLON.SetStateAction = SetStateAction;
  40450. var SetValueAction = (function (_super) {
  40451. __extends(SetValueAction, _super);
  40452. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  40453. var _this = _super.call(this, triggerOptions, condition) || this;
  40454. _this.propertyPath = propertyPath;
  40455. _this.value = value;
  40456. _this._target = _this._effectiveTarget = target;
  40457. return _this;
  40458. }
  40459. SetValueAction.prototype._prepare = function () {
  40460. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  40461. this._property = this._getProperty(this.propertyPath);
  40462. };
  40463. SetValueAction.prototype.execute = function () {
  40464. this._effectiveTarget[this._property] = this.value;
  40465. if (this._target.markAsDirty) {
  40466. this._target.markAsDirty(this._property);
  40467. }
  40468. };
  40469. SetValueAction.prototype.serialize = function (parent) {
  40470. return _super.prototype._serialize.call(this, {
  40471. name: "SetValueAction",
  40472. properties: [
  40473. BABYLON.Action._GetTargetProperty(this._target),
  40474. { name: "propertyPath", value: this.propertyPath },
  40475. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  40476. ]
  40477. }, parent);
  40478. };
  40479. return SetValueAction;
  40480. }(BABYLON.Action));
  40481. BABYLON.SetValueAction = SetValueAction;
  40482. var IncrementValueAction = (function (_super) {
  40483. __extends(IncrementValueAction, _super);
  40484. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  40485. var _this = _super.call(this, triggerOptions, condition) || this;
  40486. _this.propertyPath = propertyPath;
  40487. _this.value = value;
  40488. _this._target = _this._effectiveTarget = target;
  40489. return _this;
  40490. }
  40491. IncrementValueAction.prototype._prepare = function () {
  40492. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  40493. this._property = this._getProperty(this.propertyPath);
  40494. if (typeof this._effectiveTarget[this._property] !== "number") {
  40495. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  40496. }
  40497. };
  40498. IncrementValueAction.prototype.execute = function () {
  40499. this._effectiveTarget[this._property] += this.value;
  40500. if (this._target.markAsDirty) {
  40501. this._target.markAsDirty(this._property);
  40502. }
  40503. };
  40504. IncrementValueAction.prototype.serialize = function (parent) {
  40505. return _super.prototype._serialize.call(this, {
  40506. name: "IncrementValueAction",
  40507. properties: [
  40508. BABYLON.Action._GetTargetProperty(this._target),
  40509. { name: "propertyPath", value: this.propertyPath },
  40510. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  40511. ]
  40512. }, parent);
  40513. };
  40514. return IncrementValueAction;
  40515. }(BABYLON.Action));
  40516. BABYLON.IncrementValueAction = IncrementValueAction;
  40517. var PlayAnimationAction = (function (_super) {
  40518. __extends(PlayAnimationAction, _super);
  40519. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  40520. var _this = _super.call(this, triggerOptions, condition) || this;
  40521. _this.from = from;
  40522. _this.to = to;
  40523. _this.loop = loop;
  40524. _this._target = target;
  40525. return _this;
  40526. }
  40527. PlayAnimationAction.prototype._prepare = function () {
  40528. };
  40529. PlayAnimationAction.prototype.execute = function () {
  40530. var scene = this._actionManager.getScene();
  40531. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  40532. };
  40533. PlayAnimationAction.prototype.serialize = function (parent) {
  40534. return _super.prototype._serialize.call(this, {
  40535. name: "PlayAnimationAction",
  40536. properties: [
  40537. BABYLON.Action._GetTargetProperty(this._target),
  40538. { name: "from", value: String(this.from) },
  40539. { name: "to", value: String(this.to) },
  40540. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  40541. ]
  40542. }, parent);
  40543. };
  40544. return PlayAnimationAction;
  40545. }(BABYLON.Action));
  40546. BABYLON.PlayAnimationAction = PlayAnimationAction;
  40547. var StopAnimationAction = (function (_super) {
  40548. __extends(StopAnimationAction, _super);
  40549. function StopAnimationAction(triggerOptions, target, condition) {
  40550. var _this = _super.call(this, triggerOptions, condition) || this;
  40551. _this._target = target;
  40552. return _this;
  40553. }
  40554. StopAnimationAction.prototype._prepare = function () {
  40555. };
  40556. StopAnimationAction.prototype.execute = function () {
  40557. var scene = this._actionManager.getScene();
  40558. scene.stopAnimation(this._target);
  40559. };
  40560. StopAnimationAction.prototype.serialize = function (parent) {
  40561. return _super.prototype._serialize.call(this, {
  40562. name: "StopAnimationAction",
  40563. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  40564. }, parent);
  40565. };
  40566. return StopAnimationAction;
  40567. }(BABYLON.Action));
  40568. BABYLON.StopAnimationAction = StopAnimationAction;
  40569. var DoNothingAction = (function (_super) {
  40570. __extends(DoNothingAction, _super);
  40571. function DoNothingAction(triggerOptions, condition) {
  40572. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  40573. return _super.call(this, triggerOptions, condition) || this;
  40574. }
  40575. DoNothingAction.prototype.execute = function () {
  40576. };
  40577. DoNothingAction.prototype.serialize = function (parent) {
  40578. return _super.prototype._serialize.call(this, {
  40579. name: "DoNothingAction",
  40580. properties: []
  40581. }, parent);
  40582. };
  40583. return DoNothingAction;
  40584. }(BABYLON.Action));
  40585. BABYLON.DoNothingAction = DoNothingAction;
  40586. var CombineAction = (function (_super) {
  40587. __extends(CombineAction, _super);
  40588. function CombineAction(triggerOptions, children, condition) {
  40589. var _this = _super.call(this, triggerOptions, condition) || this;
  40590. _this.children = children;
  40591. return _this;
  40592. }
  40593. CombineAction.prototype._prepare = function () {
  40594. for (var index = 0; index < this.children.length; index++) {
  40595. this.children[index]._actionManager = this._actionManager;
  40596. this.children[index]._prepare();
  40597. }
  40598. };
  40599. CombineAction.prototype.execute = function (evt) {
  40600. for (var index = 0; index < this.children.length; index++) {
  40601. this.children[index].execute(evt);
  40602. }
  40603. };
  40604. CombineAction.prototype.serialize = function (parent) {
  40605. var serializationObject = _super.prototype._serialize.call(this, {
  40606. name: "CombineAction",
  40607. properties: [],
  40608. combine: []
  40609. }, parent);
  40610. for (var i = 0; i < this.children.length; i++) {
  40611. serializationObject.combine.push(this.children[i].serialize(null));
  40612. }
  40613. return serializationObject;
  40614. };
  40615. return CombineAction;
  40616. }(BABYLON.Action));
  40617. BABYLON.CombineAction = CombineAction;
  40618. var ExecuteCodeAction = (function (_super) {
  40619. __extends(ExecuteCodeAction, _super);
  40620. function ExecuteCodeAction(triggerOptions, func, condition) {
  40621. var _this = _super.call(this, triggerOptions, condition) || this;
  40622. _this.func = func;
  40623. return _this;
  40624. }
  40625. ExecuteCodeAction.prototype.execute = function (evt) {
  40626. this.func(evt);
  40627. };
  40628. return ExecuteCodeAction;
  40629. }(BABYLON.Action));
  40630. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  40631. var SetParentAction = (function (_super) {
  40632. __extends(SetParentAction, _super);
  40633. function SetParentAction(triggerOptions, target, parent, condition) {
  40634. var _this = _super.call(this, triggerOptions, condition) || this;
  40635. _this._target = target;
  40636. _this._parent = parent;
  40637. return _this;
  40638. }
  40639. SetParentAction.prototype._prepare = function () {
  40640. };
  40641. SetParentAction.prototype.execute = function () {
  40642. if (this._target.parent === this._parent) {
  40643. return;
  40644. }
  40645. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  40646. invertParentWorldMatrix.invert();
  40647. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  40648. this._target.parent = this._parent;
  40649. };
  40650. SetParentAction.prototype.serialize = function (parent) {
  40651. return _super.prototype._serialize.call(this, {
  40652. name: "SetParentAction",
  40653. properties: [
  40654. BABYLON.Action._GetTargetProperty(this._target),
  40655. BABYLON.Action._GetTargetProperty(this._parent),
  40656. ]
  40657. }, parent);
  40658. };
  40659. return SetParentAction;
  40660. }(BABYLON.Action));
  40661. BABYLON.SetParentAction = SetParentAction;
  40662. var PlaySoundAction = (function (_super) {
  40663. __extends(PlaySoundAction, _super);
  40664. function PlaySoundAction(triggerOptions, sound, condition) {
  40665. var _this = _super.call(this, triggerOptions, condition) || this;
  40666. _this._sound = sound;
  40667. return _this;
  40668. }
  40669. PlaySoundAction.prototype._prepare = function () {
  40670. };
  40671. PlaySoundAction.prototype.execute = function () {
  40672. if (this._sound !== undefined)
  40673. this._sound.play();
  40674. };
  40675. PlaySoundAction.prototype.serialize = function (parent) {
  40676. return _super.prototype._serialize.call(this, {
  40677. name: "PlaySoundAction",
  40678. properties: [{ name: "sound", value: this._sound.name }]
  40679. }, parent);
  40680. };
  40681. return PlaySoundAction;
  40682. }(BABYLON.Action));
  40683. BABYLON.PlaySoundAction = PlaySoundAction;
  40684. var StopSoundAction = (function (_super) {
  40685. __extends(StopSoundAction, _super);
  40686. function StopSoundAction(triggerOptions, sound, condition) {
  40687. var _this = _super.call(this, triggerOptions, condition) || this;
  40688. _this._sound = sound;
  40689. return _this;
  40690. }
  40691. StopSoundAction.prototype._prepare = function () {
  40692. };
  40693. StopSoundAction.prototype.execute = function () {
  40694. if (this._sound !== undefined)
  40695. this._sound.stop();
  40696. };
  40697. StopSoundAction.prototype.serialize = function (parent) {
  40698. return _super.prototype._serialize.call(this, {
  40699. name: "StopSoundAction",
  40700. properties: [{ name: "sound", value: this._sound.name }]
  40701. }, parent);
  40702. };
  40703. return StopSoundAction;
  40704. }(BABYLON.Action));
  40705. BABYLON.StopSoundAction = StopSoundAction;
  40706. })(BABYLON || (BABYLON = {}));
  40707. //# sourceMappingURL=babylon.directActions.js.map
  40708. var BABYLON;
  40709. (function (BABYLON) {
  40710. var Geometry = (function () {
  40711. function Geometry(id, scene, vertexData, updatable, mesh) {
  40712. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  40713. this._totalVertices = 0;
  40714. this._isDisposed = false;
  40715. this.id = id;
  40716. this._engine = scene.getEngine();
  40717. this._meshes = [];
  40718. this._scene = scene;
  40719. //Init vertex buffer cache
  40720. this._vertexBuffers = {};
  40721. this._indices = [];
  40722. // vertexData
  40723. if (vertexData) {
  40724. this.setAllVerticesData(vertexData, updatable);
  40725. }
  40726. else {
  40727. this._totalVertices = 0;
  40728. this._indices = [];
  40729. }
  40730. if (this._engine.getCaps().vertexArrayObject) {
  40731. this._vertexArrayObjects = {};
  40732. }
  40733. // applyToMesh
  40734. if (mesh) {
  40735. if (mesh instanceof BABYLON.LinesMesh) {
  40736. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  40737. this.updateExtend();
  40738. }
  40739. this.applyToMesh(mesh);
  40740. mesh.computeWorldMatrix(true);
  40741. }
  40742. }
  40743. Object.defineProperty(Geometry.prototype, "boundingBias", {
  40744. /**
  40745. * 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
  40746. * @returns The Bias Vector
  40747. */
  40748. get: function () {
  40749. return this._boundingBias;
  40750. },
  40751. set: function (value) {
  40752. if (this._boundingBias && this._boundingBias.equals(value)) {
  40753. return;
  40754. }
  40755. this._boundingBias = value.clone();
  40756. this.updateBoundingInfo(true, null);
  40757. },
  40758. enumerable: true,
  40759. configurable: true
  40760. });
  40761. Object.defineProperty(Geometry.prototype, "extend", {
  40762. get: function () {
  40763. return this._extend;
  40764. },
  40765. enumerable: true,
  40766. configurable: true
  40767. });
  40768. Geometry.prototype.getScene = function () {
  40769. return this._scene;
  40770. };
  40771. Geometry.prototype.getEngine = function () {
  40772. return this._engine;
  40773. };
  40774. Geometry.prototype.isReady = function () {
  40775. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  40776. };
  40777. Object.defineProperty(Geometry.prototype, "doNotSerialize", {
  40778. get: function () {
  40779. for (var index = 0; index < this._meshes.length; index++) {
  40780. if (!this._meshes[index].doNotSerialize) {
  40781. return false;
  40782. }
  40783. }
  40784. return true;
  40785. },
  40786. enumerable: true,
  40787. configurable: true
  40788. });
  40789. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  40790. vertexData.applyToGeometry(this, updatable);
  40791. this.notifyUpdate();
  40792. };
  40793. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  40794. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  40795. this.setVerticesBuffer(buffer);
  40796. };
  40797. Geometry.prototype.setVerticesBuffer = function (buffer) {
  40798. var kind = buffer.getKind();
  40799. if (this._vertexBuffers[kind]) {
  40800. this._vertexBuffers[kind].dispose();
  40801. }
  40802. this._vertexBuffers[kind] = buffer;
  40803. if (kind === BABYLON.VertexBuffer.PositionKind) {
  40804. var data = buffer.getData();
  40805. var stride = buffer.getStrideSize();
  40806. this._totalVertices = data.length / stride;
  40807. this.updateExtend(data, stride);
  40808. var meshes = this._meshes;
  40809. var numOfMeshes = meshes.length;
  40810. for (var index = 0; index < numOfMeshes; index++) {
  40811. var mesh = meshes[index];
  40812. mesh._resetPointsArrayCache();
  40813. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  40814. mesh._createGlobalSubMesh();
  40815. mesh.computeWorldMatrix(true);
  40816. }
  40817. }
  40818. this.notifyUpdate(kind);
  40819. if (this._vertexArrayObjects) {
  40820. this._disposeVertexArrayObjects();
  40821. this._vertexArrayObjects = {}; // Will trigger a rebuild of the VAO if supported
  40822. }
  40823. };
  40824. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  40825. var vertexBuffer = this.getVertexBuffer(kind);
  40826. if (!vertexBuffer) {
  40827. return;
  40828. }
  40829. vertexBuffer.updateDirectly(data, offset);
  40830. this.notifyUpdate(kind);
  40831. };
  40832. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  40833. var vertexBuffer = this.getVertexBuffer(kind);
  40834. if (!vertexBuffer) {
  40835. return;
  40836. }
  40837. vertexBuffer.update(data);
  40838. if (kind === BABYLON.VertexBuffer.PositionKind) {
  40839. var stride = vertexBuffer.getStrideSize();
  40840. this._totalVertices = data.length / stride;
  40841. this.updateBoundingInfo(updateExtends, data);
  40842. }
  40843. this.notifyUpdate(kind);
  40844. };
  40845. Geometry.prototype.updateBoundingInfo = function (updateExtends, data) {
  40846. if (updateExtends) {
  40847. this.updateExtend(data);
  40848. }
  40849. var meshes = this._meshes;
  40850. var numOfMeshes = meshes.length;
  40851. for (var index = 0; index < numOfMeshes; index++) {
  40852. var mesh = meshes[index];
  40853. mesh._resetPointsArrayCache();
  40854. if (updateExtends) {
  40855. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  40856. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  40857. var subMesh = mesh.subMeshes[subIndex];
  40858. subMesh.refreshBoundingInfo();
  40859. }
  40860. }
  40861. }
  40862. };
  40863. Geometry.prototype._bind = function (effect, indexToBind) {
  40864. if (indexToBind === void 0) { indexToBind = undefined; }
  40865. if (indexToBind === undefined) {
  40866. indexToBind = this._indexBuffer;
  40867. }
  40868. if (indexToBind != this._indexBuffer || !this._vertexArrayObjects) {
  40869. this._engine.bindBuffers(this.getVertexBuffers(), indexToBind, effect);
  40870. return;
  40871. }
  40872. // Using VAO
  40873. if (!this._vertexArrayObjects[effect.key]) {
  40874. this._vertexArrayObjects[effect.key] = this._engine.recordVertexArrayObject(this.getVertexBuffers(), indexToBind, effect);
  40875. }
  40876. this._engine.bindVertexArrayObject(this._vertexArrayObjects[effect.key], indexToBind);
  40877. };
  40878. Geometry.prototype.getTotalVertices = function () {
  40879. if (!this.isReady()) {
  40880. return 0;
  40881. }
  40882. return this._totalVertices;
  40883. };
  40884. Geometry.prototype.getVerticesData = function (kind, copyWhenShared) {
  40885. var vertexBuffer = this.getVertexBuffer(kind);
  40886. if (!vertexBuffer) {
  40887. return null;
  40888. }
  40889. var orig = vertexBuffer.getData();
  40890. if (!copyWhenShared || this._meshes.length === 1) {
  40891. return orig;
  40892. }
  40893. else {
  40894. var len = orig.length;
  40895. var copy = [];
  40896. for (var i = 0; i < len; i++) {
  40897. copy.push(orig[i]);
  40898. }
  40899. return copy;
  40900. }
  40901. };
  40902. Geometry.prototype.getVertexBuffer = function (kind) {
  40903. if (!this.isReady()) {
  40904. return null;
  40905. }
  40906. return this._vertexBuffers[kind];
  40907. };
  40908. Geometry.prototype.getVertexBuffers = function () {
  40909. if (!this.isReady()) {
  40910. return null;
  40911. }
  40912. return this._vertexBuffers;
  40913. };
  40914. Geometry.prototype.isVerticesDataPresent = function (kind) {
  40915. if (!this._vertexBuffers) {
  40916. if (this._delayInfo) {
  40917. return this._delayInfo.indexOf(kind) !== -1;
  40918. }
  40919. return false;
  40920. }
  40921. return this._vertexBuffers[kind] !== undefined;
  40922. };
  40923. Geometry.prototype.getVerticesDataKinds = function () {
  40924. var result = [];
  40925. var kind;
  40926. if (!this._vertexBuffers && this._delayInfo) {
  40927. for (kind in this._delayInfo) {
  40928. result.push(kind);
  40929. }
  40930. }
  40931. else {
  40932. for (kind in this._vertexBuffers) {
  40933. result.push(kind);
  40934. }
  40935. }
  40936. return result;
  40937. };
  40938. Geometry.prototype.setIndices = function (indices, totalVertices) {
  40939. if (this._indexBuffer) {
  40940. this._engine._releaseBuffer(this._indexBuffer);
  40941. }
  40942. this._disposeVertexArrayObjects();
  40943. this._indices = indices;
  40944. if (this._meshes.length !== 0 && this._indices) {
  40945. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  40946. }
  40947. if (totalVertices !== undefined) {
  40948. this._totalVertices = totalVertices;
  40949. }
  40950. var meshes = this._meshes;
  40951. var numOfMeshes = meshes.length;
  40952. for (var index = 0; index < numOfMeshes; index++) {
  40953. meshes[index]._createGlobalSubMesh();
  40954. }
  40955. this.notifyUpdate();
  40956. };
  40957. Geometry.prototype.getTotalIndices = function () {
  40958. if (!this.isReady()) {
  40959. return 0;
  40960. }
  40961. return this._indices.length;
  40962. };
  40963. Geometry.prototype.getIndices = function (copyWhenShared) {
  40964. if (!this.isReady()) {
  40965. return null;
  40966. }
  40967. var orig = this._indices;
  40968. if (!copyWhenShared || this._meshes.length === 1) {
  40969. return orig;
  40970. }
  40971. else {
  40972. var len = orig.length;
  40973. var copy = [];
  40974. for (var i = 0; i < len; i++) {
  40975. copy.push(orig[i]);
  40976. }
  40977. return copy;
  40978. }
  40979. };
  40980. Geometry.prototype.getIndexBuffer = function () {
  40981. if (!this.isReady()) {
  40982. return null;
  40983. }
  40984. return this._indexBuffer;
  40985. };
  40986. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  40987. var meshes = this._meshes;
  40988. var index = meshes.indexOf(mesh);
  40989. if (index === -1) {
  40990. return;
  40991. }
  40992. meshes.splice(index, 1);
  40993. mesh._geometry = null;
  40994. if (meshes.length === 0 && shouldDispose) {
  40995. this.dispose();
  40996. }
  40997. };
  40998. Geometry.prototype.applyToMesh = function (mesh) {
  40999. if (mesh._geometry === this) {
  41000. return;
  41001. }
  41002. var previousGeometry = mesh._geometry;
  41003. if (previousGeometry) {
  41004. previousGeometry.releaseForMesh(mesh);
  41005. }
  41006. var meshes = this._meshes;
  41007. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  41008. mesh._geometry = this;
  41009. this._scene.pushGeometry(this);
  41010. meshes.push(mesh);
  41011. if (this.isReady()) {
  41012. this._applyToMesh(mesh);
  41013. }
  41014. else {
  41015. mesh._boundingInfo = this._boundingInfo;
  41016. }
  41017. };
  41018. Geometry.prototype.updateExtend = function (data, stride) {
  41019. if (data === void 0) { data = null; }
  41020. if (!data) {
  41021. data = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind].getData();
  41022. }
  41023. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, stride);
  41024. };
  41025. Geometry.prototype._applyToMesh = function (mesh) {
  41026. var numOfMeshes = this._meshes.length;
  41027. // vertexBuffers
  41028. for (var kind in this._vertexBuffers) {
  41029. if (numOfMeshes === 1) {
  41030. this._vertexBuffers[kind].create();
  41031. }
  41032. var buffer = this._vertexBuffers[kind].getBuffer();
  41033. if (buffer)
  41034. buffer.references = numOfMeshes;
  41035. if (kind === BABYLON.VertexBuffer.PositionKind) {
  41036. mesh._resetPointsArrayCache();
  41037. if (!this._extend) {
  41038. this.updateExtend(this._vertexBuffers[kind].getData());
  41039. }
  41040. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  41041. mesh._createGlobalSubMesh();
  41042. //bounding info was just created again, world matrix should be applied again.
  41043. mesh._updateBoundingInfo();
  41044. }
  41045. }
  41046. // indexBuffer
  41047. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  41048. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  41049. }
  41050. if (this._indexBuffer) {
  41051. this._indexBuffer.references = numOfMeshes;
  41052. }
  41053. };
  41054. Geometry.prototype.notifyUpdate = function (kind) {
  41055. if (this.onGeometryUpdated) {
  41056. this.onGeometryUpdated(this, kind);
  41057. }
  41058. };
  41059. Geometry.prototype.load = function (scene, onLoaded) {
  41060. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  41061. return;
  41062. }
  41063. if (this.isReady()) {
  41064. if (onLoaded) {
  41065. onLoaded();
  41066. }
  41067. return;
  41068. }
  41069. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  41070. this._queueLoad(scene, onLoaded);
  41071. };
  41072. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  41073. var _this = this;
  41074. scene._addPendingData(this);
  41075. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  41076. _this._delayLoadingFunction(JSON.parse(data), _this);
  41077. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  41078. _this._delayInfo = [];
  41079. scene._removePendingData(_this);
  41080. var meshes = _this._meshes;
  41081. var numOfMeshes = meshes.length;
  41082. for (var index = 0; index < numOfMeshes; index++) {
  41083. _this._applyToMesh(meshes[index]);
  41084. }
  41085. if (onLoaded) {
  41086. onLoaded();
  41087. }
  41088. }, function () { }, scene.database);
  41089. };
  41090. /**
  41091. * Invert the geometry to move from a right handed system to a left handed one.
  41092. */
  41093. Geometry.prototype.toLeftHanded = function () {
  41094. // Flip faces
  41095. var tIndices = this.getIndices(false);
  41096. if (tIndices != null && tIndices.length > 0) {
  41097. for (var i = 0; i < tIndices.length; i += 3) {
  41098. var tTemp = tIndices[i + 0];
  41099. tIndices[i + 0] = tIndices[i + 2];
  41100. tIndices[i + 2] = tTemp;
  41101. }
  41102. this.setIndices(tIndices);
  41103. }
  41104. // Negate position.z
  41105. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  41106. if (tPositions != null && tPositions.length > 0) {
  41107. for (var i = 0; i < tPositions.length; i += 3) {
  41108. tPositions[i + 2] = -tPositions[i + 2];
  41109. }
  41110. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  41111. }
  41112. // Negate normal.z
  41113. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  41114. if (tNormals != null && tNormals.length > 0) {
  41115. for (var i = 0; i < tNormals.length; i += 3) {
  41116. tNormals[i + 2] = -tNormals[i + 2];
  41117. }
  41118. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  41119. }
  41120. };
  41121. Geometry.prototype.isDisposed = function () {
  41122. return this._isDisposed;
  41123. };
  41124. Geometry.prototype._disposeVertexArrayObjects = function () {
  41125. if (this._vertexArrayObjects) {
  41126. for (var kind in this._vertexArrayObjects) {
  41127. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[kind]);
  41128. }
  41129. this._vertexArrayObjects = {};
  41130. }
  41131. };
  41132. Geometry.prototype.dispose = function () {
  41133. var meshes = this._meshes;
  41134. var numOfMeshes = meshes.length;
  41135. var index;
  41136. for (index = 0; index < numOfMeshes; index++) {
  41137. this.releaseForMesh(meshes[index]);
  41138. }
  41139. this._meshes = [];
  41140. this._disposeVertexArrayObjects();
  41141. for (var kind in this._vertexBuffers) {
  41142. this._vertexBuffers[kind].dispose();
  41143. }
  41144. this._vertexBuffers = {};
  41145. this._totalVertices = 0;
  41146. if (this._indexBuffer) {
  41147. this._engine._releaseBuffer(this._indexBuffer);
  41148. }
  41149. this._indexBuffer = null;
  41150. this._indices = [];
  41151. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  41152. this.delayLoadingFile = null;
  41153. this._delayLoadingFunction = null;
  41154. this._delayInfo = [];
  41155. this._boundingInfo = null;
  41156. this._scene.removeGeometry(this);
  41157. this._isDisposed = true;
  41158. };
  41159. Geometry.prototype.copy = function (id) {
  41160. var vertexData = new BABYLON.VertexData();
  41161. vertexData.indices = [];
  41162. var indices = this.getIndices();
  41163. for (var index = 0; index < indices.length; index++) {
  41164. vertexData.indices.push(indices[index]);
  41165. }
  41166. var updatable = false;
  41167. var stopChecking = false;
  41168. var kind;
  41169. for (kind in this._vertexBuffers) {
  41170. // using slice() to make a copy of the array and not just reference it
  41171. var data = this.getVerticesData(kind);
  41172. if (data instanceof Float32Array) {
  41173. vertexData.set(new Float32Array(data), kind);
  41174. }
  41175. else {
  41176. vertexData.set(data.slice(0), kind);
  41177. }
  41178. if (!stopChecking) {
  41179. updatable = this.getVertexBuffer(kind).isUpdatable();
  41180. stopChecking = !updatable;
  41181. }
  41182. }
  41183. var geometry = new Geometry(id, this._scene, vertexData, updatable, null);
  41184. geometry.delayLoadState = this.delayLoadState;
  41185. geometry.delayLoadingFile = this.delayLoadingFile;
  41186. geometry._delayLoadingFunction = this._delayLoadingFunction;
  41187. for (kind in this._delayInfo) {
  41188. geometry._delayInfo = geometry._delayInfo || [];
  41189. geometry._delayInfo.push(kind);
  41190. }
  41191. // Bounding info
  41192. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  41193. return geometry;
  41194. };
  41195. Geometry.prototype.serialize = function () {
  41196. var serializationObject = {};
  41197. serializationObject.id = this.id;
  41198. if (BABYLON.Tags.HasTags(this)) {
  41199. serializationObject.tags = BABYLON.Tags.GetTags(this);
  41200. }
  41201. return serializationObject;
  41202. };
  41203. Geometry.prototype.serializeVerticeData = function () {
  41204. var serializationObject = this.serialize();
  41205. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  41206. serializationObject.positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  41207. if (this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable) {
  41208. serializationObject.positions._updatable = true;
  41209. }
  41210. }
  41211. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  41212. serializationObject.normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  41213. if (this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable) {
  41214. serializationObject.normals._updatable = true;
  41215. }
  41216. }
  41217. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  41218. serializationObject.uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  41219. if (this.getVertexBuffer(BABYLON.VertexBuffer.UVKind).isUpdatable) {
  41220. serializationObject.uvs._updatable = true;
  41221. }
  41222. }
  41223. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  41224. serializationObject.uv2s = this.getVerticesData(BABYLON.VertexBuffer.UV2Kind);
  41225. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV2Kind).isUpdatable) {
  41226. serializationObject.uv2s._updatable = true;
  41227. }
  41228. }
  41229. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  41230. serializationObject.uv3s = this.getVerticesData(BABYLON.VertexBuffer.UV3Kind);
  41231. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV3Kind).isUpdatable) {
  41232. serializationObject.uv3s._updatable = true;
  41233. }
  41234. }
  41235. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  41236. serializationObject.uv4s = this.getVerticesData(BABYLON.VertexBuffer.UV4Kind);
  41237. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV4Kind).isUpdatable) {
  41238. serializationObject.uv4s._updatable = true;
  41239. }
  41240. }
  41241. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  41242. serializationObject.uv5s = this.getVerticesData(BABYLON.VertexBuffer.UV5Kind);
  41243. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV5Kind).isUpdatable) {
  41244. serializationObject.uv5s._updatable = true;
  41245. }
  41246. }
  41247. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  41248. serializationObject.uv6s = this.getVerticesData(BABYLON.VertexBuffer.UV6Kind);
  41249. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV6Kind).isUpdatable) {
  41250. serializationObject.uv6s._updatable = true;
  41251. }
  41252. }
  41253. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  41254. serializationObject.colors = this.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  41255. if (this.getVertexBuffer(BABYLON.VertexBuffer.ColorKind).isUpdatable) {
  41256. serializationObject.colors._updatable = true;
  41257. }
  41258. }
  41259. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  41260. serializationObject.matricesIndices = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  41261. serializationObject.matricesIndices._isExpanded = true;
  41262. if (this.getVertexBuffer(BABYLON.VertexBuffer.MatricesIndicesKind).isUpdatable) {
  41263. serializationObject.matricesIndices._updatable = true;
  41264. }
  41265. }
  41266. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  41267. serializationObject.matricesWeights = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  41268. if (this.getVertexBuffer(BABYLON.VertexBuffer.MatricesWeightsKind).isUpdatable) {
  41269. serializationObject.matricesWeights._updatable = true;
  41270. }
  41271. }
  41272. serializationObject.indices = this.getIndices();
  41273. return serializationObject;
  41274. };
  41275. // Statics
  41276. Geometry.ExtractFromMesh = function (mesh, id) {
  41277. var geometry = mesh._geometry;
  41278. if (!geometry) {
  41279. return null;
  41280. }
  41281. return geometry.copy(id);
  41282. };
  41283. /**
  41284. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  41285. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  41286. * Be aware Math.random() could cause collisions, but:
  41287. * "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"
  41288. */
  41289. Geometry.RandomId = function () {
  41290. return BABYLON.Tools.RandomId();
  41291. };
  41292. Geometry.ImportGeometry = function (parsedGeometry, mesh) {
  41293. var scene = mesh.getScene();
  41294. // Geometry
  41295. var geometryId = parsedGeometry.geometryId;
  41296. if (geometryId) {
  41297. var geometry = scene.getGeometryByID(geometryId);
  41298. if (geometry) {
  41299. geometry.applyToMesh(mesh);
  41300. }
  41301. }
  41302. else if (parsedGeometry instanceof ArrayBuffer) {
  41303. var binaryInfo = mesh._binaryInfo;
  41304. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  41305. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  41306. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  41307. }
  41308. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  41309. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  41310. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  41311. }
  41312. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  41313. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  41314. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  41315. }
  41316. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  41317. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  41318. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  41319. }
  41320. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  41321. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  41322. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  41323. }
  41324. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  41325. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  41326. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  41327. }
  41328. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  41329. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  41330. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  41331. }
  41332. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  41333. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  41334. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  41335. }
  41336. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  41337. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  41338. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  41339. }
  41340. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  41341. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  41342. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  41343. }
  41344. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  41345. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  41346. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  41347. }
  41348. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  41349. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  41350. mesh.setIndices(indicesData);
  41351. }
  41352. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  41353. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  41354. mesh.subMeshes = [];
  41355. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  41356. var materialIndex = subMeshesData[(i * 5) + 0];
  41357. var verticesStart = subMeshesData[(i * 5) + 1];
  41358. var verticesCount = subMeshesData[(i * 5) + 2];
  41359. var indexStart = subMeshesData[(i * 5) + 3];
  41360. var indexCount = subMeshesData[(i * 5) + 4];
  41361. var subMesh = new BABYLON.SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  41362. }
  41363. }
  41364. }
  41365. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  41366. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, parsedGeometry.positions._updatable);
  41367. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, parsedGeometry.normals._updatable);
  41368. if (parsedGeometry.uvs) {
  41369. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, parsedGeometry.uvs._updatable);
  41370. }
  41371. if (parsedGeometry.uvs2) {
  41372. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, parsedGeometry.uvs2._updatable);
  41373. }
  41374. if (parsedGeometry.uvs3) {
  41375. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, parsedGeometry.uvs3._updatable);
  41376. }
  41377. if (parsedGeometry.uvs4) {
  41378. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, parsedGeometry.uvs4._updatable);
  41379. }
  41380. if (parsedGeometry.uvs5) {
  41381. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, parsedGeometry.uvs5._updatable);
  41382. }
  41383. if (parsedGeometry.uvs6) {
  41384. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, parsedGeometry.uvs6._updatable);
  41385. }
  41386. if (parsedGeometry.colors) {
  41387. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), parsedGeometry.colors._updatable);
  41388. }
  41389. if (parsedGeometry.matricesIndices) {
  41390. if (!parsedGeometry.matricesIndices._isExpanded) {
  41391. var floatIndices = [];
  41392. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  41393. var matricesIndex = parsedGeometry.matricesIndices[i];
  41394. floatIndices.push(matricesIndex & 0x000000FF);
  41395. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  41396. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  41397. floatIndices.push(matricesIndex >> 24);
  41398. }
  41399. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, parsedGeometry.matricesIndices._updatable);
  41400. }
  41401. else {
  41402. delete parsedGeometry.matricesIndices._isExpanded;
  41403. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, parsedGeometry.matricesIndices._updatable);
  41404. }
  41405. }
  41406. if (parsedGeometry.matricesIndicesExtra) {
  41407. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  41408. var floatIndices = [];
  41409. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  41410. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  41411. floatIndices.push(matricesIndex & 0x000000FF);
  41412. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  41413. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  41414. floatIndices.push(matricesIndex >> 24);
  41415. }
  41416. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, parsedGeometry.matricesIndicesExtra._updatable);
  41417. }
  41418. else {
  41419. delete parsedGeometry.matricesIndices._isExpanded;
  41420. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, parsedGeometry.matricesIndicesExtra._updatable);
  41421. }
  41422. }
  41423. if (parsedGeometry.matricesWeights) {
  41424. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, parsedGeometry.matricesWeights._updatable);
  41425. }
  41426. if (parsedGeometry.matricesWeightsExtra) {
  41427. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, parsedGeometry.matricesWeights._updatable);
  41428. }
  41429. mesh.setIndices(parsedGeometry.indices);
  41430. }
  41431. // SubMeshes
  41432. if (parsedGeometry.subMeshes) {
  41433. mesh.subMeshes = [];
  41434. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  41435. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  41436. var subMesh = new BABYLON.SubMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  41437. }
  41438. }
  41439. // Flat shading
  41440. if (mesh._shouldGenerateFlatShading) {
  41441. mesh.convertToFlatShadedMesh();
  41442. delete mesh._shouldGenerateFlatShading;
  41443. }
  41444. // Update
  41445. mesh.computeWorldMatrix(true);
  41446. // Octree
  41447. if (scene['_selectionOctree']) {
  41448. scene['_selectionOctree'].addMesh(mesh);
  41449. }
  41450. };
  41451. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  41452. if (scene.getGeometryByID(parsedVertexData.id)) {
  41453. return null; // null since geometry could be something else than a box...
  41454. }
  41455. var geometry = new Geometry(parsedVertexData.id, scene);
  41456. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  41457. if (parsedVertexData.delayLoadingFile) {
  41458. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  41459. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  41460. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  41461. geometry._delayInfo = [];
  41462. if (parsedVertexData.hasUVs) {
  41463. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  41464. }
  41465. if (parsedVertexData.hasUVs2) {
  41466. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  41467. }
  41468. if (parsedVertexData.hasUVs3) {
  41469. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  41470. }
  41471. if (parsedVertexData.hasUVs4) {
  41472. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  41473. }
  41474. if (parsedVertexData.hasUVs5) {
  41475. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  41476. }
  41477. if (parsedVertexData.hasUVs6) {
  41478. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  41479. }
  41480. if (parsedVertexData.hasColors) {
  41481. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  41482. }
  41483. if (parsedVertexData.hasMatricesIndices) {
  41484. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  41485. }
  41486. if (parsedVertexData.hasMatricesWeights) {
  41487. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  41488. }
  41489. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  41490. }
  41491. else {
  41492. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  41493. }
  41494. scene.pushGeometry(geometry, true);
  41495. return geometry;
  41496. };
  41497. return Geometry;
  41498. }());
  41499. BABYLON.Geometry = Geometry;
  41500. /////// Primitives //////////////////////////////////////////////
  41501. (function (Geometry) {
  41502. var Primitives;
  41503. (function (Primitives) {
  41504. /// Abstract class
  41505. var _Primitive = (function (_super) {
  41506. __extends(_Primitive, _super);
  41507. function _Primitive(id, scene, _canBeRegenerated, mesh) {
  41508. var _this = _super.call(this, id, scene, null, false, mesh) || this;
  41509. _this._canBeRegenerated = _canBeRegenerated;
  41510. _this._beingRegenerated = true;
  41511. _this.regenerate();
  41512. _this._beingRegenerated = false;
  41513. return _this;
  41514. }
  41515. _Primitive.prototype.canBeRegenerated = function () {
  41516. return this._canBeRegenerated;
  41517. };
  41518. _Primitive.prototype.regenerate = function () {
  41519. if (!this._canBeRegenerated) {
  41520. return;
  41521. }
  41522. this._beingRegenerated = true;
  41523. this.setAllVerticesData(this._regenerateVertexData(), false);
  41524. this._beingRegenerated = false;
  41525. };
  41526. _Primitive.prototype.asNewGeometry = function (id) {
  41527. return _super.prototype.copy.call(this, id);
  41528. };
  41529. // overrides
  41530. _Primitive.prototype.setAllVerticesData = function (vertexData, updatable) {
  41531. if (!this._beingRegenerated) {
  41532. return;
  41533. }
  41534. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  41535. };
  41536. _Primitive.prototype.setVerticesData = function (kind, data, updatable) {
  41537. if (!this._beingRegenerated) {
  41538. return;
  41539. }
  41540. _super.prototype.setVerticesData.call(this, kind, data, false);
  41541. };
  41542. // to override
  41543. // protected
  41544. _Primitive.prototype._regenerateVertexData = function () {
  41545. throw new Error("Abstract method");
  41546. };
  41547. _Primitive.prototype.copy = function (id) {
  41548. throw new Error("Must be overriden in sub-classes.");
  41549. };
  41550. _Primitive.prototype.serialize = function () {
  41551. var serializationObject = _super.prototype.serialize.call(this);
  41552. serializationObject.canBeRegenerated = this.canBeRegenerated();
  41553. return serializationObject;
  41554. };
  41555. return _Primitive;
  41556. }(Geometry));
  41557. Primitives._Primitive = _Primitive;
  41558. var Ribbon = (function (_super) {
  41559. __extends(Ribbon, _super);
  41560. // Members
  41561. function Ribbon(id, scene, pathArray, closeArray, closePath, offset, canBeRegenerated, mesh, side) {
  41562. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  41563. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  41564. _this.pathArray = pathArray;
  41565. _this.closeArray = closeArray;
  41566. _this.closePath = closePath;
  41567. _this.offset = offset;
  41568. _this.side = side;
  41569. return _this;
  41570. }
  41571. Ribbon.prototype._regenerateVertexData = function () {
  41572. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  41573. };
  41574. Ribbon.prototype.copy = function (id) {
  41575. return new Ribbon(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), null, this.side);
  41576. };
  41577. return Ribbon;
  41578. }(_Primitive));
  41579. Primitives.Ribbon = Ribbon;
  41580. var Box = (function (_super) {
  41581. __extends(Box, _super);
  41582. // Members
  41583. function Box(id, scene, size, canBeRegenerated, mesh, side) {
  41584. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  41585. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  41586. _this.size = size;
  41587. _this.side = side;
  41588. return _this;
  41589. }
  41590. Box.prototype._regenerateVertexData = function () {
  41591. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  41592. };
  41593. Box.prototype.copy = function (id) {
  41594. return new Box(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  41595. };
  41596. Box.prototype.serialize = function () {
  41597. var serializationObject = _super.prototype.serialize.call(this);
  41598. serializationObject.size = this.size;
  41599. return serializationObject;
  41600. };
  41601. Box.Parse = function (parsedBox, scene) {
  41602. if (scene.getGeometryByID(parsedBox.id)) {
  41603. return null; // null since geometry could be something else than a box...
  41604. }
  41605. var box = new Geometry.Primitives.Box(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  41606. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  41607. scene.pushGeometry(box, true);
  41608. return box;
  41609. };
  41610. return Box;
  41611. }(_Primitive));
  41612. Primitives.Box = Box;
  41613. var Sphere = (function (_super) {
  41614. __extends(Sphere, _super);
  41615. function Sphere(id, scene, segments, diameter, canBeRegenerated, mesh, side) {
  41616. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  41617. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  41618. _this.segments = segments;
  41619. _this.diameter = diameter;
  41620. _this.side = side;
  41621. return _this;
  41622. }
  41623. Sphere.prototype._regenerateVertexData = function () {
  41624. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  41625. };
  41626. Sphere.prototype.copy = function (id) {
  41627. return new Sphere(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  41628. };
  41629. Sphere.prototype.serialize = function () {
  41630. var serializationObject = _super.prototype.serialize.call(this);
  41631. serializationObject.segments = this.segments;
  41632. serializationObject.diameter = this.diameter;
  41633. return serializationObject;
  41634. };
  41635. Sphere.Parse = function (parsedSphere, scene) {
  41636. if (scene.getGeometryByID(parsedSphere.id)) {
  41637. return null; // null since geometry could be something else than a sphere...
  41638. }
  41639. var sphere = new Geometry.Primitives.Sphere(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  41640. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  41641. scene.pushGeometry(sphere, true);
  41642. return sphere;
  41643. };
  41644. return Sphere;
  41645. }(_Primitive));
  41646. Primitives.Sphere = Sphere;
  41647. var Disc = (function (_super) {
  41648. __extends(Disc, _super);
  41649. // Members
  41650. function Disc(id, scene, radius, tessellation, canBeRegenerated, mesh, side) {
  41651. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  41652. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  41653. _this.radius = radius;
  41654. _this.tessellation = tessellation;
  41655. _this.side = side;
  41656. return _this;
  41657. }
  41658. Disc.prototype._regenerateVertexData = function () {
  41659. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  41660. };
  41661. Disc.prototype.copy = function (id) {
  41662. return new Disc(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  41663. };
  41664. return Disc;
  41665. }(_Primitive));
  41666. Primitives.Disc = Disc;
  41667. var Cylinder = (function (_super) {
  41668. __extends(Cylinder, _super);
  41669. function Cylinder(id, scene, height, diameterTop, diameterBottom, tessellation, subdivisions, canBeRegenerated, mesh, side) {
  41670. if (subdivisions === void 0) { subdivisions = 1; }
  41671. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  41672. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  41673. _this.height = height;
  41674. _this.diameterTop = diameterTop;
  41675. _this.diameterBottom = diameterBottom;
  41676. _this.tessellation = tessellation;
  41677. _this.subdivisions = subdivisions;
  41678. _this.side = side;
  41679. return _this;
  41680. }
  41681. Cylinder.prototype._regenerateVertexData = function () {
  41682. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  41683. };
  41684. Cylinder.prototype.copy = function (id) {
  41685. return new Cylinder(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  41686. };
  41687. Cylinder.prototype.serialize = function () {
  41688. var serializationObject = _super.prototype.serialize.call(this);
  41689. serializationObject.height = this.height;
  41690. serializationObject.diameterTop = this.diameterTop;
  41691. serializationObject.diameterBottom = this.diameterBottom;
  41692. serializationObject.tessellation = this.tessellation;
  41693. return serializationObject;
  41694. };
  41695. Cylinder.Parse = function (parsedCylinder, scene) {
  41696. if (scene.getGeometryByID(parsedCylinder.id)) {
  41697. return null; // null since geometry could be something else than a cylinder...
  41698. }
  41699. var cylinder = new Geometry.Primitives.Cylinder(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  41700. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  41701. scene.pushGeometry(cylinder, true);
  41702. return cylinder;
  41703. };
  41704. return Cylinder;
  41705. }(_Primitive));
  41706. Primitives.Cylinder = Cylinder;
  41707. var Torus = (function (_super) {
  41708. __extends(Torus, _super);
  41709. function Torus(id, scene, diameter, thickness, tessellation, canBeRegenerated, mesh, side) {
  41710. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  41711. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  41712. _this.diameter = diameter;
  41713. _this.thickness = thickness;
  41714. _this.tessellation = tessellation;
  41715. _this.side = side;
  41716. return _this;
  41717. }
  41718. Torus.prototype._regenerateVertexData = function () {
  41719. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  41720. };
  41721. Torus.prototype.copy = function (id) {
  41722. return new Torus(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  41723. };
  41724. Torus.prototype.serialize = function () {
  41725. var serializationObject = _super.prototype.serialize.call(this);
  41726. serializationObject.diameter = this.diameter;
  41727. serializationObject.thickness = this.thickness;
  41728. serializationObject.tessellation = this.tessellation;
  41729. return serializationObject;
  41730. };
  41731. Torus.Parse = function (parsedTorus, scene) {
  41732. if (scene.getGeometryByID(parsedTorus.id)) {
  41733. return null; // null since geometry could be something else than a torus...
  41734. }
  41735. var torus = new Geometry.Primitives.Torus(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  41736. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  41737. scene.pushGeometry(torus, true);
  41738. return torus;
  41739. };
  41740. return Torus;
  41741. }(_Primitive));
  41742. Primitives.Torus = Torus;
  41743. var Ground = (function (_super) {
  41744. __extends(Ground, _super);
  41745. function Ground(id, scene, width, height, subdivisions, canBeRegenerated, mesh) {
  41746. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  41747. _this.width = width;
  41748. _this.height = height;
  41749. _this.subdivisions = subdivisions;
  41750. return _this;
  41751. }
  41752. Ground.prototype._regenerateVertexData = function () {
  41753. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  41754. };
  41755. Ground.prototype.copy = function (id) {
  41756. return new Ground(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  41757. };
  41758. Ground.prototype.serialize = function () {
  41759. var serializationObject = _super.prototype.serialize.call(this);
  41760. serializationObject.width = this.width;
  41761. serializationObject.height = this.height;
  41762. serializationObject.subdivisions = this.subdivisions;
  41763. return serializationObject;
  41764. };
  41765. Ground.Parse = function (parsedGround, scene) {
  41766. if (scene.getGeometryByID(parsedGround.id)) {
  41767. return null; // null since geometry could be something else than a ground...
  41768. }
  41769. var ground = new Geometry.Primitives.Ground(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  41770. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  41771. scene.pushGeometry(ground, true);
  41772. return ground;
  41773. };
  41774. return Ground;
  41775. }(_Primitive));
  41776. Primitives.Ground = Ground;
  41777. var TiledGround = (function (_super) {
  41778. __extends(TiledGround, _super);
  41779. function TiledGround(id, scene, xmin, zmin, xmax, zmax, subdivisions, precision, canBeRegenerated, mesh) {
  41780. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  41781. _this.xmin = xmin;
  41782. _this.zmin = zmin;
  41783. _this.xmax = xmax;
  41784. _this.zmax = zmax;
  41785. _this.subdivisions = subdivisions;
  41786. _this.precision = precision;
  41787. return _this;
  41788. }
  41789. TiledGround.prototype._regenerateVertexData = function () {
  41790. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  41791. };
  41792. TiledGround.prototype.copy = function (id) {
  41793. return new TiledGround(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  41794. };
  41795. return TiledGround;
  41796. }(_Primitive));
  41797. Primitives.TiledGround = TiledGround;
  41798. var Plane = (function (_super) {
  41799. __extends(Plane, _super);
  41800. function Plane(id, scene, size, canBeRegenerated, mesh, side) {
  41801. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  41802. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  41803. _this.size = size;
  41804. _this.side = side;
  41805. return _this;
  41806. }
  41807. Plane.prototype._regenerateVertexData = function () {
  41808. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  41809. };
  41810. Plane.prototype.copy = function (id) {
  41811. return new Plane(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  41812. };
  41813. Plane.prototype.serialize = function () {
  41814. var serializationObject = _super.prototype.serialize.call(this);
  41815. serializationObject.size = this.size;
  41816. return serializationObject;
  41817. };
  41818. Plane.Parse = function (parsedPlane, scene) {
  41819. if (scene.getGeometryByID(parsedPlane.id)) {
  41820. return null; // null since geometry could be something else than a ground...
  41821. }
  41822. var plane = new Geometry.Primitives.Plane(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  41823. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  41824. scene.pushGeometry(plane, true);
  41825. return plane;
  41826. };
  41827. return Plane;
  41828. }(_Primitive));
  41829. Primitives.Plane = Plane;
  41830. var TorusKnot = (function (_super) {
  41831. __extends(TorusKnot, _super);
  41832. function TorusKnot(id, scene, radius, tube, radialSegments, tubularSegments, p, q, canBeRegenerated, mesh, side) {
  41833. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  41834. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  41835. _this.radius = radius;
  41836. _this.tube = tube;
  41837. _this.radialSegments = radialSegments;
  41838. _this.tubularSegments = tubularSegments;
  41839. _this.p = p;
  41840. _this.q = q;
  41841. _this.side = side;
  41842. return _this;
  41843. }
  41844. TorusKnot.prototype._regenerateVertexData = function () {
  41845. 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 });
  41846. };
  41847. TorusKnot.prototype.copy = function (id) {
  41848. return new TorusKnot(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  41849. };
  41850. TorusKnot.prototype.serialize = function () {
  41851. var serializationObject = _super.prototype.serialize.call(this);
  41852. serializationObject.radius = this.radius;
  41853. serializationObject.tube = this.tube;
  41854. serializationObject.radialSegments = this.radialSegments;
  41855. serializationObject.tubularSegments = this.tubularSegments;
  41856. serializationObject.p = this.p;
  41857. serializationObject.q = this.q;
  41858. return serializationObject;
  41859. };
  41860. ;
  41861. TorusKnot.Parse = function (parsedTorusKnot, scene) {
  41862. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  41863. return null; // null since geometry could be something else than a ground...
  41864. }
  41865. var torusKnot = new Geometry.Primitives.TorusKnot(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  41866. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  41867. scene.pushGeometry(torusKnot, true);
  41868. return torusKnot;
  41869. };
  41870. return TorusKnot;
  41871. }(_Primitive));
  41872. Primitives.TorusKnot = TorusKnot;
  41873. })(Primitives = Geometry.Primitives || (Geometry.Primitives = {}));
  41874. })(Geometry = BABYLON.Geometry || (BABYLON.Geometry = {}));
  41875. })(BABYLON || (BABYLON = {}));
  41876. //# sourceMappingURL=babylon.geometry.js.map
  41877. /// <reference path="babylon.mesh.ts" />
  41878. var BABYLON;
  41879. (function (BABYLON) {
  41880. var GroundMesh = (function (_super) {
  41881. __extends(GroundMesh, _super);
  41882. function GroundMesh(name, scene) {
  41883. var _this = _super.call(this, name, scene) || this;
  41884. _this.generateOctree = false;
  41885. _this._worldInverse = new BABYLON.Matrix();
  41886. return _this;
  41887. }
  41888. GroundMesh.prototype.getClassName = function () {
  41889. return "GroundMesh";
  41890. };
  41891. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  41892. get: function () {
  41893. return Math.min(this._subdivisionsX, this._subdivisionsY);
  41894. },
  41895. enumerable: true,
  41896. configurable: true
  41897. });
  41898. Object.defineProperty(GroundMesh.prototype, "subdivisionsX", {
  41899. get: function () {
  41900. return this._subdivisionsX;
  41901. },
  41902. enumerable: true,
  41903. configurable: true
  41904. });
  41905. Object.defineProperty(GroundMesh.prototype, "subdivisionsY", {
  41906. get: function () {
  41907. return this._subdivisionsY;
  41908. },
  41909. enumerable: true,
  41910. configurable: true
  41911. });
  41912. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  41913. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  41914. this._subdivisionsX = chunksCount;
  41915. this._subdivisionsY = chunksCount;
  41916. this.subdivide(chunksCount);
  41917. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  41918. };
  41919. /**
  41920. * Returns a height (y) value in the Worl system :
  41921. * the ground altitude at the coordinates (x, z) expressed in the World system.
  41922. * Returns the ground y position if (x, z) are outside the ground surface.
  41923. */
  41924. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  41925. var world = this.getWorldMatrix();
  41926. var invMat = BABYLON.Tmp.Matrix[5];
  41927. world.invertToRef(invMat);
  41928. var tmpVect = BABYLON.Tmp.Vector3[8];
  41929. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, invMat, tmpVect); // transform x,z in the mesh local space
  41930. x = tmpVect.x;
  41931. z = tmpVect.z;
  41932. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  41933. return this.position.y;
  41934. }
  41935. if (!this._heightQuads || this._heightQuads.length == 0) {
  41936. this._initHeightQuads();
  41937. this._computeHeightQuads();
  41938. }
  41939. var facet = this._getFacetAt(x, z);
  41940. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  41941. // return y in the World system
  41942. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0.0, y, 0.0, world, tmpVect);
  41943. return tmpVect.y;
  41944. };
  41945. /**
  41946. * Returns a normalized vector (Vector3) orthogonal to the ground
  41947. * at the ground coordinates (x, z) expressed in the World system.
  41948. * Returns Vector3(0.0, 1.0, 0.0) if (x, z) are outside the ground surface.
  41949. */
  41950. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  41951. var normal = new BABYLON.Vector3(0.0, 1.0, 0.0);
  41952. this.getNormalAtCoordinatesToRef(x, z, normal);
  41953. return normal;
  41954. };
  41955. /**
  41956. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  41957. * at the ground coordinates (x, z) expressed in the World system.
  41958. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  41959. * Returns the GroundMesh.
  41960. */
  41961. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  41962. var world = this.getWorldMatrix();
  41963. var tmpMat = BABYLON.Tmp.Matrix[5];
  41964. world.invertToRef(tmpMat);
  41965. var tmpVect = BABYLON.Tmp.Vector3[8];
  41966. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, tmpMat, tmpVect); // transform x,z in the mesh local space
  41967. x = tmpVect.x;
  41968. z = tmpVect.z;
  41969. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  41970. return this;
  41971. }
  41972. if (!this._heightQuads || this._heightQuads.length == 0) {
  41973. this._initHeightQuads();
  41974. this._computeHeightQuads();
  41975. }
  41976. var facet = this._getFacetAt(x, z);
  41977. BABYLON.Vector3.TransformNormalFromFloatsToRef(facet.x, facet.y, facet.z, world, ref);
  41978. return this;
  41979. };
  41980. /**
  41981. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  41982. * if the ground has been updated.
  41983. * This can be used in the render loop.
  41984. * Returns the GroundMesh.
  41985. */
  41986. GroundMesh.prototype.updateCoordinateHeights = function () {
  41987. if (!this._heightQuads || this._heightQuads.length == 0) {
  41988. this._initHeightQuads();
  41989. }
  41990. this._computeHeightQuads();
  41991. return this;
  41992. };
  41993. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  41994. GroundMesh.prototype._getFacetAt = function (x, z) {
  41995. // retrieve col and row from x, z coordinates in the ground local system
  41996. var subdivisionsX = this._subdivisionsX;
  41997. var subdivisionsY = this._subdivisionsY;
  41998. var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);
  41999. var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);
  42000. var quad = this._heightQuads[row * this._subdivisionsX + col];
  42001. var facet;
  42002. if (z < quad.slope.x * x + quad.slope.y) {
  42003. facet = quad.facet1;
  42004. }
  42005. else {
  42006. facet = quad.facet2;
  42007. }
  42008. return facet;
  42009. };
  42010. // Creates and populates the heightMap array with "facet" elements :
  42011. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  42012. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  42013. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  42014. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  42015. // Returns the GroundMesh.
  42016. GroundMesh.prototype._initHeightQuads = function () {
  42017. var subdivisionsX = this._subdivisionsX;
  42018. var subdivisionsY = this._subdivisionsY;
  42019. this._heightQuads = new Array();
  42020. for (var row = 0; row < subdivisionsY; row++) {
  42021. for (var col = 0; col < subdivisionsX; col++) {
  42022. 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) };
  42023. this._heightQuads[row * subdivisionsX + col] = quad;
  42024. }
  42025. }
  42026. return this;
  42027. };
  42028. // Compute each quad element values and update the the heightMap array :
  42029. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  42030. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  42031. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  42032. // Returns the GroundMesh.
  42033. GroundMesh.prototype._computeHeightQuads = function () {
  42034. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  42035. var v1 = BABYLON.Tmp.Vector3[3];
  42036. var v2 = BABYLON.Tmp.Vector3[2];
  42037. var v3 = BABYLON.Tmp.Vector3[1];
  42038. var v4 = BABYLON.Tmp.Vector3[0];
  42039. var v1v2 = BABYLON.Tmp.Vector3[4];
  42040. var v1v3 = BABYLON.Tmp.Vector3[5];
  42041. var v1v4 = BABYLON.Tmp.Vector3[6];
  42042. var norm1 = BABYLON.Tmp.Vector3[7];
  42043. var norm2 = BABYLON.Tmp.Vector3[8];
  42044. var i = 0;
  42045. var j = 0;
  42046. var k = 0;
  42047. var cd = 0; // 2D slope coefficient : z = cd * x + h
  42048. var h = 0;
  42049. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  42050. var d2 = 0;
  42051. var subdivisionsX = this._subdivisionsX;
  42052. var subdivisionsY = this._subdivisionsY;
  42053. for (var row = 0; row < subdivisionsY; row++) {
  42054. for (var col = 0; col < subdivisionsX; col++) {
  42055. i = col * 3;
  42056. j = row * (subdivisionsX + 1) * 3;
  42057. k = (row + 1) * (subdivisionsX + 1) * 3;
  42058. v1.x = positions[j + i];
  42059. v1.y = positions[j + i + 1];
  42060. v1.z = positions[j + i + 2];
  42061. v2.x = positions[j + i + 3];
  42062. v2.y = positions[j + i + 4];
  42063. v2.z = positions[j + i + 5];
  42064. v3.x = positions[k + i];
  42065. v3.y = positions[k + i + 1];
  42066. v3.z = positions[k + i + 2];
  42067. v4.x = positions[k + i + 3];
  42068. v4.y = positions[k + i + 4];
  42069. v4.z = positions[k + i + 5];
  42070. // 2D slope V1V4
  42071. cd = (v4.z - v1.z) / (v4.x - v1.x);
  42072. h = v1.z - cd * v1.x; // v1 belongs to the slope
  42073. // facet equations :
  42074. // we compute each facet normal vector
  42075. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  42076. // we compute the value d by applying the equation to v1 which belongs to the plane
  42077. // then we store the facet equation in a Vector4
  42078. v2.subtractToRef(v1, v1v2);
  42079. v3.subtractToRef(v1, v1v3);
  42080. v4.subtractToRef(v1, v1v4);
  42081. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  42082. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  42083. norm1.normalize();
  42084. norm2.normalize();
  42085. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  42086. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  42087. var quad = this._heightQuads[row * subdivisionsX + col];
  42088. quad.slope.copyFromFloats(cd, h);
  42089. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  42090. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  42091. }
  42092. }
  42093. return this;
  42094. };
  42095. GroundMesh.prototype.serialize = function (serializationObject) {
  42096. _super.prototype.serialize.call(this, serializationObject);
  42097. serializationObject.subdivisionsX = this._subdivisionsX;
  42098. serializationObject.subdivisionsY = this._subdivisionsY;
  42099. serializationObject.minX = this._minX;
  42100. serializationObject.maxX = this._maxX;
  42101. serializationObject.minZ = this._minZ;
  42102. serializationObject.maxZ = this._maxZ;
  42103. serializationObject.width = this._width;
  42104. serializationObject.height = this._height;
  42105. };
  42106. GroundMesh.Parse = function (parsedMesh, scene) {
  42107. var result = new GroundMesh(parsedMesh.name, scene);
  42108. result._subdivisionsX = parsedMesh.subdivisionsX || 1;
  42109. result._subdivisionsY = parsedMesh.subdivisionsY || 1;
  42110. result._minX = parsedMesh.minX;
  42111. result._maxX = parsedMesh.maxX;
  42112. result._minZ = parsedMesh.minZ;
  42113. result._maxZ = parsedMesh.maxZ;
  42114. result._width = parsedMesh.width;
  42115. result._height = parsedMesh.height;
  42116. return result;
  42117. };
  42118. return GroundMesh;
  42119. }(BABYLON.Mesh));
  42120. BABYLON.GroundMesh = GroundMesh;
  42121. })(BABYLON || (BABYLON = {}));
  42122. //# sourceMappingURL=babylon.groundMesh.js.map
  42123. /// <reference path="babylon.mesh.ts" />
  42124. var BABYLON;
  42125. (function (BABYLON) {
  42126. var LinesMesh = (function (_super) {
  42127. __extends(LinesMesh, _super);
  42128. function LinesMesh(name, scene, parent, source, doNotCloneChildren) {
  42129. if (parent === void 0) { parent = null; }
  42130. var _this = _super.call(this, name, scene, parent, source, doNotCloneChildren) || this;
  42131. _this.color = new BABYLON.Color3(1, 1, 1);
  42132. _this.alpha = 1;
  42133. _this._positionBuffer = {};
  42134. if (source) {
  42135. _this.color = source.color.clone();
  42136. _this.alpha = source.alpha;
  42137. }
  42138. _this._intersectionThreshold = 0.1;
  42139. _this._colorShader = new BABYLON.ShaderMaterial("colorShader", scene, "color", {
  42140. attributes: [BABYLON.VertexBuffer.PositionKind],
  42141. uniforms: ["worldViewProjection", "color"],
  42142. needAlphaBlending: true
  42143. });
  42144. _this._positionBuffer[BABYLON.VertexBuffer.PositionKind] = null;
  42145. return _this;
  42146. }
  42147. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  42148. /**
  42149. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  42150. * This margin is expressed in world space coordinates, so its value may vary.
  42151. * Default value is 0.1
  42152. * @returns the intersection Threshold value.
  42153. */
  42154. get: function () {
  42155. return this._intersectionThreshold;
  42156. },
  42157. /**
  42158. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  42159. * This margin is expressed in world space coordinates, so its value may vary.
  42160. * @param value the new threshold to apply
  42161. */
  42162. set: function (value) {
  42163. if (this._intersectionThreshold === value) {
  42164. return;
  42165. }
  42166. this._intersectionThreshold = value;
  42167. if (this.geometry) {
  42168. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  42169. }
  42170. },
  42171. enumerable: true,
  42172. configurable: true
  42173. });
  42174. /**
  42175. * Returns the string "LineMesh"
  42176. */
  42177. LinesMesh.prototype.getClassName = function () {
  42178. return "LinesMesh";
  42179. };
  42180. Object.defineProperty(LinesMesh.prototype, "material", {
  42181. get: function () {
  42182. return this._colorShader;
  42183. },
  42184. enumerable: true,
  42185. configurable: true
  42186. });
  42187. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  42188. get: function () {
  42189. return false;
  42190. },
  42191. enumerable: true,
  42192. configurable: true
  42193. });
  42194. LinesMesh.prototype.createInstance = function (name) {
  42195. BABYLON.Tools.Log("LinesMeshes do not support createInstance.");
  42196. return null;
  42197. };
  42198. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  42199. var engine = this.getScene().getEngine();
  42200. this._positionBuffer[BABYLON.VertexBuffer.PositionKind] = this._geometry.getVertexBuffer(BABYLON.VertexBuffer.PositionKind);
  42201. // VBOs
  42202. engine.bindBuffers(this._positionBuffer, this._geometry.getIndexBuffer(), this._colorShader.getEffect());
  42203. // Color
  42204. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  42205. return this;
  42206. };
  42207. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  42208. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  42209. return this;
  42210. }
  42211. var engine = this.getScene().getEngine();
  42212. // Draw order
  42213. engine.draw(false, subMesh.indexStart, subMesh.indexCount);
  42214. return this;
  42215. };
  42216. LinesMesh.prototype.dispose = function (doNotRecurse) {
  42217. this._colorShader.dispose();
  42218. _super.prototype.dispose.call(this, doNotRecurse);
  42219. };
  42220. /**
  42221. * Returns a new LineMesh object cloned from the current one.
  42222. */
  42223. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  42224. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  42225. };
  42226. return LinesMesh;
  42227. }(BABYLON.Mesh));
  42228. BABYLON.LinesMesh = LinesMesh;
  42229. })(BABYLON || (BABYLON = {}));
  42230. //# sourceMappingURL=babylon.linesMesh.js.map
  42231. var BABYLON;
  42232. (function (BABYLON) {
  42233. var DefaultLoadingScreen = (function () {
  42234. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  42235. if (_loadingText === void 0) { _loadingText = ""; }
  42236. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  42237. var _this = this;
  42238. this._renderingCanvas = _renderingCanvas;
  42239. this._loadingText = _loadingText;
  42240. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  42241. // Resize
  42242. this._resizeLoadingUI = function () {
  42243. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  42244. _this._loadingDiv.style.position = "absolute";
  42245. _this._loadingDiv.style.left = canvasRect.left + "px";
  42246. _this._loadingDiv.style.top = canvasRect.top + "px";
  42247. _this._loadingDiv.style.width = canvasRect.width + "px";
  42248. _this._loadingDiv.style.height = canvasRect.height + "px";
  42249. };
  42250. }
  42251. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  42252. var _this = this;
  42253. if (this._loadingDiv) {
  42254. // Do not add a loading screen if there is already one
  42255. return;
  42256. }
  42257. this._loadingDiv = document.createElement("div");
  42258. this._loadingDiv.id = "babylonjsLoadingDiv";
  42259. this._loadingDiv.style.opacity = "0";
  42260. this._loadingDiv.style.transition = "opacity 1.5s ease";
  42261. // Loading text
  42262. this._loadingTextDiv = document.createElement("div");
  42263. this._loadingTextDiv.style.position = "absolute";
  42264. this._loadingTextDiv.style.left = "0";
  42265. this._loadingTextDiv.style.top = "50%";
  42266. this._loadingTextDiv.style.marginTop = "80px";
  42267. this._loadingTextDiv.style.width = "100%";
  42268. this._loadingTextDiv.style.height = "20px";
  42269. this._loadingTextDiv.style.fontFamily = "Arial";
  42270. this._loadingTextDiv.style.fontSize = "14px";
  42271. this._loadingTextDiv.style.color = "white";
  42272. this._loadingTextDiv.style.textAlign = "center";
  42273. this._loadingTextDiv.innerHTML = "Loading";
  42274. this._loadingDiv.appendChild(this._loadingTextDiv);
  42275. //set the predefined text
  42276. this._loadingTextDiv.innerHTML = this._loadingText;
  42277. // Loading img
  42278. var imgBack = new Image();
  42279. 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==";
  42280. imgBack.style.position = "absolute";
  42281. imgBack.style.left = "50%";
  42282. imgBack.style.top = "50%";
  42283. imgBack.style.marginLeft = "-50px";
  42284. imgBack.style.marginTop = "-50px";
  42285. imgBack.style.transition = "transform 1.0s ease";
  42286. imgBack.style.webkitTransition = "-webkit-transform 1.0s ease";
  42287. var deg = 360;
  42288. var onTransitionEnd = function () {
  42289. deg += 360;
  42290. imgBack.style.transform = "rotateZ(" + deg + "deg)";
  42291. imgBack.style.webkitTransform = "rotateZ(" + deg + "deg)";
  42292. };
  42293. imgBack.addEventListener("transitionend", onTransitionEnd);
  42294. imgBack.addEventListener("webkitTransitionEnd", onTransitionEnd);
  42295. this._loadingDiv.appendChild(imgBack);
  42296. // front image
  42297. var imgFront = new Image();
  42298. 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=";
  42299. imgFront.style.position = "absolute";
  42300. imgFront.style.left = "50%";
  42301. imgFront.style.top = "50%";
  42302. imgFront.style.marginLeft = "-50px";
  42303. imgFront.style.marginTop = "-50px";
  42304. this._loadingDiv.appendChild(imgFront);
  42305. this._resizeLoadingUI();
  42306. window.addEventListener("resize", this._resizeLoadingUI);
  42307. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  42308. document.body.appendChild(this._loadingDiv);
  42309. setTimeout(function () {
  42310. _this._loadingDiv.style.opacity = "1";
  42311. imgBack.style.transform = "rotateZ(360deg)";
  42312. imgBack.style.webkitTransform = "rotateZ(360deg)";
  42313. }, 0);
  42314. };
  42315. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  42316. var _this = this;
  42317. if (!this._loadingDiv) {
  42318. return;
  42319. }
  42320. var onTransitionEnd = function () {
  42321. if (!_this._loadingDiv) {
  42322. return;
  42323. }
  42324. document.body.removeChild(_this._loadingDiv);
  42325. window.removeEventListener("resize", _this._resizeLoadingUI);
  42326. _this._loadingDiv = null;
  42327. };
  42328. this._loadingDiv.style.opacity = "0";
  42329. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  42330. };
  42331. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  42332. set: function (text) {
  42333. this._loadingText = text;
  42334. if (this._loadingTextDiv) {
  42335. this._loadingTextDiv.innerHTML = this._loadingText;
  42336. }
  42337. },
  42338. enumerable: true,
  42339. configurable: true
  42340. });
  42341. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  42342. get: function () {
  42343. return this._loadingDivBackgroundColor;
  42344. },
  42345. set: function (color) {
  42346. this._loadingDivBackgroundColor = color;
  42347. if (!this._loadingDiv) {
  42348. return;
  42349. }
  42350. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  42351. },
  42352. enumerable: true,
  42353. configurable: true
  42354. });
  42355. return DefaultLoadingScreen;
  42356. }());
  42357. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  42358. })(BABYLON || (BABYLON = {}));
  42359. //# sourceMappingURL=babylon.loadingScreen.js.map
  42360. var BABYLON;
  42361. (function (BABYLON) {
  42362. var AudioEngine = (function () {
  42363. function AudioEngine() {
  42364. this._audioContext = null;
  42365. this._audioContextInitialized = false;
  42366. this.canUseWebAudio = false;
  42367. this.WarnedWebAudioUnsupported = false;
  42368. this.unlocked = false;
  42369. this.isMP3supported = false;
  42370. this.isOGGsupported = false;
  42371. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  42372. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  42373. this.canUseWebAudio = true;
  42374. }
  42375. var audioElem = document.createElement('audio');
  42376. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/, '')) {
  42377. this.isMP3supported = true;
  42378. }
  42379. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) {
  42380. this.isOGGsupported = true;
  42381. }
  42382. if (/iPad|iPhone|iPod/.test(navigator.platform)) {
  42383. this._unlockiOSaudio();
  42384. }
  42385. else {
  42386. this.unlocked = true;
  42387. }
  42388. }
  42389. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  42390. get: function () {
  42391. if (!this._audioContextInitialized) {
  42392. this._initializeAudioContext();
  42393. }
  42394. return this._audioContext;
  42395. },
  42396. enumerable: true,
  42397. configurable: true
  42398. });
  42399. AudioEngine.prototype._unlockiOSaudio = function () {
  42400. var _this = this;
  42401. var unlockaudio = function () {
  42402. var buffer = _this.audioContext.createBuffer(1, 1, 22050);
  42403. var source = _this.audioContext.createBufferSource();
  42404. source.buffer = buffer;
  42405. source.connect(_this.audioContext.destination);
  42406. source.start(0);
  42407. setTimeout(function () {
  42408. if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
  42409. _this.unlocked = true;
  42410. window.removeEventListener('touchend', unlockaudio, false);
  42411. if (_this.onAudioUnlocked) {
  42412. _this.onAudioUnlocked();
  42413. }
  42414. }
  42415. }, 0);
  42416. };
  42417. window.addEventListener('touchend', unlockaudio, false);
  42418. };
  42419. AudioEngine.prototype._initializeAudioContext = function () {
  42420. try {
  42421. if (this.canUseWebAudio) {
  42422. this._audioContext = new AudioContext();
  42423. // create a global volume gain node
  42424. this.masterGain = this._audioContext.createGain();
  42425. this.masterGain.gain.value = 1;
  42426. this.masterGain.connect(this._audioContext.destination);
  42427. this._audioContextInitialized = true;
  42428. }
  42429. }
  42430. catch (e) {
  42431. this.canUseWebAudio = false;
  42432. BABYLON.Tools.Error("Web Audio: " + e.message);
  42433. }
  42434. };
  42435. AudioEngine.prototype.dispose = function () {
  42436. if (this.canUseWebAudio && this._audioContextInitialized) {
  42437. if (this._connectedAnalyser) {
  42438. this._connectedAnalyser.stopDebugCanvas();
  42439. this._connectedAnalyser.dispose();
  42440. this.masterGain.disconnect();
  42441. this.masterGain.connect(this._audioContext.destination);
  42442. this._connectedAnalyser = null;
  42443. }
  42444. this.masterGain.gain.value = 1;
  42445. }
  42446. this.WarnedWebAudioUnsupported = false;
  42447. };
  42448. AudioEngine.prototype.getGlobalVolume = function () {
  42449. if (this.canUseWebAudio && this._audioContextInitialized) {
  42450. return this.masterGain.gain.value;
  42451. }
  42452. else {
  42453. return -1;
  42454. }
  42455. };
  42456. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  42457. if (this.canUseWebAudio && this._audioContextInitialized) {
  42458. this.masterGain.gain.value = newVolume;
  42459. }
  42460. };
  42461. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  42462. if (this._connectedAnalyser) {
  42463. this._connectedAnalyser.stopDebugCanvas();
  42464. }
  42465. if (this.canUseWebAudio && this._audioContextInitialized) {
  42466. this._connectedAnalyser = analyser;
  42467. this.masterGain.disconnect();
  42468. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  42469. }
  42470. };
  42471. return AudioEngine;
  42472. }());
  42473. BABYLON.AudioEngine = AudioEngine;
  42474. })(BABYLON || (BABYLON = {}));
  42475. //# sourceMappingURL=babylon.audioEngine.js.map
  42476. var BABYLON;
  42477. (function (BABYLON) {
  42478. var Sound = (function () {
  42479. /**
  42480. * Create a sound and attach it to a scene
  42481. * @param name Name of your sound
  42482. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  42483. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  42484. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  42485. */
  42486. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  42487. var _this = this;
  42488. this.autoplay = false;
  42489. this.loop = false;
  42490. this.useCustomAttenuation = false;
  42491. this.spatialSound = false;
  42492. this.refDistance = 1;
  42493. this.rolloffFactor = 1;
  42494. this.maxDistance = 100;
  42495. this.distanceModel = "linear";
  42496. this._panningModel = "equalpower";
  42497. this._playbackRate = 1;
  42498. this._streaming = false;
  42499. this._startTime = 0;
  42500. this._startOffset = 0;
  42501. this._position = BABYLON.Vector3.Zero();
  42502. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  42503. this._volume = 1;
  42504. this._isLoaded = false;
  42505. this._isReadyToPlay = false;
  42506. this.isPlaying = false;
  42507. this.isPaused = false;
  42508. this._isDirectional = false;
  42509. // Used if you'd like to create a directional sound.
  42510. // If not set, the sound will be omnidirectional
  42511. this._coneInnerAngle = 360;
  42512. this._coneOuterAngle = 360;
  42513. this._coneOuterGain = 0;
  42514. this._isOutputConnected = false;
  42515. this._urlType = "Unknown";
  42516. this.name = name;
  42517. this._scene = scene;
  42518. this._readyToPlayCallback = readyToPlayCallback;
  42519. // Default custom attenuation function is a linear attenuation
  42520. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  42521. if (currentDistance < maxDistance) {
  42522. return currentVolume * (1 - currentDistance / maxDistance);
  42523. }
  42524. else {
  42525. return 0;
  42526. }
  42527. };
  42528. if (options) {
  42529. this.autoplay = options.autoplay || false;
  42530. this.loop = options.loop || false;
  42531. // if volume === 0, we need another way to check this option
  42532. if (options.volume !== undefined) {
  42533. this._volume = options.volume;
  42534. }
  42535. this.spatialSound = options.spatialSound || false;
  42536. this.maxDistance = options.maxDistance || 100;
  42537. this.useCustomAttenuation = options.useCustomAttenuation || false;
  42538. this.rolloffFactor = options.rolloffFactor || 1;
  42539. this.refDistance = options.refDistance || 1;
  42540. this.distanceModel = options.distanceModel || "linear";
  42541. this._playbackRate = options.playbackRate || 1;
  42542. this._streaming = options.streaming || false;
  42543. }
  42544. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  42545. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  42546. this._soundGain.gain.value = this._volume;
  42547. this._inputAudioNode = this._soundGain;
  42548. this._ouputAudioNode = this._soundGain;
  42549. if (this.spatialSound) {
  42550. this._createSpatialParameters();
  42551. }
  42552. this._scene.mainSoundTrack.AddSound(this);
  42553. var validParameter = true;
  42554. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  42555. if (urlOrArrayBuffer) {
  42556. if (typeof (urlOrArrayBuffer) === "string")
  42557. this._urlType = "String";
  42558. if (Array.isArray(urlOrArrayBuffer))
  42559. this._urlType = "Array";
  42560. if (urlOrArrayBuffer instanceof ArrayBuffer)
  42561. this._urlType = "ArrayBuffer";
  42562. var urls = [];
  42563. var codecSupportedFound = false;
  42564. switch (this._urlType) {
  42565. case "ArrayBuffer":
  42566. if (urlOrArrayBuffer.byteLength > 0) {
  42567. codecSupportedFound = true;
  42568. this._soundLoaded(urlOrArrayBuffer);
  42569. }
  42570. break;
  42571. case "String":
  42572. urls.push(urlOrArrayBuffer);
  42573. case "Array":
  42574. if (urls.length === 0)
  42575. urls = urlOrArrayBuffer;
  42576. // If we found a supported format, we load it immediately and stop the loop
  42577. for (var i = 0; i < urls.length; i++) {
  42578. var url = urls[i];
  42579. if (url.indexOf(".mp3", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isMP3supported) {
  42580. codecSupportedFound = true;
  42581. }
  42582. if (url.indexOf(".ogg", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isOGGsupported) {
  42583. codecSupportedFound = true;
  42584. }
  42585. if (url.indexOf(".wav", url.length - 4) !== -1) {
  42586. codecSupportedFound = true;
  42587. }
  42588. if (codecSupportedFound) {
  42589. // Loading sound using XHR2
  42590. if (!this._streaming) {
  42591. BABYLON.Tools.LoadFile(url, function (data) { _this._soundLoaded(data); }, null, this._scene.database, true);
  42592. }
  42593. else {
  42594. this._htmlAudioElement = new Audio(url);
  42595. this._htmlAudioElement.controls = false;
  42596. this._htmlAudioElement.loop = this.loop;
  42597. this._htmlAudioElement.crossOrigin = "anonymous";
  42598. this._htmlAudioElement.preload = "auto";
  42599. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  42600. _this._isReadyToPlay = true;
  42601. if (_this.autoplay) {
  42602. _this.play();
  42603. }
  42604. if (_this._readyToPlayCallback) {
  42605. _this._readyToPlayCallback();
  42606. }
  42607. });
  42608. document.body.appendChild(this._htmlAudioElement);
  42609. }
  42610. break;
  42611. }
  42612. }
  42613. break;
  42614. default:
  42615. validParameter = false;
  42616. break;
  42617. }
  42618. if (!validParameter) {
  42619. BABYLON.Tools.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.");
  42620. }
  42621. else {
  42622. if (!codecSupportedFound) {
  42623. this._isReadyToPlay = true;
  42624. // Simulating a ready to play event to avoid breaking code path
  42625. if (this._readyToPlayCallback) {
  42626. window.setTimeout(function () {
  42627. _this._readyToPlayCallback();
  42628. }, 1000);
  42629. }
  42630. }
  42631. }
  42632. }
  42633. }
  42634. else {
  42635. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  42636. this._scene.mainSoundTrack.AddSound(this);
  42637. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  42638. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  42639. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  42640. }
  42641. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  42642. if (this._readyToPlayCallback) {
  42643. window.setTimeout(function () {
  42644. _this._readyToPlayCallback();
  42645. }, 1000);
  42646. }
  42647. }
  42648. }
  42649. Sound.prototype.dispose = function () {
  42650. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isReadyToPlay) {
  42651. if (this.isPlaying) {
  42652. this.stop();
  42653. }
  42654. this._isReadyToPlay = false;
  42655. if (this.soundTrackId === -1) {
  42656. this._scene.mainSoundTrack.RemoveSound(this);
  42657. }
  42658. else {
  42659. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  42660. }
  42661. if (this._soundGain) {
  42662. this._soundGain.disconnect();
  42663. this._soundGain = null;
  42664. }
  42665. if (this._soundPanner) {
  42666. this._soundPanner.disconnect();
  42667. this._soundPanner = null;
  42668. }
  42669. if (this._soundSource) {
  42670. this._soundSource.disconnect();
  42671. this._soundSource = null;
  42672. }
  42673. this._audioBuffer = null;
  42674. if (this._htmlAudioElement) {
  42675. this._htmlAudioElement.pause();
  42676. this._htmlAudioElement.src = "";
  42677. document.body.removeChild(this._htmlAudioElement);
  42678. }
  42679. if (this._connectedMesh) {
  42680. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  42681. this._connectedMesh = null;
  42682. }
  42683. }
  42684. };
  42685. Sound.prototype.isReady = function () {
  42686. return this._isReadyToPlay;
  42687. };
  42688. Sound.prototype._soundLoaded = function (audioData) {
  42689. var _this = this;
  42690. this._isLoaded = true;
  42691. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  42692. _this._audioBuffer = buffer;
  42693. _this._isReadyToPlay = true;
  42694. if (_this.autoplay) {
  42695. _this.play();
  42696. }
  42697. if (_this._readyToPlayCallback) {
  42698. _this._readyToPlayCallback();
  42699. }
  42700. }, function (err) { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name + " / Error: " + err); });
  42701. };
  42702. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  42703. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  42704. this._audioBuffer = audioBuffer;
  42705. this._isReadyToPlay = true;
  42706. }
  42707. };
  42708. Sound.prototype.updateOptions = function (options) {
  42709. if (options) {
  42710. this.loop = options.loop || this.loop;
  42711. this.maxDistance = options.maxDistance || this.maxDistance;
  42712. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  42713. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  42714. this.refDistance = options.refDistance || this.refDistance;
  42715. this.distanceModel = options.distanceModel || this.distanceModel;
  42716. this._playbackRate = options.playbackRate || this._playbackRate;
  42717. this._updateSpatialParameters();
  42718. if (this.isPlaying) {
  42719. if (this._streaming) {
  42720. this._htmlAudioElement.playbackRate = this._playbackRate;
  42721. }
  42722. else {
  42723. this._soundSource.playbackRate.value = this._playbackRate;
  42724. }
  42725. }
  42726. }
  42727. };
  42728. Sound.prototype._createSpatialParameters = function () {
  42729. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  42730. if (this._scene.headphone) {
  42731. this._panningModel = "HRTF";
  42732. }
  42733. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  42734. this._updateSpatialParameters();
  42735. this._soundPanner.connect(this._ouputAudioNode);
  42736. this._inputAudioNode = this._soundPanner;
  42737. }
  42738. };
  42739. Sound.prototype._updateSpatialParameters = function () {
  42740. if (this.spatialSound) {
  42741. if (this.useCustomAttenuation) {
  42742. // Tricks to disable in a way embedded Web Audio attenuation
  42743. this._soundPanner.distanceModel = "linear";
  42744. this._soundPanner.maxDistance = Number.MAX_VALUE;
  42745. this._soundPanner.refDistance = 1;
  42746. this._soundPanner.rolloffFactor = 1;
  42747. this._soundPanner.panningModel = this._panningModel;
  42748. }
  42749. else {
  42750. this._soundPanner.distanceModel = this.distanceModel;
  42751. this._soundPanner.maxDistance = this.maxDistance;
  42752. this._soundPanner.refDistance = this.refDistance;
  42753. this._soundPanner.rolloffFactor = this.rolloffFactor;
  42754. this._soundPanner.panningModel = this._panningModel;
  42755. }
  42756. }
  42757. };
  42758. Sound.prototype.switchPanningModelToHRTF = function () {
  42759. this._panningModel = "HRTF";
  42760. this._switchPanningModel();
  42761. };
  42762. Sound.prototype.switchPanningModelToEqualPower = function () {
  42763. this._panningModel = "equalpower";
  42764. this._switchPanningModel();
  42765. };
  42766. Sound.prototype._switchPanningModel = function () {
  42767. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  42768. this._soundPanner.panningModel = this._panningModel;
  42769. }
  42770. };
  42771. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  42772. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  42773. if (this._isOutputConnected) {
  42774. this._ouputAudioNode.disconnect();
  42775. }
  42776. this._ouputAudioNode.connect(soundTrackAudioNode);
  42777. this._isOutputConnected = true;
  42778. }
  42779. };
  42780. /**
  42781. * Transform this sound into a directional source
  42782. * @param coneInnerAngle Size of the inner cone in degree
  42783. * @param coneOuterAngle Size of the outer cone in degree
  42784. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  42785. */
  42786. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  42787. if (coneOuterAngle < coneInnerAngle) {
  42788. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  42789. return;
  42790. }
  42791. this._coneInnerAngle = coneInnerAngle;
  42792. this._coneOuterAngle = coneOuterAngle;
  42793. this._coneOuterGain = coneOuterGain;
  42794. this._isDirectional = true;
  42795. if (this.isPlaying && this.loop) {
  42796. this.stop();
  42797. this.play();
  42798. }
  42799. };
  42800. Sound.prototype.setPosition = function (newPosition) {
  42801. this._position = newPosition;
  42802. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  42803. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  42804. }
  42805. };
  42806. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  42807. this._localDirection = newLocalDirection;
  42808. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  42809. this._updateDirection();
  42810. }
  42811. };
  42812. Sound.prototype._updateDirection = function () {
  42813. var mat = this._connectedMesh.getWorldMatrix();
  42814. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  42815. direction.normalize();
  42816. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  42817. };
  42818. Sound.prototype.updateDistanceFromListener = function () {
  42819. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation) {
  42820. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  42821. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  42822. }
  42823. };
  42824. Sound.prototype.setAttenuationFunction = function (callback) {
  42825. this._customAttenuationFunction = callback;
  42826. };
  42827. /**
  42828. * Play the sound
  42829. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  42830. * @param offset (optional) Start the sound setting it at a specific time
  42831. */
  42832. Sound.prototype.play = function (time, offset) {
  42833. var _this = this;
  42834. if (this._isReadyToPlay && this._scene.audioEnabled) {
  42835. try {
  42836. if (this._startOffset < 0) {
  42837. time = -this._startOffset;
  42838. this._startOffset = 0;
  42839. }
  42840. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  42841. if (!this._soundSource || !this._streamingSource) {
  42842. if (this.spatialSound) {
  42843. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  42844. if (this._isDirectional) {
  42845. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  42846. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  42847. this._soundPanner.coneOuterGain = this._coneOuterGain;
  42848. if (this._connectedMesh) {
  42849. this._updateDirection();
  42850. }
  42851. else {
  42852. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  42853. }
  42854. }
  42855. }
  42856. }
  42857. if (this._streaming) {
  42858. if (!this._streamingSource) {
  42859. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  42860. this._htmlAudioElement.onended = function () { _this._onended(); };
  42861. this._htmlAudioElement.playbackRate = this._playbackRate;
  42862. }
  42863. this._streamingSource.disconnect();
  42864. this._streamingSource.connect(this._inputAudioNode);
  42865. this._htmlAudioElement.play();
  42866. }
  42867. else {
  42868. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  42869. this._soundSource.buffer = this._audioBuffer;
  42870. this._soundSource.connect(this._inputAudioNode);
  42871. this._soundSource.loop = this.loop;
  42872. this._soundSource.playbackRate.value = this._playbackRate;
  42873. this._soundSource.onended = function () { _this._onended(); };
  42874. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : offset ? offset : 0);
  42875. }
  42876. this._startTime = startTime;
  42877. this.isPlaying = true;
  42878. this.isPaused = false;
  42879. }
  42880. catch (ex) {
  42881. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  42882. }
  42883. }
  42884. };
  42885. Sound.prototype._onended = function () {
  42886. this.isPlaying = false;
  42887. if (this.onended) {
  42888. this.onended();
  42889. }
  42890. };
  42891. /**
  42892. * Stop the sound
  42893. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  42894. */
  42895. Sound.prototype.stop = function (time) {
  42896. if (this.isPlaying) {
  42897. if (this._streaming) {
  42898. this._htmlAudioElement.pause();
  42899. // Test needed for Firefox or it will generate an Invalid State Error
  42900. if (this._htmlAudioElement.currentTime > 0) {
  42901. this._htmlAudioElement.currentTime = 0;
  42902. }
  42903. }
  42904. else {
  42905. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  42906. this._soundSource.stop(stopTime);
  42907. this._soundSource.onended = null;
  42908. if (!this.isPaused) {
  42909. this._startOffset = 0;
  42910. }
  42911. }
  42912. this.isPlaying = false;
  42913. }
  42914. };
  42915. Sound.prototype.pause = function () {
  42916. if (this.isPlaying) {
  42917. this.isPaused = true;
  42918. if (this._streaming) {
  42919. this._htmlAudioElement.pause();
  42920. }
  42921. else {
  42922. this.stop(0);
  42923. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  42924. }
  42925. }
  42926. };
  42927. Sound.prototype.setVolume = function (newVolume, time) {
  42928. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  42929. if (time) {
  42930. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  42931. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  42932. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  42933. }
  42934. else {
  42935. this._soundGain.gain.value = newVolume;
  42936. }
  42937. }
  42938. this._volume = newVolume;
  42939. };
  42940. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  42941. this._playbackRate = newPlaybackRate;
  42942. if (this.isPlaying) {
  42943. if (this._streaming) {
  42944. this._htmlAudioElement.playbackRate = this._playbackRate;
  42945. }
  42946. else {
  42947. this._soundSource.playbackRate.value = this._playbackRate;
  42948. }
  42949. }
  42950. };
  42951. Sound.prototype.getVolume = function () {
  42952. return this._volume;
  42953. };
  42954. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  42955. var _this = this;
  42956. if (this._connectedMesh) {
  42957. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  42958. this._registerFunc = null;
  42959. }
  42960. this._connectedMesh = meshToConnectTo;
  42961. if (!this.spatialSound) {
  42962. this.spatialSound = true;
  42963. this._createSpatialParameters();
  42964. if (this.isPlaying && this.loop) {
  42965. this.stop();
  42966. this.play();
  42967. }
  42968. }
  42969. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  42970. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  42971. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  42972. };
  42973. Sound.prototype.detachFromMesh = function () {
  42974. if (this._connectedMesh) {
  42975. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  42976. this._registerFunc = null;
  42977. this._connectedMesh = null;
  42978. }
  42979. };
  42980. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (connectedMesh) {
  42981. this.setPosition(connectedMesh.getBoundingInfo().boundingSphere.centerWorld);
  42982. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  42983. this._updateDirection();
  42984. }
  42985. };
  42986. Sound.prototype.clone = function () {
  42987. var _this = this;
  42988. if (!this._streaming) {
  42989. var setBufferAndRun = function () {
  42990. if (_this._isReadyToPlay) {
  42991. clonedSound._audioBuffer = _this.getAudioBuffer();
  42992. clonedSound._isReadyToPlay = true;
  42993. if (clonedSound.autoplay) {
  42994. clonedSound.play();
  42995. }
  42996. }
  42997. else {
  42998. window.setTimeout(setBufferAndRun, 300);
  42999. }
  43000. };
  43001. var currentOptions = {
  43002. autoplay: this.autoplay, loop: this.loop,
  43003. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  43004. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  43005. refDistance: this.refDistance, distanceModel: this.distanceModel
  43006. };
  43007. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  43008. if (this.useCustomAttenuation) {
  43009. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  43010. }
  43011. clonedSound.setPosition(this._position);
  43012. clonedSound.setPlaybackRate(this._playbackRate);
  43013. setBufferAndRun();
  43014. return clonedSound;
  43015. }
  43016. else {
  43017. return null;
  43018. }
  43019. };
  43020. Sound.prototype.getAudioBuffer = function () {
  43021. return this._audioBuffer;
  43022. };
  43023. Sound.prototype.serialize = function () {
  43024. var serializationObject = {
  43025. name: this.name,
  43026. url: this.name,
  43027. autoplay: this.autoplay,
  43028. loop: this.loop,
  43029. volume: this._volume,
  43030. spatialSound: this.spatialSound,
  43031. maxDistance: this.maxDistance,
  43032. rolloffFactor: this.rolloffFactor,
  43033. refDistance: this.refDistance,
  43034. distanceModel: this.distanceModel,
  43035. playbackRate: this._playbackRate,
  43036. panningModel: this._panningModel,
  43037. soundTrackId: this.soundTrackId
  43038. };
  43039. if (this.spatialSound) {
  43040. if (this._connectedMesh)
  43041. serializationObject.connectedMeshId = this._connectedMesh.id;
  43042. serializationObject.position = this._position.asArray();
  43043. serializationObject.refDistance = this.refDistance;
  43044. serializationObject.distanceModel = this.distanceModel;
  43045. serializationObject.isDirectional = this._isDirectional;
  43046. serializationObject.localDirectionToMesh = this._localDirection.asArray();
  43047. serializationObject.coneInnerAngle = this._coneInnerAngle;
  43048. serializationObject.coneOuterAngle = this._coneOuterAngle;
  43049. serializationObject.coneOuterGain = this._coneOuterGain;
  43050. }
  43051. return serializationObject;
  43052. };
  43053. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  43054. var soundName = parsedSound.name;
  43055. var soundUrl;
  43056. if (parsedSound.url) {
  43057. soundUrl = rootUrl + parsedSound.url;
  43058. }
  43059. else {
  43060. soundUrl = rootUrl + soundName;
  43061. }
  43062. var options = {
  43063. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  43064. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  43065. rolloffFactor: parsedSound.rolloffFactor,
  43066. refDistance: parsedSound.refDistance,
  43067. distanceModel: parsedSound.distanceModel,
  43068. playbackRate: parsedSound.playbackRate
  43069. };
  43070. var newSound;
  43071. if (!sourceSound) {
  43072. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  43073. scene._addPendingData(newSound);
  43074. }
  43075. else {
  43076. var setBufferAndRun = function () {
  43077. if (sourceSound._isReadyToPlay) {
  43078. newSound._audioBuffer = sourceSound.getAudioBuffer();
  43079. newSound._isReadyToPlay = true;
  43080. if (newSound.autoplay) {
  43081. newSound.play();
  43082. }
  43083. }
  43084. else {
  43085. window.setTimeout(setBufferAndRun, 300);
  43086. }
  43087. };
  43088. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  43089. setBufferAndRun();
  43090. }
  43091. if (parsedSound.position) {
  43092. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  43093. newSound.setPosition(soundPosition);
  43094. }
  43095. if (parsedSound.isDirectional) {
  43096. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  43097. if (parsedSound.localDirectionToMesh) {
  43098. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  43099. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  43100. }
  43101. }
  43102. if (parsedSound.connectedMeshId) {
  43103. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  43104. if (connectedMesh) {
  43105. newSound.attachToMesh(connectedMesh);
  43106. }
  43107. }
  43108. return newSound;
  43109. };
  43110. return Sound;
  43111. }());
  43112. BABYLON.Sound = Sound;
  43113. })(BABYLON || (BABYLON = {}));
  43114. //# sourceMappingURL=babylon.sound.js.map
  43115. var BABYLON;
  43116. (function (BABYLON) {
  43117. var SoundTrack = (function () {
  43118. function SoundTrack(scene, options) {
  43119. this.id = -1;
  43120. this._isMainTrack = false;
  43121. this._isInitialized = false;
  43122. this._scene = scene;
  43123. this.soundCollection = new Array();
  43124. this._options = options;
  43125. if (!this._isMainTrack) {
  43126. this._scene.soundTracks.push(this);
  43127. this.id = this._scene.soundTracks.length - 1;
  43128. }
  43129. }
  43130. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  43131. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  43132. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  43133. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  43134. if (this._options) {
  43135. if (this._options.volume) {
  43136. this._outputAudioNode.gain.value = this._options.volume;
  43137. }
  43138. if (this._options.mainTrack) {
  43139. this._isMainTrack = this._options.mainTrack;
  43140. }
  43141. }
  43142. this._isInitialized = true;
  43143. }
  43144. };
  43145. SoundTrack.prototype.dispose = function () {
  43146. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  43147. if (this._connectedAnalyser) {
  43148. this._connectedAnalyser.stopDebugCanvas();
  43149. }
  43150. while (this.soundCollection.length) {
  43151. this.soundCollection[0].dispose();
  43152. }
  43153. if (this._outputAudioNode) {
  43154. this._outputAudioNode.disconnect();
  43155. }
  43156. this._outputAudioNode = null;
  43157. }
  43158. };
  43159. SoundTrack.prototype.AddSound = function (sound) {
  43160. if (!this._isInitialized) {
  43161. this._initializeSoundTrackAudioGraph();
  43162. }
  43163. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  43164. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  43165. }
  43166. if (sound.soundTrackId) {
  43167. if (sound.soundTrackId === -1) {
  43168. this._scene.mainSoundTrack.RemoveSound(sound);
  43169. }
  43170. else {
  43171. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  43172. }
  43173. }
  43174. this.soundCollection.push(sound);
  43175. sound.soundTrackId = this.id;
  43176. };
  43177. SoundTrack.prototype.RemoveSound = function (sound) {
  43178. var index = this.soundCollection.indexOf(sound);
  43179. if (index !== -1) {
  43180. this.soundCollection.splice(index, 1);
  43181. }
  43182. };
  43183. SoundTrack.prototype.setVolume = function (newVolume) {
  43184. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  43185. this._outputAudioNode.gain.value = newVolume;
  43186. }
  43187. };
  43188. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  43189. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  43190. for (var i = 0; i < this.soundCollection.length; i++) {
  43191. this.soundCollection[i].switchPanningModelToHRTF();
  43192. }
  43193. }
  43194. };
  43195. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  43196. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  43197. for (var i = 0; i < this.soundCollection.length; i++) {
  43198. this.soundCollection[i].switchPanningModelToEqualPower();
  43199. }
  43200. }
  43201. };
  43202. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  43203. if (this._connectedAnalyser) {
  43204. this._connectedAnalyser.stopDebugCanvas();
  43205. }
  43206. this._connectedAnalyser = analyser;
  43207. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  43208. this._outputAudioNode.disconnect();
  43209. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  43210. }
  43211. };
  43212. return SoundTrack;
  43213. }());
  43214. BABYLON.SoundTrack = SoundTrack;
  43215. })(BABYLON || (BABYLON = {}));
  43216. //# sourceMappingURL=babylon.soundtrack.js.map
  43217. /// <reference path="..\PostProcess\babylon.postProcess.ts" />
  43218. /// <reference path="..\Math\babylon.math.ts" />
  43219. var BABYLON;
  43220. (function (BABYLON) {
  43221. /**
  43222. * Special Glow Blur post process only blurring the alpha channel
  43223. * It enforces keeping the most luminous color in the color channel.
  43224. */
  43225. var GlowBlurPostProcess = (function (_super) {
  43226. __extends(GlowBlurPostProcess, _super);
  43227. function GlowBlurPostProcess(name, direction, blurWidth, options, camera, samplingMode, engine, reusable) {
  43228. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  43229. var _this = _super.call(this, name, "glowBlurPostProcess", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable) || this;
  43230. _this.direction = direction;
  43231. _this.blurWidth = blurWidth;
  43232. _this.onApplyObservable.add(function (effect) {
  43233. effect.setFloat2("screenSize", _this.width, _this.height);
  43234. effect.setVector2("direction", _this.direction);
  43235. effect.setFloat("blurWidth", _this.blurWidth);
  43236. });
  43237. return _this;
  43238. }
  43239. return GlowBlurPostProcess;
  43240. }(BABYLON.PostProcess));
  43241. /**
  43242. * The highlight layer Helps adding a glow effect around a mesh.
  43243. *
  43244. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  43245. * glowy meshes to your scene.
  43246. *
  43247. * !!! THIS REQUIRES AN ACTIVE STENCIL BUFFER ON THE CANVAS !!!
  43248. */
  43249. var HighlightLayer = (function () {
  43250. /**
  43251. * Instantiates a new highlight Layer and references it to the scene..
  43252. * @param name The name of the layer
  43253. * @param scene The scene to use the layer in
  43254. * @param options Sets of none mandatory options to use with the layer (see IHighlightLayerOptions for more information)
  43255. */
  43256. function HighlightLayer(name, scene, options) {
  43257. this.name = name;
  43258. this._vertexBuffers = {};
  43259. this._mainTextureDesiredSize = { width: 0, height: 0 };
  43260. this._meshes = {};
  43261. this._maxSize = 0;
  43262. this._shouldRender = false;
  43263. this._instanceGlowingMeshStencilReference = HighlightLayer.glowingMeshStencilReference++;
  43264. this._excludedMeshes = {};
  43265. /**
  43266. * Specifies whether or not the inner glow is ACTIVE in the layer.
  43267. */
  43268. this.innerGlow = true;
  43269. /**
  43270. * Specifies whether or not the outer glow is ACTIVE in the layer.
  43271. */
  43272. this.outerGlow = true;
  43273. /**
  43274. * Specifies wether the highlight layer is enabled or not.
  43275. */
  43276. this.isEnabled = true;
  43277. /**
  43278. * An event triggered when the highlight layer has been disposed.
  43279. * @type {BABYLON.Observable}
  43280. */
  43281. this.onDisposeObservable = new BABYLON.Observable();
  43282. /**
  43283. * An event triggered when the highlight layer is about rendering the main texture with the glowy parts.
  43284. * @type {BABYLON.Observable}
  43285. */
  43286. this.onBeforeRenderMainTextureObservable = new BABYLON.Observable();
  43287. /**
  43288. * An event triggered when the highlight layer is being blurred.
  43289. * @type {BABYLON.Observable}
  43290. */
  43291. this.onBeforeBlurObservable = new BABYLON.Observable();
  43292. /**
  43293. * An event triggered when the highlight layer has been blurred.
  43294. * @type {BABYLON.Observable}
  43295. */
  43296. this.onAfterBlurObservable = new BABYLON.Observable();
  43297. /**
  43298. * An event triggered when the glowing blurred texture is being merged in the scene.
  43299. * @type {BABYLON.Observable}
  43300. */
  43301. this.onBeforeComposeObservable = new BABYLON.Observable();
  43302. /**
  43303. * An event triggered when the glowing blurred texture has been merged in the scene.
  43304. * @type {BABYLON.Observable}
  43305. */
  43306. this.onAfterComposeObservable = new BABYLON.Observable();
  43307. /**
  43308. * An event triggered when the highlight layer changes its size.
  43309. * @type {BABYLON.Observable}
  43310. */
  43311. this.onSizeChangedObservable = new BABYLON.Observable();
  43312. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  43313. var engine = scene.getEngine();
  43314. this._engine = engine;
  43315. this._maxSize = this._engine.getCaps().maxTextureSize;
  43316. this._scene.highlightLayers.push(this);
  43317. // Warn on stencil.
  43318. if (!this._engine.isStencilEnable) {
  43319. 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 }");
  43320. }
  43321. // Adapt options
  43322. this._options = options || {
  43323. mainTextureRatio: 0.25,
  43324. blurTextureSizeRatio: 0.5,
  43325. blurHorizontalSize: 1,
  43326. blurVerticalSize: 1,
  43327. alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE
  43328. };
  43329. this._options.mainTextureRatio = this._options.mainTextureRatio || 0.25;
  43330. this._options.blurTextureSizeRatio = this._options.blurTextureSizeRatio || 0.5;
  43331. this._options.blurHorizontalSize = this._options.blurHorizontalSize || 1;
  43332. this._options.blurVerticalSize = this._options.blurVerticalSize || 1;
  43333. this._options.alphaBlendingMode = this._options.alphaBlendingMode || BABYLON.Engine.ALPHA_COMBINE;
  43334. // VBO
  43335. var vertices = [];
  43336. vertices.push(1, 1);
  43337. vertices.push(-1, 1);
  43338. vertices.push(-1, -1);
  43339. vertices.push(1, -1);
  43340. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  43341. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  43342. // Indices
  43343. var indices = [];
  43344. indices.push(0);
  43345. indices.push(1);
  43346. indices.push(2);
  43347. indices.push(0);
  43348. indices.push(2);
  43349. indices.push(3);
  43350. this._indexBuffer = engine.createIndexBuffer(indices);
  43351. // Effect
  43352. this._glowMapMergeEffect = engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler"], "");
  43353. // Render target
  43354. this.setMainTextureSize();
  43355. // Create Textures and post processes
  43356. this.createTextureAndPostProcesses();
  43357. }
  43358. Object.defineProperty(HighlightLayer.prototype, "blurHorizontalSize", {
  43359. /**
  43360. * Gets the horizontal size of the blur.
  43361. */
  43362. get: function () {
  43363. return this._horizontalBlurPostprocess.blurWidth;
  43364. },
  43365. /**
  43366. * Specifies the horizontal size of the blur.
  43367. */
  43368. set: function (value) {
  43369. this._horizontalBlurPostprocess.blurWidth = value;
  43370. },
  43371. enumerable: true,
  43372. configurable: true
  43373. });
  43374. Object.defineProperty(HighlightLayer.prototype, "blurVerticalSize", {
  43375. /**
  43376. * Gets the vertical size of the blur.
  43377. */
  43378. get: function () {
  43379. return this._verticalBlurPostprocess.blurWidth;
  43380. },
  43381. /**
  43382. * Specifies the vertical size of the blur.
  43383. */
  43384. set: function (value) {
  43385. this._verticalBlurPostprocess.blurWidth = value;
  43386. },
  43387. enumerable: true,
  43388. configurable: true
  43389. });
  43390. Object.defineProperty(HighlightLayer.prototype, "camera", {
  43391. /**
  43392. * Gets the camera attached to the layer.
  43393. */
  43394. get: function () {
  43395. return this._options.camera;
  43396. },
  43397. enumerable: true,
  43398. configurable: true
  43399. });
  43400. /**
  43401. * Creates the render target textures and post processes used in the highlight layer.
  43402. */
  43403. HighlightLayer.prototype.createTextureAndPostProcesses = function () {
  43404. var _this = this;
  43405. var blurTextureWidth = this._mainTextureDesiredSize.width * this._options.blurTextureSizeRatio;
  43406. var blurTextureHeight = this._mainTextureDesiredSize.height * this._options.blurTextureSizeRatio;
  43407. blurTextureWidth = BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize);
  43408. blurTextureHeight = BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize);
  43409. this._mainTexture = new BABYLON.RenderTargetTexture("HighlightLayerMainRTT", {
  43410. width: this._mainTextureDesiredSize.width,
  43411. height: this._mainTextureDesiredSize.height
  43412. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  43413. this._mainTexture.activeCamera = this._options.camera;
  43414. this._mainTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  43415. this._mainTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  43416. this._mainTexture.anisotropicFilteringLevel = 1;
  43417. this._mainTexture.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  43418. this._mainTexture.renderParticles = false;
  43419. this._mainTexture.renderList = null;
  43420. this._blurTexture = new BABYLON.RenderTargetTexture("HighlightLayerBlurRTT", {
  43421. width: blurTextureWidth,
  43422. height: blurTextureHeight
  43423. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  43424. this._blurTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  43425. this._blurTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  43426. this._blurTexture.anisotropicFilteringLevel = 16;
  43427. this._blurTexture.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  43428. this._blurTexture.renderParticles = false;
  43429. this._downSamplePostprocess = new BABYLON.PassPostProcess("HighlightLayerPPP", this._options.blurTextureSizeRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  43430. this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  43431. effect.setTexture("textureSampler", _this._mainTexture);
  43432. });
  43433. if (this._options.alphaBlendingMode === BABYLON.Engine.ALPHA_COMBINE) {
  43434. this._horizontalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  43435. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  43436. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  43437. });
  43438. this._verticalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  43439. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  43440. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  43441. });
  43442. }
  43443. else {
  43444. this._horizontalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  43445. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  43446. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  43447. });
  43448. this._verticalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  43449. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  43450. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  43451. });
  43452. }
  43453. this._mainTexture.onAfterUnbindObservable.add(function () {
  43454. _this.onBeforeBlurObservable.notifyObservers(_this);
  43455. _this._scene.postProcessManager.directRender([_this._downSamplePostprocess, _this._horizontalBlurPostprocess, _this._verticalBlurPostprocess], _this._blurTexture.getInternalTexture());
  43456. _this.onAfterBlurObservable.notifyObservers(_this);
  43457. });
  43458. // Custom render function
  43459. var renderSubMesh = function (subMesh) {
  43460. var mesh = subMesh.getRenderingMesh();
  43461. var scene = _this._scene;
  43462. var engine = scene.getEngine();
  43463. // Culling
  43464. engine.setState(subMesh.getMaterial().backFaceCulling);
  43465. // Managing instances
  43466. var batch = mesh._getInstancesRenderList(subMesh._id);
  43467. if (batch.mustReturn) {
  43468. return;
  43469. }
  43470. // Excluded Mesh
  43471. if (_this._excludedMeshes[mesh.uniqueId]) {
  43472. return;
  43473. }
  43474. ;
  43475. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  43476. var highlightLayerMesh = _this._meshes[mesh.uniqueId];
  43477. var material = subMesh.getMaterial();
  43478. var emissiveTexture = null;
  43479. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  43480. emissiveTexture = material.emissiveTexture;
  43481. }
  43482. if (_this.isReady(subMesh, hardwareInstancedRendering, emissiveTexture)) {
  43483. engine.enableEffect(_this._glowMapGenerationEffect);
  43484. mesh._bind(subMesh, _this._glowMapGenerationEffect, BABYLON.Material.TriangleFillMode);
  43485. _this._glowMapGenerationEffect.setMatrix("viewProjection", scene.getTransformMatrix());
  43486. if (highlightLayerMesh) {
  43487. _this._glowMapGenerationEffect.setFloat4("color", highlightLayerMesh.color.r, highlightLayerMesh.color.g, highlightLayerMesh.color.b, 1.0);
  43488. }
  43489. else {
  43490. _this._glowMapGenerationEffect.setFloat4("color", HighlightLayer.neutralColor.r, HighlightLayer.neutralColor.g, HighlightLayer.neutralColor.b, HighlightLayer.neutralColor.a);
  43491. }
  43492. // Alpha test
  43493. if (material && material.needAlphaTesting()) {
  43494. var alphaTexture = material.getAlphaTestTexture();
  43495. _this._glowMapGenerationEffect.setTexture("diffuseSampler", alphaTexture);
  43496. _this._glowMapGenerationEffect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  43497. }
  43498. // Glow emissive only
  43499. if (emissiveTexture) {
  43500. _this._glowMapGenerationEffect.setTexture("emissiveSampler", emissiveTexture);
  43501. _this._glowMapGenerationEffect.setMatrix("emissiveMatrix", emissiveTexture.getTextureMatrix());
  43502. }
  43503. // Bones
  43504. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  43505. _this._glowMapGenerationEffect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  43506. }
  43507. // Draw
  43508. mesh._processRendering(subMesh, _this._glowMapGenerationEffect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._glowMapGenerationEffect.setMatrix("world", world); });
  43509. }
  43510. else {
  43511. // Need to reset refresh rate of the shadowMap
  43512. _this._mainTexture.resetRefreshCounter();
  43513. }
  43514. };
  43515. this._mainTexture.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  43516. _this.onBeforeRenderMainTextureObservable.notifyObservers(_this);
  43517. var index;
  43518. for (index = 0; index < opaqueSubMeshes.length; index++) {
  43519. renderSubMesh(opaqueSubMeshes.data[index]);
  43520. }
  43521. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  43522. renderSubMesh(alphaTestSubMeshes.data[index]);
  43523. }
  43524. for (index = 0; index < transparentSubMeshes.length; index++) {
  43525. renderSubMesh(transparentSubMeshes.data[index]);
  43526. }
  43527. };
  43528. this._mainTexture.onClearObservable.add(function (engine) {
  43529. engine.clear(HighlightLayer.neutralColor, true, true, true);
  43530. });
  43531. };
  43532. /**
  43533. * Checks for the readiness of the element composing the layer.
  43534. * @param subMesh the mesh to check for
  43535. * @param useInstances specify wether or not to use instances to render the mesh
  43536. * @param emissiveTexture the associated emissive texture used to generate the glow
  43537. * @return true if ready otherwise, false
  43538. */
  43539. HighlightLayer.prototype.isReady = function (subMesh, useInstances, emissiveTexture) {
  43540. if (!subMesh.getMaterial().isReady(subMesh.getMesh(), useInstances)) {
  43541. return false;
  43542. }
  43543. var defines = [];
  43544. var attribs = [BABYLON.VertexBuffer.PositionKind];
  43545. var mesh = subMesh.getMesh();
  43546. var material = subMesh.getMaterial();
  43547. var uv1 = false;
  43548. var uv2 = false;
  43549. // Alpha test
  43550. if (material && material.needAlphaTesting()) {
  43551. var alphaTexture = material.getAlphaTestTexture();
  43552. if (alphaTexture) {
  43553. defines.push("#define ALPHATEST");
  43554. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  43555. alphaTexture.coordinatesIndex === 1) {
  43556. defines.push("#define DIFFUSEUV2");
  43557. uv2 = true;
  43558. }
  43559. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  43560. defines.push("#define DIFFUSEUV1");
  43561. uv1 = true;
  43562. }
  43563. }
  43564. }
  43565. // Emissive
  43566. if (emissiveTexture) {
  43567. defines.push("#define EMISSIVE");
  43568. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  43569. emissiveTexture.coordinatesIndex === 1) {
  43570. defines.push("#define EMISSIVEUV2");
  43571. uv2 = true;
  43572. }
  43573. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  43574. defines.push("#define EMISSIVEUV1");
  43575. uv1 = true;
  43576. }
  43577. }
  43578. if (uv1) {
  43579. attribs.push(BABYLON.VertexBuffer.UVKind);
  43580. defines.push("#define UV1");
  43581. }
  43582. if (uv2) {
  43583. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  43584. defines.push("#define UV2");
  43585. }
  43586. // Bones
  43587. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  43588. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  43589. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  43590. if (mesh.numBoneInfluencers > 4) {
  43591. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  43592. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  43593. }
  43594. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  43595. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  43596. }
  43597. else {
  43598. defines.push("#define NUM_BONE_INFLUENCERS 0");
  43599. }
  43600. // Instances
  43601. if (useInstances) {
  43602. defines.push("#define INSTANCES");
  43603. attribs.push("world0");
  43604. attribs.push("world1");
  43605. attribs.push("world2");
  43606. attribs.push("world3");
  43607. }
  43608. // Get correct effect
  43609. var join = defines.join("\n");
  43610. if (this._cachedDefines !== join) {
  43611. this._cachedDefines = join;
  43612. this._glowMapGenerationEffect = this._scene.getEngine().createEffect("glowMapGeneration", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "color", "emissiveMatrix"], ["diffuseSampler", "emissiveSampler"], join);
  43613. }
  43614. return this._glowMapGenerationEffect.isReady();
  43615. };
  43616. /**
  43617. * Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene.
  43618. */
  43619. HighlightLayer.prototype.render = function () {
  43620. var currentEffect = this._glowMapMergeEffect;
  43621. // Check
  43622. if (!currentEffect.isReady() || !this._blurTexture.isReady())
  43623. return;
  43624. var engine = this._scene.getEngine();
  43625. this.onBeforeComposeObservable.notifyObservers(this);
  43626. // Render
  43627. engine.enableEffect(currentEffect);
  43628. engine.setState(false);
  43629. // Cache
  43630. var previousStencilBuffer = engine.getStencilBuffer();
  43631. var previousStencilFunction = engine.getStencilFunction();
  43632. var previousStencilMask = engine.getStencilMask();
  43633. var previousAlphaMode = engine.getAlphaMode();
  43634. // Texture
  43635. currentEffect.setTexture("textureSampler", this._blurTexture);
  43636. // VBOs
  43637. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  43638. // Draw order
  43639. engine.setAlphaMode(this._options.alphaBlendingMode);
  43640. engine.setStencilMask(0x00);
  43641. engine.setStencilBuffer(true);
  43642. engine.setStencilFunctionReference(this._instanceGlowingMeshStencilReference);
  43643. if (this.outerGlow) {
  43644. currentEffect.setFloat("offset", 0);
  43645. engine.setStencilFunction(BABYLON.Engine.NOTEQUAL);
  43646. engine.draw(true, 0, 6);
  43647. }
  43648. if (this.innerGlow) {
  43649. currentEffect.setFloat("offset", 1);
  43650. engine.setStencilFunction(BABYLON.Engine.EQUAL);
  43651. engine.draw(true, 0, 6);
  43652. }
  43653. // Restore Cache
  43654. engine.setStencilFunction(previousStencilFunction);
  43655. engine.setStencilMask(previousStencilMask);
  43656. engine.setAlphaMode(previousAlphaMode);
  43657. engine.setStencilBuffer(previousStencilBuffer);
  43658. this.onAfterComposeObservable.notifyObservers(this);
  43659. // Handle size changes.
  43660. var size = this._mainTexture.getSize();
  43661. this.setMainTextureSize();
  43662. if (size.width !== this._mainTextureDesiredSize.width || size.height !== this._mainTextureDesiredSize.height) {
  43663. // Recreate RTT and post processes on size change.
  43664. this.onSizeChangedObservable.notifyObservers(this);
  43665. this.disposeTextureAndPostProcesses();
  43666. this.createTextureAndPostProcesses();
  43667. }
  43668. };
  43669. /**
  43670. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the highlight layer.
  43671. * @param mesh The mesh to exclude from the highlight layer
  43672. */
  43673. HighlightLayer.prototype.addExcludedMesh = function (mesh) {
  43674. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  43675. if (!meshExcluded) {
  43676. this._excludedMeshes[mesh.uniqueId] = {
  43677. mesh: mesh,
  43678. beforeRender: mesh.onBeforeRenderObservable.add(function (mesh) {
  43679. mesh.getEngine().setStencilBuffer(false);
  43680. }),
  43681. afterRender: mesh.onAfterRenderObservable.add(function (mesh) {
  43682. mesh.getEngine().setStencilBuffer(true);
  43683. }),
  43684. };
  43685. }
  43686. };
  43687. /**
  43688. * Remove a mesh from the exclusion list to let it impact or being impacted by the highlight layer.
  43689. * @param mesh The mesh to highlight
  43690. */
  43691. HighlightLayer.prototype.removeExcludedMesh = function (mesh) {
  43692. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  43693. if (meshExcluded) {
  43694. mesh.onBeforeRenderObservable.remove(meshExcluded.beforeRender);
  43695. mesh.onAfterRenderObservable.remove(meshExcluded.afterRender);
  43696. }
  43697. this._excludedMeshes[mesh.uniqueId] = undefined;
  43698. };
  43699. /**
  43700. * Add a mesh in the highlight layer in order to make it glow with the chosen color.
  43701. * @param mesh The mesh to highlight
  43702. * @param color The color of the highlight
  43703. * @param glowEmissiveOnly Extract the glow from the emissive texture
  43704. */
  43705. HighlightLayer.prototype.addMesh = function (mesh, color, glowEmissiveOnly) {
  43706. var _this = this;
  43707. if (glowEmissiveOnly === void 0) { glowEmissiveOnly = false; }
  43708. var meshHighlight = this._meshes[mesh.uniqueId];
  43709. if (meshHighlight) {
  43710. meshHighlight.color = color;
  43711. }
  43712. else {
  43713. this._meshes[mesh.uniqueId] = {
  43714. mesh: mesh,
  43715. color: color,
  43716. // Lambda required for capture due to Observable this context
  43717. observerHighlight: mesh.onBeforeRenderObservable.add(function (mesh) {
  43718. if (_this._excludedMeshes[mesh.uniqueId]) {
  43719. _this.defaultStencilReference(mesh);
  43720. }
  43721. else {
  43722. mesh.getScene().getEngine().setStencilFunctionReference(_this._instanceGlowingMeshStencilReference);
  43723. }
  43724. }),
  43725. observerDefault: mesh.onAfterRenderObservable.add(this.defaultStencilReference),
  43726. glowEmissiveOnly: glowEmissiveOnly
  43727. };
  43728. }
  43729. this._shouldRender = true;
  43730. };
  43731. /**
  43732. * Remove a mesh from the highlight layer in order to make it stop glowing.
  43733. * @param mesh The mesh to highlight
  43734. */
  43735. HighlightLayer.prototype.removeMesh = function (mesh) {
  43736. var meshHighlight = this._meshes[mesh.uniqueId];
  43737. if (meshHighlight) {
  43738. mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  43739. mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  43740. }
  43741. this._meshes[mesh.uniqueId] = undefined;
  43742. this._shouldRender = false;
  43743. for (var meshHighlightToCheck in this._meshes) {
  43744. if (meshHighlightToCheck) {
  43745. this._shouldRender = true;
  43746. break;
  43747. }
  43748. }
  43749. };
  43750. /**
  43751. * Returns true if the layer contains information to display, otherwise false.
  43752. */
  43753. HighlightLayer.prototype.shouldRender = function () {
  43754. return this.isEnabled && this._shouldRender;
  43755. };
  43756. /**
  43757. * Sets the main texture desired size which is the closest power of two
  43758. * of the engine canvas size.
  43759. */
  43760. HighlightLayer.prototype.setMainTextureSize = function () {
  43761. if (this._options.mainTextureFixedSize) {
  43762. this._mainTextureDesiredSize.width = this._options.mainTextureFixedSize;
  43763. this._mainTextureDesiredSize.height = this._options.mainTextureFixedSize;
  43764. }
  43765. else {
  43766. this._mainTextureDesiredSize.width = this._engine.getRenderingCanvas().width * this._options.mainTextureRatio;
  43767. this._mainTextureDesiredSize.height = this._engine.getRenderingCanvas().height * this._options.mainTextureRatio;
  43768. this._mainTextureDesiredSize.width = BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.width, this._maxSize);
  43769. this._mainTextureDesiredSize.height = BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.height, this._maxSize);
  43770. }
  43771. };
  43772. /**
  43773. * Force the stencil to the normal expected value for none glowing parts
  43774. */
  43775. HighlightLayer.prototype.defaultStencilReference = function (mesh) {
  43776. mesh.getScene().getEngine().setStencilFunctionReference(HighlightLayer.normalMeshStencilReference);
  43777. };
  43778. /**
  43779. * Dispose only the render target textures and post process.
  43780. */
  43781. HighlightLayer.prototype.disposeTextureAndPostProcesses = function () {
  43782. this._blurTexture.dispose();
  43783. this._mainTexture.dispose();
  43784. this._downSamplePostprocess.dispose();
  43785. this._horizontalBlurPostprocess.dispose();
  43786. this._verticalBlurPostprocess.dispose();
  43787. };
  43788. /**
  43789. * Dispose the highlight layer and free resources.
  43790. */
  43791. HighlightLayer.prototype.dispose = function () {
  43792. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  43793. if (vertexBuffer) {
  43794. vertexBuffer.dispose();
  43795. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  43796. }
  43797. if (this._indexBuffer) {
  43798. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  43799. this._indexBuffer = null;
  43800. }
  43801. // Clean textures and post processes
  43802. this.disposeTextureAndPostProcesses();
  43803. // Clean mesh references
  43804. for (var id in this._meshes) {
  43805. var meshHighlight = this._meshes[id];
  43806. if (meshHighlight && meshHighlight.mesh) {
  43807. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  43808. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  43809. }
  43810. }
  43811. this._meshes = null;
  43812. for (var id in this._excludedMeshes) {
  43813. var meshHighlight = this._excludedMeshes[id];
  43814. if (meshHighlight) {
  43815. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.beforeRender);
  43816. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.afterRender);
  43817. }
  43818. }
  43819. this._excludedMeshes = null;
  43820. // Remove from scene
  43821. var index = this._scene.highlightLayers.indexOf(this, 0);
  43822. if (index > -1) {
  43823. this._scene.highlightLayers.splice(index, 1);
  43824. }
  43825. // Callback
  43826. this.onDisposeObservable.notifyObservers(this);
  43827. this.onDisposeObservable.clear();
  43828. this.onBeforeRenderMainTextureObservable.clear();
  43829. this.onBeforeBlurObservable.clear();
  43830. this.onBeforeComposeObservable.clear();
  43831. this.onAfterComposeObservable.clear();
  43832. this.onSizeChangedObservable.clear();
  43833. };
  43834. return HighlightLayer;
  43835. }());
  43836. /**
  43837. * The neutral color used during the preparation of the glow effect.
  43838. * This is black by default as the blend operation is a blend operation.
  43839. */
  43840. HighlightLayer.neutralColor = new BABYLON.Color4(0, 0, 0, 0);
  43841. /**
  43842. * Stencil value used for glowing meshes.
  43843. */
  43844. HighlightLayer.glowingMeshStencilReference = 0x02;
  43845. /**
  43846. * Stencil value used for the other meshes in the scene.
  43847. */
  43848. HighlightLayer.normalMeshStencilReference = 0x01;
  43849. BABYLON.HighlightLayer = HighlightLayer;
  43850. })(BABYLON || (BABYLON = {}));
  43851. //# sourceMappingURL=babylon.highlightlayer.js.map
  43852. var BABYLON;
  43853. (function (BABYLON) {
  43854. var SIMDVector3 = (function () {
  43855. function SIMDVector3() {
  43856. }
  43857. SIMDVector3.TransformCoordinatesToRefSIMD = function (vector, transformation, result) {
  43858. SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD(vector.x, vector.y, vector.z, transformation, result);
  43859. };
  43860. SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD = function (x, y, z, transformation, result) {
  43861. var m = transformation.m;
  43862. var m0 = SIMD.Float32x4.load(m, 0);
  43863. var m1 = SIMD.Float32x4.load(m, 4);
  43864. var m2 = SIMD.Float32x4.load(m, 8);
  43865. var m3 = SIMD.Float32x4.load(m, 12);
  43866. 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));
  43867. r = SIMD.Float32x4.div(r, SIMD.Float32x4.swizzle(r, 3, 3, 3, 3));
  43868. result.x = SIMD.Float32x4.extractLane(r, 0);
  43869. result.y = SIMD.Float32x4.extractLane(r, 1);
  43870. result.z = SIMD.Float32x4.extractLane(r, 2);
  43871. };
  43872. return SIMDVector3;
  43873. }());
  43874. var SIMDMatrix = (function () {
  43875. function SIMDMatrix() {
  43876. }
  43877. SIMDMatrix.prototype.multiplyToArraySIMD = function (other, result, offset) {
  43878. var tm = this.m;
  43879. var om = other.m;
  43880. var m0 = SIMD.Float32x4.load(om, 0);
  43881. var m1 = SIMD.Float32x4.load(om, 4);
  43882. var m2 = SIMD.Float32x4.load(om, 8);
  43883. var m3 = SIMD.Float32x4.load(om, 12);
  43884. for (var i = 0; i < 16; i += 4) {
  43885. 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)))));
  43886. }
  43887. return this;
  43888. };
  43889. SIMDMatrix.prototype.invertToRefSIMD = function (other) {
  43890. var src = this.m;
  43891. var dest = other.m;
  43892. // Load the 4 rows
  43893. var src0 = SIMD.Float32x4.load(src, 0);
  43894. var src1 = SIMD.Float32x4.load(src, 4);
  43895. var src2 = SIMD.Float32x4.load(src, 8);
  43896. var src3 = SIMD.Float32x4.load(src, 12);
  43897. // Transpose the source matrix. Sort of. Not a true transpose operation
  43898. var tmp1 = SIMD.Float32x4.shuffle(src0, src1, 0, 1, 4, 5);
  43899. var row1 = SIMD.Float32x4.shuffle(src2, src3, 0, 1, 4, 5);
  43900. var row0 = SIMD.Float32x4.shuffle(tmp1, row1, 0, 2, 4, 6);
  43901. row1 = SIMD.Float32x4.shuffle(row1, tmp1, 1, 3, 5, 7);
  43902. tmp1 = SIMD.Float32x4.shuffle(src0, src1, 2, 3, 6, 7);
  43903. var row3 = SIMD.Float32x4.shuffle(src2, src3, 2, 3, 6, 7);
  43904. var row2 = SIMD.Float32x4.shuffle(tmp1, row3, 0, 2, 4, 6);
  43905. row3 = SIMD.Float32x4.shuffle(row3, tmp1, 1, 3, 5, 7);
  43906. // This is a true transposition, but it will lead to an incorrect result
  43907. //tmp1 = shuffle(src0, src1, 0, 1, 4, 5);
  43908. //tmp2 = shuffle(src2, src3, 0, 1, 4, 5);
  43909. //row0 = shuffle(tmp1, tmp2, 0, 2, 4, 6);
  43910. //row1 = shuffle(tmp1, tmp2, 1, 3, 5, 7);
  43911. //tmp1 = shuffle(src0, src1, 2, 3, 6, 7);
  43912. //tmp2 = shuffle(src2, src3, 2, 3, 6, 7);
  43913. //row2 = shuffle(tmp1, tmp2, 0, 2, 4, 6);
  43914. //row3 = shuffle(tmp1, tmp2, 1, 3, 5, 7);
  43915. // ----
  43916. tmp1 = SIMD.Float32x4.mul(row2, row3);
  43917. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  43918. var minor0 = SIMD.Float32x4.mul(row1, tmp1);
  43919. var minor1 = SIMD.Float32x4.mul(row0, tmp1);
  43920. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  43921. minor0 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row1, tmp1), minor0);
  43922. minor1 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row0, tmp1), minor1);
  43923. minor1 = SIMD.Float32x4.swizzle(minor1, 2, 3, 0, 1); // 0x4E = 01001110
  43924. // ----
  43925. tmp1 = SIMD.Float32x4.mul(row1, row2);
  43926. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  43927. minor0 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row3, tmp1), minor0);
  43928. var minor3 = SIMD.Float32x4.mul(row0, tmp1);
  43929. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  43930. minor0 = SIMD.Float32x4.sub(minor0, SIMD.Float32x4.mul(row3, tmp1));
  43931. minor3 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row0, tmp1), minor3);
  43932. minor3 = SIMD.Float32x4.swizzle(minor3, 2, 3, 0, 1); // 0x4E = 01001110
  43933. // ----
  43934. tmp1 = SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(row1, 2, 3, 0, 1), row3); // 0x4E = 01001110
  43935. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  43936. row2 = SIMD.Float32x4.swizzle(row2, 2, 3, 0, 1); // 0x4E = 01001110
  43937. minor0 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row2, tmp1), minor0);
  43938. var minor2 = SIMD.Float32x4.mul(row0, tmp1);
  43939. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  43940. minor0 = SIMD.Float32x4.sub(minor0, SIMD.Float32x4.mul(row2, tmp1));
  43941. minor2 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row0, tmp1), minor2);
  43942. minor2 = SIMD.Float32x4.swizzle(minor2, 2, 3, 0, 1); // 0x4E = 01001110
  43943. // ----
  43944. tmp1 = SIMD.Float32x4.mul(row0, row1);
  43945. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  43946. minor2 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row3, tmp1), minor2);
  43947. minor3 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row2, tmp1), minor3);
  43948. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  43949. minor2 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row3, tmp1), minor2);
  43950. minor3 = SIMD.Float32x4.sub(minor3, SIMD.Float32x4.mul(row2, tmp1));
  43951. // ----
  43952. tmp1 = SIMD.Float32x4.mul(row0, row3);
  43953. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  43954. minor1 = SIMD.Float32x4.sub(minor1, SIMD.Float32x4.mul(row2, tmp1));
  43955. minor2 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row1, tmp1), minor2);
  43956. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  43957. minor1 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row2, tmp1), minor1);
  43958. minor2 = SIMD.Float32x4.sub(minor2, SIMD.Float32x4.mul(row1, tmp1));
  43959. // ----
  43960. tmp1 = SIMD.Float32x4.mul(row0, row2);
  43961. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  43962. minor1 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row3, tmp1), minor1);
  43963. minor3 = SIMD.Float32x4.sub(minor3, SIMD.Float32x4.mul(row1, tmp1));
  43964. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  43965. minor1 = SIMD.Float32x4.sub(minor1, SIMD.Float32x4.mul(row3, tmp1));
  43966. minor3 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row1, tmp1), minor3);
  43967. // Compute determinant
  43968. var det = SIMD.Float32x4.mul(row0, minor0);
  43969. det = SIMD.Float32x4.add(SIMD.Float32x4.swizzle(det, 2, 3, 0, 1), det); // 0x4E = 01001110
  43970. det = SIMD.Float32x4.add(SIMD.Float32x4.swizzle(det, 1, 0, 3, 2), det); // 0xB1 = 10110001
  43971. tmp1 = SIMD.Float32x4.reciprocalApproximation(det);
  43972. det = SIMD.Float32x4.sub(SIMD.Float32x4.add(tmp1, tmp1), SIMD.Float32x4.mul(det, SIMD.Float32x4.mul(tmp1, tmp1)));
  43973. det = SIMD.Float32x4.swizzle(det, 0, 0, 0, 0);
  43974. // These shuffles aren't necessary if the faulty transposition is done
  43975. // up at the top of this function.
  43976. //minor0 =SIMD.Float32x4.swizzle(minor0, 2, 1, 0, 3);
  43977. //minor1 =SIMD.Float32x4.swizzle(minor1, 2, 1, 0, 3);
  43978. //minor2 =SIMD.Float32x4.swizzle(minor2, 2, 1, 0, 3);
  43979. //minor3 =SIMD.Float32x4.swizzle(minor3, 2, 1, 0, 3);
  43980. // Compute final values by multiplying with 1/det
  43981. SIMD.Float32x4.store(dest, 0, SIMD.Float32x4.mul(det, minor0));
  43982. SIMD.Float32x4.store(dest, 4, SIMD.Float32x4.mul(det, minor1));
  43983. SIMD.Float32x4.store(dest, 8, minor2 = SIMD.Float32x4.mul(det, minor2));
  43984. SIMD.Float32x4.store(dest, 12, SIMD.Float32x4.mul(det, minor3));
  43985. return this;
  43986. };
  43987. SIMDMatrix.LookAtLHToRefSIMD = function (eyeRef, targetRef, upRef, result) {
  43988. var out = result.m;
  43989. var center = SIMD.Float32x4(targetRef.x, targetRef.y, targetRef.z, 0.0);
  43990. var eye = SIMD.Float32x4(eyeRef.x, eyeRef.y, eyeRef.z, 0.0);
  43991. var up = SIMD.Float32x4(upRef.x, upRef.y, upRef.z, 0.0);
  43992. // cc.kmVec3Subtract(f, pCenter, pEye);
  43993. var f = SIMD.Float32x4.sub(center, eye);
  43994. // cc.kmVec3Normalize(f, f);
  43995. var tmp = SIMD.Float32x4.mul(f, f);
  43996. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  43997. f = SIMD.Float32x4.mul(f, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  43998. // cc.kmVec3Assign(up, pUp);
  43999. // cc.kmVec3Normalize(up, up);
  44000. tmp = SIMD.Float32x4.mul(up, up);
  44001. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  44002. up = SIMD.Float32x4.mul(up, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  44003. // cc.kmVec3Cross(s, f, up);
  44004. 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)));
  44005. // cc.kmVec3Normalize(s, s);
  44006. tmp = SIMD.Float32x4.mul(s, s);
  44007. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  44008. s = SIMD.Float32x4.mul(s, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  44009. // cc.kmVec3Cross(u, s, f);
  44010. 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)));
  44011. // cc.kmVec3Normalize(s, s);
  44012. tmp = SIMD.Float32x4.mul(s, s);
  44013. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  44014. s = SIMD.Float32x4.mul(s, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  44015. var zero = SIMD.Float32x4.splat(0.0);
  44016. s = SIMD.Float32x4.neg(s);
  44017. var tmp01 = SIMD.Float32x4.shuffle(s, u, 0, 1, 4, 5);
  44018. var tmp23 = SIMD.Float32x4.shuffle(f, zero, 0, 1, 4, 5);
  44019. var a0 = SIMD.Float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6);
  44020. var a1 = SIMD.Float32x4.shuffle(tmp01, tmp23, 1, 3, 5, 7);
  44021. 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);
  44022. var a3 = SIMD.Float32x4(0.0, 0.0, 0.0, 1.0);
  44023. var b = SIMD.Float32x4(1.0, 0.0, 0.0, 0.0);
  44024. 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)))));
  44025. b = SIMD.Float32x4(0.0, 1.0, 0.0, 0.0);
  44026. 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)))));
  44027. b = SIMD.Float32x4(0.0, 0.0, 1.0, 0.0);
  44028. 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)))));
  44029. b = SIMD.Float32x4.replaceLane(SIMD.Float32x4.neg(eye), 3, 1.0);
  44030. 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)))));
  44031. };
  44032. return SIMDMatrix;
  44033. }());
  44034. var previousMultiplyToArray = BABYLON.Matrix.prototype.multiplyToArray;
  44035. var previousInvertToRef = BABYLON.Matrix.prototype.invertToRef;
  44036. var previousLookAtLHToRef = BABYLON.Matrix.LookAtLHToRef;
  44037. var previousTransformCoordinatesToRef = BABYLON.Vector3.TransformCoordinatesToRef;
  44038. var previousTransformCoordinatesFromFloatsToRef = BABYLON.Vector3.TransformCoordinatesFromFloatsToRef;
  44039. var SIMDHelper = (function () {
  44040. function SIMDHelper() {
  44041. }
  44042. Object.defineProperty(SIMDHelper, "IsEnabled", {
  44043. get: function () {
  44044. return SIMDHelper._isEnabled;
  44045. },
  44046. enumerable: true,
  44047. configurable: true
  44048. });
  44049. SIMDHelper.DisableSIMD = function () {
  44050. // Replace functions
  44051. BABYLON.Matrix.prototype.multiplyToArray = previousMultiplyToArray;
  44052. BABYLON.Matrix.prototype.invertToRef = previousInvertToRef;
  44053. BABYLON.Matrix.LookAtLHToRef = previousLookAtLHToRef;
  44054. BABYLON.Vector3.TransformCoordinatesToRef = previousTransformCoordinatesToRef;
  44055. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = previousTransformCoordinatesFromFloatsToRef;
  44056. SIMDHelper._isEnabled = false;
  44057. };
  44058. SIMDHelper.EnableSIMD = function () {
  44059. if (self.SIMD === undefined) {
  44060. return;
  44061. }
  44062. // check if polyfills needed
  44063. if (!self.Math.fround) {
  44064. self.Math.fround = (function (array) { return function (x) {
  44065. return array[0] = x, array[0];
  44066. }; })(new Float32Array(1));
  44067. }
  44068. if (!self.Math.imul) {
  44069. self.Math.imul = function (a, b) {
  44070. var ah = (a >>> 16) & 0xffff;
  44071. var al = a & 0xffff;
  44072. var bh = (b >>> 16) & 0xffff;
  44073. var bl = b & 0xffff;
  44074. // the shift by 0 fixes the sign on the high part
  44075. // the final |0 converts the unsigned value into a signed value
  44076. return ((al * bl) + (((ah * bl + al * bh) << 16) >>> 0) | 0);
  44077. };
  44078. }
  44079. // Replace functions
  44080. BABYLON.Matrix.prototype.multiplyToArray = SIMDMatrix.prototype.multiplyToArraySIMD;
  44081. BABYLON.Matrix.prototype.invertToRef = SIMDMatrix.prototype.invertToRefSIMD;
  44082. BABYLON.Matrix.LookAtLHToRef = SIMDMatrix.LookAtLHToRefSIMD;
  44083. BABYLON.Vector3.TransformCoordinatesToRef = SIMDVector3.TransformCoordinatesToRefSIMD;
  44084. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD;
  44085. SIMDHelper._isEnabled = true;
  44086. };
  44087. return SIMDHelper;
  44088. }());
  44089. SIMDHelper._isEnabled = false;
  44090. BABYLON.SIMDHelper = SIMDHelper;
  44091. })(BABYLON || (BABYLON = {}));
  44092. //# sourceMappingURL=babylon.math.SIMD.js.map
  44093. var BABYLON;
  44094. (function (BABYLON) {
  44095. /**
  44096. * This class describe a rectangle that were added to the map.
  44097. * You have access to its coordinates either in pixel or normalized (UV)
  44098. */
  44099. var PackedRect = (function () {
  44100. function PackedRect(root, parent, pos, size) {
  44101. this._pos = pos;
  44102. this._size = size;
  44103. this._root = root;
  44104. this._parent = parent;
  44105. this._contentSize = null;
  44106. this._bottomNode = null;
  44107. this._leftNode = null;
  44108. this._initialSize = null;
  44109. this._rightNode = null;
  44110. }
  44111. Object.defineProperty(PackedRect.prototype, "pos", {
  44112. /**
  44113. * @returns the position of this node into the map
  44114. */
  44115. get: function () {
  44116. return this._pos;
  44117. },
  44118. enumerable: true,
  44119. configurable: true
  44120. });
  44121. Object.defineProperty(PackedRect.prototype, "contentSize", {
  44122. /**
  44123. * @returns the size of the rectangle this node handles
  44124. */
  44125. get: function () {
  44126. return this._contentSize;
  44127. },
  44128. enumerable: true,
  44129. configurable: true
  44130. });
  44131. /**
  44132. * Retrieve the inner position (considering the margin) and stores it into the res object
  44133. * @param res must be a valid Vector2 that will contain the inner position after this call
  44134. */
  44135. PackedRect.prototype.getInnerPosToRef = function (res) {
  44136. var m = this._root._margin;
  44137. res.x = this._pos.x + m;
  44138. res.y = this._pos.y + m;
  44139. };
  44140. /**
  44141. * Retrieve the inner size (considering the margin) and stores it into the res object
  44142. * @param res must be a valid Size that will contain the inner size after this call
  44143. */
  44144. PackedRect.prototype.getInnerSizeToRef = function (res) {
  44145. var m = this._root._margin;
  44146. res.width = this._contentSize.width - (m * 2);
  44147. res.height = this._contentSize.height - (m * 2);
  44148. };
  44149. Object.defineProperty(PackedRect.prototype, "UVs", {
  44150. /**
  44151. * Compute the UV of the top/left, top/right, bottom/right, bottom/left points of the rectangle this node handles into the map
  44152. * @returns And array of 4 Vector2, containing UV coordinates for the four corners of the Rectangle into the map
  44153. */
  44154. get: function () {
  44155. if (!this._contentSize) {
  44156. throw new Error("Can't compute UVs for this object because it's nor allocated");
  44157. }
  44158. return this.getUVsForCustomSize(this._contentSize);
  44159. },
  44160. enumerable: true,
  44161. configurable: true
  44162. });
  44163. /**
  44164. * You may have allocated the PackedRect using over-provisioning (you allocated more than you need in order to prevent frequent deallocations/reallocations)
  44165. * and then using only a part of the PackRect.
  44166. * This method will return the UVs for this part by given the custom size of what you really use
  44167. * @param customSize must be less/equal to the allocated size, UV will be compute from this
  44168. */
  44169. PackedRect.prototype.getUVsForCustomSize = function (customSize) {
  44170. var mainWidth = this._root._size.width;
  44171. var mainHeight = this._root._size.height;
  44172. var margin = this._root._margin;
  44173. var topLeft = new BABYLON.Vector2((this._pos.x + margin) / mainWidth, (this._pos.y + margin) / mainHeight);
  44174. var rightBottom = new BABYLON.Vector2((this._pos.x + customSize.width + margin - 1) / mainWidth, (this._pos.y + customSize.height + margin - 1) / mainHeight);
  44175. var uvs = new Array();
  44176. uvs.push(topLeft);
  44177. uvs.push(new BABYLON.Vector2(rightBottom.x, topLeft.y));
  44178. uvs.push(rightBottom);
  44179. uvs.push(new BABYLON.Vector2(topLeft.x, rightBottom.y));
  44180. return uvs;
  44181. };
  44182. /**
  44183. * Free this rectangle from the map.
  44184. * Call this method when you no longer need the rectangle to be in the map.
  44185. */
  44186. PackedRect.prototype.freeContent = function () {
  44187. if (!this.contentSize) {
  44188. return;
  44189. }
  44190. this._contentSize = null;
  44191. // If everything below is also free, reset the whole node, and attempt to reset parents if they also become free
  44192. this.attemptDefrag();
  44193. };
  44194. Object.defineProperty(PackedRect.prototype, "isUsed", {
  44195. get: function () {
  44196. return this._contentSize != null || this._leftNode != null;
  44197. },
  44198. enumerable: true,
  44199. configurable: true
  44200. });
  44201. PackedRect.prototype.findAndSplitNode = function (contentSize) {
  44202. var node = this.findNode(contentSize);
  44203. // Not enough space...
  44204. if (!node) {
  44205. return null;
  44206. }
  44207. node.splitNode(contentSize);
  44208. return node;
  44209. };
  44210. PackedRect.prototype.findNode = function (size) {
  44211. var resNode = null;
  44212. var margin = this._root._margin * 2;
  44213. // If this node is used, recurse to each of his subNodes to find an available one in its branch
  44214. if (this.isUsed) {
  44215. if (this._leftNode) {
  44216. resNode = this._leftNode.findNode(size);
  44217. }
  44218. if (!resNode && this._rightNode) {
  44219. resNode = this._rightNode.findNode(size);
  44220. }
  44221. if (!resNode && this._bottomNode) {
  44222. resNode = this._bottomNode.findNode(size);
  44223. }
  44224. }
  44225. else if (this._initialSize) {
  44226. if (((size.width + margin) <= this._initialSize.width) && ((size.height + margin) <= this._initialSize.height)) {
  44227. resNode = this;
  44228. }
  44229. else {
  44230. return null;
  44231. }
  44232. }
  44233. else if (((size.width + margin) <= this._size.width) && ((size.height + margin) <= this._size.height)) {
  44234. resNode = this;
  44235. }
  44236. return resNode;
  44237. };
  44238. PackedRect.prototype.splitNode = function (contentSize) {
  44239. var cs = PackedRect.TpsSize;
  44240. var margin = this._root._margin * 2;
  44241. cs.copyFrom(contentSize);
  44242. cs.width += margin;
  44243. cs.height += margin;
  44244. // 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)
  44245. if (!this._contentSize && this._initialSize) {
  44246. this._contentSize = cs.clone();
  44247. 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));
  44248. return this._leftNode.splitNode(contentSize);
  44249. }
  44250. else {
  44251. this._contentSize = cs.clone();
  44252. this._initialSize = cs.clone();
  44253. if (cs.width !== this._size.width) {
  44254. this._rightNode = new PackedRect(this._root, this, new BABYLON.Vector2(this._pos.x + cs.width, this._pos.y), new BABYLON.Size(this._size.width - cs.width, cs.height));
  44255. }
  44256. if (cs.height !== this._size.height) {
  44257. this._bottomNode = new PackedRect(this._root, this, new BABYLON.Vector2(this._pos.x, this._pos.y + cs.height), new BABYLON.Size(this._size.width, this._size.height - cs.height));
  44258. }
  44259. return this;
  44260. }
  44261. };
  44262. PackedRect.prototype.attemptDefrag = function () {
  44263. if (!this.isUsed && this.isRecursiveFree) {
  44264. this.clearNode();
  44265. if (this._parent) {
  44266. this._parent.attemptDefrag();
  44267. }
  44268. }
  44269. };
  44270. PackedRect.prototype.clearNode = function () {
  44271. this._initialSize = null;
  44272. this._rightNode = null;
  44273. this._bottomNode = null;
  44274. };
  44275. Object.defineProperty(PackedRect.prototype, "isRecursiveFree", {
  44276. get: function () {
  44277. return !this.contentSize && (!this._leftNode || this._leftNode.isRecursiveFree) && (!this._rightNode || this._rightNode.isRecursiveFree) && (!this._bottomNode || this._bottomNode.isRecursiveFree);
  44278. },
  44279. enumerable: true,
  44280. configurable: true
  44281. });
  44282. PackedRect.prototype.evalFreeSize = function (size) {
  44283. var levelSize = 0;
  44284. if (!this.isUsed) {
  44285. var margin = this._root._margin;
  44286. var is = this._initialSize;
  44287. if (is) {
  44288. levelSize = is.surface - (is.width * margin) - (is.height * margin);
  44289. }
  44290. else {
  44291. var size_1 = this._size;
  44292. levelSize = size_1.surface - (size_1.width * margin) - (size_1.height * margin);
  44293. }
  44294. }
  44295. if (this._rightNode) {
  44296. levelSize += this._rightNode.evalFreeSize(0);
  44297. }
  44298. if (this._bottomNode) {
  44299. levelSize += this._bottomNode.evalFreeSize(0);
  44300. }
  44301. return levelSize + size;
  44302. };
  44303. return PackedRect;
  44304. }());
  44305. PackedRect.TpsSize = BABYLON.Size.Zero();
  44306. BABYLON.PackedRect = PackedRect;
  44307. /**
  44308. * The purpose of this class is to pack several Rectangles into a big map, while trying to fit everything as optimally as possible.
  44309. * This class is typically used to build lightmaps, sprite map or to pack several little textures into a big one.
  44310. * 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.
  44311. * In case you need a margin around the allocated rect, specify the amount in the margin argument during construction.
  44312. * In such case you will have to rely on innerPositionToRef and innerSizeToRef calls to get the proper size
  44313. */
  44314. var RectPackingMap = (function (_super) {
  44315. __extends(RectPackingMap, _super);
  44316. /**
  44317. * Create an instance of the object with a dimension using the given size
  44318. * @param size The dimension of the rectangle that will contain all the sub ones.
  44319. * @param margin The margin (empty space) created (in pixels) around the allocated Rectangles
  44320. */
  44321. function RectPackingMap(size, margin) {
  44322. if (margin === void 0) { margin = 0; }
  44323. var _this = _super.call(this, null, null, BABYLON.Vector2.Zero(), size) || this;
  44324. _this._margin = margin;
  44325. _this._root = _this;
  44326. return _this;
  44327. }
  44328. /**
  44329. * Add a rectangle, finding the best location to store it into the map
  44330. * @param size the dimension of the rectangle to store
  44331. * @return the Node containing the rectangle information, or null if we couldn't find a free spot
  44332. */
  44333. RectPackingMap.prototype.addRect = function (size) {
  44334. var node = this.findAndSplitNode(size);
  44335. return node;
  44336. };
  44337. Object.defineProperty(RectPackingMap.prototype, "freeSpace", {
  44338. /**
  44339. * Return the current space free normalized between [0;1]
  44340. * @returns {}
  44341. */
  44342. get: function () {
  44343. var freeSize = 0;
  44344. freeSize = this.evalFreeSize(freeSize);
  44345. return freeSize / (this._size.width * this._size.height);
  44346. },
  44347. enumerable: true,
  44348. configurable: true
  44349. });
  44350. return RectPackingMap;
  44351. }(PackedRect));
  44352. BABYLON.RectPackingMap = RectPackingMap;
  44353. })(BABYLON || (BABYLON = {}));
  44354. //# sourceMappingURL=babylon.rectPackingMap.js.map
  44355. var BABYLON;
  44356. (function (BABYLON) {
  44357. var DynamicFloatArrayElementInfo = (function () {
  44358. function DynamicFloatArrayElementInfo() {
  44359. }
  44360. return DynamicFloatArrayElementInfo;
  44361. }());
  44362. BABYLON.DynamicFloatArrayElementInfo = DynamicFloatArrayElementInfo;
  44363. /**
  44364. * 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.
  44365. * The intent is to maintain through time data that will be bound to a WebGlBuffer with the ability to change add/remove elements.
  44366. * It was first built to efficiently maintain the WebGlBuffer that contain instancing based data.
  44367. * 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.
  44368. * 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.
  44369. * 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".
  44370. */
  44371. var DynamicFloatArray = (function () {
  44372. /**
  44373. * Construct an instance of the dynamic float array
  44374. * @param stride size of one element in float (i.e. not bytes!)
  44375. * @param initialElementCount the number of available entries at construction
  44376. */
  44377. function DynamicFloatArray(stride, initialElementCount) {
  44378. this.compareValueOffset = null;
  44379. this.sortingAscending = true;
  44380. this._stride = stride;
  44381. this.buffer = new Float32Array(stride * initialElementCount);
  44382. this._lastUsed = 0;
  44383. this._firstFree = 0;
  44384. this._allEntries = new Array(initialElementCount);
  44385. this._freeEntries = new Array(initialElementCount);
  44386. for (var i = 0; i < initialElementCount; i++) {
  44387. var element = new DynamicFloatArrayElementInfo();
  44388. element.offset = i * stride;
  44389. this._allEntries[i] = element;
  44390. this._freeEntries[initialElementCount - i - 1] = element;
  44391. }
  44392. }
  44393. /**
  44394. * Allocate an element in the array.
  44395. * @return the element info instance that contains the offset into the main buffer of the element's location.
  44396. * Beware, this offset may change when you call pack()
  44397. */
  44398. DynamicFloatArray.prototype.allocElement = function () {
  44399. if (this._freeEntries.length === 0) {
  44400. this._growBuffer();
  44401. }
  44402. var el = this._freeEntries.pop();
  44403. this._lastUsed = Math.max(el.offset, this._lastUsed);
  44404. if (el.offset === this._firstFree) {
  44405. if (this._freeEntries.length > 0) {
  44406. this._firstFree = this._freeEntries[this._freeEntries.length - 1].offset;
  44407. }
  44408. else {
  44409. this._firstFree += this._stride;
  44410. }
  44411. }
  44412. return el;
  44413. };
  44414. /**
  44415. * Free the element corresponding to the given element info
  44416. * @param elInfo the element that describe the allocated element
  44417. */
  44418. DynamicFloatArray.prototype.freeElement = function (elInfo) {
  44419. this._firstFree = Math.min(elInfo.offset, this._firstFree);
  44420. this._freeEntries.push(elInfo);
  44421. };
  44422. /**
  44423. * This method will pack all the used elements into a linear sequence and put all the free space at the end.
  44424. * 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().
  44425. * @return the subArray that is the view of the used elements area, you can use it as a source to update a WebGLBuffer
  44426. */
  44427. DynamicFloatArray.prototype.pack = function () {
  44428. // no free slot? no need to pack
  44429. if (this._freeEntries.length === 0) {
  44430. return this.buffer;
  44431. }
  44432. // If the buffer is already packed the last used will always be lower than the first free
  44433. // 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.
  44434. if (this._lastUsed < this._firstFree) {
  44435. var elementsBuffer_1 = this.buffer.subarray(0, this._lastUsed + this._stride);
  44436. return elementsBuffer_1;
  44437. }
  44438. var s = this._stride;
  44439. // 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
  44440. var lastFree = new DynamicFloatArrayElementInfo();
  44441. lastFree.offset = this.totalElementCount * s;
  44442. this._freeEntries.push(lastFree);
  44443. var sortedFree = this._freeEntries.sort(function (a, b) { return a.offset - b.offset; });
  44444. var sortedAll = this._allEntries.sort(function (a, b) { return a.offset - b.offset; });
  44445. var firstFreeSlotOffset = sortedFree[0].offset;
  44446. var freeZoneSize = 1;
  44447. var occupiedZoneSize = (this.usedElementCount + 1) * s;
  44448. var prevOffset = sortedFree[0].offset;
  44449. for (var i = 1; i < sortedFree.length; i++) {
  44450. // 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
  44451. if (firstFreeSlotOffset >= occupiedZoneSize) {
  44452. break;
  44453. }
  44454. var curFree = sortedFree[i];
  44455. var curOffset = curFree.offset;
  44456. // Compute the distance between this offset and the previous
  44457. var distance = curOffset - prevOffset;
  44458. // If the distance is the stride size, they are adjacent, it good, move to the next
  44459. if (distance === s) {
  44460. // Free zone is one element bigger
  44461. ++freeZoneSize;
  44462. // as we're about to iterate to the next, the cur becomes the previous...
  44463. prevOffset = curOffset;
  44464. continue;
  44465. }
  44466. // Distance is bigger, which means there's x element between the previous free and this one
  44467. var usedRange = (distance / s) - 1;
  44468. // Two cases the free zone is smaller than the data to move or bigger
  44469. // Copy what can fit in the free zone
  44470. var curMoveOffset = curOffset - s;
  44471. var copyCount = Math.min(freeZoneSize, usedRange);
  44472. for (var j = 0; j < copyCount; j++) {
  44473. var freeI = firstFreeSlotOffset / s;
  44474. var curI = curMoveOffset / s;
  44475. var moveEl = sortedAll[curI];
  44476. this._moveElement(moveEl, firstFreeSlotOffset);
  44477. var replacedEl = sortedAll[freeI];
  44478. // set the offset of the element we replaced with a value that will make it discard at the end of the method
  44479. replacedEl.offset = curMoveOffset;
  44480. // Swap the element we moved and the one it replaced in the sorted array to reflect the action we've made
  44481. sortedAll[freeI] = moveEl;
  44482. sortedAll[curI] = replacedEl;
  44483. curMoveOffset -= s;
  44484. firstFreeSlotOffset += s;
  44485. }
  44486. // Free Zone is smaller or equal so it's no longer a free zone, set the new one to the current location
  44487. if (freeZoneSize <= usedRange) {
  44488. firstFreeSlotOffset = curMoveOffset + s;
  44489. freeZoneSize = 1 + copyCount;
  44490. }
  44491. else {
  44492. freeZoneSize = ((curOffset - firstFreeSlotOffset) / s) + 1;
  44493. }
  44494. // as we're about to iterate to the next, the cur becomes the previous...
  44495. prevOffset = curOffset;
  44496. }
  44497. var elementsBuffer = this.buffer.subarray(0, firstFreeSlotOffset);
  44498. this._lastUsed = firstFreeSlotOffset - s;
  44499. this._firstFree = firstFreeSlotOffset;
  44500. sortedFree.pop(); // Remove the last free because that's the one we added at the start of the method
  44501. this._freeEntries = sortedFree.sort(function (a, b) { return b.offset - a.offset; });
  44502. this._allEntries = sortedAll;
  44503. return elementsBuffer;
  44504. };
  44505. DynamicFloatArray.prototype._moveElement = function (element, destOffset) {
  44506. for (var i = 0; i < this._stride; i++) {
  44507. this.buffer[destOffset + i] = this.buffer[element.offset + i];
  44508. }
  44509. element.offset = destOffset;
  44510. };
  44511. DynamicFloatArray.prototype._growBuffer = function () {
  44512. // Allocate the new buffer with 50% more entries, copy the content of the current one
  44513. var newElCount = Math.floor(this.totalElementCount * 1.5);
  44514. var newBuffer = new Float32Array(newElCount * this._stride);
  44515. newBuffer.set(this.buffer);
  44516. var curCount = this.totalElementCount;
  44517. var addedCount = newElCount - this.totalElementCount;
  44518. for (var i = 0; i < addedCount; i++) {
  44519. var element = new DynamicFloatArrayElementInfo();
  44520. element.offset = (curCount + i) * this.stride;
  44521. this._allEntries.push(element);
  44522. this._freeEntries[addedCount - i - 1] = element;
  44523. }
  44524. this._firstFree = curCount * this.stride;
  44525. this.buffer = newBuffer;
  44526. };
  44527. Object.defineProperty(DynamicFloatArray.prototype, "totalElementCount", {
  44528. /**
  44529. * Get the total count of entries that can fit in the current buffer
  44530. * @returns the elements count
  44531. */
  44532. get: function () {
  44533. return this._allEntries.length;
  44534. },
  44535. enumerable: true,
  44536. configurable: true
  44537. });
  44538. Object.defineProperty(DynamicFloatArray.prototype, "freeElementCount", {
  44539. /**
  44540. * Get the count of free entries that can still be allocated without resizing the buffer
  44541. * @returns the free elements count
  44542. */
  44543. get: function () {
  44544. return this._freeEntries.length;
  44545. },
  44546. enumerable: true,
  44547. configurable: true
  44548. });
  44549. Object.defineProperty(DynamicFloatArray.prototype, "usedElementCount", {
  44550. /**
  44551. * Get the count of allocated elements
  44552. * @returns the allocated elements count
  44553. */
  44554. get: function () {
  44555. return this._allEntries.length - this._freeEntries.length;
  44556. },
  44557. enumerable: true,
  44558. configurable: true
  44559. });
  44560. Object.defineProperty(DynamicFloatArray.prototype, "stride", {
  44561. /**
  44562. * Return the size of one element in float
  44563. * @returns the size in float
  44564. */
  44565. get: function () {
  44566. return this._stride;
  44567. },
  44568. enumerable: true,
  44569. configurable: true
  44570. });
  44571. DynamicFloatArray.prototype.sort = function () {
  44572. var _this = this;
  44573. if (!this.compareValueOffset) {
  44574. throw new Error("The DynamicFloatArray.sort() method needs a valid 'compareValueOffset' property");
  44575. }
  44576. var count = this.usedElementCount;
  44577. // Do we have to (re)create the sort table?
  44578. if (!this._sortTable || this._sortTable.length < count) {
  44579. // 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...
  44580. var newCount = Math.min(this.totalElementCount, count * 2);
  44581. this._sortTable = new Array(newCount);
  44582. }
  44583. if (!this._sortedTable || this._sortedTable.length !== count) {
  44584. this._sortedTable = new Array(count);
  44585. }
  44586. // Because, you know...
  44587. this.pack();
  44588. //let stride = this.stride;
  44589. //for (let i = 0; i < count; i++) {
  44590. // let si = this._sortTable[i];
  44591. // if (!si) {
  44592. // si = new SortInfo();
  44593. // this._sortTable[i] = si;
  44594. // }
  44595. // si.entry = this._allEntries[i];
  44596. // si.compareData = this.buffer[si.entry.offset + this.compareValueOffset];
  44597. // si.swapedOffset = null;
  44598. // this._sortedTable[i] = si;
  44599. //}
  44600. var curOffset = 0;
  44601. var stride = this.stride;
  44602. for (var i = 0; i < count; i++, curOffset += stride) {
  44603. var si = this._sortTable[i];
  44604. if (!si) {
  44605. si = new SortInfo();
  44606. this._sortTable[i] = si;
  44607. }
  44608. si.compareData = this.buffer[curOffset + this.compareValueOffset];
  44609. si.offset = curOffset;
  44610. si.swapedOffset = null;
  44611. this._sortedTable[i] = si;
  44612. }
  44613. // Let's sort the sorted table, we want to keep a track of the original one (that's why we have two buffers)
  44614. if (this.sortingAscending) {
  44615. this._sortedTable.sort(function (a, b) { return a.compareData - b.compareData; });
  44616. }
  44617. else {
  44618. this._sortedTable.sort(function (a, b) { return b.compareData - a.compareData; });
  44619. }
  44620. var swapElements = function (src, dst) {
  44621. for (var i = 0; i < stride; i++) {
  44622. var tps = _this.buffer[dst + i];
  44623. _this.buffer[dst + i] = _this.buffer[src + i];
  44624. _this.buffer[src + i] = tps;
  44625. }
  44626. };
  44627. // 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:
  44628. // 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),
  44629. // and I still want something with a good algorithm complexity.
  44630. // 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,
  44631. // we need sortTable for that, it contains the original layout of SortInfo object, not the sorted one.
  44632. // The best way is to use an extra field in SortInfo, because potentially every element can be replaced.
  44633. // 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
  44634. // until we find a SortInfo object without a swapedOffset which means we got the right location
  44635. // 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
  44636. // than a double allocation of the whole float32Array or a O(n²/2) typical algorithm.
  44637. for (var i = 0; i < count; i++) {
  44638. // Get the element to move
  44639. var sourceSI = this._sortedTable[i];
  44640. var destSI = this._sortTable[i];
  44641. var sourceOff = sourceSI.offset;
  44642. // If the source changed location, find the new one
  44643. if (sourceSI.swapedOffset) {
  44644. // Follow the swapedOffset until there's none, it will mean that curSI contains the new location in its offset member
  44645. var curSI = sourceSI;
  44646. while (curSI.swapedOffset) {
  44647. curSI = this._sortTable[curSI.swapedOffset / stride];
  44648. }
  44649. // Finally get the right location
  44650. sourceOff = curSI.offset;
  44651. }
  44652. // Tag the element being replaced with its new location
  44653. destSI.swapedOffset = sourceOff;
  44654. // Swap elements (only if needed)
  44655. if (sourceOff !== destSI.offset) {
  44656. swapElements(sourceOff, destSI.offset);
  44657. }
  44658. // Update the offset in the corresponding DFAE
  44659. //sourceSI.entry.offset = destSI.entry.offset;
  44660. this._allEntries[sourceSI.offset / stride].offset = destSI.offset;
  44661. }
  44662. this._allEntries.sort(function (a, b) { return a.offset - b.offset; });
  44663. return true;
  44664. };
  44665. return DynamicFloatArray;
  44666. }());
  44667. BABYLON.DynamicFloatArray = DynamicFloatArray;
  44668. var SortInfo = (function () {
  44669. function SortInfo() {
  44670. this.compareData = this.offset = this.swapedOffset = null;
  44671. }
  44672. return SortInfo;
  44673. }());
  44674. })(BABYLON || (BABYLON = {}));
  44675. //# sourceMappingURL=babylon.dynamicFloatArray.js.map
  44676. var BABYLON;
  44677. (function (BABYLON) {
  44678. var MapTexture = (function (_super) {
  44679. __extends(MapTexture, _super);
  44680. function MapTexture(name, scene, size, samplingMode, useMipMap, margin) {
  44681. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  44682. if (useMipMap === void 0) { useMipMap = false; }
  44683. if (margin === void 0) { margin = 0; }
  44684. var _this = _super.call(this, null, scene, !useMipMap, false, samplingMode) || this;
  44685. _this.name = name;
  44686. _this._size = size;
  44687. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  44688. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  44689. // Create the rectPackMap that will allocate portion of the texture
  44690. _this._rectPackingMap = new BABYLON.RectPackingMap(new BABYLON.Size(size.width, size.height), margin);
  44691. // Create the texture that will store the content
  44692. _this._texture = scene.getEngine().createRenderTargetTexture(size, { generateMipMaps: !_this.noMipmap, type: BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT });
  44693. return _this;
  44694. }
  44695. /**
  44696. * Allocate a rectangle of a given size in the texture map
  44697. * @param size the size of the rectangle to allocation
  44698. * @return the PackedRect instance corresponding to the allocated rect or null is there was not enough space to allocate it.
  44699. */
  44700. MapTexture.prototype.allocateRect = function (size) {
  44701. return this._rectPackingMap.addRect(size);
  44702. };
  44703. /**
  44704. * Free a given rectangle from the texture map
  44705. * @param rectInfo the instance corresponding to the rect to free.
  44706. */
  44707. MapTexture.prototype.freeRect = function (rectInfo) {
  44708. if (rectInfo) {
  44709. rectInfo.freeContent();
  44710. }
  44711. };
  44712. Object.defineProperty(MapTexture.prototype, "freeSpace", {
  44713. /**
  44714. * Return the available space in the range of [O;1]. 0 being not space left at all, 1 being an empty texture map.
  44715. * This is the cumulated space, not the biggest available surface. Due to fragmentation you may not allocate a rect corresponding to this surface.
  44716. * @returns {}
  44717. */
  44718. get: function () {
  44719. return this._rectPackingMap.freeSpace;
  44720. },
  44721. enumerable: true,
  44722. configurable: true
  44723. });
  44724. /**
  44725. * Bind the texture to the rendering engine to render in the zone of a given rectangle.
  44726. * 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.
  44727. * Don't forget to call unbindTexture when you're done rendering
  44728. * @param rect the zone to render to
  44729. * @param clear true to clear the portion's color/depth data
  44730. */
  44731. MapTexture.prototype.bindTextureForRect = function (rect, clear) {
  44732. return this.bindTextureForPosSize(rect.pos, rect.contentSize, clear);
  44733. };
  44734. /**
  44735. * Bind the texture to the rendering engine to render in the zone of the given size at the given position.
  44736. * 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.
  44737. * Don't forget to call unbindTexture when you're done rendering
  44738. * @param pos the position into the texture
  44739. * @param size the portion to fit the clip space to
  44740. * @param clear true to clear the portion's color/depth data
  44741. */
  44742. MapTexture.prototype.bindTextureForPosSize = function (pos, size, clear) {
  44743. var engine = this.getScene().getEngine();
  44744. engine.bindFramebuffer(this._texture);
  44745. this._replacedViewport = engine.setDirectViewport(pos.x, pos.y, size.width, size.height);
  44746. if (clear) {
  44747. // We only want to clear the part of the texture we're binding to, only the scissor can help us to achieve that
  44748. engine.scissorClear(pos.x, pos.y, size.width, size.height, new BABYLON.Color4(0, 0, 0, 0));
  44749. }
  44750. };
  44751. /**
  44752. * Unbind the texture map from the rendering engine.
  44753. * Call this method when you're done rendering. A previous call to bindTextureForRect has to be made.
  44754. * @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.
  44755. */
  44756. MapTexture.prototype.unbindTexture = function (dumpForDebug) {
  44757. // Dump ?
  44758. if (dumpForDebug) {
  44759. BABYLON.Tools.DumpFramebuffer(this._size.width, this._size.height, this.getScene().getEngine());
  44760. }
  44761. var engine = this.getScene().getEngine();
  44762. if (this._replacedViewport) {
  44763. engine.setViewport(this._replacedViewport);
  44764. this._replacedViewport = null;
  44765. }
  44766. engine.unBindFramebuffer(this._texture);
  44767. };
  44768. Object.defineProperty(MapTexture.prototype, "canRescale", {
  44769. get: function () {
  44770. return false;
  44771. },
  44772. enumerable: true,
  44773. configurable: true
  44774. });
  44775. // Note, I don't know what behavior this method should have: clone the underlying texture/rectPackingMap or just reference them?
  44776. // Anyway, there's not much point to use this method for this kind of texture I guess
  44777. MapTexture.prototype.clone = function () {
  44778. return null;
  44779. };
  44780. return MapTexture;
  44781. }(BABYLON.Texture));
  44782. BABYLON.MapTexture = MapTexture;
  44783. })(BABYLON || (BABYLON = {}));
  44784. //# sourceMappingURL=babylon.mapTexture.js.map
  44785. var BABYLON;
  44786. (function (BABYLON) {
  44787. var ShaderMaterial = (function (_super) {
  44788. __extends(ShaderMaterial, _super);
  44789. function ShaderMaterial(name, scene, shaderPath, options) {
  44790. var _this = _super.call(this, name, scene) || this;
  44791. _this._textures = {};
  44792. _this._textureArrays = {};
  44793. _this._floats = {};
  44794. _this._floatsArrays = {};
  44795. _this._colors3 = {};
  44796. _this._colors4 = {};
  44797. _this._vectors2 = {};
  44798. _this._vectors3 = {};
  44799. _this._vectors4 = {};
  44800. _this._matrices = {};
  44801. _this._matrices3x3 = {};
  44802. _this._matrices2x2 = {};
  44803. _this._vectors3Arrays = {};
  44804. _this._cachedWorldViewMatrix = new BABYLON.Matrix();
  44805. _this._shaderPath = shaderPath;
  44806. options.needAlphaBlending = options.needAlphaBlending || false;
  44807. options.needAlphaTesting = options.needAlphaTesting || false;
  44808. options.attributes = options.attributes || ["position", "normal", "uv"];
  44809. options.uniforms = options.uniforms || ["worldViewProjection"];
  44810. options.samplers = options.samplers || [];
  44811. options.defines = options.defines || [];
  44812. _this._options = options;
  44813. return _this;
  44814. }
  44815. ShaderMaterial.prototype.getClassName = function () {
  44816. return "ShaderMaterial";
  44817. };
  44818. ShaderMaterial.prototype.needAlphaBlending = function () {
  44819. return this._options.needAlphaBlending;
  44820. };
  44821. ShaderMaterial.prototype.needAlphaTesting = function () {
  44822. return this._options.needAlphaTesting;
  44823. };
  44824. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  44825. if (this._options.uniforms.indexOf(uniformName) === -1) {
  44826. this._options.uniforms.push(uniformName);
  44827. }
  44828. };
  44829. ShaderMaterial.prototype.setTexture = function (name, texture) {
  44830. if (this._options.samplers.indexOf(name) === -1) {
  44831. this._options.samplers.push(name);
  44832. }
  44833. this._textures[name] = texture;
  44834. return this;
  44835. };
  44836. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  44837. if (this._options.samplers.indexOf(name) === -1) {
  44838. this._options.samplers.push(name);
  44839. }
  44840. this._checkUniform(name);
  44841. this._textureArrays[name] = textures;
  44842. return this;
  44843. };
  44844. ShaderMaterial.prototype.setFloat = function (name, value) {
  44845. this._checkUniform(name);
  44846. this._floats[name] = value;
  44847. return this;
  44848. };
  44849. ShaderMaterial.prototype.setFloats = function (name, value) {
  44850. this._checkUniform(name);
  44851. this._floatsArrays[name] = value;
  44852. return this;
  44853. };
  44854. ShaderMaterial.prototype.setColor3 = function (name, value) {
  44855. this._checkUniform(name);
  44856. this._colors3[name] = value;
  44857. return this;
  44858. };
  44859. ShaderMaterial.prototype.setColor4 = function (name, value) {
  44860. this._checkUniform(name);
  44861. this._colors4[name] = value;
  44862. return this;
  44863. };
  44864. ShaderMaterial.prototype.setVector2 = function (name, value) {
  44865. this._checkUniform(name);
  44866. this._vectors2[name] = value;
  44867. return this;
  44868. };
  44869. ShaderMaterial.prototype.setVector3 = function (name, value) {
  44870. this._checkUniform(name);
  44871. this._vectors3[name] = value;
  44872. return this;
  44873. };
  44874. ShaderMaterial.prototype.setVector4 = function (name, value) {
  44875. this._checkUniform(name);
  44876. this._vectors4[name] = value;
  44877. return this;
  44878. };
  44879. ShaderMaterial.prototype.setMatrix = function (name, value) {
  44880. this._checkUniform(name);
  44881. this._matrices[name] = value;
  44882. return this;
  44883. };
  44884. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  44885. this._checkUniform(name);
  44886. this._matrices3x3[name] = value;
  44887. return this;
  44888. };
  44889. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  44890. this._checkUniform(name);
  44891. this._matrices2x2[name] = value;
  44892. return this;
  44893. };
  44894. ShaderMaterial.prototype.setArray3 = function (name, value) {
  44895. this._checkUniform(name);
  44896. this._vectors3Arrays[name] = value;
  44897. return this;
  44898. };
  44899. ShaderMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  44900. if (!mesh) {
  44901. return true;
  44902. }
  44903. if (this._effect && (this._effect.defines.indexOf("#define INSTANCES") !== -1) !== useInstances) {
  44904. return false;
  44905. }
  44906. return false;
  44907. };
  44908. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  44909. var scene = this.getScene();
  44910. var engine = scene.getEngine();
  44911. if (!this.checkReadyOnEveryCall) {
  44912. if (this._renderId === scene.getRenderId()) {
  44913. if (this._checkCache(scene, mesh, useInstances)) {
  44914. return true;
  44915. }
  44916. }
  44917. }
  44918. // Instances
  44919. var defines = [];
  44920. var fallbacks = new BABYLON.EffectFallbacks();
  44921. if (useInstances) {
  44922. defines.push("#define INSTANCES");
  44923. }
  44924. for (var index = 0; index < this._options.defines.length; index++) {
  44925. defines.push(this._options.defines[index]);
  44926. }
  44927. // Bones
  44928. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  44929. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  44930. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  44931. fallbacks.addCPUSkinningFallback(0, mesh);
  44932. }
  44933. // Alpha test
  44934. if (engine.getAlphaTesting()) {
  44935. defines.push("#define ALPHATEST");
  44936. }
  44937. var previousEffect = this._effect;
  44938. var join = defines.join("\n");
  44939. this._effect = engine.createEffect(this._shaderPath, this._options.attributes, this._options.uniforms, this._options.samplers, join, fallbacks, this.onCompiled, this.onError);
  44940. if (!this._effect.isReady()) {
  44941. return false;
  44942. }
  44943. if (previousEffect !== this._effect) {
  44944. scene.resetCachedMaterial();
  44945. }
  44946. this._renderId = scene.getRenderId();
  44947. return true;
  44948. };
  44949. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  44950. var scene = this.getScene();
  44951. if (this._options.uniforms.indexOf("world") !== -1) {
  44952. this._effect.setMatrix("world", world);
  44953. }
  44954. if (this._options.uniforms.indexOf("worldView") !== -1) {
  44955. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  44956. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  44957. }
  44958. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  44959. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  44960. }
  44961. };
  44962. ShaderMaterial.prototype.bind = function (world, mesh) {
  44963. // Std values
  44964. this.bindOnlyWorldMatrix(world);
  44965. if (this.getScene().getCachedMaterial() !== this) {
  44966. if (this._options.uniforms.indexOf("view") !== -1) {
  44967. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  44968. }
  44969. if (this._options.uniforms.indexOf("projection") !== -1) {
  44970. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  44971. }
  44972. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  44973. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  44974. }
  44975. // Bones
  44976. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  44977. var name;
  44978. // Texture
  44979. for (name in this._textures) {
  44980. this._effect.setTexture(name, this._textures[name]);
  44981. }
  44982. // Texture arrays
  44983. for (name in this._textureArrays) {
  44984. this._effect.setTextureArray(name, this._textureArrays[name]);
  44985. }
  44986. // Float
  44987. for (name in this._floats) {
  44988. this._effect.setFloat(name, this._floats[name]);
  44989. }
  44990. // Float s
  44991. for (name in this._floatsArrays) {
  44992. this._effect.setArray(name, this._floatsArrays[name]);
  44993. }
  44994. // Color3
  44995. for (name in this._colors3) {
  44996. this._effect.setColor3(name, this._colors3[name]);
  44997. }
  44998. // Color4
  44999. for (name in this._colors4) {
  45000. var color = this._colors4[name];
  45001. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  45002. }
  45003. // Vector2
  45004. for (name in this._vectors2) {
  45005. this._effect.setVector2(name, this._vectors2[name]);
  45006. }
  45007. // Vector3
  45008. for (name in this._vectors3) {
  45009. this._effect.setVector3(name, this._vectors3[name]);
  45010. }
  45011. // Vector4
  45012. for (name in this._vectors4) {
  45013. this._effect.setVector4(name, this._vectors4[name]);
  45014. }
  45015. // Matrix
  45016. for (name in this._matrices) {
  45017. this._effect.setMatrix(name, this._matrices[name]);
  45018. }
  45019. // Matrix 3x3
  45020. for (name in this._matrices3x3) {
  45021. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  45022. }
  45023. // Matrix 2x2
  45024. for (name in this._matrices2x2) {
  45025. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  45026. }
  45027. // Vector3Array
  45028. for (name in this._vectors3Arrays) {
  45029. this._effect.setArray3(name, this._vectors3Arrays[name]);
  45030. }
  45031. }
  45032. _super.prototype.bind.call(this, world, mesh);
  45033. };
  45034. ShaderMaterial.prototype.clone = function (name) {
  45035. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  45036. return newShaderMaterial;
  45037. };
  45038. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  45039. if (forceDisposeTextures) {
  45040. var name;
  45041. for (name in this._textures) {
  45042. this._textures[name].dispose();
  45043. }
  45044. for (name in this._textureArrays) {
  45045. var array = this._textureArrays[name];
  45046. for (var index = 0; index < array.length; index++) {
  45047. array[index].dispose();
  45048. }
  45049. }
  45050. }
  45051. this._textures = {};
  45052. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  45053. };
  45054. ShaderMaterial.prototype.serialize = function () {
  45055. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  45056. serializationObject.customType = "BABYLON.ShaderMaterial";
  45057. serializationObject.options = this._options;
  45058. serializationObject.shaderPath = this._shaderPath;
  45059. var name;
  45060. // Texture
  45061. serializationObject.textures = {};
  45062. for (name in this._textures) {
  45063. serializationObject.textures[name] = this._textures[name].serialize();
  45064. }
  45065. // Texture arrays
  45066. serializationObject.textureArrays = {};
  45067. for (name in this._textureArrays) {
  45068. serializationObject.textureArrays[name] = [];
  45069. var array = this._textureArrays[name];
  45070. for (var index = 0; index < array.length; index++) {
  45071. serializationObject.textureArrays[name].push(array[index].serialize());
  45072. }
  45073. }
  45074. // Float
  45075. serializationObject.floats = {};
  45076. for (name in this._floats) {
  45077. serializationObject.floats[name] = this._floats[name];
  45078. }
  45079. // Float s
  45080. serializationObject.floatArrays = {};
  45081. for (name in this._floatsArrays) {
  45082. serializationObject.floatArrays[name] = this._floatsArrays[name];
  45083. }
  45084. // Color3
  45085. serializationObject.colors3 = {};
  45086. for (name in this._colors3) {
  45087. serializationObject.colors3[name] = this._colors3[name].asArray();
  45088. }
  45089. // Color4
  45090. serializationObject.colors4 = {};
  45091. for (name in this._colors4) {
  45092. serializationObject.colors4[name] = this._colors4[name].asArray();
  45093. }
  45094. // Vector2
  45095. serializationObject.vectors2 = {};
  45096. for (name in this._vectors2) {
  45097. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  45098. }
  45099. // Vector3
  45100. serializationObject.vectors3 = {};
  45101. for (name in this._vectors3) {
  45102. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  45103. }
  45104. // Vector4
  45105. serializationObject.vectors4 = {};
  45106. for (name in this._vectors4) {
  45107. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  45108. }
  45109. // Matrix
  45110. serializationObject.matrices = {};
  45111. for (name in this._matrices) {
  45112. serializationObject.matrices[name] = this._matrices[name].asArray();
  45113. }
  45114. // Matrix 3x3
  45115. serializationObject.matrices3x3 = {};
  45116. for (name in this._matrices3x3) {
  45117. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  45118. }
  45119. // Matrix 2x2
  45120. serializationObject.matrices2x2 = {};
  45121. for (name in this._matrices2x2) {
  45122. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  45123. }
  45124. // Vector3Array
  45125. serializationObject.vectors3Arrays = {};
  45126. for (name in this._vectors3Arrays) {
  45127. serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];
  45128. }
  45129. return serializationObject;
  45130. };
  45131. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  45132. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  45133. var name;
  45134. // Texture
  45135. for (name in source.textures) {
  45136. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  45137. }
  45138. // Texture arrays
  45139. for (name in source.textureArrays) {
  45140. var array = source.textureArrays[name];
  45141. var textureArray = new Array();
  45142. for (var index = 0; index < array.length; index++) {
  45143. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  45144. }
  45145. material.setTextureArray(name, textureArray);
  45146. }
  45147. // Float
  45148. for (name in source.floats) {
  45149. material.setFloat(name, source.floats[name]);
  45150. }
  45151. // Float s
  45152. for (name in source.floatsArrays) {
  45153. material.setFloats(name, source.floatsArrays[name]);
  45154. }
  45155. // Color3
  45156. for (name in source.colors3) {
  45157. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  45158. }
  45159. // Color4
  45160. for (name in source.colors4) {
  45161. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  45162. }
  45163. // Vector2
  45164. for (name in source.vectors2) {
  45165. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  45166. }
  45167. // Vector3
  45168. for (name in source.vectors3) {
  45169. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  45170. }
  45171. // Vector4
  45172. for (name in source.vectors4) {
  45173. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  45174. }
  45175. // Matrix
  45176. for (name in source.matrices) {
  45177. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  45178. }
  45179. // Matrix 3x3
  45180. for (name in source.matrices3x3) {
  45181. material.setMatrix3x3(name, source.matrices3x3[name]);
  45182. }
  45183. // Matrix 2x2
  45184. for (name in source.matrices2x2) {
  45185. material.setMatrix2x2(name, source.matrices2x2[name]);
  45186. }
  45187. // Vector3Array
  45188. for (name in source.vectors3Arrays) {
  45189. material.setArray3(name, source.vectors3Arrays[name]);
  45190. }
  45191. return material;
  45192. };
  45193. return ShaderMaterial;
  45194. }(BABYLON.Material));
  45195. BABYLON.ShaderMaterial = ShaderMaterial;
  45196. })(BABYLON || (BABYLON = {}));
  45197. //# sourceMappingURL=babylon.shaderMaterial.js.map
  45198. var BABYLON;
  45199. (function (BABYLON) {
  45200. var Internals;
  45201. (function (Internals) {
  45202. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  45203. // All values and structures referenced from:
  45204. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  45205. var DDS_MAGIC = 0x20534444;
  45206. 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;
  45207. var DDSCAPS_COMPLEX = 0x8, DDSCAPS_MIPMAP = 0x400000, DDSCAPS_TEXTURE = 0x1000;
  45208. 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;
  45209. var DDPF_ALPHAPIXELS = 0x1, DDPF_ALPHA = 0x2, DDPF_FOURCC = 0x4, DDPF_RGB = 0x40, DDPF_YUV = 0x200, DDPF_LUMINANCE = 0x20000;
  45210. function FourCCToInt32(value) {
  45211. return value.charCodeAt(0) +
  45212. (value.charCodeAt(1) << 8) +
  45213. (value.charCodeAt(2) << 16) +
  45214. (value.charCodeAt(3) << 24);
  45215. }
  45216. function Int32ToFourCC(value) {
  45217. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  45218. }
  45219. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  45220. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  45221. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  45222. var headerLengthInt = 31; // The header length in 32 bit ints
  45223. // Offsets into the header array
  45224. var off_magic = 0;
  45225. var off_size = 1;
  45226. var off_flags = 2;
  45227. var off_height = 3;
  45228. var off_width = 4;
  45229. var off_mipmapCount = 7;
  45230. var off_pfFlags = 20;
  45231. var off_pfFourCC = 21;
  45232. var off_RGBbpp = 22;
  45233. var off_RMask = 23;
  45234. var off_GMask = 24;
  45235. var off_BMask = 25;
  45236. var off_AMask = 26;
  45237. var off_caps1 = 27;
  45238. var off_caps2 = 28;
  45239. ;
  45240. var DDSTools = (function () {
  45241. function DDSTools() {
  45242. }
  45243. DDSTools.GetDDSInfo = function (arrayBuffer) {
  45244. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  45245. var mipmapCount = 1;
  45246. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  45247. mipmapCount = Math.max(1, header[off_mipmapCount]);
  45248. }
  45249. return {
  45250. width: header[off_width],
  45251. height: header[off_height],
  45252. mipmapCount: mipmapCount,
  45253. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  45254. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  45255. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  45256. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP
  45257. };
  45258. };
  45259. DDSTools.GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  45260. var byteArray = new Uint8Array(dataLength);
  45261. var srcData = new Uint8Array(arrayBuffer);
  45262. var index = 0;
  45263. for (var y = height - 1; y >= 0; y--) {
  45264. for (var x = 0; x < width; x++) {
  45265. var srcPos = dataOffset + (x + y * width) * 4;
  45266. byteArray[index + 2] = srcData[srcPos];
  45267. byteArray[index + 1] = srcData[srcPos + 1];
  45268. byteArray[index] = srcData[srcPos + 2];
  45269. byteArray[index + 3] = srcData[srcPos + 3];
  45270. index += 4;
  45271. }
  45272. }
  45273. return byteArray;
  45274. };
  45275. DDSTools.GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  45276. var byteArray = new Uint8Array(dataLength);
  45277. var srcData = new Uint8Array(arrayBuffer);
  45278. var index = 0;
  45279. for (var y = height - 1; y >= 0; y--) {
  45280. for (var x = 0; x < width; x++) {
  45281. var srcPos = dataOffset + (x + y * width) * 3;
  45282. byteArray[index + 2] = srcData[srcPos];
  45283. byteArray[index + 1] = srcData[srcPos + 1];
  45284. byteArray[index] = srcData[srcPos + 2];
  45285. index += 3;
  45286. }
  45287. }
  45288. return byteArray;
  45289. };
  45290. DDSTools.GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  45291. var byteArray = new Uint8Array(dataLength);
  45292. var srcData = new Uint8Array(arrayBuffer);
  45293. var index = 0;
  45294. for (var y = height - 1; y >= 0; y--) {
  45295. for (var x = 0; x < width; x++) {
  45296. var srcPos = dataOffset + (x + y * width);
  45297. byteArray[index] = srcData[srcPos];
  45298. index++;
  45299. }
  45300. }
  45301. return byteArray;
  45302. };
  45303. DDSTools.UploadDDSLevels = function (gl, ext, arrayBuffer, info, loadMipmaps, faces) {
  45304. var header = new Int32Array(arrayBuffer, 0, headerLengthInt), fourCC, blockBytes, internalFormat, width, height, dataLength, dataOffset, byteArray, mipmapCount, i;
  45305. if (header[off_magic] != DDS_MAGIC) {
  45306. BABYLON.Tools.Error("Invalid magic number in DDS header");
  45307. return;
  45308. }
  45309. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  45310. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  45311. return;
  45312. }
  45313. if (info.isFourCC) {
  45314. fourCC = header[off_pfFourCC];
  45315. switch (fourCC) {
  45316. case FOURCC_DXT1:
  45317. blockBytes = 8;
  45318. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  45319. break;
  45320. case FOURCC_DXT3:
  45321. blockBytes = 16;
  45322. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  45323. break;
  45324. case FOURCC_DXT5:
  45325. blockBytes = 16;
  45326. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  45327. break;
  45328. default:
  45329. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  45330. return;
  45331. }
  45332. }
  45333. mipmapCount = 1;
  45334. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  45335. mipmapCount = Math.max(1, header[off_mipmapCount]);
  45336. }
  45337. var bpp = header[off_RGBbpp];
  45338. for (var face = 0; face < faces; face++) {
  45339. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  45340. width = header[off_width];
  45341. height = header[off_height];
  45342. dataOffset = header[off_size] + 4;
  45343. for (i = 0; i < mipmapCount; ++i) {
  45344. if (info.isRGB) {
  45345. if (bpp === 24) {
  45346. dataLength = width * height * 3;
  45347. byteArray = DDSTools.GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  45348. gl.texImage2D(sampler, i, gl.RGB, width, height, 0, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  45349. }
  45350. else {
  45351. dataLength = width * height * 4;
  45352. byteArray = DDSTools.GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  45353. gl.texImage2D(sampler, i, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  45354. }
  45355. }
  45356. else if (info.isLuminance) {
  45357. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  45358. var unpaddedRowSize = width;
  45359. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  45360. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  45361. byteArray = DDSTools.GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  45362. gl.texImage2D(sampler, i, gl.LUMINANCE, width, height, 0, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  45363. }
  45364. else {
  45365. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  45366. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  45367. gl.compressedTexImage2D(sampler, i, internalFormat, width, height, 0, byteArray);
  45368. }
  45369. dataOffset += dataLength;
  45370. width *= 0.5;
  45371. height *= 0.5;
  45372. width = Math.max(1.0, width);
  45373. height = Math.max(1.0, height);
  45374. }
  45375. }
  45376. };
  45377. return DDSTools;
  45378. }());
  45379. Internals.DDSTools = DDSTools;
  45380. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  45381. })(BABYLON || (BABYLON = {}));
  45382. //# sourceMappingURL=babylon.tools.dds.js.map
  45383. var BABYLON;
  45384. (function (BABYLON) {
  45385. var Internals;
  45386. (function (Internals) {
  45387. /**
  45388. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  45389. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  45390. */
  45391. var KhronosTextureContainer = (function () {
  45392. /**
  45393. * @param {ArrayBuffer} arrayBuffer- contents of the KTX container file
  45394. * @param {number} facesExpected- should be either 1 or 6, based whether a cube texture or or
  45395. * @param {boolean} threeDExpected- provision for indicating that data should be a 3D texture, not implemented
  45396. * @param {boolean} textureArrayExpected- provision for indicating that data should be a texture array, not implemented
  45397. */
  45398. function KhronosTextureContainer(arrayBuffer, facesExpected, threeDExpected, textureArrayExpected) {
  45399. this.arrayBuffer = arrayBuffer;
  45400. // Test that it is a ktx formatted file, based on the first 12 bytes, character representation is:
  45401. // '�', 'K', 'T', 'X', ' ', '1', '1', '�', '\r', '\n', '\x1A', '\n'
  45402. // 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A
  45403. var identifier = new Uint8Array(this.arrayBuffer, 0, 12);
  45404. if (identifier[0] !== 0xAB || identifier[1] !== 0x4B || identifier[2] !== 0x54 || identifier[3] !== 0x58 || identifier[4] !== 0x20 || identifier[5] !== 0x31 ||
  45405. identifier[6] !== 0x31 || identifier[7] !== 0xBB || identifier[8] !== 0x0D || identifier[9] !== 0x0A || identifier[10] !== 0x1A || identifier[11] !== 0x0A) {
  45406. BABYLON.Tools.Error("texture missing KTX identifier");
  45407. return;
  45408. }
  45409. // load the reset of the header in native 32 bit int
  45410. var header = new Int32Array(this.arrayBuffer, 12, 13);
  45411. // determine of the remaining header values are recorded in the opposite endianness & require conversion
  45412. var oppositeEndianess = header[0] === 0x01020304;
  45413. // read all the header elements in order they exist in the file, without modification (sans endainness)
  45414. this.glType = oppositeEndianess ? this.switchEndainness(header[1]) : header[1]; // must be 0 for compressed textures
  45415. this.glTypeSize = oppositeEndianess ? this.switchEndainness(header[2]) : header[2]; // must be 1 for compressed textures
  45416. this.glFormat = oppositeEndianess ? this.switchEndainness(header[3]) : header[3]; // must be 0 for compressed textures
  45417. this.glInternalFormat = oppositeEndianess ? this.switchEndainness(header[4]) : header[4]; // the value of arg passed to gl.compressedTexImage2D(,,x,,,,)
  45418. this.glBaseInternalFormat = oppositeEndianess ? this.switchEndainness(header[5]) : header[5]; // specify GL_RGB, GL_RGBA, GL_ALPHA, etc (un-compressed only)
  45419. this.pixelWidth = oppositeEndianess ? this.switchEndainness(header[6]) : header[6]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,x,,,)
  45420. this.pixelHeight = oppositeEndianess ? this.switchEndainness(header[7]) : header[7]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,,x,,)
  45421. this.pixelDepth = oppositeEndianess ? this.switchEndainness(header[8]) : header[8]; // level 0 value of arg passed to gl.compressedTexImage3D(,,,,,x,,)
  45422. this.numberOfArrayElements = oppositeEndianess ? this.switchEndainness(header[9]) : header[9]; // used for texture arrays
  45423. this.numberOfFaces = oppositeEndianess ? this.switchEndainness(header[10]) : header[10]; // used for cubemap textures, should either be 1 or 6
  45424. this.numberOfMipmapLevels = oppositeEndianess ? this.switchEndainness(header[11]) : header[11]; // number of levels; disregard possibility of 0 for compressed textures
  45425. this.bytesOfKeyValueData = oppositeEndianess ? this.switchEndainness(header[12]) : header[12]; // the amount of space after the header for meta-data
  45426. // Make sure we have a compressed type. Not only reduces work, but probably better to let dev know they are not compressing.
  45427. if (this.glType !== 0) {
  45428. BABYLON.Tools.Error("only compressed formats currently supported");
  45429. return;
  45430. }
  45431. else {
  45432. // value of zero is an indication to generate mipmaps @ runtime. Not usually allowed for compressed, so disregard.
  45433. this.numberOfMipmapLevels = Math.max(1, this.numberOfMipmapLevels);
  45434. }
  45435. if (this.pixelHeight === 0 || this.pixelDepth !== 0) {
  45436. BABYLON.Tools.Error("only 2D textures currently supported");
  45437. return;
  45438. }
  45439. if (this.numberOfArrayElements !== 0) {
  45440. BABYLON.Tools.Error("texture arrays not currently supported");
  45441. return;
  45442. }
  45443. if (this.numberOfFaces !== facesExpected) {
  45444. BABYLON.Tools.Error("number of faces expected" + facesExpected + ", but found " + this.numberOfFaces);
  45445. return;
  45446. }
  45447. // we now have a completely validated file, so could use existence of loadType as success
  45448. // would need to make this more elaborate & adjust checks above to support more than one load type
  45449. this.loadType = KhronosTextureContainer.COMPRESSED_2D;
  45450. }
  45451. // not as fast hardware based, but will probably never need to use
  45452. KhronosTextureContainer.prototype.switchEndainness = function (val) {
  45453. return ((val & 0xFF) << 24)
  45454. | ((val & 0xFF00) << 8)
  45455. | ((val >> 8) & 0xFF00)
  45456. | ((val >> 24) & 0xFF);
  45457. };
  45458. /**
  45459. * It is assumed that the texture has already been created & is currently bound
  45460. */
  45461. KhronosTextureContainer.prototype.uploadLevels = function (gl, loadMipmaps) {
  45462. switch (this.loadType) {
  45463. case KhronosTextureContainer.COMPRESSED_2D:
  45464. this._upload2DCompressedLevels(gl, loadMipmaps);
  45465. break;
  45466. case KhronosTextureContainer.TEX_2D:
  45467. case KhronosTextureContainer.COMPRESSED_3D:
  45468. case KhronosTextureContainer.TEX_3D:
  45469. }
  45470. };
  45471. KhronosTextureContainer.prototype._upload2DCompressedLevels = function (gl, loadMipmaps) {
  45472. // initialize width & height for level 1
  45473. var dataOffset = KhronosTextureContainer.HEADER_LEN + this.bytesOfKeyValueData;
  45474. var width = this.pixelWidth;
  45475. var height = this.pixelHeight;
  45476. var mipmapCount = loadMipmaps ? this.numberOfMipmapLevels : 1;
  45477. for (var level = 0; level < mipmapCount; level++) {
  45478. var imageSize = new Int32Array(this.arrayBuffer, dataOffset, 1)[0]; // size per face, since not supporting array cubemaps
  45479. for (var face = 0; face < this.numberOfFaces; face++) {
  45480. var sampler = this.numberOfFaces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  45481. var byteArray = new Uint8Array(this.arrayBuffer, dataOffset + 4, imageSize);
  45482. gl.compressedTexImage2D(sampler, level, this.glInternalFormat, width, height, 0, byteArray);
  45483. dataOffset += imageSize + 4; // size of the image + 4 for the imageSize field
  45484. dataOffset += 3 - ((imageSize + 3) % 4); // add padding for odd sized image
  45485. }
  45486. width = Math.max(1.0, width * 0.5);
  45487. height = Math.max(1.0, height * 0.5);
  45488. }
  45489. };
  45490. return KhronosTextureContainer;
  45491. }());
  45492. KhronosTextureContainer.HEADER_LEN = 12 + (13 * 4); // identifier + header elements (not including key value meta-data pairs)
  45493. // load types
  45494. KhronosTextureContainer.COMPRESSED_2D = 0; // uses a gl.compressedTexImage2D()
  45495. KhronosTextureContainer.COMPRESSED_3D = 1; // uses a gl.compressedTexImage3D()
  45496. KhronosTextureContainer.TEX_2D = 2; // uses a gl.texImage2D()
  45497. KhronosTextureContainer.TEX_3D = 3; // uses a gl.texImage3D()
  45498. Internals.KhronosTextureContainer = KhronosTextureContainer;
  45499. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  45500. })(BABYLON || (BABYLON = {}));
  45501. //# sourceMappingURL=babylon.khronosTextureContainer.js.map
  45502. var BABYLON;
  45503. (function (BABYLON) {
  45504. var CannonJSPlugin = (function () {
  45505. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  45506. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  45507. if (iterations === void 0) { iterations = 10; }
  45508. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  45509. this.name = "CannonJSPlugin";
  45510. this._physicsMaterials = [];
  45511. this._fixedTimeStep = 1 / 60;
  45512. //See https://github.com/schteppe/cannon.js/blob/gh-pages/demos/collisionFilter.html
  45513. this._currentCollisionGroup = 2;
  45514. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  45515. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  45516. this._tmpPosition = BABYLON.Vector3.Zero();
  45517. this._tmpQuaternion = new BABYLON.Quaternion();
  45518. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  45519. this._tmpDeltaRotation = new BABYLON.Quaternion();
  45520. this._tmpUnityRotation = new BABYLON.Quaternion();
  45521. if (!this.isSupported()) {
  45522. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  45523. return;
  45524. }
  45525. this.world = new CANNON.World();
  45526. this.world.broadphase = new CANNON.NaiveBroadphase();
  45527. this.world.solver.iterations = iterations;
  45528. }
  45529. CannonJSPlugin.prototype.setGravity = function (gravity) {
  45530. this.world.gravity.copy(gravity);
  45531. };
  45532. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  45533. this._fixedTimeStep = timeStep;
  45534. };
  45535. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  45536. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta * 1000 : 0, 3);
  45537. };
  45538. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  45539. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  45540. var impulse = new CANNON.Vec3(force.x, force.y, force.z);
  45541. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  45542. };
  45543. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  45544. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  45545. var impulse = new CANNON.Vec3(force.x, force.y, force.z);
  45546. impostor.physicsBody.applyForce(impulse, worldPoint);
  45547. };
  45548. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  45549. //parent-child relationship. Does this impostor has a parent impostor?
  45550. if (impostor.parent) {
  45551. if (impostor.physicsBody) {
  45552. this.removePhysicsBody(impostor);
  45553. //TODO is that needed?
  45554. impostor.forceUpdate();
  45555. }
  45556. return;
  45557. }
  45558. //should a new body be created for this impostor?
  45559. if (impostor.isBodyInitRequired()) {
  45560. var shape = this._createShape(impostor);
  45561. //unregister events, if body is being changed
  45562. var oldBody = impostor.physicsBody;
  45563. if (oldBody) {
  45564. this.removePhysicsBody(impostor);
  45565. }
  45566. //create the body and material
  45567. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  45568. var bodyCreationObject = {
  45569. mass: impostor.getParam("mass"),
  45570. material: material
  45571. };
  45572. // A simple extend, in case native options were used.
  45573. var nativeOptions = impostor.getParam("nativeOptions");
  45574. for (var key in nativeOptions) {
  45575. if (nativeOptions.hasOwnProperty(key)) {
  45576. bodyCreationObject[key] = nativeOptions[key];
  45577. }
  45578. }
  45579. impostor.physicsBody = new CANNON.Body(bodyCreationObject);
  45580. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  45581. this.world.addEventListener("preStep", impostor.beforeStep);
  45582. this.world.addEventListener("postStep", impostor.afterStep);
  45583. impostor.physicsBody.addShape(shape);
  45584. this.world.add(impostor.physicsBody);
  45585. //try to keep the body moving in the right direction by taking old properties.
  45586. //Should be tested!
  45587. if (oldBody) {
  45588. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  45589. impostor.physicsBody[param].copy(oldBody[param]);
  45590. });
  45591. }
  45592. this._processChildMeshes(impostor);
  45593. }
  45594. //now update the body's transformation
  45595. this._updatePhysicsBodyTransformation(impostor);
  45596. };
  45597. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  45598. var _this = this;
  45599. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes() : [];
  45600. if (meshChildren.length) {
  45601. var processMesh = function (localPosition, mesh) {
  45602. var childImpostor = mesh.getPhysicsImpostor();
  45603. if (childImpostor) {
  45604. var parent = childImpostor.parent;
  45605. if (parent !== mainImpostor) {
  45606. var localPosition = mesh.position;
  45607. if (childImpostor.physicsBody) {
  45608. _this.removePhysicsBody(childImpostor);
  45609. childImpostor.physicsBody = null;
  45610. }
  45611. childImpostor.parent = mainImpostor;
  45612. childImpostor.resetUpdateFlags();
  45613. mainImpostor.physicsBody.addShape(_this._createShape(childImpostor), new CANNON.Vec3(localPosition.x, localPosition.y, localPosition.z));
  45614. //Add the mass of the children.
  45615. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  45616. }
  45617. }
  45618. mesh.getChildMeshes().forEach(processMesh.bind(_this, mesh.position));
  45619. };
  45620. meshChildren.forEach(processMesh.bind(this, BABYLON.Vector3.Zero()));
  45621. }
  45622. };
  45623. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  45624. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  45625. this.world.removeEventListener("preStep", impostor.beforeStep);
  45626. this.world.removeEventListener("postStep", impostor.afterStep);
  45627. this.world.remove(impostor.physicsBody);
  45628. };
  45629. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  45630. var mainBody = impostorJoint.mainImpostor.physicsBody;
  45631. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  45632. if (!mainBody || !connectedBody) {
  45633. return;
  45634. }
  45635. var constraint;
  45636. var jointData = impostorJoint.joint.jointData;
  45637. //TODO - https://github.com/schteppe/cannon.js/blob/gh-pages/demos/collisionFilter.html
  45638. var constraintData = {
  45639. pivotA: jointData.mainPivot ? new CANNON.Vec3().copy(jointData.mainPivot) : null,
  45640. pivotB: jointData.connectedPivot ? new CANNON.Vec3().copy(jointData.connectedPivot) : null,
  45641. axisA: jointData.mainAxis ? new CANNON.Vec3().copy(jointData.mainAxis) : null,
  45642. axisB: jointData.connectedAxis ? new CANNON.Vec3().copy(jointData.connectedAxis) : null,
  45643. maxForce: jointData.nativeParams.maxForce,
  45644. collideConnected: !!jointData.collision
  45645. };
  45646. switch (impostorJoint.joint.type) {
  45647. case BABYLON.PhysicsJoint.HingeJoint:
  45648. case BABYLON.PhysicsJoint.Hinge2Joint:
  45649. constraint = new CANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  45650. break;
  45651. case BABYLON.PhysicsJoint.DistanceJoint:
  45652. constraint = new CANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  45653. break;
  45654. case BABYLON.PhysicsJoint.SpringJoint:
  45655. var springData = jointData;
  45656. constraint = new CANNON.Spring(mainBody, connectedBody, {
  45657. restLength: springData.length,
  45658. stiffness: springData.stiffness,
  45659. damping: springData.damping,
  45660. localAnchorA: constraintData.pivotA,
  45661. localAnchorB: constraintData.pivotB
  45662. });
  45663. break;
  45664. case BABYLON.PhysicsJoint.LockJoint:
  45665. constraint = new CANNON.LockConstraint(mainBody, connectedBody, constraintData);
  45666. break;
  45667. case BABYLON.PhysicsJoint.PointToPointJoint:
  45668. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  45669. default:
  45670. constraint = new CANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  45671. break;
  45672. }
  45673. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  45674. constraint.collideConnected = !!jointData.collision;
  45675. impostorJoint.joint.physicsJoint = constraint;
  45676. //don't add spring as constraint, as it is not one.
  45677. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  45678. this.world.addConstraint(constraint);
  45679. }
  45680. else {
  45681. impostorJoint.mainImpostor.registerAfterPhysicsStep(function () {
  45682. constraint.applyForce();
  45683. });
  45684. }
  45685. };
  45686. CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
  45687. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  45688. };
  45689. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  45690. var index;
  45691. var mat;
  45692. for (index = 0; index < this._physicsMaterials.length; index++) {
  45693. mat = this._physicsMaterials[index];
  45694. if (mat.friction === friction && mat.restitution === restitution) {
  45695. return mat;
  45696. }
  45697. }
  45698. var currentMat = new CANNON.Material(name);
  45699. currentMat.friction = friction;
  45700. currentMat.restitution = restitution;
  45701. this._physicsMaterials.push(currentMat);
  45702. return currentMat;
  45703. };
  45704. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  45705. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  45706. };
  45707. CannonJSPlugin.prototype._createShape = function (impostor) {
  45708. var object = impostor.object;
  45709. var returnValue;
  45710. var extendSize = impostor.getObjectExtendSize();
  45711. switch (impostor.type) {
  45712. case BABYLON.PhysicsImpostor.SphereImpostor:
  45713. var radiusX = extendSize.x;
  45714. var radiusY = extendSize.y;
  45715. var radiusZ = extendSize.z;
  45716. returnValue = new CANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  45717. break;
  45718. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  45719. case BABYLON.PhysicsImpostor.CylinderImpostor:
  45720. returnValue = new CANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  45721. break;
  45722. case BABYLON.PhysicsImpostor.BoxImpostor:
  45723. var box = extendSize.scale(0.5);
  45724. returnValue = new CANNON.Box(new CANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  45725. break;
  45726. case BABYLON.PhysicsImpostor.PlaneImpostor:
  45727. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  45728. returnValue = new CANNON.Plane();
  45729. break;
  45730. case BABYLON.PhysicsImpostor.MeshImpostor:
  45731. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  45732. var rawFaces = object.getIndices ? object.getIndices() : [];
  45733. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  45734. returnValue = new CANNON.Trimesh(rawVerts, rawFaces);
  45735. break;
  45736. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  45737. returnValue = this._createHeightmap(object);
  45738. break;
  45739. case BABYLON.PhysicsImpostor.ParticleImpostor:
  45740. returnValue = new CANNON.Particle();
  45741. break;
  45742. }
  45743. return returnValue;
  45744. };
  45745. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  45746. var pos = object.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  45747. var matrix = [];
  45748. //For now pointDepth will not be used and will be automatically calculated.
  45749. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  45750. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  45751. var dim = Math.min(object.getBoundingInfo().boundingBox.extendSize.x, object.getBoundingInfo().boundingBox.extendSize.z);
  45752. var elementSize = dim * 2 / arraySize;
  45753. var minY = object.getBoundingInfo().boundingBox.extendSize.y;
  45754. for (var i = 0; i < pos.length; i = i + 3) {
  45755. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  45756. var z = Math.round(((pos[i + 2]) / elementSize - arraySize / 2) * -1);
  45757. var y = pos[i + 1] + minY;
  45758. if (!matrix[x]) {
  45759. matrix[x] = [];
  45760. }
  45761. if (!matrix[x][z]) {
  45762. matrix[x][z] = y;
  45763. }
  45764. matrix[x][z] = Math.max(y, matrix[x][z]);
  45765. }
  45766. for (var x = 0; x <= arraySize; ++x) {
  45767. if (!matrix[x]) {
  45768. var loc = 1;
  45769. while (!matrix[(x + loc) % arraySize]) {
  45770. loc++;
  45771. }
  45772. matrix[x] = matrix[(x + loc) % arraySize].slice();
  45773. }
  45774. for (var z = 0; z <= arraySize; ++z) {
  45775. if (!matrix[x][z]) {
  45776. var loc = 1;
  45777. var newValue;
  45778. while (newValue === undefined) {
  45779. newValue = matrix[x][(z + loc++) % arraySize];
  45780. }
  45781. matrix[x][z] = newValue;
  45782. }
  45783. }
  45784. }
  45785. var shape = new CANNON.Heightfield(matrix, {
  45786. elementSize: elementSize
  45787. });
  45788. //For future reference, needed for body transformation
  45789. shape.minY = minY;
  45790. return shape;
  45791. };
  45792. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  45793. var object = impostor.object;
  45794. //make sure it is updated...
  45795. object.computeWorldMatrix && object.computeWorldMatrix(true);
  45796. // The delta between the mesh position and the mesh bounding box center
  45797. var center = impostor.getObjectCenter();
  45798. var extendSize = impostor.getObjectExtendSize();
  45799. this._tmpDeltaPosition.copyFrom(object.position.subtract(center));
  45800. this._tmpPosition.copyFrom(center);
  45801. var quaternion = object.rotationQuaternion;
  45802. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  45803. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  45804. //-90 DEG in X, precalculated
  45805. quaternion = quaternion.multiply(this._minus90X);
  45806. //Invert! (Precalculated, 90 deg in X)
  45807. //No need to clone. this will never change.
  45808. impostor.setDeltaRotation(this._plus90X);
  45809. }
  45810. //If it is a heightfield, if should be centered.
  45811. if (impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor) {
  45812. var mesh = object;
  45813. //calculate the correct body position:
  45814. var rotationQuaternion = mesh.rotationQuaternion;
  45815. mesh.rotationQuaternion = this._tmpUnityRotation;
  45816. mesh.computeWorldMatrix(true);
  45817. //get original center with no rotation
  45818. var c = center.clone();
  45819. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  45820. //rotation is back
  45821. mesh.rotationQuaternion = rotationQuaternion;
  45822. //calculate the new center using a pivot (since Cannon.js doesn't center height maps)
  45823. var p = BABYLON.Matrix.Translation(mesh.getBoundingInfo().boundingBox.extendSize.x, 0, -mesh.getBoundingInfo().boundingBox.extendSize.z);
  45824. mesh.setPivotMatrix(p);
  45825. mesh.computeWorldMatrix(true);
  45826. //calculate the translation
  45827. var translation = mesh.getBoundingInfo().boundingBox.center.subtract(center).subtract(mesh.position).negate();
  45828. this._tmpPosition.copyFromFloats(translation.x, translation.y - mesh.getBoundingInfo().boundingBox.extendSize.y, translation.z);
  45829. //add it inverted to the delta
  45830. this._tmpDeltaPosition.copyFrom(mesh.getBoundingInfo().boundingBox.center.subtract(c));
  45831. this._tmpDeltaPosition.y += mesh.getBoundingInfo().boundingBox.extendSize.y;
  45832. mesh.setPivotMatrix(oldPivot);
  45833. mesh.computeWorldMatrix(true);
  45834. }
  45835. else if (impostor.type === BABYLON.PhysicsImpostor.MeshImpostor) {
  45836. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  45837. this._tmpPosition.copyFrom(object.position);
  45838. }
  45839. impostor.setDeltaPosition(this._tmpDeltaPosition);
  45840. //Now update the impostor object
  45841. impostor.physicsBody.position.copy(this._tmpPosition);
  45842. impostor.physicsBody.quaternion.copy(quaternion);
  45843. };
  45844. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  45845. impostor.object.position.copyFrom(impostor.physicsBody.position);
  45846. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  45847. };
  45848. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  45849. impostor.physicsBody.position.copy(newPosition);
  45850. impostor.physicsBody.quaternion.copy(newRotation);
  45851. };
  45852. CannonJSPlugin.prototype.isSupported = function () {
  45853. return window.CANNON !== undefined;
  45854. };
  45855. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  45856. impostor.physicsBody.velocity.copy(velocity);
  45857. };
  45858. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  45859. impostor.physicsBody.angularVelocity.copy(velocity);
  45860. };
  45861. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  45862. var v = impostor.physicsBody.velocity;
  45863. if (!v)
  45864. return null;
  45865. return new BABYLON.Vector3(v.x, v.y, v.z);
  45866. };
  45867. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  45868. var v = impostor.physicsBody.angularVelocity;
  45869. if (!v)
  45870. return null;
  45871. return new BABYLON.Vector3(v.x, v.y, v.z);
  45872. };
  45873. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  45874. impostor.physicsBody.mass = mass;
  45875. impostor.physicsBody.updateMassProperties();
  45876. };
  45877. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  45878. impostor.physicsBody.sleep();
  45879. };
  45880. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  45881. impostor.physicsBody.wakeUp();
  45882. };
  45883. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  45884. joint.physicsJoint.distance = maxDistance;
  45885. };
  45886. CannonJSPlugin.prototype.enableMotor = function (joint, motorIndex) {
  45887. if (!motorIndex) {
  45888. joint.physicsJoint.enableMotor();
  45889. }
  45890. };
  45891. CannonJSPlugin.prototype.disableMotor = function (joint, motorIndex) {
  45892. if (!motorIndex) {
  45893. joint.physicsJoint.disableMotor();
  45894. }
  45895. };
  45896. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  45897. if (!motorIndex) {
  45898. joint.physicsJoint.enableMotor();
  45899. joint.physicsJoint.setMotorSpeed(speed);
  45900. if (maxForce) {
  45901. this.setLimit(joint, maxForce);
  45902. }
  45903. }
  45904. };
  45905. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  45906. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  45907. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  45908. };
  45909. CannonJSPlugin.prototype.dispose = function () {
  45910. //nothing to do, actually.
  45911. };
  45912. return CannonJSPlugin;
  45913. }());
  45914. BABYLON.CannonJSPlugin = CannonJSPlugin;
  45915. })(BABYLON || (BABYLON = {}));
  45916. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  45917. var BABYLON;
  45918. (function (BABYLON) {
  45919. var OimoJSPlugin = (function () {
  45920. function OimoJSPlugin(iterations) {
  45921. this.name = "OimoJSPlugin";
  45922. this._tmpImpostorsArray = [];
  45923. this._tmpPositionVector = BABYLON.Vector3.Zero();
  45924. this.world = new OIMO.World(1 / 60, 2, iterations, true);
  45925. this.world.worldscale(1);
  45926. this.world.clear();
  45927. //making sure no stats are calculated
  45928. this.world.isNoStat = true;
  45929. }
  45930. OimoJSPlugin.prototype.setGravity = function (gravity) {
  45931. this.world.gravity.copy(gravity);
  45932. };
  45933. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  45934. this.world.timeStep = timeStep;
  45935. };
  45936. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  45937. var _this = this;
  45938. impostors.forEach(function (impostor) {
  45939. impostor.beforeStep();
  45940. });
  45941. this.world.step();
  45942. impostors.forEach(function (impostor) {
  45943. impostor.afterStep();
  45944. //update the ordered impostors array
  45945. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  45946. });
  45947. //check for collisions
  45948. var contact = this.world.contacts;
  45949. while (contact !== null) {
  45950. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  45951. contact = contact.next;
  45952. continue;
  45953. }
  45954. //is this body colliding with any other? get the impostor
  45955. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  45956. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  45957. if (!mainImpostor || !collidingImpostor) {
  45958. contact = contact.next;
  45959. continue;
  45960. }
  45961. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  45962. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  45963. contact = contact.next;
  45964. }
  45965. };
  45966. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  45967. var mass = impostor.physicsBody.massInfo.mass;
  45968. impostor.physicsBody.applyImpulse(contactPoint.scale(OIMO.INV_SCALE), force.scale(OIMO.INV_SCALE * mass));
  45969. };
  45970. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  45971. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  45972. this.applyImpulse(impostor, force, contactPoint);
  45973. };
  45974. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  45975. var _this = this;
  45976. //parent-child relationship. Does this impostor has a parent impostor?
  45977. if (impostor.parent) {
  45978. if (impostor.physicsBody) {
  45979. this.removePhysicsBody(impostor);
  45980. //TODO is that needed?
  45981. impostor.forceUpdate();
  45982. }
  45983. return;
  45984. }
  45985. if (impostor.isBodyInitRequired()) {
  45986. var bodyConfig = {
  45987. name: impostor.uniqueId,
  45988. //Oimo must have mass, also for static objects.
  45989. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  45990. size: [],
  45991. type: [],
  45992. pos: [],
  45993. rot: [],
  45994. move: impostor.getParam("mass") !== 0,
  45995. //Supporting older versions of Oimo
  45996. world: this.world
  45997. };
  45998. var impostors = [impostor];
  45999. var addToArray = function (parent) {
  46000. if (!parent.getChildMeshes)
  46001. return;
  46002. parent.getChildMeshes().forEach(function (m) {
  46003. if (m.physicsImpostor) {
  46004. impostors.push(m.physicsImpostor);
  46005. m.physicsImpostor._init();
  46006. }
  46007. });
  46008. };
  46009. addToArray(impostor.object);
  46010. var checkWithEpsilon_1 = function (value) {
  46011. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  46012. };
  46013. impostors.forEach(function (i) {
  46014. //get the correct bounding box
  46015. var oldQuaternion = i.object.rotationQuaternion;
  46016. var rot = new OIMO.Euler().setFromQuaternion({
  46017. x: impostor.object.rotationQuaternion.x,
  46018. y: impostor.object.rotationQuaternion.y,
  46019. z: impostor.object.rotationQuaternion.z,
  46020. s: impostor.object.rotationQuaternion.w
  46021. });
  46022. var extendSize = i.getObjectExtendSize();
  46023. if (i === impostor) {
  46024. var center = impostor.getObjectCenter();
  46025. impostor.object.position.subtractToRef(center, _this._tmpPositionVector);
  46026. //Can also use Array.prototype.push.apply
  46027. bodyConfig.pos.push(center.x);
  46028. bodyConfig.pos.push(center.y);
  46029. bodyConfig.pos.push(center.z);
  46030. //tmp solution
  46031. bodyConfig.rot.push(rot.x / (OIMO.degtorad || OIMO.TO_RAD));
  46032. bodyConfig.rot.push(rot.y / (OIMO.degtorad || OIMO.TO_RAD));
  46033. bodyConfig.rot.push(rot.z / (OIMO.degtorad || OIMO.TO_RAD));
  46034. }
  46035. else {
  46036. bodyConfig.pos.push(i.object.position.x);
  46037. bodyConfig.pos.push(i.object.position.y);
  46038. bodyConfig.pos.push(i.object.position.z);
  46039. //tmp solution until https://github.com/lo-th/Oimo.js/pull/37 is merged
  46040. bodyConfig.rot.push(0);
  46041. bodyConfig.rot.push(0);
  46042. bodyConfig.rot.push(0);
  46043. }
  46044. // register mesh
  46045. switch (i.type) {
  46046. case BABYLON.PhysicsImpostor.ParticleImpostor:
  46047. BABYLON.Tools.Warn("No Particle support in Oimo.js. using SphereImpostor instead");
  46048. case BABYLON.PhysicsImpostor.SphereImpostor:
  46049. var radiusX = extendSize.x;
  46050. var radiusY = extendSize.y;
  46051. var radiusZ = extendSize.z;
  46052. var size = Math.max(checkWithEpsilon_1(radiusX), checkWithEpsilon_1(radiusY), checkWithEpsilon_1(radiusZ)) / 2;
  46053. bodyConfig.type.push('sphere');
  46054. //due to the way oimo works with compounds, add 3 times
  46055. bodyConfig.size.push(size);
  46056. bodyConfig.size.push(size);
  46057. bodyConfig.size.push(size);
  46058. break;
  46059. case BABYLON.PhysicsImpostor.CylinderImpostor:
  46060. var sizeX = checkWithEpsilon_1(extendSize.x) / 2;
  46061. var sizeY = checkWithEpsilon_1(extendSize.y);
  46062. bodyConfig.type.push('cylinder');
  46063. bodyConfig.size.push(sizeX);
  46064. bodyConfig.size.push(sizeY);
  46065. //due to the way oimo works with compounds, add one more value.
  46066. bodyConfig.size.push(sizeY);
  46067. break;
  46068. case BABYLON.PhysicsImpostor.PlaneImpostor:
  46069. case BABYLON.PhysicsImpostor.BoxImpostor:
  46070. default:
  46071. var sizeX = checkWithEpsilon_1(extendSize.x);
  46072. var sizeY = checkWithEpsilon_1(extendSize.y);
  46073. var sizeZ = checkWithEpsilon_1(extendSize.z);
  46074. bodyConfig.type.push('box');
  46075. bodyConfig.size.push(sizeX);
  46076. bodyConfig.size.push(sizeY);
  46077. bodyConfig.size.push(sizeZ);
  46078. break;
  46079. }
  46080. //actually not needed, but hey...
  46081. i.object.rotationQuaternion = oldQuaternion;
  46082. });
  46083. impostor.physicsBody = new OIMO.Body(bodyConfig).body; //this.world.add(bodyConfig);
  46084. }
  46085. else {
  46086. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  46087. }
  46088. impostor.setDeltaPosition(this._tmpPositionVector);
  46089. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  46090. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  46091. };
  46092. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  46093. //impostor.physicsBody.dispose();
  46094. //Same as : (older oimo versions)
  46095. this.world.removeRigidBody(impostor.physicsBody);
  46096. };
  46097. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  46098. var mainBody = impostorJoint.mainImpostor.physicsBody;
  46099. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  46100. if (!mainBody || !connectedBody) {
  46101. return;
  46102. }
  46103. var jointData = impostorJoint.joint.jointData;
  46104. var options = jointData.nativeParams || {};
  46105. var type;
  46106. var nativeJointData = {
  46107. body1: mainBody,
  46108. body2: connectedBody,
  46109. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  46110. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  46111. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  46112. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  46113. min: options.min,
  46114. max: options.max,
  46115. collision: options.collision || jointData.collision,
  46116. spring: options.spring,
  46117. //supporting older version of Oimo
  46118. world: this.world
  46119. };
  46120. switch (impostorJoint.joint.type) {
  46121. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  46122. type = "jointBall";
  46123. break;
  46124. case BABYLON.PhysicsJoint.SpringJoint:
  46125. BABYLON.Tools.Warn("Oimo.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  46126. var springData = jointData;
  46127. nativeJointData.min = springData.length || nativeJointData.min;
  46128. //Max should also be set, just make sure it is at least min
  46129. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  46130. case BABYLON.PhysicsJoint.DistanceJoint:
  46131. type = "jointDistance";
  46132. nativeJointData.max = jointData.maxDistance;
  46133. break;
  46134. case BABYLON.PhysicsJoint.PrismaticJoint:
  46135. type = "jointPrisme";
  46136. break;
  46137. case BABYLON.PhysicsJoint.SliderJoint:
  46138. type = "jointSlide";
  46139. break;
  46140. case BABYLON.PhysicsJoint.WheelJoint:
  46141. type = "jointWheel";
  46142. break;
  46143. case BABYLON.PhysicsJoint.HingeJoint:
  46144. default:
  46145. type = "jointHinge";
  46146. break;
  46147. }
  46148. nativeJointData.type = type;
  46149. impostorJoint.joint.physicsJoint = new OIMO.Link(nativeJointData).joint; //this.world.add(nativeJointData);
  46150. };
  46151. OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
  46152. //Bug in Oimo prevents us from disposing a joint in the playground
  46153. //joint.joint.physicsJoint.dispose();
  46154. //So we will bruteforce it!
  46155. try {
  46156. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  46157. }
  46158. catch (e) {
  46159. BABYLON.Tools.Warn(e);
  46160. }
  46161. };
  46162. OimoJSPlugin.prototype.isSupported = function () {
  46163. return OIMO !== undefined;
  46164. };
  46165. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  46166. if (!impostor.physicsBody.sleeping) {
  46167. //TODO check that
  46168. if (impostor.physicsBody.shapes.next) {
  46169. var parentShape = this._getLastShape(impostor.physicsBody);
  46170. impostor.object.position.x = parentShape.position.x * OIMO.WORLD_SCALE;
  46171. impostor.object.position.y = parentShape.position.y * OIMO.WORLD_SCALE;
  46172. impostor.object.position.z = parentShape.position.z * OIMO.WORLD_SCALE;
  46173. }
  46174. else {
  46175. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  46176. }
  46177. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  46178. impostor.object.rotationQuaternion.normalize();
  46179. }
  46180. };
  46181. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  46182. var body = impostor.physicsBody;
  46183. body.position.init(newPosition.x * OIMO.INV_SCALE, newPosition.y * OIMO.INV_SCALE, newPosition.z * OIMO.INV_SCALE);
  46184. body.orientation.init(newRotation.w, newRotation.x, newRotation.y, newRotation.z);
  46185. body.syncShapes();
  46186. body.awake();
  46187. };
  46188. OimoJSPlugin.prototype._getLastShape = function (body) {
  46189. var lastShape = body.shapes;
  46190. while (lastShape.next) {
  46191. lastShape = lastShape.next;
  46192. }
  46193. return lastShape;
  46194. };
  46195. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  46196. impostor.physicsBody.linearVelocity.init(velocity.x, velocity.y, velocity.z);
  46197. };
  46198. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  46199. impostor.physicsBody.angularVelocity.init(velocity.x, velocity.y, velocity.z);
  46200. };
  46201. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  46202. var v = impostor.physicsBody.linearVelocity;
  46203. if (!v)
  46204. return null;
  46205. return new BABYLON.Vector3(v.x, v.y, v.z);
  46206. };
  46207. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  46208. var v = impostor.physicsBody.angularVelocity;
  46209. if (!v)
  46210. return null;
  46211. return new BABYLON.Vector3(v.x, v.y, v.z);
  46212. };
  46213. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  46214. var staticBody = mass === 0;
  46215. //this will actually set the body's density and not its mass.
  46216. //But this is how oimo treats the mass variable.
  46217. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  46218. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  46219. };
  46220. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  46221. impostor.physicsBody.sleep();
  46222. };
  46223. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  46224. impostor.physicsBody.awake();
  46225. };
  46226. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  46227. joint.physicsJoint.limitMotor.upperLimit = maxDistance;
  46228. if (minDistance !== void 0) {
  46229. joint.physicsJoint.limitMotor.lowerLimit = minDistance;
  46230. }
  46231. };
  46232. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  46233. //TODO separate rotational and transational motors.
  46234. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  46235. if (motor) {
  46236. motor.setMotor(speed, maxForce);
  46237. }
  46238. };
  46239. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  46240. //TODO separate rotational and transational motors.
  46241. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  46242. if (motor) {
  46243. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  46244. }
  46245. };
  46246. OimoJSPlugin.prototype.dispose = function () {
  46247. this.world.clear();
  46248. };
  46249. return OimoJSPlugin;
  46250. }());
  46251. BABYLON.OimoJSPlugin = OimoJSPlugin;
  46252. })(BABYLON || (BABYLON = {}));
  46253. //# sourceMappingURL=babylon.oimoJSPlugin.js.map
  46254. var BABYLON;
  46255. (function (BABYLON) {
  46256. var DisplayPassPostProcess = (function (_super) {
  46257. __extends(DisplayPassPostProcess, _super);
  46258. function DisplayPassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  46259. return _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], options, camera, samplingMode, engine, reusable) || this;
  46260. }
  46261. return DisplayPassPostProcess;
  46262. }(BABYLON.PostProcess));
  46263. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  46264. })(BABYLON || (BABYLON = {}));
  46265. //# sourceMappingURL=babylon.displayPassPostProcess.js.map
  46266. var BABYLON;
  46267. (function (BABYLON) {
  46268. var SimplificationSettings = (function () {
  46269. function SimplificationSettings(quality, distance, optimizeMesh) {
  46270. this.quality = quality;
  46271. this.distance = distance;
  46272. this.optimizeMesh = optimizeMesh;
  46273. }
  46274. return SimplificationSettings;
  46275. }());
  46276. BABYLON.SimplificationSettings = SimplificationSettings;
  46277. var SimplificationQueue = (function () {
  46278. function SimplificationQueue() {
  46279. this.running = false;
  46280. this._simplificationArray = [];
  46281. }
  46282. SimplificationQueue.prototype.addTask = function (task) {
  46283. this._simplificationArray.push(task);
  46284. };
  46285. SimplificationQueue.prototype.executeNext = function () {
  46286. var task = this._simplificationArray.pop();
  46287. if (task) {
  46288. this.running = true;
  46289. this.runSimplification(task);
  46290. }
  46291. else {
  46292. this.running = false;
  46293. }
  46294. };
  46295. SimplificationQueue.prototype.runSimplification = function (task) {
  46296. var _this = this;
  46297. if (task.parallelProcessing) {
  46298. //parallel simplifier
  46299. task.settings.forEach(function (setting) {
  46300. var simplifier = _this.getSimplifier(task);
  46301. simplifier.simplify(setting, function (newMesh) {
  46302. task.mesh.addLODLevel(setting.distance, newMesh);
  46303. newMesh.isVisible = true;
  46304. //check if it is the last
  46305. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  46306. //all done, run the success callback.
  46307. task.successCallback();
  46308. }
  46309. _this.executeNext();
  46310. });
  46311. });
  46312. }
  46313. else {
  46314. //single simplifier.
  46315. var simplifier = this.getSimplifier(task);
  46316. var runDecimation = function (setting, callback) {
  46317. simplifier.simplify(setting, function (newMesh) {
  46318. task.mesh.addLODLevel(setting.distance, newMesh);
  46319. newMesh.isVisible = true;
  46320. //run the next quality level
  46321. callback();
  46322. });
  46323. };
  46324. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  46325. runDecimation(task.settings[loop.index], function () {
  46326. loop.executeNext();
  46327. });
  46328. }, function () {
  46329. //execution ended, run the success callback.
  46330. if (task.successCallback) {
  46331. task.successCallback();
  46332. }
  46333. _this.executeNext();
  46334. });
  46335. }
  46336. };
  46337. SimplificationQueue.prototype.getSimplifier = function (task) {
  46338. switch (task.simplificationType) {
  46339. case SimplificationType.QUADRATIC:
  46340. default:
  46341. return new QuadraticErrorSimplification(task.mesh);
  46342. }
  46343. };
  46344. return SimplificationQueue;
  46345. }());
  46346. BABYLON.SimplificationQueue = SimplificationQueue;
  46347. /**
  46348. * The implemented types of simplification.
  46349. * At the moment only Quadratic Error Decimation is implemented.
  46350. */
  46351. var SimplificationType;
  46352. (function (SimplificationType) {
  46353. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  46354. })(SimplificationType = BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  46355. var DecimationTriangle = (function () {
  46356. function DecimationTriangle(vertices) {
  46357. this.vertices = vertices;
  46358. this.error = new Array(4);
  46359. this.deleted = false;
  46360. this.isDirty = false;
  46361. this.deletePending = false;
  46362. this.borderFactor = 0;
  46363. }
  46364. return DecimationTriangle;
  46365. }());
  46366. BABYLON.DecimationTriangle = DecimationTriangle;
  46367. var DecimationVertex = (function () {
  46368. function DecimationVertex(position, id) {
  46369. this.position = position;
  46370. this.id = id;
  46371. this.isBorder = true;
  46372. this.q = new QuadraticMatrix();
  46373. this.triangleCount = 0;
  46374. this.triangleStart = 0;
  46375. this.originalOffsets = [];
  46376. }
  46377. DecimationVertex.prototype.updatePosition = function (newPosition) {
  46378. this.position.copyFrom(newPosition);
  46379. };
  46380. return DecimationVertex;
  46381. }());
  46382. BABYLON.DecimationVertex = DecimationVertex;
  46383. var QuadraticMatrix = (function () {
  46384. function QuadraticMatrix(data) {
  46385. this.data = new Array(10);
  46386. for (var i = 0; i < 10; ++i) {
  46387. if (data && data[i]) {
  46388. this.data[i] = data[i];
  46389. }
  46390. else {
  46391. this.data[i] = 0;
  46392. }
  46393. }
  46394. }
  46395. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  46396. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  46397. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  46398. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  46399. return det;
  46400. };
  46401. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  46402. for (var i = 0; i < 10; ++i) {
  46403. this.data[i] += matrix.data[i];
  46404. }
  46405. };
  46406. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  46407. for (var i = 0; i < 10; ++i) {
  46408. this.data[i] += data[i];
  46409. }
  46410. };
  46411. QuadraticMatrix.prototype.add = function (matrix) {
  46412. var m = new QuadraticMatrix();
  46413. for (var i = 0; i < 10; ++i) {
  46414. m.data[i] = this.data[i] + matrix.data[i];
  46415. }
  46416. return m;
  46417. };
  46418. QuadraticMatrix.FromData = function (a, b, c, d) {
  46419. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  46420. };
  46421. //returning an array to avoid garbage collection
  46422. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  46423. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  46424. };
  46425. return QuadraticMatrix;
  46426. }());
  46427. BABYLON.QuadraticMatrix = QuadraticMatrix;
  46428. var Reference = (function () {
  46429. function Reference(vertexId, triangleId) {
  46430. this.vertexId = vertexId;
  46431. this.triangleId = triangleId;
  46432. }
  46433. return Reference;
  46434. }());
  46435. BABYLON.Reference = Reference;
  46436. /**
  46437. * An implementation of the Quadratic Error simplification algorithm.
  46438. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  46439. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  46440. * @author RaananW
  46441. */
  46442. var QuadraticErrorSimplification = (function () {
  46443. function QuadraticErrorSimplification(_mesh) {
  46444. this._mesh = _mesh;
  46445. this.initialized = false;
  46446. this.syncIterations = 5000;
  46447. this.aggressiveness = 7;
  46448. this.decimationIterations = 100;
  46449. this.boundingBoxEpsilon = BABYLON.Epsilon;
  46450. }
  46451. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  46452. var _this = this;
  46453. this.initDecimatedMesh();
  46454. //iterating through the submeshes array, one after the other.
  46455. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  46456. _this.initWithMesh(loop.index, function () {
  46457. _this.runDecimation(settings, loop.index, function () {
  46458. loop.executeNext();
  46459. });
  46460. }, settings.optimizeMesh);
  46461. }, function () {
  46462. setTimeout(function () {
  46463. successCallback(_this._reconstructedMesh);
  46464. }, 0);
  46465. });
  46466. };
  46467. QuadraticErrorSimplification.prototype.isTriangleOnBoundingBox = function (triangle) {
  46468. var _this = this;
  46469. var gCount = 0;
  46470. triangle.vertices.forEach(function (vertex) {
  46471. var count = 0;
  46472. var vPos = vertex.position;
  46473. var bbox = _this._mesh.getBoundingInfo().boundingBox;
  46474. if (bbox.maximum.x - vPos.x < _this.boundingBoxEpsilon || vPos.x - bbox.minimum.x > _this.boundingBoxEpsilon)
  46475. ++count;
  46476. if (bbox.maximum.y === vPos.y || vPos.y === bbox.minimum.y)
  46477. ++count;
  46478. if (bbox.maximum.z === vPos.z || vPos.z === bbox.minimum.z)
  46479. ++count;
  46480. if (count > 1) {
  46481. ++gCount;
  46482. }
  46483. ;
  46484. });
  46485. if (gCount > 1) {
  46486. console.log(triangle, gCount);
  46487. }
  46488. return gCount > 1;
  46489. };
  46490. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  46491. var _this = this;
  46492. var targetCount = ~~(this.triangles.length * settings.quality);
  46493. var deletedTriangles = 0;
  46494. var triangleCount = this.triangles.length;
  46495. var iterationFunction = function (iteration, callback) {
  46496. setTimeout(function () {
  46497. if (iteration % 5 === 0) {
  46498. _this.updateMesh(iteration === 0);
  46499. }
  46500. for (var i = 0; i < _this.triangles.length; ++i) {
  46501. _this.triangles[i].isDirty = false;
  46502. }
  46503. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  46504. var trianglesIterator = function (i) {
  46505. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  46506. var t = _this.triangles[tIdx];
  46507. if (!t)
  46508. return;
  46509. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  46510. return;
  46511. }
  46512. for (var j = 0; j < 3; ++j) {
  46513. if (t.error[j] < threshold) {
  46514. var deleted0 = [];
  46515. var deleted1 = [];
  46516. var v0 = t.vertices[j];
  46517. var v1 = t.vertices[(j + 1) % 3];
  46518. if (v0.isBorder || v1.isBorder)
  46519. continue;
  46520. var p = BABYLON.Vector3.Zero();
  46521. var n = BABYLON.Vector3.Zero();
  46522. var uv = BABYLON.Vector2.Zero();
  46523. var color = new BABYLON.Color4(0, 0, 0, 1);
  46524. _this.calculateError(v0, v1, p, n, uv, color);
  46525. var delTr = [];
  46526. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  46527. continue;
  46528. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  46529. continue;
  46530. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  46531. continue;
  46532. var uniqueArray = [];
  46533. delTr.forEach(function (deletedT) {
  46534. if (uniqueArray.indexOf(deletedT) === -1) {
  46535. deletedT.deletePending = true;
  46536. uniqueArray.push(deletedT);
  46537. }
  46538. });
  46539. if (uniqueArray.length % 2 !== 0) {
  46540. continue;
  46541. }
  46542. v0.q = v1.q.add(v0.q);
  46543. v0.updatePosition(p);
  46544. var tStart = _this.references.length;
  46545. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  46546. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  46547. var tCount = _this.references.length - tStart;
  46548. if (tCount <= v0.triangleCount) {
  46549. if (tCount) {
  46550. for (var c = 0; c < tCount; c++) {
  46551. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  46552. }
  46553. }
  46554. }
  46555. else {
  46556. v0.triangleStart = tStart;
  46557. }
  46558. v0.triangleCount = tCount;
  46559. break;
  46560. }
  46561. }
  46562. };
  46563. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  46564. }, 0);
  46565. };
  46566. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  46567. if (triangleCount - deletedTriangles <= targetCount)
  46568. loop.breakLoop();
  46569. else {
  46570. iterationFunction(loop.index, function () {
  46571. loop.executeNext();
  46572. });
  46573. }
  46574. }, function () {
  46575. setTimeout(function () {
  46576. //reconstruct this part of the mesh
  46577. _this.reconstructMesh(submeshIndex);
  46578. successCallback();
  46579. }, 0);
  46580. });
  46581. };
  46582. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  46583. var _this = this;
  46584. this.vertices = [];
  46585. this.triangles = [];
  46586. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  46587. var indices = this._mesh.getIndices();
  46588. var submesh = this._mesh.subMeshes[submeshIndex];
  46589. var findInVertices = function (positionToSearch) {
  46590. if (optimizeMesh) {
  46591. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  46592. if (_this.vertices[ii].position.equals(positionToSearch)) {
  46593. return _this.vertices[ii];
  46594. }
  46595. }
  46596. }
  46597. return null;
  46598. };
  46599. var vertexReferences = [];
  46600. var vertexInit = function (i) {
  46601. var offset = i + submesh.verticesStart;
  46602. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  46603. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  46604. vertex.originalOffsets.push(offset);
  46605. if (vertex.id === _this.vertices.length) {
  46606. _this.vertices.push(vertex);
  46607. }
  46608. vertexReferences.push(vertex.id);
  46609. };
  46610. //var totalVertices = mesh.getTotalVertices();
  46611. var totalVertices = submesh.verticesCount;
  46612. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  46613. var indicesInit = function (i) {
  46614. var offset = (submesh.indexStart / 3) + i;
  46615. var pos = (offset * 3);
  46616. var i0 = indices[pos + 0];
  46617. var i1 = indices[pos + 1];
  46618. var i2 = indices[pos + 2];
  46619. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  46620. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  46621. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  46622. var triangle = new DecimationTriangle([v0, v1, v2]);
  46623. triangle.originalOffset = pos;
  46624. _this.triangles.push(triangle);
  46625. };
  46626. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  46627. _this.init(callback);
  46628. });
  46629. });
  46630. };
  46631. QuadraticErrorSimplification.prototype.init = function (callback) {
  46632. var _this = this;
  46633. var triangleInit1 = function (i) {
  46634. var t = _this.triangles[i];
  46635. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  46636. for (var j = 0; j < 3; j++) {
  46637. 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))));
  46638. }
  46639. };
  46640. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  46641. var triangleInit2 = function (i) {
  46642. var t = _this.triangles[i];
  46643. for (var j = 0; j < 3; ++j) {
  46644. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  46645. }
  46646. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  46647. };
  46648. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  46649. _this.initialized = true;
  46650. callback();
  46651. });
  46652. });
  46653. };
  46654. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  46655. var newTriangles = [];
  46656. var i;
  46657. for (i = 0; i < this.vertices.length; ++i) {
  46658. this.vertices[i].triangleCount = 0;
  46659. }
  46660. var t;
  46661. var j;
  46662. for (i = 0; i < this.triangles.length; ++i) {
  46663. if (!this.triangles[i].deleted) {
  46664. t = this.triangles[i];
  46665. for (j = 0; j < 3; ++j) {
  46666. t.vertices[j].triangleCount = 1;
  46667. }
  46668. newTriangles.push(t);
  46669. }
  46670. }
  46671. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  46672. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  46673. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  46674. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  46675. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  46676. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  46677. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  46678. var vertexCount = 0;
  46679. for (i = 0; i < this.vertices.length; ++i) {
  46680. var vertex = this.vertices[i];
  46681. vertex.id = vertexCount;
  46682. if (vertex.triangleCount) {
  46683. vertex.originalOffsets.forEach(function (originalOffset) {
  46684. newPositionData.push(vertex.position.x);
  46685. newPositionData.push(vertex.position.y);
  46686. newPositionData.push(vertex.position.z);
  46687. newNormalData.push(normalData[originalOffset * 3]);
  46688. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  46689. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  46690. if (uvs && uvs.length) {
  46691. newUVsData.push(uvs[(originalOffset * 2)]);
  46692. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  46693. }
  46694. else if (colorsData && colorsData.length) {
  46695. newColorsData.push(colorsData[(originalOffset * 4)]);
  46696. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  46697. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  46698. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  46699. }
  46700. ++vertexCount;
  46701. });
  46702. }
  46703. }
  46704. var startingIndex = this._reconstructedMesh.getTotalIndices();
  46705. var startingVertex = this._reconstructedMesh.getTotalVertices();
  46706. var submeshesArray = this._reconstructedMesh.subMeshes;
  46707. this._reconstructedMesh.subMeshes = [];
  46708. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  46709. var originalIndices = this._mesh.getIndices();
  46710. for (i = 0; i < newTriangles.length; ++i) {
  46711. t = newTriangles[i]; //now get the new referencing point for each vertex
  46712. [0, 1, 2].forEach(function (idx) {
  46713. var id = originalIndices[t.originalOffset + idx];
  46714. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  46715. if (offset < 0)
  46716. offset = 0;
  46717. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  46718. });
  46719. }
  46720. //overwriting the old vertex buffers and indices.
  46721. this._reconstructedMesh.setIndices(newIndicesArray);
  46722. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  46723. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  46724. if (newUVsData.length > 0)
  46725. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  46726. if (newColorsData.length > 0)
  46727. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  46728. //create submesh
  46729. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  46730. if (submeshIndex > 0) {
  46731. this._reconstructedMesh.subMeshes = [];
  46732. submeshesArray.forEach(function (submesh) {
  46733. new BABYLON.SubMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  46734. });
  46735. var newSubmesh = new BABYLON.SubMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  46736. }
  46737. };
  46738. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  46739. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  46740. this._reconstructedMesh.material = this._mesh.material;
  46741. this._reconstructedMesh.parent = this._mesh.parent;
  46742. this._reconstructedMesh.isVisible = false;
  46743. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  46744. };
  46745. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  46746. for (var i = 0; i < vertex1.triangleCount; ++i) {
  46747. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  46748. if (t.deleted)
  46749. continue;
  46750. var s = this.references[vertex1.triangleStart + i].vertexId;
  46751. var v1 = t.vertices[(s + 1) % 3];
  46752. var v2 = t.vertices[(s + 2) % 3];
  46753. if ((v1 === vertex2 || v2 === vertex2) /* && !this.isTriangleOnBoundingBox(t)*/) {
  46754. deletedArray[i] = true;
  46755. delTr.push(t);
  46756. continue;
  46757. }
  46758. var d1 = v1.position.subtract(point);
  46759. d1 = d1.normalize();
  46760. var d2 = v2.position.subtract(point);
  46761. d2 = d2.normalize();
  46762. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  46763. return true;
  46764. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  46765. deletedArray[i] = false;
  46766. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  46767. return true;
  46768. }
  46769. return false;
  46770. };
  46771. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  46772. var newDeleted = deletedTriangles;
  46773. for (var i = 0; i < vertex.triangleCount; ++i) {
  46774. var ref = this.references[vertex.triangleStart + i];
  46775. var t = this.triangles[ref.triangleId];
  46776. if (t.deleted)
  46777. continue;
  46778. if (deletedArray[i] && t.deletePending) {
  46779. t.deleted = true;
  46780. newDeleted++;
  46781. continue;
  46782. }
  46783. t.vertices[ref.vertexId] = origVertex;
  46784. t.isDirty = true;
  46785. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  46786. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  46787. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  46788. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  46789. this.references.push(ref);
  46790. }
  46791. return newDeleted;
  46792. };
  46793. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  46794. for (var i = 0; i < this.vertices.length; ++i) {
  46795. var vCount = [];
  46796. var vId = [];
  46797. var v = this.vertices[i];
  46798. var j;
  46799. for (j = 0; j < v.triangleCount; ++j) {
  46800. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  46801. for (var ii = 0; ii < 3; ii++) {
  46802. var ofs = 0;
  46803. var vv = triangle.vertices[ii];
  46804. while (ofs < vCount.length) {
  46805. if (vId[ofs] === vv.id)
  46806. break;
  46807. ++ofs;
  46808. }
  46809. if (ofs === vCount.length) {
  46810. vCount.push(1);
  46811. vId.push(vv.id);
  46812. }
  46813. else {
  46814. vCount[ofs]++;
  46815. }
  46816. }
  46817. }
  46818. for (j = 0; j < vCount.length; ++j) {
  46819. if (vCount[j] === 1) {
  46820. this.vertices[vId[j]].isBorder = true;
  46821. }
  46822. else {
  46823. this.vertices[vId[j]].isBorder = false;
  46824. }
  46825. }
  46826. }
  46827. };
  46828. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  46829. if (identifyBorders === void 0) { identifyBorders = false; }
  46830. var i;
  46831. if (!identifyBorders) {
  46832. var newTrianglesVector = [];
  46833. for (i = 0; i < this.triangles.length; ++i) {
  46834. if (!this.triangles[i].deleted) {
  46835. newTrianglesVector.push(this.triangles[i]);
  46836. }
  46837. }
  46838. this.triangles = newTrianglesVector;
  46839. }
  46840. for (i = 0; i < this.vertices.length; ++i) {
  46841. this.vertices[i].triangleCount = 0;
  46842. this.vertices[i].triangleStart = 0;
  46843. }
  46844. var t;
  46845. var j;
  46846. var v;
  46847. for (i = 0; i < this.triangles.length; ++i) {
  46848. t = this.triangles[i];
  46849. for (j = 0; j < 3; ++j) {
  46850. v = t.vertices[j];
  46851. v.triangleCount++;
  46852. }
  46853. }
  46854. var tStart = 0;
  46855. for (i = 0; i < this.vertices.length; ++i) {
  46856. this.vertices[i].triangleStart = tStart;
  46857. tStart += this.vertices[i].triangleCount;
  46858. this.vertices[i].triangleCount = 0;
  46859. }
  46860. var newReferences = new Array(this.triangles.length * 3);
  46861. for (i = 0; i < this.triangles.length; ++i) {
  46862. t = this.triangles[i];
  46863. for (j = 0; j < 3; ++j) {
  46864. v = t.vertices[j];
  46865. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  46866. v.triangleCount++;
  46867. }
  46868. }
  46869. this.references = newReferences;
  46870. if (identifyBorders) {
  46871. this.identifyBorder();
  46872. }
  46873. };
  46874. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  46875. var x = point.x;
  46876. var y = point.y;
  46877. var z = point.z;
  46878. 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
  46879. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  46880. };
  46881. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  46882. var q = vertex1.q.add(vertex2.q);
  46883. var border = vertex1.isBorder && vertex2.isBorder;
  46884. var error = 0;
  46885. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  46886. if (qDet !== 0 && !border) {
  46887. if (!pointResult) {
  46888. pointResult = BABYLON.Vector3.Zero();
  46889. }
  46890. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  46891. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  46892. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  46893. error = this.vertexError(q, pointResult);
  46894. }
  46895. else {
  46896. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  46897. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  46898. var error1 = this.vertexError(q, vertex1.position);
  46899. var error2 = this.vertexError(q, vertex2.position);
  46900. var error3 = this.vertexError(q, p3);
  46901. error = Math.min(error1, error2, error3);
  46902. if (error === error1) {
  46903. if (pointResult) {
  46904. pointResult.copyFrom(vertex1.position);
  46905. }
  46906. }
  46907. else if (error === error2) {
  46908. if (pointResult) {
  46909. pointResult.copyFrom(vertex2.position);
  46910. }
  46911. }
  46912. else {
  46913. if (pointResult) {
  46914. pointResult.copyFrom(p3);
  46915. }
  46916. }
  46917. }
  46918. return error;
  46919. };
  46920. return QuadraticErrorSimplification;
  46921. }());
  46922. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  46923. })(BABYLON || (BABYLON = {}));
  46924. //# sourceMappingURL=babylon.meshSimplification.js.map
  46925. var BABYLON;
  46926. (function (BABYLON) {
  46927. var serializedGeometries = [];
  46928. var serializeGeometry = function (geometry, serializationGeometries) {
  46929. if (serializedGeometries[geometry.id]) {
  46930. return;
  46931. }
  46932. if (geometry.doNotSerialize) {
  46933. return;
  46934. }
  46935. if (geometry instanceof BABYLON.Geometry.Primitives.Box) {
  46936. serializationGeometries.boxes.push(geometry.serialize());
  46937. }
  46938. else if (geometry instanceof BABYLON.Geometry.Primitives.Sphere) {
  46939. serializationGeometries.spheres.push(geometry.serialize());
  46940. }
  46941. else if (geometry instanceof BABYLON.Geometry.Primitives.Cylinder) {
  46942. serializationGeometries.cylinders.push(geometry.serialize());
  46943. }
  46944. else if (geometry instanceof BABYLON.Geometry.Primitives.Torus) {
  46945. serializationGeometries.toruses.push(geometry.serialize());
  46946. }
  46947. else if (geometry instanceof BABYLON.Geometry.Primitives.Ground) {
  46948. serializationGeometries.grounds.push(geometry.serialize());
  46949. }
  46950. else if (geometry instanceof BABYLON.Geometry.Primitives.Plane) {
  46951. serializationGeometries.planes.push(geometry.serialize());
  46952. }
  46953. else if (geometry instanceof BABYLON.Geometry.Primitives.TorusKnot) {
  46954. serializationGeometries.torusKnots.push(geometry.serialize());
  46955. }
  46956. else if (geometry instanceof BABYLON.Geometry.Primitives._Primitive) {
  46957. throw new Error("Unknown primitive type");
  46958. }
  46959. else {
  46960. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  46961. }
  46962. serializedGeometries[geometry.id] = true;
  46963. };
  46964. var serializeMesh = function (mesh, serializationScene) {
  46965. var serializationObject = {};
  46966. // Geometry
  46967. var geometry = mesh._geometry;
  46968. if (geometry) {
  46969. if (!mesh.getScene().getGeometryByID(geometry.id)) {
  46970. // 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
  46971. serializeGeometry(geometry, serializationScene.geometries);
  46972. }
  46973. }
  46974. // Custom
  46975. if (mesh.serialize) {
  46976. mesh.serialize(serializationObject);
  46977. }
  46978. return serializationObject;
  46979. };
  46980. var finalizeSingleMesh = function (mesh, serializationObject) {
  46981. //only works if the mesh is already loaded
  46982. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  46983. //serialize material
  46984. if (mesh.material) {
  46985. if (mesh.material instanceof BABYLON.StandardMaterial) {
  46986. serializationObject.materials = serializationObject.materials || [];
  46987. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  46988. serializationObject.materials.push(mesh.material.serialize());
  46989. }
  46990. }
  46991. else if (mesh.material instanceof BABYLON.MultiMaterial) {
  46992. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  46993. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  46994. serializationObject.multiMaterials.push(mesh.material.serialize());
  46995. }
  46996. }
  46997. }
  46998. //serialize geometry
  46999. var geometry = mesh._geometry;
  47000. if (geometry) {
  47001. if (!serializationObject.geometries) {
  47002. serializationObject.geometries = {};
  47003. serializationObject.geometries.boxes = [];
  47004. serializationObject.geometries.spheres = [];
  47005. serializationObject.geometries.cylinders = [];
  47006. serializationObject.geometries.toruses = [];
  47007. serializationObject.geometries.grounds = [];
  47008. serializationObject.geometries.planes = [];
  47009. serializationObject.geometries.torusKnots = [];
  47010. serializationObject.geometries.vertexData = [];
  47011. }
  47012. serializeGeometry(geometry, serializationObject.geometries);
  47013. }
  47014. // Skeletons
  47015. if (mesh.skeleton) {
  47016. serializationObject.skeletons = serializationObject.skeletons || [];
  47017. serializationObject.skeletons.push(mesh.skeleton.serialize());
  47018. }
  47019. //serialize the actual mesh
  47020. serializationObject.meshes = serializationObject.meshes || [];
  47021. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  47022. }
  47023. };
  47024. var SceneSerializer = (function () {
  47025. function SceneSerializer() {
  47026. }
  47027. SceneSerializer.ClearCache = function () {
  47028. serializedGeometries = [];
  47029. };
  47030. SceneSerializer.Serialize = function (scene) {
  47031. var serializationObject = {};
  47032. SceneSerializer.ClearCache();
  47033. // Scene
  47034. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  47035. serializationObject.autoClear = scene.autoClear;
  47036. serializationObject.clearColor = scene.clearColor.asArray();
  47037. serializationObject.ambientColor = scene.ambientColor.asArray();
  47038. serializationObject.gravity = scene.gravity.asArray();
  47039. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  47040. serializationObject.workerCollisions = scene.workerCollisions;
  47041. // Fog
  47042. if (scene.fogMode && scene.fogMode !== 0) {
  47043. serializationObject.fogMode = scene.fogMode;
  47044. serializationObject.fogColor = scene.fogColor.asArray();
  47045. serializationObject.fogStart = scene.fogStart;
  47046. serializationObject.fogEnd = scene.fogEnd;
  47047. serializationObject.fogDensity = scene.fogDensity;
  47048. }
  47049. //Physics
  47050. if (scene.isPhysicsEnabled()) {
  47051. serializationObject.physicsEnabled = true;
  47052. serializationObject.physicsGravity = scene.getPhysicsEngine().gravity.asArray();
  47053. serializationObject.physicsEngine = scene.getPhysicsEngine().getPhysicsPluginName();
  47054. }
  47055. // Metadata
  47056. if (scene.metadata) {
  47057. serializationObject.metadata = scene.metadata;
  47058. }
  47059. // Lights
  47060. serializationObject.lights = [];
  47061. var index;
  47062. var light;
  47063. for (index = 0; index < scene.lights.length; index++) {
  47064. light = scene.lights[index];
  47065. if (!light.doNotSerialize) {
  47066. serializationObject.lights.push(light.serialize());
  47067. }
  47068. }
  47069. // Cameras
  47070. serializationObject.cameras = [];
  47071. for (index = 0; index < scene.cameras.length; index++) {
  47072. var camera = scene.cameras[index];
  47073. if (!camera.doNotSerialize) {
  47074. serializationObject.cameras.push(camera.serialize());
  47075. }
  47076. }
  47077. if (scene.activeCamera) {
  47078. serializationObject.activeCameraID = scene.activeCamera.id;
  47079. }
  47080. // Animations
  47081. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  47082. // Materials
  47083. serializationObject.materials = [];
  47084. serializationObject.multiMaterials = [];
  47085. var material;
  47086. for (index = 0; index < scene.materials.length; index++) {
  47087. material = scene.materials[index];
  47088. if (!material.doNotSerialize) {
  47089. serializationObject.materials.push(material.serialize());
  47090. }
  47091. }
  47092. // MultiMaterials
  47093. serializationObject.multiMaterials = [];
  47094. for (index = 0; index < scene.multiMaterials.length; index++) {
  47095. var multiMaterial = scene.multiMaterials[index];
  47096. serializationObject.multiMaterials.push(multiMaterial.serialize());
  47097. }
  47098. // Skeletons
  47099. serializationObject.skeletons = [];
  47100. for (index = 0; index < scene.skeletons.length; index++) {
  47101. serializationObject.skeletons.push(scene.skeletons[index].serialize());
  47102. }
  47103. // Geometries
  47104. serializationObject.geometries = {};
  47105. serializationObject.geometries.boxes = [];
  47106. serializationObject.geometries.spheres = [];
  47107. serializationObject.geometries.cylinders = [];
  47108. serializationObject.geometries.toruses = [];
  47109. serializationObject.geometries.grounds = [];
  47110. serializationObject.geometries.planes = [];
  47111. serializationObject.geometries.torusKnots = [];
  47112. serializationObject.geometries.vertexData = [];
  47113. serializedGeometries = [];
  47114. var geometries = scene.getGeometries();
  47115. for (index = 0; index < geometries.length; index++) {
  47116. var geometry = geometries[index];
  47117. if (geometry.isReady()) {
  47118. serializeGeometry(geometry, serializationObject.geometries);
  47119. }
  47120. }
  47121. // Meshes
  47122. serializationObject.meshes = [];
  47123. for (index = 0; index < scene.meshes.length; index++) {
  47124. var abstractMesh = scene.meshes[index];
  47125. if (abstractMesh instanceof BABYLON.Mesh) {
  47126. var mesh = abstractMesh;
  47127. if (!mesh.doNotSerialize) {
  47128. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  47129. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  47130. }
  47131. }
  47132. }
  47133. }
  47134. // Particles Systems
  47135. serializationObject.particleSystems = [];
  47136. for (index = 0; index < scene.particleSystems.length; index++) {
  47137. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  47138. }
  47139. // Lens flares
  47140. serializationObject.lensFlareSystems = [];
  47141. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  47142. serializationObject.lensFlareSystems.push(scene.lensFlareSystems[index].serialize());
  47143. }
  47144. // Shadows
  47145. serializationObject.shadowGenerators = [];
  47146. for (index = 0; index < scene.lights.length; index++) {
  47147. light = scene.lights[index];
  47148. var shadowGenerator = light.getShadowGenerator();
  47149. // Only support serialization for official generator so far.
  47150. if (shadowGenerator && shadowGenerator instanceof BABYLON.ShadowGenerator) {
  47151. serializationObject.shadowGenerators.push(shadowGenerator.serialize());
  47152. }
  47153. }
  47154. // Action Manager
  47155. if (scene.actionManager) {
  47156. serializationObject.actions = scene.actionManager.serialize("scene");
  47157. }
  47158. // Audio
  47159. serializationObject.sounds = [];
  47160. for (index = 0; index < scene.soundTracks.length; index++) {
  47161. var soundtrack = scene.soundTracks[index];
  47162. for (var soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) {
  47163. serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize());
  47164. }
  47165. }
  47166. return serializationObject;
  47167. };
  47168. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  47169. if (withParents === void 0) { withParents = false; }
  47170. if (withChildren === void 0) { withChildren = false; }
  47171. var serializationObject = {};
  47172. SceneSerializer.ClearCache();
  47173. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  47174. if (withParents || withChildren) {
  47175. //deliberate for loop! not for each, appended should be processed as well.
  47176. for (var i = 0; i < toSerialize.length; ++i) {
  47177. if (withChildren) {
  47178. toSerialize[i].getDescendants().forEach(function (node) {
  47179. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  47180. toSerialize.push(node);
  47181. }
  47182. });
  47183. }
  47184. //make sure the array doesn't contain the object already
  47185. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  47186. toSerialize.push(toSerialize[i].parent);
  47187. }
  47188. }
  47189. }
  47190. toSerialize.forEach(function (mesh) {
  47191. finalizeSingleMesh(mesh, serializationObject);
  47192. });
  47193. return serializationObject;
  47194. };
  47195. return SceneSerializer;
  47196. }());
  47197. BABYLON.SceneSerializer = SceneSerializer;
  47198. })(BABYLON || (BABYLON = {}));
  47199. //# sourceMappingURL=babylon.sceneSerializer.js.map
  47200. // All the credit goes to this project and the guy who's behind it https://github.com/mapbox/earcut
  47201. // Huge respect for a such great lib.
  47202. // Earcut license:
  47203. // Copyright (c) 2016, Mapbox
  47204. //
  47205. // Permission to use, copy, modify, and/or distribute this software for any purpose
  47206. // with or without fee is hereby granted, provided that the above copyright notice
  47207. // and this permission notice appear in all copies.
  47208. //
  47209. // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
  47210. // REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
  47211. // FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
  47212. // INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
  47213. // OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
  47214. // TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
  47215. // THIS SOFTWARE.
  47216. var Earcut;
  47217. (function (Earcut) {
  47218. /**
  47219. * The fastest and smallest JavaScript polygon triangulation library for your WebGL apps
  47220. * @param data is a flat array of vertice coordinates like [x0, y0, x1, y1, x2, y2, ...].
  47221. * @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).
  47222. * @param dim is the number of coordinates per vertice in the input array (2 by default).
  47223. */
  47224. function earcut(data, holeIndices, dim) {
  47225. dim = dim || 2;
  47226. var hasHoles = holeIndices && holeIndices.length, outerLen = hasHoles ? holeIndices[0] * dim : data.length, outerNode = linkedList(data, 0, outerLen, dim, true), triangles = [];
  47227. if (!outerNode)
  47228. return triangles;
  47229. var minX, minY, maxX, maxY, x, y, size;
  47230. if (hasHoles)
  47231. outerNode = eliminateHoles(data, holeIndices, outerNode, dim);
  47232. // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
  47233. if (data.length > 80 * dim) {
  47234. minX = maxX = data[0];
  47235. minY = maxY = data[1];
  47236. for (var i = dim; i < outerLen; i += dim) {
  47237. x = data[i];
  47238. y = data[i + 1];
  47239. if (x < minX)
  47240. minX = x;
  47241. if (y < minY)
  47242. minY = y;
  47243. if (x > maxX)
  47244. maxX = x;
  47245. if (y > maxY)
  47246. maxY = y;
  47247. }
  47248. // minX, minY and size are later used to transform coords into integers for z-order calculation
  47249. size = Math.max(maxX - minX, maxY - minY);
  47250. }
  47251. earcutLinked(outerNode, triangles, dim, minX, minY, size, undefined);
  47252. return triangles;
  47253. }
  47254. Earcut.earcut = earcut;
  47255. // create a circular doubly linked list from polygon points in the specified winding order
  47256. function linkedList(data, start, end, dim, clockwise) {
  47257. var i, last;
  47258. if (clockwise === (signedArea(data, start, end, dim) > 0)) {
  47259. for (i = start; i < end; i += dim)
  47260. last = insertNode(i, data[i], data[i + 1], last);
  47261. }
  47262. else {
  47263. for (i = end - dim; i >= start; i -= dim)
  47264. last = insertNode(i, data[i], data[i + 1], last);
  47265. }
  47266. if (last && equals(last, last.next)) {
  47267. removeNode(last);
  47268. last = last.next;
  47269. }
  47270. return last;
  47271. }
  47272. // eliminate colinear or duplicate points
  47273. function filterPoints(start, end) {
  47274. if (!start)
  47275. return start;
  47276. if (!end)
  47277. end = start;
  47278. var p = start, again;
  47279. do {
  47280. again = false;
  47281. if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) {
  47282. removeNode(p);
  47283. p = end = p.prev;
  47284. if (p === p.next)
  47285. return null;
  47286. again = true;
  47287. }
  47288. else {
  47289. p = p.next;
  47290. }
  47291. } while (again || p !== end);
  47292. return end;
  47293. }
  47294. // main ear slicing loop which triangulates a polygon (given as a linked list)
  47295. function earcutLinked(ear, triangles, dim, minX, minY, size, pass) {
  47296. if (!ear)
  47297. return;
  47298. // interlink polygon nodes in z-order
  47299. if (!pass && size)
  47300. indexCurve(ear, minX, minY, size);
  47301. var stop = ear, prev, next;
  47302. // iterate through ears, slicing them one by one
  47303. while (ear.prev !== ear.next) {
  47304. prev = ear.prev;
  47305. next = ear.next;
  47306. if (size ? isEarHashed(ear, minX, minY, size) : isEar(ear)) {
  47307. // cut off the triangle
  47308. triangles.push(prev.i / dim);
  47309. triangles.push(ear.i / dim);
  47310. triangles.push(next.i / dim);
  47311. removeNode(ear);
  47312. // skipping the next vertice leads to less sliver triangles
  47313. ear = next.next;
  47314. stop = next.next;
  47315. continue;
  47316. }
  47317. ear = next;
  47318. // if we looped through the whole remaining polygon and can't find any more ears
  47319. if (ear === stop) {
  47320. // try filtering points and slicing again
  47321. if (!pass) {
  47322. earcutLinked(filterPoints(ear, undefined), triangles, dim, minX, minY, size, 1);
  47323. }
  47324. else if (pass === 1) {
  47325. ear = cureLocalIntersections(ear, triangles, dim);
  47326. earcutLinked(ear, triangles, dim, minX, minY, size, 2);
  47327. }
  47328. else if (pass === 2) {
  47329. splitEarcut(ear, triangles, dim, minX, minY, size);
  47330. }
  47331. break;
  47332. }
  47333. }
  47334. }
  47335. // check whether a polygon node forms a valid ear with adjacent nodes
  47336. function isEar(ear) {
  47337. var a = ear.prev, b = ear, c = ear.next;
  47338. if (area(a, b, c) >= 0)
  47339. return false; // reflex, can't be an ear
  47340. // now make sure we don't have other points inside the potential ear
  47341. var p = ear.next.next;
  47342. while (p !== ear.prev) {
  47343. if (pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  47344. area(p.prev, p, p.next) >= 0)
  47345. return false;
  47346. p = p.next;
  47347. }
  47348. return true;
  47349. }
  47350. function isEarHashed(ear, minX, minY, size) {
  47351. var a = ear.prev, b = ear, c = ear.next;
  47352. if (area(a, b, c) >= 0)
  47353. return false; // reflex, can't be an ear
  47354. // triangle bbox; min & max are calculated like this for speed
  47355. 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);
  47356. // z-order range for the current triangle bbox;
  47357. var minZ = zOrder(minTX, minTY, minX, minY, size), maxZ = zOrder(maxTX, maxTY, minX, minY, size);
  47358. // first look for points inside the triangle in increasing z-order
  47359. var p = ear.nextZ;
  47360. while (p && p.z <= maxZ) {
  47361. if (p !== ear.prev &&
  47362. p !== ear.next &&
  47363. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  47364. area(p.prev, p, p.next) >= 0)
  47365. return false;
  47366. p = p.nextZ;
  47367. }
  47368. // then look for points in decreasing z-order
  47369. p = ear.prevZ;
  47370. while (p && p.z >= minZ) {
  47371. if (p !== ear.prev &&
  47372. p !== ear.next &&
  47373. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  47374. area(p.prev, p, p.next) >= 0)
  47375. return false;
  47376. p = p.prevZ;
  47377. }
  47378. return true;
  47379. }
  47380. // go through all polygon nodes and cure small local self-intersections
  47381. function cureLocalIntersections(start, triangles, dim) {
  47382. var p = start;
  47383. do {
  47384. var a = p.prev, b = p.next.next;
  47385. if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) {
  47386. triangles.push(a.i / dim);
  47387. triangles.push(p.i / dim);
  47388. triangles.push(b.i / dim);
  47389. // remove two nodes involved
  47390. removeNode(p);
  47391. removeNode(p.next);
  47392. p = start = b;
  47393. }
  47394. p = p.next;
  47395. } while (p !== start);
  47396. return p;
  47397. }
  47398. // try splitting polygon into two and triangulate them independently
  47399. function splitEarcut(start, triangles, dim, minX, minY, size) {
  47400. // look for a valid diagonal that divides the polygon into two
  47401. var a = start;
  47402. do {
  47403. var b = a.next.next;
  47404. while (b !== a.prev) {
  47405. if (a.i !== b.i && isValidDiagonal(a, b)) {
  47406. // split the polygon in two by the diagonal
  47407. var c = splitPolygon(a, b);
  47408. // filter colinear points around the cuts
  47409. a = filterPoints(a, a.next);
  47410. c = filterPoints(c, c.next);
  47411. // run earcut on each half
  47412. earcutLinked(a, triangles, dim, minX, minY, size, undefined);
  47413. earcutLinked(c, triangles, dim, minX, minY, size, undefined);
  47414. return;
  47415. }
  47416. b = b.next;
  47417. }
  47418. a = a.next;
  47419. } while (a !== start);
  47420. }
  47421. // link every hole into the outer loop, producing a single-ring polygon without holes
  47422. function eliminateHoles(data, holeIndices, outerNode, dim) {
  47423. var queue = [], i, len, start, end, list;
  47424. for (i = 0, len = holeIndices.length; i < len; i++) {
  47425. start = holeIndices[i] * dim;
  47426. end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  47427. list = linkedList(data, start, end, dim, false);
  47428. if (list === list.next)
  47429. list.steiner = true;
  47430. queue.push(getLeftmost(list));
  47431. }
  47432. queue.sort(compareX);
  47433. // process holes from left to right
  47434. for (i = 0; i < queue.length; i++) {
  47435. eliminateHole(queue[i], outerNode);
  47436. outerNode = filterPoints(outerNode, outerNode.next);
  47437. }
  47438. return outerNode;
  47439. }
  47440. function compareX(a, b) {
  47441. return a.x - b.x;
  47442. }
  47443. // find a bridge between vertices that connects hole with an outer ring and and link it
  47444. function eliminateHole(hole, outerNode) {
  47445. outerNode = findHoleBridge(hole, outerNode);
  47446. if (outerNode) {
  47447. var b = splitPolygon(outerNode, hole);
  47448. filterPoints(b, b.next);
  47449. }
  47450. }
  47451. // David Eberly's algorithm for finding a bridge between hole and outer polygon
  47452. function findHoleBridge(hole, outerNode) {
  47453. var p = outerNode, hx = hole.x, hy = hole.y, qx = -Infinity, m;
  47454. // find a segment intersected by a ray from the hole's leftmost point to the left;
  47455. // segment's endpoint with lesser x will be potential connection point
  47456. do {
  47457. if (hy <= p.y && hy >= p.next.y) {
  47458. var x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y);
  47459. if (x <= hx && x > qx) {
  47460. qx = x;
  47461. if (x === hx) {
  47462. if (hy === p.y)
  47463. return p;
  47464. if (hy === p.next.y)
  47465. return p.next;
  47466. }
  47467. m = p.x < p.next.x ? p : p.next;
  47468. }
  47469. }
  47470. p = p.next;
  47471. } while (p !== outerNode);
  47472. if (!m)
  47473. return null;
  47474. if (hx === qx)
  47475. return m.prev; // hole touches outer segment; pick lower endpoint
  47476. // look for points inside the triangle of hole point, segment intersection and endpoint;
  47477. // if there are no points found, we have a valid connection;
  47478. // otherwise choose the point of the minimum angle with the ray as connection point
  47479. var stop = m, mx = m.x, my = m.y, tanMin = Infinity, tan;
  47480. p = m.next;
  47481. while (p !== stop) {
  47482. if (hx >= p.x &&
  47483. p.x >= mx &&
  47484. pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y)) {
  47485. tan = Math.abs(hy - p.y) / (hx - p.x); // tangential
  47486. if ((tan < tanMin || (tan === tanMin && p.x > m.x)) && locallyInside(p, hole)) {
  47487. m = p;
  47488. tanMin = tan;
  47489. }
  47490. }
  47491. p = p.next;
  47492. }
  47493. return m;
  47494. }
  47495. // interlink polygon nodes in z-order
  47496. function indexCurve(start, minX, minY, size) {
  47497. var p = start;
  47498. do {
  47499. if (p.z === null)
  47500. p.z = zOrder(p.x, p.y, minX, minY, size);
  47501. p.prevZ = p.prev;
  47502. p.nextZ = p.next;
  47503. p = p.next;
  47504. } while (p !== start);
  47505. p.prevZ.nextZ = null;
  47506. p.prevZ = null;
  47507. sortLinked(p);
  47508. }
  47509. // Simon Tatham's linked list merge sort algorithm
  47510. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  47511. function sortLinked(list) {
  47512. var i, p, q, e, tail, numMerges, pSize, qSize, inSize = 1;
  47513. do {
  47514. p = list;
  47515. list = null;
  47516. tail = null;
  47517. numMerges = 0;
  47518. while (p) {
  47519. numMerges++;
  47520. q = p;
  47521. pSize = 0;
  47522. for (i = 0; i < inSize; i++) {
  47523. pSize++;
  47524. q = q.nextZ;
  47525. if (!q)
  47526. break;
  47527. }
  47528. qSize = inSize;
  47529. while (pSize > 0 || (qSize > 0 && q)) {
  47530. if (pSize === 0) {
  47531. e = q;
  47532. q = q.nextZ;
  47533. qSize--;
  47534. }
  47535. else if (qSize === 0 || !q) {
  47536. e = p;
  47537. p = p.nextZ;
  47538. pSize--;
  47539. }
  47540. else if (p.z <= q.z) {
  47541. e = p;
  47542. p = p.nextZ;
  47543. pSize--;
  47544. }
  47545. else {
  47546. e = q;
  47547. q = q.nextZ;
  47548. qSize--;
  47549. }
  47550. if (tail)
  47551. tail.nextZ = e;
  47552. else
  47553. list = e;
  47554. e.prevZ = tail;
  47555. tail = e;
  47556. }
  47557. p = q;
  47558. }
  47559. tail.nextZ = null;
  47560. inSize *= 2;
  47561. } while (numMerges > 1);
  47562. return list;
  47563. }
  47564. // z-order of a point given coords and size of the data bounding box
  47565. function zOrder(x, y, minX, minY, size) {
  47566. // coords are transformed into non-negative 15-bit integer range
  47567. x = 32767 * (x - minX) / size;
  47568. y = 32767 * (y - minY) / size;
  47569. x = (x | (x << 8)) & 0x00FF00FF;
  47570. x = (x | (x << 4)) & 0x0F0F0F0F;
  47571. x = (x | (x << 2)) & 0x33333333;
  47572. x = (x | (x << 1)) & 0x55555555;
  47573. y = (y | (y << 8)) & 0x00FF00FF;
  47574. y = (y | (y << 4)) & 0x0F0F0F0F;
  47575. y = (y | (y << 2)) & 0x33333333;
  47576. y = (y | (y << 1)) & 0x55555555;
  47577. return x | (y << 1);
  47578. }
  47579. // find the leftmost node of a polygon ring
  47580. function getLeftmost(start) {
  47581. var p = start, leftmost = start;
  47582. do {
  47583. if (p.x < leftmost.x)
  47584. leftmost = p;
  47585. p = p.next;
  47586. } while (p !== start);
  47587. return leftmost;
  47588. }
  47589. // check if a point lies within a convex triangle
  47590. function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) {
  47591. return (cx - px) * (ay - py) - (ax - px) * (cy - py) >= 0 &&
  47592. (ax - px) * (by - py) - (bx - px) * (ay - py) >= 0 &&
  47593. (bx - px) * (cy - py) - (cx - px) * (by - py) >= 0;
  47594. }
  47595. // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  47596. function isValidDiagonal(a, b) {
  47597. return a.next.i !== b.i &&
  47598. a.prev.i !== b.i &&
  47599. !intersectsPolygon(a, b) &&
  47600. locallyInside(a, b) &&
  47601. locallyInside(b, a) &&
  47602. middleInside(a, b);
  47603. }
  47604. // signed area of a triangle
  47605. function area(p, q, r) {
  47606. return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);
  47607. }
  47608. // check if two points are equal
  47609. function equals(p1, p2) {
  47610. return p1.x === p2.x && p1.y === p2.y;
  47611. }
  47612. // check if two segments intersect
  47613. function intersects(p1, q1, p2, q2) {
  47614. if ((equals(p1, q1) && equals(p2, q2)) ||
  47615. (equals(p1, q2) && equals(p2, q1)))
  47616. return true;
  47617. return area(p1, q1, p2) > 0 !== area(p1, q1, q2) > 0 &&
  47618. area(p2, q2, p1) > 0 !== area(p2, q2, q1) > 0;
  47619. }
  47620. // check if a polygon diagonal intersects any polygon segments
  47621. function intersectsPolygon(a, b) {
  47622. var p = a;
  47623. do {
  47624. if (p.i !== a.i &&
  47625. p.next.i !== a.i &&
  47626. p.i !== b.i &&
  47627. p.next.i !== b.i &&
  47628. intersects(p, p.next, a, b))
  47629. return true;
  47630. p = p.next;
  47631. } while (p !== a);
  47632. return false;
  47633. }
  47634. // check if a polygon diagonal is locally inside the polygon
  47635. function locallyInside(a, b) {
  47636. return area(a.prev, a, a.next) < 0
  47637. ? area(a, b, a.next) >= 0 && area(a, a.prev, b) >= 0
  47638. : area(a, b, a.prev) < 0 || area(a, a.next, b) < 0;
  47639. }
  47640. // check if the middle point of a polygon diagonal is inside the polygon
  47641. function middleInside(a, b) {
  47642. var p = a, inside = false, px = (a.x + b.x) / 2, py = (a.y + b.y) / 2;
  47643. do {
  47644. if (((p.y > py) !== (p.next.y > py)) && (px < (p.next.x - p.x) * (py - p.y) / (p.next.y - p.y) + p.x))
  47645. inside = !inside;
  47646. p = p.next;
  47647. } while (p !== a);
  47648. return inside;
  47649. }
  47650. // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  47651. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  47652. function splitPolygon(a, b) {
  47653. 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;
  47654. a.next = b;
  47655. b.prev = a;
  47656. a2.next = an;
  47657. an.prev = a2;
  47658. b2.next = a2;
  47659. a2.prev = b2;
  47660. bp.next = b2;
  47661. b2.prev = bp;
  47662. return b2;
  47663. }
  47664. // create a node and optionally link it with previous one (in a circular doubly linked list)
  47665. function insertNode(i, x, y, last) {
  47666. var p = new Node(i, x, y);
  47667. if (!last) {
  47668. p.prev = p;
  47669. p.next = p;
  47670. }
  47671. else {
  47672. p.next = last.next;
  47673. p.prev = last;
  47674. last.next.prev = p;
  47675. last.next = p;
  47676. }
  47677. return p;
  47678. }
  47679. function removeNode(p) {
  47680. p.next.prev = p.prev;
  47681. p.prev.next = p.next;
  47682. if (p.prevZ)
  47683. p.prevZ.nextZ = p.nextZ;
  47684. if (p.nextZ)
  47685. p.nextZ.prevZ = p.prevZ;
  47686. }
  47687. function Node(i, x, y) {
  47688. // vertice index in coordinates array
  47689. this.i = i;
  47690. // vertex coordinates
  47691. this.x = x;
  47692. this.y = y;
  47693. // previous and next vertice nodes in a polygon ring
  47694. this.prev = null;
  47695. this.next = null;
  47696. // z-order curve value
  47697. this.z = null;
  47698. // previous and next nodes in z-order
  47699. this.prevZ = null;
  47700. this.nextZ = null;
  47701. // indicates whether this is a steiner point
  47702. this.steiner = false;
  47703. }
  47704. /**
  47705. * return a percentage difference between the polygon area and its triangulation area;
  47706. * used to verify correctness of triangulation
  47707. */
  47708. function deviation(data, holeIndices, dim, triangles) {
  47709. var hasHoles = holeIndices && holeIndices.length;
  47710. var outerLen = hasHoles ? holeIndices[0] * dim : data.length;
  47711. var polygonArea = Math.abs(signedArea(data, 0, outerLen, dim));
  47712. if (hasHoles) {
  47713. for (var i = 0, len = holeIndices.length; i < len; i++) {
  47714. var start = holeIndices[i] * dim;
  47715. var end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  47716. polygonArea -= Math.abs(signedArea(data, start, end, dim));
  47717. }
  47718. }
  47719. var trianglesArea = 0;
  47720. for (i = 0; i < triangles.length; i += 3) {
  47721. var a = triangles[i] * dim;
  47722. var b = triangles[i + 1] * dim;
  47723. var c = triangles[i + 2] * dim;
  47724. trianglesArea += Math.abs((data[a] - data[c]) * (data[b + 1] - data[a + 1]) -
  47725. (data[a] - data[b]) * (data[c + 1] - data[a + 1]));
  47726. }
  47727. return polygonArea === 0 && trianglesArea === 0 ? 0 : Math.abs((trianglesArea - polygonArea) / polygonArea);
  47728. }
  47729. Earcut.deviation = deviation;
  47730. ;
  47731. function signedArea(data, start, end, dim) {
  47732. var sum = 0;
  47733. for (var i = start, j = end - dim; i < end; i += dim) {
  47734. sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]);
  47735. j = i;
  47736. }
  47737. return sum;
  47738. }
  47739. /**
  47740. * turn a polygon in a multi-dimensional array form (e.g. as in GeoJSON) into a form Earcut accepts
  47741. */
  47742. function flatten(data) {
  47743. var dim = data[0][0].length, result = { vertices: [], holes: [], dimensions: dim }, holeIndex = 0;
  47744. for (var i = 0; i < data.length; i++) {
  47745. for (var j = 0; j < data[i].length; j++) {
  47746. for (var d = 0; d < dim; d++)
  47747. result.vertices.push(data[i][j][d]);
  47748. }
  47749. if (i > 0) {
  47750. holeIndex += data[i - 1].length;
  47751. result.holes.push(holeIndex);
  47752. }
  47753. }
  47754. return result;
  47755. }
  47756. Earcut.flatten = flatten;
  47757. ;
  47758. })(Earcut || (Earcut = {}));
  47759. //# sourceMappingURL=babylon.earcut.js.map
  47760. var BABYLON;
  47761. (function (BABYLON) {
  47762. // Unique ID when we import meshes from Babylon to CSG
  47763. var currentCSGMeshId = 0;
  47764. // # class Vertex
  47765. // Represents a vertex of a polygon. Use your own vertex class instead of this
  47766. // one to provide additional features like texture coordinates and vertex
  47767. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  47768. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  47769. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  47770. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  47771. // is not used anywhere else.
  47772. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  47773. var Vertex = (function () {
  47774. function Vertex(pos, normal, uv) {
  47775. this.pos = pos;
  47776. this.normal = normal;
  47777. this.uv = uv;
  47778. }
  47779. Vertex.prototype.clone = function () {
  47780. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  47781. };
  47782. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  47783. // orientation of a polygon is flipped.
  47784. Vertex.prototype.flip = function () {
  47785. this.normal = this.normal.scale(-1);
  47786. };
  47787. // Create a new vertex between this vertex and `other` by linearly
  47788. // interpolating all properties using a parameter of `t`. Subclasses should
  47789. // override this to interpolate additional properties.
  47790. Vertex.prototype.interpolate = function (other, t) {
  47791. 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));
  47792. };
  47793. return Vertex;
  47794. }());
  47795. // # class Plane
  47796. // Represents a plane in 3D space.
  47797. var Plane = (function () {
  47798. function Plane(normal, w) {
  47799. this.normal = normal;
  47800. this.w = w;
  47801. }
  47802. Plane.FromPoints = function (a, b, c) {
  47803. var v0 = c.subtract(a);
  47804. var v1 = b.subtract(a);
  47805. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  47806. return null;
  47807. }
  47808. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  47809. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  47810. };
  47811. Plane.prototype.clone = function () {
  47812. return new Plane(this.normal.clone(), this.w);
  47813. };
  47814. Plane.prototype.flip = function () {
  47815. this.normal.scaleInPlace(-1);
  47816. this.w = -this.w;
  47817. };
  47818. // Split `polygon` by this plane if needed, then put the polygon or polygon
  47819. // fragments in the appropriate lists. Coplanar polygons go into either
  47820. // `coplanarFront` or `coplanarBack` depending on their orientation with
  47821. // respect to this plane. Polygons in front or in back of this plane go into
  47822. // either `front` or `back`.
  47823. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  47824. var COPLANAR = 0;
  47825. var FRONT = 1;
  47826. var BACK = 2;
  47827. var SPANNING = 3;
  47828. // Classify each point as well as the entire polygon into one of the above
  47829. // four classes.
  47830. var polygonType = 0;
  47831. var types = [];
  47832. var i;
  47833. var t;
  47834. for (i = 0; i < polygon.vertices.length; i++) {
  47835. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  47836. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  47837. polygonType |= type;
  47838. types.push(type);
  47839. }
  47840. // Put the polygon in the correct list, splitting it when necessary.
  47841. switch (polygonType) {
  47842. case COPLANAR:
  47843. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  47844. break;
  47845. case FRONT:
  47846. front.push(polygon);
  47847. break;
  47848. case BACK:
  47849. back.push(polygon);
  47850. break;
  47851. case SPANNING:
  47852. var f = [], b = [];
  47853. for (i = 0; i < polygon.vertices.length; i++) {
  47854. var j = (i + 1) % polygon.vertices.length;
  47855. var ti = types[i], tj = types[j];
  47856. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  47857. if (ti !== BACK)
  47858. f.push(vi);
  47859. if (ti !== FRONT)
  47860. b.push(ti !== BACK ? vi.clone() : vi);
  47861. if ((ti | tj) === SPANNING) {
  47862. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  47863. var v = vi.interpolate(vj, t);
  47864. f.push(v);
  47865. b.push(v.clone());
  47866. }
  47867. }
  47868. var poly;
  47869. if (f.length >= 3) {
  47870. poly = new Polygon(f, polygon.shared);
  47871. if (poly.plane)
  47872. front.push(poly);
  47873. }
  47874. if (b.length >= 3) {
  47875. poly = new Polygon(b, polygon.shared);
  47876. if (poly.plane)
  47877. back.push(poly);
  47878. }
  47879. break;
  47880. }
  47881. };
  47882. return Plane;
  47883. }());
  47884. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  47885. // point is on the plane.
  47886. Plane.EPSILON = 1e-5;
  47887. // # class Polygon
  47888. // Represents a convex polygon. The vertices used to initialize a polygon must
  47889. // be coplanar and form a convex loop.
  47890. //
  47891. // Each convex polygon has a `shared` property, which is shared between all
  47892. // polygons that are clones of each other or were split from the same polygon.
  47893. // This can be used to define per-polygon properties (such as surface color).
  47894. var Polygon = (function () {
  47895. function Polygon(vertices, shared) {
  47896. this.vertices = vertices;
  47897. this.shared = shared;
  47898. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  47899. }
  47900. Polygon.prototype.clone = function () {
  47901. var vertices = this.vertices.map(function (v) { return v.clone(); });
  47902. return new Polygon(vertices, this.shared);
  47903. };
  47904. Polygon.prototype.flip = function () {
  47905. this.vertices.reverse().map(function (v) { v.flip(); });
  47906. this.plane.flip();
  47907. };
  47908. return Polygon;
  47909. }());
  47910. // # class Node
  47911. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  47912. // by picking a polygon to split along. That polygon (and all other coplanar
  47913. // polygons) are added directly to that node and the other polygons are added to
  47914. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  47915. // no distinction between internal and leaf nodes.
  47916. var Node = (function () {
  47917. function Node(polygons) {
  47918. this.plane = null;
  47919. this.front = null;
  47920. this.back = null;
  47921. this.polygons = [];
  47922. if (polygons) {
  47923. this.build(polygons);
  47924. }
  47925. }
  47926. Node.prototype.clone = function () {
  47927. var node = new Node();
  47928. node.plane = this.plane && this.plane.clone();
  47929. node.front = this.front && this.front.clone();
  47930. node.back = this.back && this.back.clone();
  47931. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  47932. return node;
  47933. };
  47934. // Convert solid space to empty space and empty space to solid space.
  47935. Node.prototype.invert = function () {
  47936. for (var i = 0; i < this.polygons.length; i++) {
  47937. this.polygons[i].flip();
  47938. }
  47939. if (this.plane) {
  47940. this.plane.flip();
  47941. }
  47942. if (this.front) {
  47943. this.front.invert();
  47944. }
  47945. if (this.back) {
  47946. this.back.invert();
  47947. }
  47948. var temp = this.front;
  47949. this.front = this.back;
  47950. this.back = temp;
  47951. };
  47952. // Recursively remove all polygons in `polygons` that are inside this BSP
  47953. // tree.
  47954. Node.prototype.clipPolygons = function (polygons) {
  47955. if (!this.plane)
  47956. return polygons.slice();
  47957. var front = [], back = [];
  47958. for (var i = 0; i < polygons.length; i++) {
  47959. this.plane.splitPolygon(polygons[i], front, back, front, back);
  47960. }
  47961. if (this.front) {
  47962. front = this.front.clipPolygons(front);
  47963. }
  47964. if (this.back) {
  47965. back = this.back.clipPolygons(back);
  47966. }
  47967. else {
  47968. back = [];
  47969. }
  47970. return front.concat(back);
  47971. };
  47972. // Remove all polygons in this BSP tree that are inside the other BSP tree
  47973. // `bsp`.
  47974. Node.prototype.clipTo = function (bsp) {
  47975. this.polygons = bsp.clipPolygons(this.polygons);
  47976. if (this.front)
  47977. this.front.clipTo(bsp);
  47978. if (this.back)
  47979. this.back.clipTo(bsp);
  47980. };
  47981. // Return a list of all polygons in this BSP tree.
  47982. Node.prototype.allPolygons = function () {
  47983. var polygons = this.polygons.slice();
  47984. if (this.front)
  47985. polygons = polygons.concat(this.front.allPolygons());
  47986. if (this.back)
  47987. polygons = polygons.concat(this.back.allPolygons());
  47988. return polygons;
  47989. };
  47990. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  47991. // new polygons are filtered down to the bottom of the tree and become new
  47992. // nodes there. Each set of polygons is partitioned using the first polygon
  47993. // (no heuristic is used to pick a good split).
  47994. Node.prototype.build = function (polygons) {
  47995. if (!polygons.length)
  47996. return;
  47997. if (!this.plane)
  47998. this.plane = polygons[0].plane.clone();
  47999. var front = [], back = [];
  48000. for (var i = 0; i < polygons.length; i++) {
  48001. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  48002. }
  48003. if (front.length) {
  48004. if (!this.front)
  48005. this.front = new Node();
  48006. this.front.build(front);
  48007. }
  48008. if (back.length) {
  48009. if (!this.back)
  48010. this.back = new Node();
  48011. this.back.build(back);
  48012. }
  48013. };
  48014. return Node;
  48015. }());
  48016. var CSG = (function () {
  48017. function CSG() {
  48018. this.polygons = new Array();
  48019. }
  48020. // Convert BABYLON.Mesh to BABYLON.CSG
  48021. CSG.FromMesh = function (mesh) {
  48022. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  48023. var matrix, meshPosition, meshRotation, meshRotationQuaternion, meshScaling;
  48024. if (mesh instanceof BABYLON.Mesh) {
  48025. mesh.computeWorldMatrix(true);
  48026. matrix = mesh.getWorldMatrix();
  48027. meshPosition = mesh.position.clone();
  48028. meshRotation = mesh.rotation.clone();
  48029. if (mesh.rotationQuaternion) {
  48030. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  48031. }
  48032. meshScaling = mesh.scaling.clone();
  48033. }
  48034. else {
  48035. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  48036. }
  48037. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  48038. var subMeshes = mesh.subMeshes;
  48039. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  48040. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  48041. vertices = [];
  48042. for (var j = 0; j < 3; j++) {
  48043. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  48044. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  48045. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  48046. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  48047. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  48048. vertex = new Vertex(position, normal, uv);
  48049. vertices.push(vertex);
  48050. }
  48051. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  48052. // To handle the case of degenerated triangle
  48053. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  48054. if (polygon.plane)
  48055. polygons.push(polygon);
  48056. }
  48057. }
  48058. var csg = CSG.FromPolygons(polygons);
  48059. csg.matrix = matrix;
  48060. csg.position = meshPosition;
  48061. csg.rotation = meshRotation;
  48062. csg.scaling = meshScaling;
  48063. csg.rotationQuaternion = meshRotationQuaternion;
  48064. currentCSGMeshId++;
  48065. return csg;
  48066. };
  48067. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  48068. CSG.FromPolygons = function (polygons) {
  48069. var csg = new CSG();
  48070. csg.polygons = polygons;
  48071. return csg;
  48072. };
  48073. CSG.prototype.clone = function () {
  48074. var csg = new CSG();
  48075. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  48076. csg.copyTransformAttributes(this);
  48077. return csg;
  48078. };
  48079. CSG.prototype.toPolygons = function () {
  48080. return this.polygons;
  48081. };
  48082. CSG.prototype.union = function (csg) {
  48083. var a = new Node(this.clone().polygons);
  48084. var b = new Node(csg.clone().polygons);
  48085. a.clipTo(b);
  48086. b.clipTo(a);
  48087. b.invert();
  48088. b.clipTo(a);
  48089. b.invert();
  48090. a.build(b.allPolygons());
  48091. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  48092. };
  48093. CSG.prototype.unionInPlace = function (csg) {
  48094. var a = new Node(this.polygons);
  48095. var b = new Node(csg.polygons);
  48096. a.clipTo(b);
  48097. b.clipTo(a);
  48098. b.invert();
  48099. b.clipTo(a);
  48100. b.invert();
  48101. a.build(b.allPolygons());
  48102. this.polygons = a.allPolygons();
  48103. };
  48104. CSG.prototype.subtract = function (csg) {
  48105. var a = new Node(this.clone().polygons);
  48106. var b = new Node(csg.clone().polygons);
  48107. a.invert();
  48108. a.clipTo(b);
  48109. b.clipTo(a);
  48110. b.invert();
  48111. b.clipTo(a);
  48112. b.invert();
  48113. a.build(b.allPolygons());
  48114. a.invert();
  48115. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  48116. };
  48117. CSG.prototype.subtractInPlace = function (csg) {
  48118. var a = new Node(this.polygons);
  48119. var b = new Node(csg.polygons);
  48120. a.invert();
  48121. a.clipTo(b);
  48122. b.clipTo(a);
  48123. b.invert();
  48124. b.clipTo(a);
  48125. b.invert();
  48126. a.build(b.allPolygons());
  48127. a.invert();
  48128. this.polygons = a.allPolygons();
  48129. };
  48130. CSG.prototype.intersect = function (csg) {
  48131. var a = new Node(this.clone().polygons);
  48132. var b = new Node(csg.clone().polygons);
  48133. a.invert();
  48134. b.clipTo(a);
  48135. b.invert();
  48136. a.clipTo(b);
  48137. b.clipTo(a);
  48138. a.build(b.allPolygons());
  48139. a.invert();
  48140. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  48141. };
  48142. CSG.prototype.intersectInPlace = function (csg) {
  48143. var a = new Node(this.polygons);
  48144. var b = new Node(csg.polygons);
  48145. a.invert();
  48146. b.clipTo(a);
  48147. b.invert();
  48148. a.clipTo(b);
  48149. b.clipTo(a);
  48150. a.build(b.allPolygons());
  48151. a.invert();
  48152. this.polygons = a.allPolygons();
  48153. };
  48154. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  48155. // not modified.
  48156. CSG.prototype.inverse = function () {
  48157. var csg = this.clone();
  48158. csg.inverseInPlace();
  48159. return csg;
  48160. };
  48161. CSG.prototype.inverseInPlace = function () {
  48162. this.polygons.map(function (p) { p.flip(); });
  48163. };
  48164. // This is used to keep meshes transformations so they can be restored
  48165. // when we build back a Babylon Mesh
  48166. // NB : All CSG operations are performed in world coordinates
  48167. CSG.prototype.copyTransformAttributes = function (csg) {
  48168. this.matrix = csg.matrix;
  48169. this.position = csg.position;
  48170. this.rotation = csg.rotation;
  48171. this.scaling = csg.scaling;
  48172. this.rotationQuaternion = csg.rotationQuaternion;
  48173. return this;
  48174. };
  48175. // Build Raw mesh from CSG
  48176. // Coordinates here are in world space
  48177. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  48178. var matrix = this.matrix.clone();
  48179. matrix.invert();
  48180. 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;
  48181. if (keepSubMeshes) {
  48182. // Sort Polygons, since subMeshes are indices range
  48183. polygons.sort(function (a, b) {
  48184. if (a.shared.meshId === b.shared.meshId) {
  48185. return a.shared.subMeshId - b.shared.subMeshId;
  48186. }
  48187. else {
  48188. return a.shared.meshId - b.shared.meshId;
  48189. }
  48190. });
  48191. }
  48192. for (var i = 0, il = polygons.length; i < il; i++) {
  48193. polygon = polygons[i];
  48194. // Building SubMeshes
  48195. if (!subMesh_dict[polygon.shared.meshId]) {
  48196. subMesh_dict[polygon.shared.meshId] = {};
  48197. }
  48198. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  48199. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  48200. indexStart: +Infinity,
  48201. indexEnd: -Infinity,
  48202. materialIndex: polygon.shared.materialIndex
  48203. };
  48204. }
  48205. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  48206. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  48207. polygonIndices[0] = 0;
  48208. polygonIndices[1] = j - 1;
  48209. polygonIndices[2] = j;
  48210. for (var k = 0; k < 3; k++) {
  48211. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  48212. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  48213. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  48214. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  48215. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  48216. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  48217. // Check if 2 points can be merged
  48218. if (!(typeof vertex_idx !== 'undefined' &&
  48219. normals[vertex_idx * 3] === localNormal.x &&
  48220. normals[vertex_idx * 3 + 1] === localNormal.y &&
  48221. normals[vertex_idx * 3 + 2] === localNormal.z &&
  48222. uvs[vertex_idx * 2] === uv.x &&
  48223. uvs[vertex_idx * 2 + 1] === uv.y)) {
  48224. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  48225. uvs.push(uv.x, uv.y);
  48226. normals.push(normal.x, normal.y, normal.z);
  48227. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  48228. }
  48229. indices.push(vertex_idx);
  48230. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  48231. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  48232. currentIndex++;
  48233. }
  48234. }
  48235. }
  48236. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  48237. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  48238. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  48239. mesh.setIndices(indices);
  48240. if (keepSubMeshes) {
  48241. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  48242. var materialIndexOffset = 0, materialMaxIndex;
  48243. mesh.subMeshes = new Array();
  48244. for (var m in subMesh_dict) {
  48245. materialMaxIndex = -1;
  48246. for (var sm in subMesh_dict[m]) {
  48247. subMesh_obj = subMesh_dict[m][sm];
  48248. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  48249. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  48250. }
  48251. materialIndexOffset += ++materialMaxIndex;
  48252. }
  48253. }
  48254. return mesh;
  48255. };
  48256. // Build Mesh from CSG taking material and transforms into account
  48257. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  48258. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  48259. mesh.material = material;
  48260. mesh.position.copyFrom(this.position);
  48261. mesh.rotation.copyFrom(this.rotation);
  48262. if (this.rotationQuaternion) {
  48263. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  48264. }
  48265. mesh.scaling.copyFrom(this.scaling);
  48266. mesh.computeWorldMatrix(true);
  48267. return mesh;
  48268. };
  48269. return CSG;
  48270. }());
  48271. BABYLON.CSG = CSG;
  48272. })(BABYLON || (BABYLON = {}));
  48273. //# sourceMappingURL=babylon.csg.js.map
  48274. var BABYLON;
  48275. (function (BABYLON) {
  48276. var VRDistortionCorrectionPostProcess = (function (_super) {
  48277. __extends(VRDistortionCorrectionPostProcess, _super);
  48278. //ANY
  48279. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  48280. var _this = _super.call(this, name, "vrDistortionCorrection", [
  48281. 'LensCenter',
  48282. 'Scale',
  48283. 'ScaleIn',
  48284. 'HmdWarpParam'
  48285. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE, null, null) || this;
  48286. _this._isRightEye = isRightEye;
  48287. _this._distortionFactors = vrMetrics.distortionK;
  48288. _this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  48289. _this._lensCenterOffset = vrMetrics.lensCenterOffset;
  48290. _this.onSizeChangedObservable.add(function () {
  48291. _this.aspectRatio = _this.width * .5 / _this.height;
  48292. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  48293. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  48294. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  48295. });
  48296. _this.onApplyObservable.add(function (effect) {
  48297. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  48298. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  48299. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  48300. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  48301. });
  48302. return _this;
  48303. }
  48304. return VRDistortionCorrectionPostProcess;
  48305. }(BABYLON.PostProcess));
  48306. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  48307. })(BABYLON || (BABYLON = {}));
  48308. //# sourceMappingURL=babylon.vrDistortionCorrectionPostProcess.js.map
  48309. // Mainly based on these 2 articles :
  48310. // 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
  48311. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  48312. var BABYLON;
  48313. (function (BABYLON) {
  48314. var JoystickAxis;
  48315. (function (JoystickAxis) {
  48316. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  48317. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  48318. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  48319. })(JoystickAxis = BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  48320. var VirtualJoystick = (function () {
  48321. function VirtualJoystick(leftJoystick) {
  48322. var _this = this;
  48323. if (leftJoystick) {
  48324. this._leftJoystick = true;
  48325. }
  48326. else {
  48327. this._leftJoystick = false;
  48328. }
  48329. this._joystickIndex = VirtualJoystick._globalJoystickIndex;
  48330. VirtualJoystick._globalJoystickIndex++;
  48331. // By default left & right arrow keys are moving the X
  48332. // and up & down keys are moving the Y
  48333. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  48334. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  48335. this.reverseLeftRight = false;
  48336. this.reverseUpDown = false;
  48337. // collections of pointers
  48338. this._touches = new BABYLON.StringDictionary();
  48339. this.deltaPosition = BABYLON.Vector3.Zero();
  48340. this._joystickSensibility = 25;
  48341. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  48342. this._rotationSpeed = 25;
  48343. this._inverseRotationSpeed = 1 / (this._rotationSpeed / 1000);
  48344. this._rotateOnAxisRelativeToMesh = false;
  48345. this._onResize = function (evt) {
  48346. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  48347. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  48348. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  48349. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  48350. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  48351. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvasHeight / 2;
  48352. };
  48353. // injecting a canvas element on top of the canvas 3D game
  48354. if (!VirtualJoystick.vjCanvas) {
  48355. window.addEventListener("resize", this._onResize, false);
  48356. VirtualJoystick.vjCanvas = document.createElement("canvas");
  48357. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  48358. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  48359. VirtualJoystick.vjCanvas.width = window.innerWidth;
  48360. VirtualJoystick.vjCanvas.height = window.innerHeight;
  48361. VirtualJoystick.vjCanvas.style.width = "100%";
  48362. VirtualJoystick.vjCanvas.style.height = "100%";
  48363. VirtualJoystick.vjCanvas.style.position = "absolute";
  48364. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  48365. VirtualJoystick.vjCanvas.style.top = "0px";
  48366. VirtualJoystick.vjCanvas.style.left = "0px";
  48367. VirtualJoystick.vjCanvas.style.zIndex = "5";
  48368. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  48369. // Support for jQuery PEP polyfill
  48370. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  48371. VirtualJoystick.vjCanvasContext = VirtualJoystick.vjCanvas.getContext('2d');
  48372. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  48373. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  48374. document.body.appendChild(VirtualJoystick.vjCanvas);
  48375. }
  48376. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  48377. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvas.height / 2;
  48378. this.pressed = false;
  48379. // default joystick color
  48380. this._joystickColor = "cyan";
  48381. this._joystickPointerID = -1;
  48382. // current joystick position
  48383. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  48384. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  48385. // origin joystick position
  48386. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  48387. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  48388. this._onPointerDownHandlerRef = function (evt) {
  48389. _this._onPointerDown(evt);
  48390. };
  48391. this._onPointerMoveHandlerRef = function (evt) {
  48392. _this._onPointerMove(evt);
  48393. };
  48394. this._onPointerOutHandlerRef = function (evt) {
  48395. _this._onPointerUp(evt);
  48396. };
  48397. this._onPointerUpHandlerRef = function (evt) {
  48398. _this._onPointerUp(evt);
  48399. };
  48400. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  48401. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  48402. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  48403. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  48404. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  48405. evt.preventDefault(); // Disables system menu
  48406. }, false);
  48407. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  48408. }
  48409. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  48410. this._joystickSensibility = newJoystickSensibility;
  48411. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  48412. };
  48413. VirtualJoystick.prototype._onPointerDown = function (e) {
  48414. var positionOnScreenCondition;
  48415. e.preventDefault();
  48416. if (this._leftJoystick === true) {
  48417. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  48418. }
  48419. else {
  48420. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  48421. }
  48422. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  48423. // First contact will be dedicated to the virtual joystick
  48424. this._joystickPointerID = e.pointerId;
  48425. this._joystickPointerStartPos.x = e.clientX;
  48426. this._joystickPointerStartPos.y = e.clientY;
  48427. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  48428. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  48429. this._deltaJoystickVector.x = 0;
  48430. this._deltaJoystickVector.y = 0;
  48431. this.pressed = true;
  48432. this._touches.add(e.pointerId.toString(), e);
  48433. }
  48434. else {
  48435. // You can only trigger the action buttons with a joystick declared
  48436. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  48437. this._action();
  48438. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  48439. }
  48440. }
  48441. };
  48442. VirtualJoystick.prototype._onPointerMove = function (e) {
  48443. // If the current pointer is the one associated to the joystick (first touch contact)
  48444. if (this._joystickPointerID == e.pointerId) {
  48445. this._joystickPointerPos.x = e.clientX;
  48446. this._joystickPointerPos.y = e.clientY;
  48447. this._deltaJoystickVector = this._joystickPointerPos.clone();
  48448. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  48449. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  48450. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  48451. switch (this._axisTargetedByLeftAndRight) {
  48452. case JoystickAxis.X:
  48453. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  48454. break;
  48455. case JoystickAxis.Y:
  48456. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  48457. break;
  48458. case JoystickAxis.Z:
  48459. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  48460. break;
  48461. }
  48462. var directionUpDown = this.reverseUpDown ? 1 : -1;
  48463. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  48464. switch (this._axisTargetedByUpAndDown) {
  48465. case JoystickAxis.X:
  48466. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  48467. break;
  48468. case JoystickAxis.Y:
  48469. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  48470. break;
  48471. case JoystickAxis.Z:
  48472. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  48473. break;
  48474. }
  48475. }
  48476. else {
  48477. var data = this._touches.get(e.pointerId.toString());
  48478. if (data) {
  48479. data.x = e.clientX;
  48480. data.y = e.clientY;
  48481. }
  48482. }
  48483. };
  48484. VirtualJoystick.prototype._onPointerUp = function (e) {
  48485. if (this._joystickPointerID == e.pointerId) {
  48486. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 64, this._joystickPointerStartPos.y - 64, 128, 128);
  48487. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 42, this._joystickPreviousPointerPos.y - 42, 84, 84);
  48488. this._joystickPointerID = -1;
  48489. this.pressed = false;
  48490. }
  48491. else {
  48492. var touch = this._touches.get(e.pointerId.toString());
  48493. if (touch) {
  48494. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  48495. }
  48496. }
  48497. this._deltaJoystickVector.x = 0;
  48498. this._deltaJoystickVector.y = 0;
  48499. this._touches.remove(e.pointerId.toString());
  48500. };
  48501. /**
  48502. * Change the color of the virtual joystick
  48503. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  48504. */
  48505. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  48506. this._joystickColor = newColor;
  48507. };
  48508. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  48509. this._action = action;
  48510. };
  48511. // Define which axis you'd like to control for left & right
  48512. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  48513. switch (axis) {
  48514. case JoystickAxis.X:
  48515. case JoystickAxis.Y:
  48516. case JoystickAxis.Z:
  48517. this._axisTargetedByLeftAndRight = axis;
  48518. break;
  48519. default:
  48520. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  48521. break;
  48522. }
  48523. };
  48524. // Define which axis you'd like to control for up & down
  48525. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  48526. switch (axis) {
  48527. case JoystickAxis.X:
  48528. case JoystickAxis.Y:
  48529. case JoystickAxis.Z:
  48530. this._axisTargetedByUpAndDown = axis;
  48531. break;
  48532. default:
  48533. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  48534. break;
  48535. }
  48536. };
  48537. VirtualJoystick.prototype._clearCanvas = function () {
  48538. if (this._leftJoystick) {
  48539. VirtualJoystick.vjCanvasContext.clearRect(0, 0, VirtualJoystick.vjCanvasWidth / 2, VirtualJoystick.vjCanvasHeight);
  48540. }
  48541. else {
  48542. VirtualJoystick.vjCanvasContext.clearRect(VirtualJoystick.vjCanvasWidth / 2, 0, VirtualJoystick.vjCanvasWidth, VirtualJoystick.vjCanvasHeight);
  48543. }
  48544. };
  48545. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  48546. var _this = this;
  48547. if (this.pressed) {
  48548. this._touches.forEach(function (key, touch) {
  48549. if (touch.pointerId === _this._joystickPointerID) {
  48550. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 64, _this._joystickPointerStartPos.y - 64, 128, 128);
  48551. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 42, _this._joystickPreviousPointerPos.y - 42, 84, 84);
  48552. VirtualJoystick.vjCanvasContext.beginPath();
  48553. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  48554. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  48555. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  48556. VirtualJoystick.vjCanvasContext.stroke();
  48557. VirtualJoystick.vjCanvasContext.closePath();
  48558. VirtualJoystick.vjCanvasContext.beginPath();
  48559. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  48560. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  48561. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  48562. VirtualJoystick.vjCanvasContext.stroke();
  48563. VirtualJoystick.vjCanvasContext.closePath();
  48564. VirtualJoystick.vjCanvasContext.beginPath();
  48565. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  48566. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  48567. VirtualJoystick.vjCanvasContext.stroke();
  48568. VirtualJoystick.vjCanvasContext.closePath();
  48569. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  48570. }
  48571. else {
  48572. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  48573. VirtualJoystick.vjCanvasContext.beginPath();
  48574. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  48575. VirtualJoystick.vjCanvasContext.beginPath();
  48576. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  48577. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  48578. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  48579. VirtualJoystick.vjCanvasContext.stroke();
  48580. VirtualJoystick.vjCanvasContext.closePath();
  48581. touch.prevX = touch.x;
  48582. touch.prevY = touch.y;
  48583. }
  48584. ;
  48585. });
  48586. }
  48587. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  48588. };
  48589. VirtualJoystick.prototype.releaseCanvas = function () {
  48590. if (VirtualJoystick.vjCanvas) {
  48591. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  48592. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  48593. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  48594. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  48595. window.removeEventListener("resize", this._onResize);
  48596. document.body.removeChild(VirtualJoystick.vjCanvas);
  48597. VirtualJoystick.vjCanvas = null;
  48598. }
  48599. };
  48600. return VirtualJoystick;
  48601. }());
  48602. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  48603. VirtualJoystick._globalJoystickIndex = 0;
  48604. BABYLON.VirtualJoystick = VirtualJoystick;
  48605. })(BABYLON || (BABYLON = {}));
  48606. //# sourceMappingURL=babylon.virtualJoystick.js.map
  48607. var BABYLON;
  48608. (function (BABYLON) {
  48609. // We're mainly based on the logic defined into the FreeCamera code
  48610. var VirtualJoysticksCamera = (function (_super) {
  48611. __extends(VirtualJoysticksCamera, _super);
  48612. function VirtualJoysticksCamera(name, position, scene) {
  48613. var _this = _super.call(this, name, position, scene) || this;
  48614. _this.inputs.addVirtualJoystick();
  48615. return _this;
  48616. }
  48617. VirtualJoysticksCamera.prototype.getClassName = function () {
  48618. return "VirtualJoysticksCamera";
  48619. };
  48620. return VirtualJoysticksCamera;
  48621. }(BABYLON.FreeCamera));
  48622. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  48623. })(BABYLON || (BABYLON = {}));
  48624. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  48625. var BABYLON;
  48626. (function (BABYLON) {
  48627. var FreeCameraVirtualJoystickInput = (function () {
  48628. function FreeCameraVirtualJoystickInput() {
  48629. }
  48630. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  48631. return this._leftjoystick;
  48632. };
  48633. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  48634. return this._rightjoystick;
  48635. };
  48636. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  48637. if (this._leftjoystick) {
  48638. var camera = this.camera;
  48639. var speed = camera._computeLocalCameraSpeed() * 50;
  48640. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  48641. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  48642. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  48643. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  48644. if (!this._leftjoystick.pressed) {
  48645. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  48646. }
  48647. if (!this._rightjoystick.pressed) {
  48648. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  48649. }
  48650. }
  48651. };
  48652. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  48653. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  48654. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  48655. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  48656. this._leftjoystick.setJoystickSensibility(0.15);
  48657. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  48658. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  48659. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  48660. this._rightjoystick.reverseUpDown = true;
  48661. this._rightjoystick.setJoystickSensibility(0.05);
  48662. this._rightjoystick.setJoystickColor("yellow");
  48663. };
  48664. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  48665. this._leftjoystick.releaseCanvas();
  48666. this._rightjoystick.releaseCanvas();
  48667. };
  48668. FreeCameraVirtualJoystickInput.prototype.getTypeName = function () {
  48669. return "FreeCameraVirtualJoystickInput";
  48670. };
  48671. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  48672. return "virtualJoystick";
  48673. };
  48674. return FreeCameraVirtualJoystickInput;
  48675. }());
  48676. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  48677. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  48678. })(BABYLON || (BABYLON = {}));
  48679. //# sourceMappingURL=babylon.freecamera.input.virtualjoystick.js.map
  48680. var BABYLON;
  48681. (function (BABYLON) {
  48682. var AnaglyphPostProcess = (function (_super) {
  48683. __extends(AnaglyphPostProcess, _super);
  48684. function AnaglyphPostProcess(name, options, rigCameras, samplingMode, engine, reusable) {
  48685. var _this = _super.call(this, name, "anaglyph", null, ["leftSampler"], options, rigCameras[1], samplingMode, engine, reusable) || this;
  48686. _this._passedProcess = rigCameras[0]._rigPostProcess;
  48687. _this.onApplyObservable.add(function (effect) {
  48688. effect.setTextureFromPostProcess("leftSampler", _this._passedProcess);
  48689. });
  48690. return _this;
  48691. }
  48692. return AnaglyphPostProcess;
  48693. }(BABYLON.PostProcess));
  48694. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  48695. })(BABYLON || (BABYLON = {}));
  48696. //# sourceMappingURL=babylon.anaglyphPostProcess.js.map
  48697. var BABYLON;
  48698. (function (BABYLON) {
  48699. var OutlineRenderer = (function () {
  48700. function OutlineRenderer(scene) {
  48701. this._scene = scene;
  48702. }
  48703. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  48704. var _this = this;
  48705. if (useOverlay === void 0) { useOverlay = false; }
  48706. var scene = this._scene;
  48707. var engine = this._scene.getEngine();
  48708. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  48709. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  48710. return;
  48711. }
  48712. var mesh = subMesh.getRenderingMesh();
  48713. var material = subMesh.getMaterial();
  48714. engine.enableEffect(this._effect);
  48715. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  48716. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : 1.0);
  48717. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  48718. // Bones
  48719. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  48720. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  48721. }
  48722. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  48723. // Alpha test
  48724. if (material && material.needAlphaTesting()) {
  48725. var alphaTexture = material.getAlphaTestTexture();
  48726. this._effect.setTexture("diffuseSampler", alphaTexture);
  48727. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  48728. }
  48729. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  48730. };
  48731. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  48732. var defines = [];
  48733. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  48734. var mesh = subMesh.getMesh();
  48735. var material = subMesh.getMaterial();
  48736. // Alpha test
  48737. if (material && material.needAlphaTesting()) {
  48738. defines.push("#define ALPHATEST");
  48739. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  48740. attribs.push(BABYLON.VertexBuffer.UVKind);
  48741. defines.push("#define UV1");
  48742. }
  48743. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  48744. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  48745. defines.push("#define UV2");
  48746. }
  48747. }
  48748. // Bones
  48749. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  48750. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  48751. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  48752. if (mesh.numBoneInfluencers > 4) {
  48753. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  48754. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  48755. }
  48756. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  48757. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  48758. }
  48759. else {
  48760. defines.push("#define NUM_BONE_INFLUENCERS 0");
  48761. }
  48762. // Instances
  48763. if (useInstances) {
  48764. defines.push("#define INSTANCES");
  48765. attribs.push("world0");
  48766. attribs.push("world1");
  48767. attribs.push("world2");
  48768. attribs.push("world3");
  48769. }
  48770. // Get correct effect
  48771. var join = defines.join("\n");
  48772. if (this._cachedDefines !== join) {
  48773. this._cachedDefines = join;
  48774. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color"], ["diffuseSampler"], join);
  48775. }
  48776. return this._effect.isReady();
  48777. };
  48778. return OutlineRenderer;
  48779. }());
  48780. BABYLON.OutlineRenderer = OutlineRenderer;
  48781. })(BABYLON || (BABYLON = {}));
  48782. //# sourceMappingURL=babylon.outlineRenderer.js.map
  48783. var BABYLON;
  48784. (function (BABYLON) {
  48785. var MeshAssetTask = (function () {
  48786. function MeshAssetTask(name, meshesNames, rootUrl, sceneFilename) {
  48787. this.name = name;
  48788. this.meshesNames = meshesNames;
  48789. this.rootUrl = rootUrl;
  48790. this.sceneFilename = sceneFilename;
  48791. this.isCompleted = false;
  48792. }
  48793. MeshAssetTask.prototype.run = function (scene, onSuccess, onError) {
  48794. var _this = this;
  48795. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  48796. _this.loadedMeshes = meshes;
  48797. _this.loadedParticleSystems = particleSystems;
  48798. _this.loadedSkeletons = skeletons;
  48799. _this.isCompleted = true;
  48800. if (_this.onSuccess) {
  48801. _this.onSuccess(_this);
  48802. }
  48803. onSuccess();
  48804. }, null, function () {
  48805. if (_this.onError) {
  48806. _this.onError(_this);
  48807. }
  48808. onError();
  48809. });
  48810. };
  48811. return MeshAssetTask;
  48812. }());
  48813. BABYLON.MeshAssetTask = MeshAssetTask;
  48814. var TextFileAssetTask = (function () {
  48815. function TextFileAssetTask(name, url) {
  48816. this.name = name;
  48817. this.url = url;
  48818. this.isCompleted = false;
  48819. }
  48820. TextFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  48821. var _this = this;
  48822. BABYLON.Tools.LoadFile(this.url, function (data) {
  48823. _this.text = data;
  48824. _this.isCompleted = true;
  48825. if (_this.onSuccess) {
  48826. _this.onSuccess(_this);
  48827. }
  48828. onSuccess();
  48829. }, null, scene.database, false, function () {
  48830. if (_this.onError) {
  48831. _this.onError(_this);
  48832. }
  48833. onError();
  48834. });
  48835. };
  48836. return TextFileAssetTask;
  48837. }());
  48838. BABYLON.TextFileAssetTask = TextFileAssetTask;
  48839. var BinaryFileAssetTask = (function () {
  48840. function BinaryFileAssetTask(name, url) {
  48841. this.name = name;
  48842. this.url = url;
  48843. this.isCompleted = false;
  48844. }
  48845. BinaryFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  48846. var _this = this;
  48847. BABYLON.Tools.LoadFile(this.url, function (data) {
  48848. _this.data = data;
  48849. _this.isCompleted = true;
  48850. if (_this.onSuccess) {
  48851. _this.onSuccess(_this);
  48852. }
  48853. onSuccess();
  48854. }, null, scene.database, true, function () {
  48855. if (_this.onError) {
  48856. _this.onError(_this);
  48857. }
  48858. onError();
  48859. });
  48860. };
  48861. return BinaryFileAssetTask;
  48862. }());
  48863. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  48864. var ImageAssetTask = (function () {
  48865. function ImageAssetTask(name, url) {
  48866. this.name = name;
  48867. this.url = url;
  48868. this.isCompleted = false;
  48869. }
  48870. ImageAssetTask.prototype.run = function (scene, onSuccess, onError) {
  48871. var _this = this;
  48872. var img = new Image();
  48873. BABYLON.Tools.SetCorsBehavior(this.url, img);
  48874. img.onload = function () {
  48875. _this.image = img;
  48876. _this.isCompleted = true;
  48877. if (_this.onSuccess) {
  48878. _this.onSuccess(_this);
  48879. }
  48880. onSuccess();
  48881. };
  48882. img.onerror = function () {
  48883. if (_this.onError) {
  48884. _this.onError(_this);
  48885. }
  48886. onError();
  48887. };
  48888. img.src = this.url;
  48889. };
  48890. return ImageAssetTask;
  48891. }());
  48892. BABYLON.ImageAssetTask = ImageAssetTask;
  48893. var TextureAssetTask = (function () {
  48894. function TextureAssetTask(name, url, noMipmap, invertY, samplingMode) {
  48895. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  48896. this.name = name;
  48897. this.url = url;
  48898. this.noMipmap = noMipmap;
  48899. this.invertY = invertY;
  48900. this.samplingMode = samplingMode;
  48901. this.isCompleted = false;
  48902. }
  48903. TextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  48904. var _this = this;
  48905. var onload = function () {
  48906. _this.isCompleted = true;
  48907. if (_this.onSuccess) {
  48908. _this.onSuccess(_this);
  48909. }
  48910. onSuccess();
  48911. };
  48912. var onerror = function () {
  48913. if (_this.onError) {
  48914. _this.onError(_this);
  48915. }
  48916. onError();
  48917. };
  48918. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  48919. };
  48920. return TextureAssetTask;
  48921. }());
  48922. BABYLON.TextureAssetTask = TextureAssetTask;
  48923. var CubeTextureAssetTask = (function () {
  48924. function CubeTextureAssetTask(name, url, extensions, noMipmap, files) {
  48925. this.name = name;
  48926. this.url = url;
  48927. this.extensions = extensions;
  48928. this.noMipmap = noMipmap;
  48929. this.files = files;
  48930. this.isCompleted = false;
  48931. }
  48932. CubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  48933. var _this = this;
  48934. var onload = function () {
  48935. _this.isCompleted = true;
  48936. if (_this.onSuccess) {
  48937. _this.onSuccess(_this);
  48938. }
  48939. onSuccess();
  48940. };
  48941. var onerror = function () {
  48942. if (_this.onError) {
  48943. _this.onError(_this);
  48944. }
  48945. onError();
  48946. };
  48947. this.texture = new BABYLON.CubeTexture(this.url, scene, this.extensions, this.noMipmap, this.files, onload, onerror);
  48948. };
  48949. return CubeTextureAssetTask;
  48950. }());
  48951. BABYLON.CubeTextureAssetTask = CubeTextureAssetTask;
  48952. var HDRCubeTextureAssetTask = (function () {
  48953. function HDRCubeTextureAssetTask(name, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator) {
  48954. if (noMipmap === void 0) { noMipmap = false; }
  48955. if (generateHarmonics === void 0) { generateHarmonics = true; }
  48956. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  48957. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  48958. this.name = name;
  48959. this.url = url;
  48960. this.size = size;
  48961. this.noMipmap = noMipmap;
  48962. this.generateHarmonics = generateHarmonics;
  48963. this.useInGammaSpace = useInGammaSpace;
  48964. this.usePMREMGenerator = usePMREMGenerator;
  48965. this.isCompleted = false;
  48966. }
  48967. HDRCubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  48968. var _this = this;
  48969. var onload = function () {
  48970. _this.isCompleted = true;
  48971. if (_this.onSuccess) {
  48972. _this.onSuccess(_this);
  48973. }
  48974. onSuccess();
  48975. };
  48976. var onerror = function () {
  48977. if (_this.onError) {
  48978. _this.onError(_this);
  48979. }
  48980. onError();
  48981. };
  48982. this.texture = new BABYLON.HDRCubeTexture(this.url, scene, this.size, this.noMipmap, this.generateHarmonics, this.useInGammaSpace, this.usePMREMGenerator, onload, onerror);
  48983. };
  48984. return HDRCubeTextureAssetTask;
  48985. }());
  48986. BABYLON.HDRCubeTextureAssetTask = HDRCubeTextureAssetTask;
  48987. var AssetsManager = (function () {
  48988. function AssetsManager(scene) {
  48989. this.tasks = new Array();
  48990. this.waitingTasksCount = 0;
  48991. this.useDefaultLoadingScreen = true;
  48992. this._scene = scene;
  48993. }
  48994. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  48995. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  48996. this.tasks.push(task);
  48997. return task;
  48998. };
  48999. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  49000. var task = new TextFileAssetTask(taskName, url);
  49001. this.tasks.push(task);
  49002. return task;
  49003. };
  49004. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  49005. var task = new BinaryFileAssetTask(taskName, url);
  49006. this.tasks.push(task);
  49007. return task;
  49008. };
  49009. AssetsManager.prototype.addImageTask = function (taskName, url) {
  49010. var task = new ImageAssetTask(taskName, url);
  49011. this.tasks.push(task);
  49012. return task;
  49013. };
  49014. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  49015. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  49016. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  49017. this.tasks.push(task);
  49018. return task;
  49019. };
  49020. AssetsManager.prototype._decreaseWaitingTasksCount = function () {
  49021. this.waitingTasksCount--;
  49022. if (this.waitingTasksCount === 0) {
  49023. if (this.onFinish) {
  49024. this.onFinish(this.tasks);
  49025. }
  49026. this._scene.getEngine().hideLoadingUI();
  49027. }
  49028. };
  49029. AssetsManager.prototype._runTask = function (task) {
  49030. var _this = this;
  49031. task.run(this._scene, function () {
  49032. if (_this.onTaskSuccess) {
  49033. _this.onTaskSuccess(task);
  49034. }
  49035. _this._decreaseWaitingTasksCount();
  49036. }, function () {
  49037. if (_this.onTaskError) {
  49038. _this.onTaskError(task);
  49039. }
  49040. _this._decreaseWaitingTasksCount();
  49041. });
  49042. };
  49043. AssetsManager.prototype.reset = function () {
  49044. this.tasks = new Array();
  49045. return this;
  49046. };
  49047. AssetsManager.prototype.load = function () {
  49048. this.waitingTasksCount = this.tasks.length;
  49049. if (this.waitingTasksCount === 0) {
  49050. if (this.onFinish) {
  49051. this.onFinish(this.tasks);
  49052. }
  49053. return this;
  49054. }
  49055. if (this.useDefaultLoadingScreen) {
  49056. this._scene.getEngine().displayLoadingUI();
  49057. }
  49058. for (var index = 0; index < this.tasks.length; index++) {
  49059. var task = this.tasks[index];
  49060. this._runTask(task);
  49061. }
  49062. return this;
  49063. };
  49064. return AssetsManager;
  49065. }());
  49066. BABYLON.AssetsManager = AssetsManager;
  49067. })(BABYLON || (BABYLON = {}));
  49068. //# sourceMappingURL=babylon.assetsManager.js.map
  49069. var BABYLON;
  49070. (function (BABYLON) {
  49071. var VRCameraMetrics = (function () {
  49072. function VRCameraMetrics() {
  49073. this.compensateDistortion = true;
  49074. }
  49075. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  49076. get: function () {
  49077. return this.hResolution / (2 * this.vResolution);
  49078. },
  49079. enumerable: true,
  49080. configurable: true
  49081. });
  49082. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  49083. get: function () {
  49084. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  49085. },
  49086. enumerable: true,
  49087. configurable: true
  49088. });
  49089. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  49090. get: function () {
  49091. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  49092. var h = (4 * meters) / this.hScreenSize;
  49093. return BABYLON.Matrix.Translation(h, 0, 0);
  49094. },
  49095. enumerable: true,
  49096. configurable: true
  49097. });
  49098. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  49099. get: function () {
  49100. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  49101. var h = (4 * meters) / this.hScreenSize;
  49102. return BABYLON.Matrix.Translation(-h, 0, 0);
  49103. },
  49104. enumerable: true,
  49105. configurable: true
  49106. });
  49107. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  49108. get: function () {
  49109. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  49110. },
  49111. enumerable: true,
  49112. configurable: true
  49113. });
  49114. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  49115. get: function () {
  49116. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  49117. },
  49118. enumerable: true,
  49119. configurable: true
  49120. });
  49121. VRCameraMetrics.GetDefault = function () {
  49122. var result = new VRCameraMetrics();
  49123. result.hResolution = 1280;
  49124. result.vResolution = 800;
  49125. result.hScreenSize = 0.149759993;
  49126. result.vScreenSize = 0.0935999975;
  49127. result.vScreenCenter = 0.0467999987;
  49128. result.eyeToScreenDistance = 0.0410000011;
  49129. result.lensSeparationDistance = 0.0635000020;
  49130. result.interpupillaryDistance = 0.0640000030;
  49131. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  49132. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  49133. result.postProcessScaleFactor = 1.714605507808412;
  49134. result.lensCenterOffset = 0.151976421;
  49135. return result;
  49136. };
  49137. return VRCameraMetrics;
  49138. }());
  49139. BABYLON.VRCameraMetrics = VRCameraMetrics;
  49140. })(BABYLON || (BABYLON = {}));
  49141. //# sourceMappingURL=babylon.vrCameraMetrics.js.map
  49142. var BABYLON;
  49143. (function (BABYLON) {
  49144. var WebVRFreeCamera = (function (_super) {
  49145. __extends(WebVRFreeCamera, _super);
  49146. function WebVRFreeCamera(name, position, scene, webVROptions) {
  49147. if (webVROptions === void 0) { webVROptions = {}; }
  49148. var _this = _super.call(this, name, position, scene) || this;
  49149. _this.webVROptions = webVROptions;
  49150. _this._vrDevice = null;
  49151. _this.rawPose = null;
  49152. _this._vrEnabled = false;
  49153. _this._attached = false;
  49154. _this._positionOffset = BABYLON.Vector3.Zero();
  49155. _this._descendants = [];
  49156. _this.devicePosition = BABYLON.Vector3.Zero();
  49157. _this.deviceScaleFactor = 1;
  49158. _this.controllers = [];
  49159. _this.rigParenting = true; // should the rig cameras be used as parent instead of this camera.
  49160. //legacy support - the compensation boolean was removed.
  49161. if (arguments.length === 5) {
  49162. _this.webVROptions = arguments[4];
  49163. }
  49164. // default webVR options
  49165. if (_this.webVROptions.trackPosition == undefined) {
  49166. _this.webVROptions.trackPosition = true;
  49167. }
  49168. if (_this.webVROptions.controllerMeshes == undefined) {
  49169. _this.webVROptions.controllerMeshes = true;
  49170. }
  49171. _this.rotationQuaternion = new BABYLON.Quaternion();
  49172. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  49173. if (_this.webVROptions && _this.webVROptions.positionScale) {
  49174. _this.deviceScaleFactor = _this.webVROptions.positionScale;
  49175. }
  49176. //enable VR
  49177. _this.getEngine().initWebVR();
  49178. if (!_this.getEngine().vrDisplaysPromise) {
  49179. BABYLON.Tools.Error("WebVR is not enabled on your browser");
  49180. }
  49181. else {
  49182. _this._frameData = new VRFrameData();
  49183. _this.getEngine().vrDisplaysPromise.then(function (devices) {
  49184. if (devices.length > 0) {
  49185. _this._vrEnabled = true;
  49186. if (_this.webVROptions.displayName) {
  49187. var found = devices.some(function (device) {
  49188. if (device.displayName === _this.webVROptions.displayName) {
  49189. _this._vrDevice = device;
  49190. return true;
  49191. }
  49192. else {
  49193. return false;
  49194. }
  49195. });
  49196. if (!found) {
  49197. _this._vrDevice = devices[0];
  49198. BABYLON.Tools.Warn("Display " + _this.webVROptions.displayName + " was not found. Using " + _this._vrDevice.displayName);
  49199. }
  49200. }
  49201. else {
  49202. //choose the first one
  49203. _this._vrDevice = devices[0];
  49204. }
  49205. //reset the rig parameters.
  49206. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_WEBVR, { parentCamera: _this, vrDisplay: _this._vrDevice, frameData: _this._frameData });
  49207. if (_this._attached) {
  49208. _this.getEngine().enableVR(_this._vrDevice);
  49209. }
  49210. }
  49211. else {
  49212. BABYLON.Tools.Error("No WebVR devices found!");
  49213. }
  49214. });
  49215. }
  49216. // try to attach the controllers, if found.
  49217. _this.initControllers();
  49218. /**
  49219. * The idea behind the following lines:
  49220. * objects that have the camera as parent should actually have the rig cameras as a parent.
  49221. * BUT, each of those cameras has a different view matrix, which means that if we set the parent to the first rig camera,
  49222. * the second will not show it correctly.
  49223. *
  49224. * To solve this - each object that has the camera as parent will be added to a protected array.
  49225. * When the rig camera renders, it will take this array and set all of those to be its children.
  49226. * This way, the right camera will be used as a parent, and the mesh will be rendered correctly.
  49227. * Amazing!
  49228. */
  49229. scene.onBeforeCameraRenderObservable.add(function (camera) {
  49230. if (camera.parent === _this && _this.rigParenting) {
  49231. _this._descendants = _this.getDescendants(true, function (n) {
  49232. // don't take the cameras or the controllers!
  49233. var isController = _this.controllers.some(function (controller) { return controller._mesh === n; });
  49234. var isRigCamera = _this._rigCameras.indexOf(n) !== -1;
  49235. return !isController && !isRigCamera;
  49236. });
  49237. _this._descendants.forEach(function (node) {
  49238. node.parent = camera;
  49239. });
  49240. }
  49241. });
  49242. scene.onAfterCameraRenderObservable.add(function (camera) {
  49243. if (camera.parent === _this && _this.rigParenting) {
  49244. _this._descendants.forEach(function (node) {
  49245. node.parent = _this;
  49246. });
  49247. }
  49248. });
  49249. return _this;
  49250. }
  49251. WebVRFreeCamera.prototype._checkInputs = function () {
  49252. if (this._vrEnabled && this._vrDevice.getFrameData(this._frameData)) {
  49253. var currentPose = this._frameData.pose;
  49254. this.updateFromDevice(currentPose);
  49255. }
  49256. _super.prototype._checkInputs.call(this);
  49257. };
  49258. WebVRFreeCamera.prototype.updateFromDevice = function (poseData) {
  49259. if (poseData && poseData.orientation) {
  49260. this.rawPose = poseData;
  49261. this.deviceRotationQuaternion.copyFromFloats(this.rawPose.orientation[0], this.rawPose.orientation[1], -this.rawPose.orientation[2], -this.rawPose.orientation[3]);
  49262. if (this.getScene().useRightHandedSystem) {
  49263. this.deviceRotationQuaternion.z *= -1;
  49264. this.deviceRotationQuaternion.w *= -1;
  49265. }
  49266. if (this.webVROptions.trackPosition && this.rawPose.position) {
  49267. this.devicePosition.copyFromFloats(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2]);
  49268. if (this.getScene().useRightHandedSystem) {
  49269. this.devicePosition.z *= -1;
  49270. }
  49271. }
  49272. }
  49273. };
  49274. /**
  49275. * WebVR's attach control will start broadcasting frames to the device.
  49276. * Note that in certain browsers (chrome for example) this function must be called
  49277. * within a user-interaction callback. Example:
  49278. * <pre> scene.onPointerDown = function() { camera.attachControl(canvas); }</pre>
  49279. *
  49280. * @param {HTMLElement} element
  49281. * @param {boolean} [noPreventDefault]
  49282. *
  49283. * @memberOf WebVRFreeCamera
  49284. */
  49285. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  49286. _super.prototype.attachControl.call(this, element, noPreventDefault);
  49287. this._attached = true;
  49288. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  49289. if (this._vrEnabled) {
  49290. this.getEngine().enableVR(this._vrDevice);
  49291. }
  49292. };
  49293. WebVRFreeCamera.prototype.detachControl = function (element) {
  49294. _super.prototype.detachControl.call(this, element);
  49295. this._vrEnabled = false;
  49296. this._attached = false;
  49297. this.getEngine().disableVR();
  49298. };
  49299. WebVRFreeCamera.prototype.getClassName = function () {
  49300. return "WebVRFreeCamera";
  49301. };
  49302. WebVRFreeCamera.prototype.resetToCurrentRotation = function () {
  49303. //uses the vrDisplay's "resetPose()".
  49304. //pitch and roll won't be affected.
  49305. this._vrDevice.resetPose();
  49306. };
  49307. WebVRFreeCamera.prototype._updateRigCameras = function () {
  49308. var camLeft = this._rigCameras[0];
  49309. var camRight = this._rigCameras[1];
  49310. camLeft.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  49311. camRight.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  49312. camLeft.position.copyFrom(this.devicePosition);
  49313. camRight.position.copyFrom(this.devicePosition);
  49314. };
  49315. /**
  49316. * This function is called by the two RIG cameras.
  49317. * 'this' is the left or right camera (and NOT (!!!) the WebVRFreeCamera instance)
  49318. */
  49319. WebVRFreeCamera.prototype._getWebVRViewMatrix = function () {
  49320. var _this = this;
  49321. var viewArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftViewMatrix : this._cameraRigParams["frameData"].rightViewMatrix;
  49322. BABYLON.Matrix.FromArrayToRef(viewArray, 0, this._webvrViewMatrix);
  49323. if (!this.getScene().useRightHandedSystem) {
  49324. [2, 6, 8, 9, 14].forEach(function (num) {
  49325. _this._webvrViewMatrix.m[num] *= -1;
  49326. });
  49327. }
  49328. var parentCamera = this._cameraRigParams["parentCamera"];
  49329. // should the view matrix be updated with scale and position offset?
  49330. if (parentCamera.deviceScaleFactor !== 1) {
  49331. this._webvrViewMatrix.invert();
  49332. // scale the position, if set
  49333. if (parentCamera.deviceScaleFactor) {
  49334. this._webvrViewMatrix.m[12] *= parentCamera.deviceScaleFactor;
  49335. this._webvrViewMatrix.m[13] *= parentCamera.deviceScaleFactor;
  49336. this._webvrViewMatrix.m[14] *= parentCamera.deviceScaleFactor;
  49337. }
  49338. this._webvrViewMatrix.invert();
  49339. }
  49340. // update the camera rotation matrix
  49341. this._webvrViewMatrix.getRotationMatrixToRef(this._cameraRotationMatrix);
  49342. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  49343. // Computing target and final matrix
  49344. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  49345. return this._webvrViewMatrix;
  49346. };
  49347. WebVRFreeCamera.prototype._getWebVRProjectionMatrix = function () {
  49348. var _this = this;
  49349. var projectionArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftProjectionMatrix : this._cameraRigParams["frameData"].rightProjectionMatrix;
  49350. BABYLON.Matrix.FromArrayToRef(projectionArray, 0, this._projectionMatrix);
  49351. //babylon compatible matrix
  49352. if (!this.getScene().useRightHandedSystem) {
  49353. [8, 9, 10, 11].forEach(function (num) {
  49354. _this._projectionMatrix.m[num] *= -1;
  49355. });
  49356. }
  49357. return this._projectionMatrix;
  49358. };
  49359. WebVRFreeCamera.prototype.initControllers = function () {
  49360. var _this = this;
  49361. this.controllers = [];
  49362. new BABYLON.Gamepads(function (gp) {
  49363. if (gp.type === BABYLON.Gamepad.POSE_ENABLED) {
  49364. var webVrController = gp;
  49365. if (_this.webVROptions.controllerMeshes) {
  49366. webVrController.initControllerMesh(_this.getScene());
  49367. }
  49368. webVrController.attachToPoseControlledCamera(_this);
  49369. // since this is async - sanity check. Is the controller already stored?
  49370. if (_this.controllers.indexOf(webVrController) === -1) {
  49371. //add to the controllers array
  49372. _this.controllers.push(webVrController);
  49373. //did we find enough controllers? Great! let the developer know.
  49374. if (_this.onControllersAttached && _this.controllers.length === 2) {
  49375. _this.onControllersAttached(_this.controllers);
  49376. }
  49377. }
  49378. }
  49379. });
  49380. };
  49381. return WebVRFreeCamera;
  49382. }(BABYLON.FreeCamera));
  49383. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  49384. })(BABYLON || (BABYLON = {}));
  49385. //# sourceMappingURL=babylon.webVRCamera.js.map
  49386. var BABYLON;
  49387. (function (BABYLON) {
  49388. // Standard optimizations
  49389. var SceneOptimization = (function () {
  49390. function SceneOptimization(priority) {
  49391. if (priority === void 0) { priority = 0; }
  49392. this.priority = priority;
  49393. this.apply = function (scene) {
  49394. return true; // Return true if everything that can be done was applied
  49395. };
  49396. }
  49397. return SceneOptimization;
  49398. }());
  49399. BABYLON.SceneOptimization = SceneOptimization;
  49400. var TextureOptimization = (function (_super) {
  49401. __extends(TextureOptimization, _super);
  49402. function TextureOptimization(priority, maximumSize) {
  49403. if (priority === void 0) { priority = 0; }
  49404. if (maximumSize === void 0) { maximumSize = 1024; }
  49405. var _this = _super.call(this, priority) || this;
  49406. _this.priority = priority;
  49407. _this.maximumSize = maximumSize;
  49408. _this.apply = function (scene) {
  49409. var allDone = true;
  49410. for (var index = 0; index < scene.textures.length; index++) {
  49411. var texture = scene.textures[index];
  49412. if (!texture.canRescale) {
  49413. continue;
  49414. }
  49415. var currentSize = texture.getSize();
  49416. var maxDimension = Math.max(currentSize.width, currentSize.height);
  49417. if (maxDimension > _this.maximumSize) {
  49418. texture.scale(0.5);
  49419. allDone = false;
  49420. }
  49421. }
  49422. return allDone;
  49423. };
  49424. return _this;
  49425. }
  49426. return TextureOptimization;
  49427. }(SceneOptimization));
  49428. BABYLON.TextureOptimization = TextureOptimization;
  49429. var HardwareScalingOptimization = (function (_super) {
  49430. __extends(HardwareScalingOptimization, _super);
  49431. function HardwareScalingOptimization(priority, maximumScale) {
  49432. if (priority === void 0) { priority = 0; }
  49433. if (maximumScale === void 0) { maximumScale = 2; }
  49434. var _this = _super.call(this, priority) || this;
  49435. _this.priority = priority;
  49436. _this.maximumScale = maximumScale;
  49437. _this._currentScale = 1;
  49438. _this.apply = function (scene) {
  49439. _this._currentScale++;
  49440. scene.getEngine().setHardwareScalingLevel(_this._currentScale);
  49441. return _this._currentScale >= _this.maximumScale;
  49442. };
  49443. return _this;
  49444. }
  49445. return HardwareScalingOptimization;
  49446. }(SceneOptimization));
  49447. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  49448. var ShadowsOptimization = (function (_super) {
  49449. __extends(ShadowsOptimization, _super);
  49450. function ShadowsOptimization() {
  49451. var _this = _super.apply(this, arguments) || this;
  49452. _this.apply = function (scene) {
  49453. scene.shadowsEnabled = false;
  49454. return true;
  49455. };
  49456. return _this;
  49457. }
  49458. return ShadowsOptimization;
  49459. }(SceneOptimization));
  49460. BABYLON.ShadowsOptimization = ShadowsOptimization;
  49461. var PostProcessesOptimization = (function (_super) {
  49462. __extends(PostProcessesOptimization, _super);
  49463. function PostProcessesOptimization() {
  49464. var _this = _super.apply(this, arguments) || this;
  49465. _this.apply = function (scene) {
  49466. scene.postProcessesEnabled = false;
  49467. return true;
  49468. };
  49469. return _this;
  49470. }
  49471. return PostProcessesOptimization;
  49472. }(SceneOptimization));
  49473. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  49474. var LensFlaresOptimization = (function (_super) {
  49475. __extends(LensFlaresOptimization, _super);
  49476. function LensFlaresOptimization() {
  49477. var _this = _super.apply(this, arguments) || this;
  49478. _this.apply = function (scene) {
  49479. scene.lensFlaresEnabled = false;
  49480. return true;
  49481. };
  49482. return _this;
  49483. }
  49484. return LensFlaresOptimization;
  49485. }(SceneOptimization));
  49486. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  49487. var ParticlesOptimization = (function (_super) {
  49488. __extends(ParticlesOptimization, _super);
  49489. function ParticlesOptimization() {
  49490. var _this = _super.apply(this, arguments) || this;
  49491. _this.apply = function (scene) {
  49492. scene.particlesEnabled = false;
  49493. return true;
  49494. };
  49495. return _this;
  49496. }
  49497. return ParticlesOptimization;
  49498. }(SceneOptimization));
  49499. BABYLON.ParticlesOptimization = ParticlesOptimization;
  49500. var RenderTargetsOptimization = (function (_super) {
  49501. __extends(RenderTargetsOptimization, _super);
  49502. function RenderTargetsOptimization() {
  49503. var _this = _super.apply(this, arguments) || this;
  49504. _this.apply = function (scene) {
  49505. scene.renderTargetsEnabled = false;
  49506. return true;
  49507. };
  49508. return _this;
  49509. }
  49510. return RenderTargetsOptimization;
  49511. }(SceneOptimization));
  49512. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  49513. var MergeMeshesOptimization = (function (_super) {
  49514. __extends(MergeMeshesOptimization, _super);
  49515. function MergeMeshesOptimization() {
  49516. var _this = _super.apply(this, arguments) || this;
  49517. _this._canBeMerged = function (abstractMesh) {
  49518. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  49519. return false;
  49520. }
  49521. var mesh = abstractMesh;
  49522. if (!mesh.isVisible || !mesh.isEnabled()) {
  49523. return false;
  49524. }
  49525. if (mesh.instances.length > 0) {
  49526. return false;
  49527. }
  49528. if (mesh.skeleton || mesh.hasLODLevels) {
  49529. return false;
  49530. }
  49531. if (mesh.parent) {
  49532. return false;
  49533. }
  49534. return true;
  49535. };
  49536. _this.apply = function (scene, updateSelectionTree) {
  49537. var globalPool = scene.meshes.slice(0);
  49538. var globalLength = globalPool.length;
  49539. for (var index = 0; index < globalLength; index++) {
  49540. var currentPool = new Array();
  49541. var current = globalPool[index];
  49542. // Checks
  49543. if (!_this._canBeMerged(current)) {
  49544. continue;
  49545. }
  49546. currentPool.push(current);
  49547. // Find compatible meshes
  49548. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  49549. var otherMesh = globalPool[subIndex];
  49550. if (!_this._canBeMerged(otherMesh)) {
  49551. continue;
  49552. }
  49553. if (otherMesh.material !== current.material) {
  49554. continue;
  49555. }
  49556. if (otherMesh.checkCollisions !== current.checkCollisions) {
  49557. continue;
  49558. }
  49559. currentPool.push(otherMesh);
  49560. globalLength--;
  49561. globalPool.splice(subIndex, 1);
  49562. subIndex--;
  49563. }
  49564. if (currentPool.length < 2) {
  49565. continue;
  49566. }
  49567. // Merge meshes
  49568. BABYLON.Mesh.MergeMeshes(currentPool);
  49569. }
  49570. if (updateSelectionTree != undefined) {
  49571. if (updateSelectionTree) {
  49572. scene.createOrUpdateSelectionOctree();
  49573. }
  49574. }
  49575. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  49576. scene.createOrUpdateSelectionOctree();
  49577. }
  49578. return true;
  49579. };
  49580. return _this;
  49581. }
  49582. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  49583. get: function () {
  49584. return MergeMeshesOptimization._UpdateSelectionTree;
  49585. },
  49586. set: function (value) {
  49587. MergeMeshesOptimization._UpdateSelectionTree = value;
  49588. },
  49589. enumerable: true,
  49590. configurable: true
  49591. });
  49592. return MergeMeshesOptimization;
  49593. }(SceneOptimization));
  49594. MergeMeshesOptimization._UpdateSelectionTree = false;
  49595. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  49596. // Options
  49597. var SceneOptimizerOptions = (function () {
  49598. function SceneOptimizerOptions(targetFrameRate, trackerDuration) {
  49599. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  49600. if (trackerDuration === void 0) { trackerDuration = 2000; }
  49601. this.targetFrameRate = targetFrameRate;
  49602. this.trackerDuration = trackerDuration;
  49603. this.optimizations = new Array();
  49604. }
  49605. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  49606. var result = new SceneOptimizerOptions(targetFrameRate);
  49607. var priority = 0;
  49608. result.optimizations.push(new MergeMeshesOptimization(priority));
  49609. result.optimizations.push(new ShadowsOptimization(priority));
  49610. result.optimizations.push(new LensFlaresOptimization(priority));
  49611. // Next priority
  49612. priority++;
  49613. result.optimizations.push(new PostProcessesOptimization(priority));
  49614. result.optimizations.push(new ParticlesOptimization(priority));
  49615. // Next priority
  49616. priority++;
  49617. result.optimizations.push(new TextureOptimization(priority, 1024));
  49618. return result;
  49619. };
  49620. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  49621. var result = new SceneOptimizerOptions(targetFrameRate);
  49622. var priority = 0;
  49623. result.optimizations.push(new MergeMeshesOptimization(priority));
  49624. result.optimizations.push(new ShadowsOptimization(priority));
  49625. result.optimizations.push(new LensFlaresOptimization(priority));
  49626. // Next priority
  49627. priority++;
  49628. result.optimizations.push(new PostProcessesOptimization(priority));
  49629. result.optimizations.push(new ParticlesOptimization(priority));
  49630. // Next priority
  49631. priority++;
  49632. result.optimizations.push(new TextureOptimization(priority, 512));
  49633. // Next priority
  49634. priority++;
  49635. result.optimizations.push(new RenderTargetsOptimization(priority));
  49636. // Next priority
  49637. priority++;
  49638. result.optimizations.push(new HardwareScalingOptimization(priority, 2));
  49639. return result;
  49640. };
  49641. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  49642. var result = new SceneOptimizerOptions(targetFrameRate);
  49643. var priority = 0;
  49644. result.optimizations.push(new MergeMeshesOptimization(priority));
  49645. result.optimizations.push(new ShadowsOptimization(priority));
  49646. result.optimizations.push(new LensFlaresOptimization(priority));
  49647. // Next priority
  49648. priority++;
  49649. result.optimizations.push(new PostProcessesOptimization(priority));
  49650. result.optimizations.push(new ParticlesOptimization(priority));
  49651. // Next priority
  49652. priority++;
  49653. result.optimizations.push(new TextureOptimization(priority, 256));
  49654. // Next priority
  49655. priority++;
  49656. result.optimizations.push(new RenderTargetsOptimization(priority));
  49657. // Next priority
  49658. priority++;
  49659. result.optimizations.push(new HardwareScalingOptimization(priority, 4));
  49660. return result;
  49661. };
  49662. return SceneOptimizerOptions;
  49663. }());
  49664. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  49665. // Scene optimizer tool
  49666. var SceneOptimizer = (function () {
  49667. function SceneOptimizer() {
  49668. }
  49669. SceneOptimizer._CheckCurrentState = function (scene, options, currentPriorityLevel, onSuccess, onFailure) {
  49670. // TODO: add an epsilon
  49671. if (scene.getEngine().getFps() >= options.targetFrameRate) {
  49672. if (onSuccess) {
  49673. onSuccess();
  49674. }
  49675. return;
  49676. }
  49677. // Apply current level of optimizations
  49678. var allDone = true;
  49679. var noOptimizationApplied = true;
  49680. for (var index = 0; index < options.optimizations.length; index++) {
  49681. var optimization = options.optimizations[index];
  49682. if (optimization.priority === currentPriorityLevel) {
  49683. noOptimizationApplied = false;
  49684. allDone = allDone && optimization.apply(scene);
  49685. }
  49686. }
  49687. // If no optimization was applied, this is a failure :(
  49688. if (noOptimizationApplied) {
  49689. if (onFailure) {
  49690. onFailure();
  49691. }
  49692. return;
  49693. }
  49694. // If all optimizations were done, move to next level
  49695. if (allDone) {
  49696. currentPriorityLevel++;
  49697. }
  49698. // Let's the system running for a specific amount of time before checking FPS
  49699. scene.executeWhenReady(function () {
  49700. setTimeout(function () {
  49701. SceneOptimizer._CheckCurrentState(scene, options, currentPriorityLevel, onSuccess, onFailure);
  49702. }, options.trackerDuration);
  49703. });
  49704. };
  49705. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  49706. if (!options) {
  49707. options = SceneOptimizerOptions.ModerateDegradationAllowed();
  49708. }
  49709. // Let's the system running for a specific amount of time before checking FPS
  49710. scene.executeWhenReady(function () {
  49711. setTimeout(function () {
  49712. SceneOptimizer._CheckCurrentState(scene, options, 0, onSuccess, onFailure);
  49713. }, options.trackerDuration);
  49714. });
  49715. };
  49716. return SceneOptimizer;
  49717. }());
  49718. BABYLON.SceneOptimizer = SceneOptimizer;
  49719. })(BABYLON || (BABYLON = {}));
  49720. //# sourceMappingURL=babylon.sceneOptimizer.js.map
  49721. var BABYLON;
  49722. (function (BABYLON) {
  49723. var Internals;
  49724. (function (Internals) {
  49725. var MeshLODLevel = (function () {
  49726. function MeshLODLevel(distance, mesh) {
  49727. this.distance = distance;
  49728. this.mesh = mesh;
  49729. }
  49730. return MeshLODLevel;
  49731. }());
  49732. Internals.MeshLODLevel = MeshLODLevel;
  49733. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  49734. })(BABYLON || (BABYLON = {}));
  49735. //# sourceMappingURL=babylon.meshLODLevel.js.map
  49736. var BABYLON;
  49737. (function (BABYLON) {
  49738. var RawTexture = (function (_super) {
  49739. __extends(RawTexture, _super);
  49740. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode) {
  49741. if (generateMipMaps === void 0) { generateMipMaps = true; }
  49742. if (invertY === void 0) { invertY = false; }
  49743. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  49744. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  49745. _this.format = format;
  49746. _this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode);
  49747. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  49748. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  49749. return _this;
  49750. }
  49751. RawTexture.prototype.update = function (data) {
  49752. this.getScene().getEngine().updateRawTexture(this._texture, data, this.format, this._invertY);
  49753. };
  49754. // Statics
  49755. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  49756. if (generateMipMaps === void 0) { generateMipMaps = true; }
  49757. if (invertY === void 0) { invertY = false; }
  49758. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  49759. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  49760. };
  49761. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  49762. if (generateMipMaps === void 0) { generateMipMaps = true; }
  49763. if (invertY === void 0) { invertY = false; }
  49764. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  49765. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  49766. };
  49767. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  49768. if (generateMipMaps === void 0) { generateMipMaps = true; }
  49769. if (invertY === void 0) { invertY = false; }
  49770. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  49771. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  49772. };
  49773. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  49774. if (generateMipMaps === void 0) { generateMipMaps = true; }
  49775. if (invertY === void 0) { invertY = false; }
  49776. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  49777. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode);
  49778. };
  49779. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  49780. if (generateMipMaps === void 0) { generateMipMaps = true; }
  49781. if (invertY === void 0) { invertY = false; }
  49782. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  49783. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode);
  49784. };
  49785. return RawTexture;
  49786. }(BABYLON.Texture));
  49787. BABYLON.RawTexture = RawTexture;
  49788. })(BABYLON || (BABYLON = {}));
  49789. //# sourceMappingURL=babylon.rawTexture.js.map
  49790. /// <reference path="..\Math\babylon.math.ts" />
  49791. var BABYLON;
  49792. (function (BABYLON) {
  49793. var IndexedVector2 = (function (_super) {
  49794. __extends(IndexedVector2, _super);
  49795. function IndexedVector2(original, index) {
  49796. var _this = _super.call(this, original.x, original.y) || this;
  49797. _this.index = index;
  49798. return _this;
  49799. }
  49800. return IndexedVector2;
  49801. }(BABYLON.Vector2));
  49802. var PolygonPoints = (function () {
  49803. function PolygonPoints() {
  49804. this.elements = new Array();
  49805. }
  49806. PolygonPoints.prototype.add = function (originalPoints) {
  49807. var _this = this;
  49808. var result = new Array();
  49809. originalPoints.forEach(function (point) {
  49810. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  49811. var newPoint = new IndexedVector2(point, _this.elements.length);
  49812. result.push(newPoint);
  49813. _this.elements.push(newPoint);
  49814. }
  49815. });
  49816. return result;
  49817. };
  49818. PolygonPoints.prototype.computeBounds = function () {
  49819. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  49820. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  49821. this.elements.forEach(function (point) {
  49822. // x
  49823. if (point.x < lmin.x) {
  49824. lmin.x = point.x;
  49825. }
  49826. else if (point.x > lmax.x) {
  49827. lmax.x = point.x;
  49828. }
  49829. // y
  49830. if (point.y < lmin.y) {
  49831. lmin.y = point.y;
  49832. }
  49833. else if (point.y > lmax.y) {
  49834. lmax.y = point.y;
  49835. }
  49836. });
  49837. return {
  49838. min: lmin,
  49839. max: lmax,
  49840. width: lmax.x - lmin.x,
  49841. height: lmax.y - lmin.y
  49842. };
  49843. };
  49844. return PolygonPoints;
  49845. }());
  49846. var Polygon = (function () {
  49847. function Polygon() {
  49848. }
  49849. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  49850. return [
  49851. new BABYLON.Vector2(xmin, ymin),
  49852. new BABYLON.Vector2(xmax, ymin),
  49853. new BABYLON.Vector2(xmax, ymax),
  49854. new BABYLON.Vector2(xmin, ymax)
  49855. ];
  49856. };
  49857. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  49858. if (cx === void 0) { cx = 0; }
  49859. if (cy === void 0) { cy = 0; }
  49860. if (numberOfSides === void 0) { numberOfSides = 32; }
  49861. var result = new Array();
  49862. var angle = 0;
  49863. var increment = (Math.PI * 2) / numberOfSides;
  49864. for (var i = 0; i < numberOfSides; i++) {
  49865. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  49866. angle -= increment;
  49867. }
  49868. return result;
  49869. };
  49870. Polygon.Parse = function (input) {
  49871. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  49872. var i, result = [];
  49873. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  49874. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  49875. }
  49876. return result;
  49877. };
  49878. Polygon.StartingAt = function (x, y) {
  49879. return BABYLON.Path2.StartingAt(x, y);
  49880. };
  49881. return Polygon;
  49882. }());
  49883. BABYLON.Polygon = Polygon;
  49884. var PolygonMeshBuilder = (function () {
  49885. function PolygonMeshBuilder(name, contours, scene) {
  49886. this._points = new PolygonPoints();
  49887. this._outlinepoints = new PolygonPoints();
  49888. this._holes = [];
  49889. this._epoints = new Array();
  49890. this._eholes = new Array();
  49891. this._name = name;
  49892. this._scene = scene;
  49893. var points;
  49894. if (contours instanceof BABYLON.Path2) {
  49895. points = contours.getPoints();
  49896. }
  49897. else {
  49898. points = contours;
  49899. }
  49900. this._addToepoint(points);
  49901. this._points.add(points);
  49902. this._outlinepoints.add(points);
  49903. }
  49904. PolygonMeshBuilder.prototype._addToepoint = function (points) {
  49905. for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {
  49906. var p = points_1[_i];
  49907. this._epoints.push(p.x, p.y);
  49908. }
  49909. };
  49910. PolygonMeshBuilder.prototype.addHole = function (hole) {
  49911. this._points.add(hole);
  49912. var holepoints = new PolygonPoints();
  49913. holepoints.add(hole);
  49914. this._holes.push(holepoints);
  49915. this._eholes.push(this._epoints.length / 2);
  49916. this._addToepoint(hole);
  49917. return this;
  49918. };
  49919. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  49920. var _this = this;
  49921. if (updatable === void 0) { updatable = false; }
  49922. var result = new BABYLON.Mesh(this._name, this._scene);
  49923. var normals = [];
  49924. var positions = [];
  49925. var uvs = [];
  49926. var bounds = this._points.computeBounds();
  49927. this._points.elements.forEach(function (p) {
  49928. normals.push(0, 1.0, 0);
  49929. positions.push(p.x, 0, p.y);
  49930. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  49931. });
  49932. var indices = [];
  49933. var res = Earcut.earcut(this._epoints, this._eholes, 2);
  49934. for (var i = 0; i < res.length; i++) {
  49935. indices.push(res[i]);
  49936. }
  49937. if (depth > 0) {
  49938. var positionscount = (positions.length / 3); //get the current pointcount
  49939. this._points.elements.forEach(function (p) {
  49940. normals.push(0, -1.0, 0);
  49941. positions.push(p.x, -depth, p.y);
  49942. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  49943. });
  49944. var totalCount = indices.length;
  49945. for (var i = 0; i < totalCount; i += 3) {
  49946. var i0 = indices[i + 0];
  49947. var i1 = indices[i + 1];
  49948. var i2 = indices[i + 2];
  49949. indices.push(i2 + positionscount);
  49950. indices.push(i1 + positionscount);
  49951. indices.push(i0 + positionscount);
  49952. }
  49953. //Add the sides
  49954. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  49955. this._holes.forEach(function (hole) {
  49956. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  49957. });
  49958. }
  49959. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  49960. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  49961. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  49962. result.setIndices(indices);
  49963. return result;
  49964. };
  49965. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  49966. var StartIndex = positions.length / 3;
  49967. var ulength = 0;
  49968. for (var i = 0; i < points.elements.length; i++) {
  49969. var p = points.elements[i];
  49970. var p1;
  49971. if ((i + 1) > points.elements.length - 1) {
  49972. p1 = points.elements[0];
  49973. }
  49974. else {
  49975. p1 = points.elements[i + 1];
  49976. }
  49977. positions.push(p.x, 0, p.y);
  49978. positions.push(p.x, -depth, p.y);
  49979. positions.push(p1.x, 0, p1.y);
  49980. positions.push(p1.x, -depth, p1.y);
  49981. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  49982. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  49983. var v3 = v2.subtract(v1);
  49984. var v4 = new BABYLON.Vector3(0, 1, 0);
  49985. var vn = BABYLON.Vector3.Cross(v3, v4);
  49986. vn = vn.normalize();
  49987. uvs.push(ulength / bounds.width, 0);
  49988. uvs.push(ulength / bounds.width, 1);
  49989. ulength += v3.length();
  49990. uvs.push((ulength / bounds.width), 0);
  49991. uvs.push((ulength / bounds.width), 1);
  49992. if (!flip) {
  49993. normals.push(-vn.x, -vn.y, -vn.z);
  49994. normals.push(-vn.x, -vn.y, -vn.z);
  49995. normals.push(-vn.x, -vn.y, -vn.z);
  49996. normals.push(-vn.x, -vn.y, -vn.z);
  49997. indices.push(StartIndex);
  49998. indices.push(StartIndex + 1);
  49999. indices.push(StartIndex + 2);
  50000. indices.push(StartIndex + 1);
  50001. indices.push(StartIndex + 3);
  50002. indices.push(StartIndex + 2);
  50003. }
  50004. else {
  50005. normals.push(vn.x, vn.y, vn.z);
  50006. normals.push(vn.x, vn.y, vn.z);
  50007. normals.push(vn.x, vn.y, vn.z);
  50008. normals.push(vn.x, vn.y, vn.z);
  50009. indices.push(StartIndex);
  50010. indices.push(StartIndex + 2);
  50011. indices.push(StartIndex + 1);
  50012. indices.push(StartIndex + 1);
  50013. indices.push(StartIndex + 2);
  50014. indices.push(StartIndex + 3);
  50015. }
  50016. StartIndex += 4;
  50017. }
  50018. ;
  50019. };
  50020. return PolygonMeshBuilder;
  50021. }());
  50022. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  50023. })(BABYLON || (BABYLON = {}));
  50024. //# sourceMappingURL=babylon.polygonMesh.js.map
  50025. var BABYLON;
  50026. (function (BABYLON) {
  50027. var Octree = (function () {
  50028. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  50029. if (maxDepth === void 0) { maxDepth = 2; }
  50030. this.maxDepth = maxDepth;
  50031. this.dynamicContent = new Array();
  50032. this._maxBlockCapacity = maxBlockCapacity || 64;
  50033. this._selectionContent = new BABYLON.SmartArray(1024);
  50034. this._creationFunc = creationFunc;
  50035. }
  50036. // Methods
  50037. Octree.prototype.update = function (worldMin, worldMax, entries) {
  50038. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  50039. };
  50040. Octree.prototype.addMesh = function (entry) {
  50041. for (var index = 0; index < this.blocks.length; index++) {
  50042. var block = this.blocks[index];
  50043. block.addEntry(entry);
  50044. }
  50045. };
  50046. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  50047. this._selectionContent.reset();
  50048. for (var index = 0; index < this.blocks.length; index++) {
  50049. var block = this.blocks[index];
  50050. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  50051. }
  50052. if (allowDuplicate) {
  50053. this._selectionContent.concat(this.dynamicContent);
  50054. }
  50055. else {
  50056. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  50057. }
  50058. return this._selectionContent;
  50059. };
  50060. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  50061. this._selectionContent.reset();
  50062. for (var index = 0; index < this.blocks.length; index++) {
  50063. var block = this.blocks[index];
  50064. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  50065. }
  50066. if (allowDuplicate) {
  50067. this._selectionContent.concat(this.dynamicContent);
  50068. }
  50069. else {
  50070. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  50071. }
  50072. return this._selectionContent;
  50073. };
  50074. Octree.prototype.intersectsRay = function (ray) {
  50075. this._selectionContent.reset();
  50076. for (var index = 0; index < this.blocks.length; index++) {
  50077. var block = this.blocks[index];
  50078. block.intersectsRay(ray, this._selectionContent);
  50079. }
  50080. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  50081. return this._selectionContent;
  50082. };
  50083. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  50084. target.blocks = new Array();
  50085. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  50086. // Segmenting space
  50087. for (var x = 0; x < 2; x++) {
  50088. for (var y = 0; y < 2; y++) {
  50089. for (var z = 0; z < 2; z++) {
  50090. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  50091. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  50092. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  50093. block.addEntries(entries);
  50094. target.blocks.push(block);
  50095. }
  50096. }
  50097. }
  50098. };
  50099. return Octree;
  50100. }());
  50101. Octree.CreationFuncForMeshes = function (entry, block) {
  50102. if (!entry.isBlocked && entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  50103. block.entries.push(entry);
  50104. }
  50105. };
  50106. Octree.CreationFuncForSubMeshes = function (entry, block) {
  50107. if (entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  50108. block.entries.push(entry);
  50109. }
  50110. };
  50111. BABYLON.Octree = Octree;
  50112. })(BABYLON || (BABYLON = {}));
  50113. //# sourceMappingURL=babylon.octree.js.map
  50114. var BABYLON;
  50115. (function (BABYLON) {
  50116. var OctreeBlock = (function () {
  50117. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  50118. this.entries = new Array();
  50119. this._boundingVectors = new Array();
  50120. this._capacity = capacity;
  50121. this._depth = depth;
  50122. this._maxDepth = maxDepth;
  50123. this._creationFunc = creationFunc;
  50124. this._minPoint = minPoint;
  50125. this._maxPoint = maxPoint;
  50126. this._boundingVectors.push(minPoint.clone());
  50127. this._boundingVectors.push(maxPoint.clone());
  50128. this._boundingVectors.push(minPoint.clone());
  50129. this._boundingVectors[2].x = maxPoint.x;
  50130. this._boundingVectors.push(minPoint.clone());
  50131. this._boundingVectors[3].y = maxPoint.y;
  50132. this._boundingVectors.push(minPoint.clone());
  50133. this._boundingVectors[4].z = maxPoint.z;
  50134. this._boundingVectors.push(maxPoint.clone());
  50135. this._boundingVectors[5].z = minPoint.z;
  50136. this._boundingVectors.push(maxPoint.clone());
  50137. this._boundingVectors[6].x = minPoint.x;
  50138. this._boundingVectors.push(maxPoint.clone());
  50139. this._boundingVectors[7].y = minPoint.y;
  50140. }
  50141. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  50142. // Property
  50143. get: function () {
  50144. return this._capacity;
  50145. },
  50146. enumerable: true,
  50147. configurable: true
  50148. });
  50149. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  50150. get: function () {
  50151. return this._minPoint;
  50152. },
  50153. enumerable: true,
  50154. configurable: true
  50155. });
  50156. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  50157. get: function () {
  50158. return this._maxPoint;
  50159. },
  50160. enumerable: true,
  50161. configurable: true
  50162. });
  50163. // Methods
  50164. OctreeBlock.prototype.addEntry = function (entry) {
  50165. if (this.blocks) {
  50166. for (var index = 0; index < this.blocks.length; index++) {
  50167. var block = this.blocks[index];
  50168. block.addEntry(entry);
  50169. }
  50170. return;
  50171. }
  50172. this._creationFunc(entry, this);
  50173. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  50174. this.createInnerBlocks();
  50175. }
  50176. };
  50177. OctreeBlock.prototype.addEntries = function (entries) {
  50178. for (var index = 0; index < entries.length; index++) {
  50179. var mesh = entries[index];
  50180. this.addEntry(mesh);
  50181. }
  50182. };
  50183. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  50184. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  50185. if (this.blocks) {
  50186. for (var index = 0; index < this.blocks.length; index++) {
  50187. var block = this.blocks[index];
  50188. block.select(frustumPlanes, selection, allowDuplicate);
  50189. }
  50190. return;
  50191. }
  50192. if (allowDuplicate) {
  50193. selection.concat(this.entries);
  50194. }
  50195. else {
  50196. selection.concatWithNoDuplicate(this.entries);
  50197. }
  50198. }
  50199. };
  50200. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  50201. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  50202. if (this.blocks) {
  50203. for (var index = 0; index < this.blocks.length; index++) {
  50204. var block = this.blocks[index];
  50205. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  50206. }
  50207. return;
  50208. }
  50209. if (allowDuplicate) {
  50210. selection.concat(this.entries);
  50211. }
  50212. else {
  50213. selection.concatWithNoDuplicate(this.entries);
  50214. }
  50215. }
  50216. };
  50217. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  50218. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  50219. if (this.blocks) {
  50220. for (var index = 0; index < this.blocks.length; index++) {
  50221. var block = this.blocks[index];
  50222. block.intersectsRay(ray, selection);
  50223. }
  50224. return;
  50225. }
  50226. selection.concatWithNoDuplicate(this.entries);
  50227. }
  50228. };
  50229. OctreeBlock.prototype.createInnerBlocks = function () {
  50230. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  50231. };
  50232. return OctreeBlock;
  50233. }());
  50234. BABYLON.OctreeBlock = OctreeBlock;
  50235. })(BABYLON || (BABYLON = {}));
  50236. //# sourceMappingURL=babylon.octreeBlock.js.map
  50237. var BABYLON;
  50238. (function (BABYLON) {
  50239. var BlurPostProcess = (function (_super) {
  50240. __extends(BlurPostProcess, _super);
  50241. function BlurPostProcess(name, direction, blurWidth, options, camera, samplingMode, engine, reusable) {
  50242. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  50243. var _this = _super.call(this, name, "blur", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable) || this;
  50244. _this.direction = direction;
  50245. _this.blurWidth = blurWidth;
  50246. _this.onApplyObservable.add(function (effect) {
  50247. effect.setFloat2("screenSize", _this.width, _this.height);
  50248. effect.setVector2("direction", _this.direction);
  50249. effect.setFloat("blurWidth", _this.blurWidth);
  50250. });
  50251. return _this;
  50252. }
  50253. return BlurPostProcess;
  50254. }(BABYLON.PostProcess));
  50255. BABYLON.BlurPostProcess = BlurPostProcess;
  50256. })(BABYLON || (BABYLON = {}));
  50257. //# sourceMappingURL=babylon.blurPostProcess.js.map
  50258. var BABYLON;
  50259. (function (BABYLON) {
  50260. var RefractionPostProcess = (function (_super) {
  50261. __extends(RefractionPostProcess, _super);
  50262. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, options, camera, samplingMode, engine, reusable) {
  50263. var _this = _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], options, camera, samplingMode, engine, reusable) || this;
  50264. _this.color = color;
  50265. _this.depth = depth;
  50266. _this.colorLevel = colorLevel;
  50267. _this.onActivateObservable.add(function (cam) {
  50268. _this._refRexture = _this._refRexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  50269. });
  50270. _this.onApplyObservable.add(function (effect) {
  50271. effect.setColor3("baseColor", _this.color);
  50272. effect.setFloat("depth", _this.depth);
  50273. effect.setFloat("colorLevel", _this.colorLevel);
  50274. effect.setTexture("refractionSampler", _this._refRexture);
  50275. });
  50276. return _this;
  50277. }
  50278. // Methods
  50279. RefractionPostProcess.prototype.dispose = function (camera) {
  50280. if (this._refRexture) {
  50281. this._refRexture.dispose();
  50282. }
  50283. _super.prototype.dispose.call(this, camera);
  50284. };
  50285. return RefractionPostProcess;
  50286. }(BABYLON.PostProcess));
  50287. BABYLON.RefractionPostProcess = RefractionPostProcess;
  50288. })(BABYLON || (BABYLON = {}));
  50289. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  50290. var BABYLON;
  50291. (function (BABYLON) {
  50292. var BlackAndWhitePostProcess = (function (_super) {
  50293. __extends(BlackAndWhitePostProcess, _super);
  50294. function BlackAndWhitePostProcess(name, options, camera, samplingMode, engine, reusable) {
  50295. return _super.call(this, name, "blackAndWhite", null, null, options, camera, samplingMode, engine, reusable) || this;
  50296. }
  50297. return BlackAndWhitePostProcess;
  50298. }(BABYLON.PostProcess));
  50299. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  50300. })(BABYLON || (BABYLON = {}));
  50301. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  50302. var BABYLON;
  50303. (function (BABYLON) {
  50304. var ConvolutionPostProcess = (function (_super) {
  50305. __extends(ConvolutionPostProcess, _super);
  50306. function ConvolutionPostProcess(name, kernel, options, camera, samplingMode, engine, reusable) {
  50307. var _this = _super.call(this, name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable) || this;
  50308. _this.kernel = kernel;
  50309. _this.onApply = function (effect) {
  50310. effect.setFloat2("screenSize", _this.width, _this.height);
  50311. effect.setArray("kernel", _this.kernel);
  50312. };
  50313. return _this;
  50314. }
  50315. return ConvolutionPostProcess;
  50316. }(BABYLON.PostProcess));
  50317. // Statics
  50318. // Based on http://en.wikipedia.org/wiki/Kernel_(image_processing)
  50319. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  50320. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  50321. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  50322. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  50323. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  50324. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  50325. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  50326. })(BABYLON || (BABYLON = {}));
  50327. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  50328. var BABYLON;
  50329. (function (BABYLON) {
  50330. var FilterPostProcess = (function (_super) {
  50331. __extends(FilterPostProcess, _super);
  50332. function FilterPostProcess(name, kernelMatrix, options, camera, samplingMode, engine, reusable) {
  50333. var _this = _super.call(this, name, "filter", ["kernelMatrix"], null, options, camera, samplingMode, engine, reusable) || this;
  50334. _this.kernelMatrix = kernelMatrix;
  50335. _this.onApply = function (effect) {
  50336. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  50337. };
  50338. return _this;
  50339. }
  50340. return FilterPostProcess;
  50341. }(BABYLON.PostProcess));
  50342. BABYLON.FilterPostProcess = FilterPostProcess;
  50343. })(BABYLON || (BABYLON = {}));
  50344. //# sourceMappingURL=babylon.filterPostProcess.js.map
  50345. var BABYLON;
  50346. (function (BABYLON) {
  50347. var FxaaPostProcess = (function (_super) {
  50348. __extends(FxaaPostProcess, _super);
  50349. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable) {
  50350. var _this = _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode || BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable) || this;
  50351. _this.onSizeChangedObservable.add(function () {
  50352. _this.texelWidth = 1.0 / _this.width;
  50353. _this.texelHeight = 1.0 / _this.height;
  50354. });
  50355. _this.onApplyObservable.add(function (effect) {
  50356. effect.setFloat2("texelSize", _this.texelWidth, _this.texelHeight);
  50357. });
  50358. return _this;
  50359. }
  50360. return FxaaPostProcess;
  50361. }(BABYLON.PostProcess));
  50362. BABYLON.FxaaPostProcess = FxaaPostProcess;
  50363. })(BABYLON || (BABYLON = {}));
  50364. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  50365. var BABYLON;
  50366. (function (BABYLON) {
  50367. var StereoscopicInterlacePostProcess = (function (_super) {
  50368. __extends(StereoscopicInterlacePostProcess, _super);
  50369. function StereoscopicInterlacePostProcess(name, rigCameras, isStereoscopicHoriz, samplingMode, engine, reusable) {
  50370. var _this = _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined) || this;
  50371. _this._passedProcess = rigCameras[0]._rigPostProcess;
  50372. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  50373. _this.onSizeChangedObservable.add(function () {
  50374. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  50375. });
  50376. _this.onApplyObservable.add(function (effect) {
  50377. effect.setTextureFromPostProcess("camASampler", _this._passedProcess);
  50378. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  50379. });
  50380. return _this;
  50381. }
  50382. return StereoscopicInterlacePostProcess;
  50383. }(BABYLON.PostProcess));
  50384. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  50385. })(BABYLON || (BABYLON = {}));
  50386. //# sourceMappingURL=babylon.stereoscopicInterlacePostProcess.js.map
  50387. var BABYLON;
  50388. (function (BABYLON) {
  50389. var LensFlare = (function () {
  50390. function LensFlare(size, position, color, imgUrl, system) {
  50391. this.size = size;
  50392. this.position = position;
  50393. this.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  50394. this.dispose = function () {
  50395. if (this.texture) {
  50396. this.texture.dispose();
  50397. }
  50398. // Remove from scene
  50399. var index = this._system.lensFlares.indexOf(this);
  50400. this._system.lensFlares.splice(index, 1);
  50401. };
  50402. this.color = color || new BABYLON.Color3(1, 1, 1);
  50403. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  50404. this._system = system;
  50405. system.lensFlares.push(this);
  50406. }
  50407. return LensFlare;
  50408. }());
  50409. BABYLON.LensFlare = LensFlare;
  50410. })(BABYLON || (BABYLON = {}));
  50411. //# sourceMappingURL=babylon.lensFlare.js.map
  50412. var BABYLON;
  50413. (function (BABYLON) {
  50414. var LensFlareSystem = (function () {
  50415. function LensFlareSystem(name, emitter, scene) {
  50416. this.name = name;
  50417. this.lensFlares = new Array();
  50418. this.borderLimit = 300;
  50419. this.viewportBorder = 0;
  50420. this.layerMask = 0x0FFFFFFF;
  50421. this._vertexBuffers = {};
  50422. this._isEnabled = true;
  50423. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  50424. this._emitter = emitter;
  50425. this.id = name;
  50426. scene.lensFlareSystems.push(this);
  50427. this.meshesSelectionPredicate = function (m) { return m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0); };
  50428. var engine = scene.getEngine();
  50429. // VBO
  50430. var vertices = [];
  50431. vertices.push(1, 1);
  50432. vertices.push(-1, 1);
  50433. vertices.push(-1, -1);
  50434. vertices.push(1, -1);
  50435. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  50436. // Indices
  50437. var indices = [];
  50438. indices.push(0);
  50439. indices.push(1);
  50440. indices.push(2);
  50441. indices.push(0);
  50442. indices.push(2);
  50443. indices.push(3);
  50444. this._indexBuffer = engine.createIndexBuffer(indices);
  50445. // Effects
  50446. this._effect = engine.createEffect("lensFlare", [BABYLON.VertexBuffer.PositionKind], ["color", "viewportMatrix"], ["textureSampler"], "");
  50447. }
  50448. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  50449. get: function () {
  50450. return this._isEnabled;
  50451. },
  50452. set: function (value) {
  50453. this._isEnabled = value;
  50454. },
  50455. enumerable: true,
  50456. configurable: true
  50457. });
  50458. LensFlareSystem.prototype.getScene = function () {
  50459. return this._scene;
  50460. };
  50461. LensFlareSystem.prototype.getEmitter = function () {
  50462. return this._emitter;
  50463. };
  50464. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  50465. this._emitter = newEmitter;
  50466. };
  50467. LensFlareSystem.prototype.getEmitterPosition = function () {
  50468. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  50469. };
  50470. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  50471. var position = this.getEmitterPosition();
  50472. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  50473. this._positionX = position.x;
  50474. this._positionY = position.y;
  50475. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  50476. if (this.viewportBorder > 0) {
  50477. globalViewport.x -= this.viewportBorder;
  50478. globalViewport.y -= this.viewportBorder;
  50479. globalViewport.width += this.viewportBorder * 2;
  50480. globalViewport.height += this.viewportBorder * 2;
  50481. position.x += this.viewportBorder;
  50482. position.y += this.viewportBorder;
  50483. this._positionX += this.viewportBorder;
  50484. this._positionY += this.viewportBorder;
  50485. }
  50486. if (position.z > 0) {
  50487. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  50488. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  50489. return true;
  50490. }
  50491. return true;
  50492. }
  50493. return false;
  50494. };
  50495. LensFlareSystem.prototype._isVisible = function () {
  50496. if (!this._isEnabled) {
  50497. return false;
  50498. }
  50499. var emitterPosition = this.getEmitterPosition();
  50500. var direction = emitterPosition.subtract(this._scene.activeCamera.globalPosition);
  50501. var distance = direction.length();
  50502. direction.normalize();
  50503. var ray = new BABYLON.Ray(this._scene.activeCamera.globalPosition, direction);
  50504. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  50505. return !pickInfo.hit || pickInfo.distance > distance;
  50506. };
  50507. LensFlareSystem.prototype.render = function () {
  50508. if (!this._effect.isReady())
  50509. return false;
  50510. var engine = this._scene.getEngine();
  50511. var viewport = this._scene.activeCamera.viewport;
  50512. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  50513. // Position
  50514. if (!this.computeEffectivePosition(globalViewport)) {
  50515. return false;
  50516. }
  50517. // Visibility
  50518. if (!this._isVisible()) {
  50519. return false;
  50520. }
  50521. // Intensity
  50522. var awayX;
  50523. var awayY;
  50524. if (this._positionX < this.borderLimit + globalViewport.x) {
  50525. awayX = this.borderLimit + globalViewport.x - this._positionX;
  50526. }
  50527. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  50528. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  50529. }
  50530. else {
  50531. awayX = 0;
  50532. }
  50533. if (this._positionY < this.borderLimit + globalViewport.y) {
  50534. awayY = this.borderLimit + globalViewport.y - this._positionY;
  50535. }
  50536. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  50537. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  50538. }
  50539. else {
  50540. awayY = 0;
  50541. }
  50542. var away = (awayX > awayY) ? awayX : awayY;
  50543. away -= this.viewportBorder;
  50544. if (away > this.borderLimit) {
  50545. away = this.borderLimit;
  50546. }
  50547. var intensity = 1.0 - (away / this.borderLimit);
  50548. if (intensity < 0) {
  50549. return false;
  50550. }
  50551. if (intensity > 1.0) {
  50552. intensity = 1.0;
  50553. }
  50554. if (this.viewportBorder > 0) {
  50555. globalViewport.x += this.viewportBorder;
  50556. globalViewport.y += this.viewportBorder;
  50557. globalViewport.width -= this.viewportBorder * 2;
  50558. globalViewport.height -= this.viewportBorder * 2;
  50559. this._positionX -= this.viewportBorder;
  50560. this._positionY -= this.viewportBorder;
  50561. }
  50562. // Position
  50563. var centerX = globalViewport.x + globalViewport.width / 2;
  50564. var centerY = globalViewport.y + globalViewport.height / 2;
  50565. var distX = centerX - this._positionX;
  50566. var distY = centerY - this._positionY;
  50567. // Effects
  50568. engine.enableEffect(this._effect);
  50569. engine.setState(false);
  50570. engine.setDepthBuffer(false);
  50571. // VBOs
  50572. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  50573. // Flares
  50574. for (var index = 0; index < this.lensFlares.length; index++) {
  50575. var flare = this.lensFlares[index];
  50576. engine.setAlphaMode(flare.alphaMode);
  50577. var x = centerX - (distX * flare.position);
  50578. var y = centerY - (distY * flare.position);
  50579. var cw = flare.size;
  50580. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  50581. var cx = 2 * (x / (globalViewport.width + globalViewport.x * 2)) - 1.0;
  50582. var cy = 1.0 - 2 * (y / (globalViewport.height + globalViewport.y * 2));
  50583. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  50584. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  50585. // Texture
  50586. this._effect.setTexture("textureSampler", flare.texture);
  50587. // Color
  50588. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  50589. // Draw order
  50590. engine.draw(true, 0, 6);
  50591. }
  50592. engine.setDepthBuffer(true);
  50593. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  50594. return true;
  50595. };
  50596. LensFlareSystem.prototype.dispose = function () {
  50597. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  50598. if (vertexBuffer) {
  50599. vertexBuffer.dispose();
  50600. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  50601. }
  50602. if (this._indexBuffer) {
  50603. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  50604. this._indexBuffer = null;
  50605. }
  50606. while (this.lensFlares.length) {
  50607. this.lensFlares[0].dispose();
  50608. }
  50609. // Remove from scene
  50610. var index = this._scene.lensFlareSystems.indexOf(this);
  50611. this._scene.lensFlareSystems.splice(index, 1);
  50612. };
  50613. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  50614. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  50615. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  50616. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  50617. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  50618. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  50619. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  50620. var parsedFlare = parsedLensFlareSystem.flares[index];
  50621. var flare = new BABYLON.LensFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), rootUrl + parsedFlare.textureName, lensFlareSystem);
  50622. }
  50623. return lensFlareSystem;
  50624. };
  50625. LensFlareSystem.prototype.serialize = function () {
  50626. var serializationObject = {};
  50627. serializationObject.id = this.id;
  50628. serializationObject.name = this.name;
  50629. serializationObject.emitterId = this.getEmitter().id;
  50630. serializationObject.borderLimit = this.borderLimit;
  50631. serializationObject.flares = [];
  50632. for (var index = 0; index < this.lensFlares.length; index++) {
  50633. var flare = this.lensFlares[index];
  50634. serializationObject.flares.push({
  50635. size: flare.size,
  50636. position: flare.position,
  50637. color: flare.color.asArray(),
  50638. textureName: BABYLON.Tools.GetFilename(flare.texture.name)
  50639. });
  50640. }
  50641. return serializationObject;
  50642. };
  50643. return LensFlareSystem;
  50644. }());
  50645. BABYLON.LensFlareSystem = LensFlareSystem;
  50646. })(BABYLON || (BABYLON = {}));
  50647. //# sourceMappingURL=babylon.lensFlareSystem.js.map
  50648. /// <reference path="babylon.freeCamera.ts" />
  50649. var BABYLON;
  50650. (function (BABYLON) {
  50651. // We're mainly based on the logic defined into the FreeCamera code
  50652. var DeviceOrientationCamera = (function (_super) {
  50653. __extends(DeviceOrientationCamera, _super);
  50654. function DeviceOrientationCamera(name, position, scene) {
  50655. var _this = _super.call(this, name, position, scene) || this;
  50656. _this._quaternionCache = new BABYLON.Quaternion();
  50657. _this.inputs.addDeviceOrientation();
  50658. return _this;
  50659. }
  50660. DeviceOrientationCamera.prototype.getClassName = function () {
  50661. return "DeviceOrientationCamera";
  50662. };
  50663. DeviceOrientationCamera.prototype._checkInputs = function () {
  50664. _super.prototype._checkInputs.call(this);
  50665. this._quaternionCache.copyFrom(this.rotationQuaternion);
  50666. if (this._initialQuaternion) {
  50667. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  50668. }
  50669. };
  50670. DeviceOrientationCamera.prototype.resetToCurrentRotation = function (axis) {
  50671. var _this = this;
  50672. if (axis === void 0) { axis = BABYLON.Axis.Y; }
  50673. //can only work if this camera has a rotation quaternion already.
  50674. if (!this.rotationQuaternion)
  50675. return;
  50676. if (!this._initialQuaternion) {
  50677. this._initialQuaternion = new BABYLON.Quaternion();
  50678. }
  50679. this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion);
  50680. ['x', 'y', 'z'].forEach(function (axisName) {
  50681. if (!axis[axisName]) {
  50682. _this._initialQuaternion[axisName] = 0;
  50683. }
  50684. else {
  50685. _this._initialQuaternion[axisName] *= -1;
  50686. }
  50687. });
  50688. this._initialQuaternion.normalize();
  50689. //force rotation update
  50690. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  50691. };
  50692. return DeviceOrientationCamera;
  50693. }(BABYLON.FreeCamera));
  50694. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  50695. })(BABYLON || (BABYLON = {}));
  50696. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  50697. var BABYLON;
  50698. (function (BABYLON) {
  50699. var VRDeviceOrientationFreeCamera = (function (_super) {
  50700. __extends(VRDeviceOrientationFreeCamera, _super);
  50701. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  50702. if (compensateDistortion === void 0) { compensateDistortion = true; }
  50703. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  50704. var _this = _super.call(this, name, position, scene) || this;
  50705. vrCameraMetrics.compensateDistortion = compensateDistortion;
  50706. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  50707. return _this;
  50708. }
  50709. VRDeviceOrientationFreeCamera.prototype.getClassName = function () {
  50710. return "VRDeviceOrientationFreeCamera";
  50711. };
  50712. return VRDeviceOrientationFreeCamera;
  50713. }(BABYLON.DeviceOrientationCamera));
  50714. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  50715. var VRDeviceOrientationGamepadCamera = (function (_super) {
  50716. __extends(VRDeviceOrientationGamepadCamera, _super);
  50717. function VRDeviceOrientationGamepadCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  50718. if (compensateDistortion === void 0) { compensateDistortion = true; }
  50719. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  50720. var _this = _super.call(this, name, position, scene, compensateDistortion, vrCameraMetrics) || this;
  50721. _this.inputs.addGamepad();
  50722. return _this;
  50723. }
  50724. VRDeviceOrientationGamepadCamera.prototype.getClassName = function () {
  50725. return "VRDeviceOrientationGamepadCamera";
  50726. };
  50727. return VRDeviceOrientationGamepadCamera;
  50728. }(VRDeviceOrientationFreeCamera));
  50729. BABYLON.VRDeviceOrientationGamepadCamera = VRDeviceOrientationGamepadCamera;
  50730. var VRDeviceOrientationArcRotateCamera = (function (_super) {
  50731. __extends(VRDeviceOrientationArcRotateCamera, _super);
  50732. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion, vrCameraMetrics) {
  50733. if (compensateDistortion === void 0) { compensateDistortion = true; }
  50734. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  50735. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  50736. vrCameraMetrics.compensateDistortion = compensateDistortion;
  50737. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  50738. _this.inputs.addVRDeviceOrientation();
  50739. return _this;
  50740. }
  50741. VRDeviceOrientationArcRotateCamera.prototype.getClassName = function () {
  50742. return "VRDeviceOrientationArcRotateCamera";
  50743. };
  50744. return VRDeviceOrientationArcRotateCamera;
  50745. }(BABYLON.ArcRotateCamera));
  50746. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  50747. })(BABYLON || (BABYLON = {}));
  50748. //# sourceMappingURL=babylon.vrDeviceOrientationCamera.js.map
  50749. /// <reference path="babylon.touchCamera.ts" />
  50750. var BABYLON;
  50751. (function (BABYLON) {
  50752. // We're mainly based on the logic defined into the FreeCamera code
  50753. var UniversalCamera = (function (_super) {
  50754. __extends(UniversalCamera, _super);
  50755. //-- end properties for backward compatibility for inputs
  50756. function UniversalCamera(name, position, scene) {
  50757. var _this = _super.call(this, name, position, scene) || this;
  50758. _this.inputs.addGamepad();
  50759. return _this;
  50760. }
  50761. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  50762. //-- Begin properties for backward compatibility for inputs
  50763. get: function () {
  50764. var gamepad = this.inputs.attached["gamepad"];
  50765. if (gamepad)
  50766. return gamepad.gamepadAngularSensibility;
  50767. },
  50768. set: function (value) {
  50769. var gamepad = this.inputs.attached["gamepad"];
  50770. if (gamepad)
  50771. gamepad.gamepadAngularSensibility = value;
  50772. },
  50773. enumerable: true,
  50774. configurable: true
  50775. });
  50776. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  50777. get: function () {
  50778. var gamepad = this.inputs.attached["gamepad"];
  50779. if (gamepad)
  50780. return gamepad.gamepadMoveSensibility;
  50781. },
  50782. set: function (value) {
  50783. var gamepad = this.inputs.attached["gamepad"];
  50784. if (gamepad)
  50785. gamepad.gamepadMoveSensibility = value;
  50786. },
  50787. enumerable: true,
  50788. configurable: true
  50789. });
  50790. UniversalCamera.prototype.getClassName = function () {
  50791. return "UniversalCamera";
  50792. };
  50793. return UniversalCamera;
  50794. }(BABYLON.TouchCamera));
  50795. BABYLON.UniversalCamera = UniversalCamera;
  50796. })(BABYLON || (BABYLON = {}));
  50797. //# sourceMappingURL=babylon.universalCamera.js.map
  50798. var BABYLON;
  50799. (function (BABYLON) {
  50800. var Gamepads = (function () {
  50801. function Gamepads(ongamedpadconnected) {
  50802. var _this = this;
  50803. this.babylonGamepads = [];
  50804. this.oneGamepadConnected = false;
  50805. this.isMonitoring = false;
  50806. this.gamepadEventSupported = 'GamepadEvent' in window;
  50807. this.gamepadSupport = (navigator.getGamepads ||
  50808. navigator.webkitGetGamepads || navigator.msGetGamepads || navigator.webkitGamepads);
  50809. this._callbackGamepadConnected = ongamedpadconnected;
  50810. if (this.gamepadSupport) {
  50811. //first add already-connected gamepads
  50812. this._updateGamepadObjects();
  50813. if (this.babylonGamepads.length) {
  50814. this._startMonitoringGamepads();
  50815. }
  50816. // Checking if the gamepad connected event is supported (like in Firefox)
  50817. if (this.gamepadEventSupported) {
  50818. this._onGamepadConnectedEvent = function (evt) {
  50819. _this._onGamepadConnected(evt.gamepad);
  50820. };
  50821. this._onGamepadDisonnectedEvent = function (evt) {
  50822. _this._onGamepadDisconnected(evt);
  50823. };
  50824. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  50825. window.addEventListener('gamepaddisconnected', this._onGamepadDisonnectedEvent, false);
  50826. }
  50827. else {
  50828. this._startMonitoringGamepads();
  50829. }
  50830. }
  50831. }
  50832. Gamepads.prototype.dispose = function () {
  50833. if (Gamepads.gamepadDOMInfo) {
  50834. document.body.removeChild(Gamepads.gamepadDOMInfo);
  50835. }
  50836. if (this._onGamepadConnectedEvent) {
  50837. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  50838. window.removeEventListener('gamepaddisconnected', this._onGamepadDisonnectedEvent, false);
  50839. this._onGamepadConnectedEvent = null;
  50840. this._onGamepadDisonnectedEvent = null;
  50841. }
  50842. };
  50843. Gamepads.prototype._onGamepadConnected = function (gamepad) {
  50844. var newGamepad = this._addNewGamepad(gamepad);
  50845. if (this._callbackGamepadConnected)
  50846. this._callbackGamepadConnected(newGamepad);
  50847. this._startMonitoringGamepads();
  50848. };
  50849. Gamepads.prototype._addNewGamepad = function (gamepad) {
  50850. if (!this.oneGamepadConnected) {
  50851. this.oneGamepadConnected = true;
  50852. if (Gamepads.gamepadDOMInfo) {
  50853. document.body.removeChild(Gamepads.gamepadDOMInfo);
  50854. Gamepads.gamepadDOMInfo = null;
  50855. }
  50856. }
  50857. var newGamepad;
  50858. var xboxOne = (gamepad.id.search("Xbox One") !== -1);
  50859. if (xboxOne || gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  50860. newGamepad = new Xbox360Pad(gamepad.id, gamepad.index, gamepad, xboxOne);
  50861. }
  50862. else if (gamepad.pose) {
  50863. newGamepad = BABYLON.PoseEnabledControllerHelper.InitiateController(gamepad);
  50864. }
  50865. else {
  50866. newGamepad = new GenericPad(gamepad.id, gamepad.index, gamepad);
  50867. }
  50868. this.babylonGamepads.push(newGamepad);
  50869. return newGamepad;
  50870. };
  50871. Gamepads.prototype._onGamepadDisconnected = function (evt) {
  50872. // Remove the gamepad from the list of gamepads to monitor.
  50873. for (var i in this.babylonGamepads) {
  50874. if (this.babylonGamepads[i].index == evt.gamepad.index) {
  50875. this.babylonGamepads.splice(+i, 1);
  50876. break;
  50877. }
  50878. }
  50879. // If no gamepads are left, stop the polling loop.
  50880. if (this.babylonGamepads.length == 0) {
  50881. this._stopMonitoringGamepads();
  50882. }
  50883. };
  50884. Gamepads.prototype._startMonitoringGamepads = function () {
  50885. if (!this.isMonitoring) {
  50886. this.isMonitoring = true;
  50887. this._checkGamepadsStatus();
  50888. }
  50889. };
  50890. Gamepads.prototype._stopMonitoringGamepads = function () {
  50891. this.isMonitoring = false;
  50892. };
  50893. Gamepads.prototype._checkGamepadsStatus = function () {
  50894. var _this = this;
  50895. // updating gamepad objects
  50896. this._updateGamepadObjects();
  50897. for (var i in this.babylonGamepads) {
  50898. this.babylonGamepads[i].update();
  50899. }
  50900. if (this.isMonitoring) {
  50901. if (window.requestAnimationFrame) {
  50902. window.requestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  50903. }
  50904. else if (window.mozRequestAnimationFrame) {
  50905. window.mozRequestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  50906. }
  50907. else if (window.webkitRequestAnimationFrame) {
  50908. window.webkitRequestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  50909. }
  50910. }
  50911. };
  50912. // This function is called only on Chrome, which does not yet support
  50913. // connection/disconnection events, but requires you to monitor
  50914. // an array for changes.
  50915. Gamepads.prototype._updateGamepadObjects = function () {
  50916. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  50917. for (var i = 0; i < gamepads.length; i++) {
  50918. if (gamepads[i]) {
  50919. if (!(gamepads[i].index in this.babylonGamepads)) {
  50920. var newGamepad = this._addNewGamepad(gamepads[i]);
  50921. if (this._callbackGamepadConnected) {
  50922. this._callbackGamepadConnected(newGamepad);
  50923. }
  50924. }
  50925. else {
  50926. this.babylonGamepads[i].browserGamepad = gamepads[i];
  50927. }
  50928. }
  50929. }
  50930. };
  50931. return Gamepads;
  50932. }());
  50933. BABYLON.Gamepads = Gamepads;
  50934. var StickValues = (function () {
  50935. function StickValues(x, y) {
  50936. this.x = x;
  50937. this.y = y;
  50938. }
  50939. return StickValues;
  50940. }());
  50941. BABYLON.StickValues = StickValues;
  50942. var Gamepad = (function () {
  50943. function Gamepad(id, index, browserGamepad, leftStickX, leftStickY, rightStickX, rightStickY) {
  50944. if (leftStickX === void 0) { leftStickX = 0; }
  50945. if (leftStickY === void 0) { leftStickY = 1; }
  50946. if (rightStickX === void 0) { rightStickX = 2; }
  50947. if (rightStickY === void 0) { rightStickY = 3; }
  50948. this.id = id;
  50949. this.index = index;
  50950. this.browserGamepad = browserGamepad;
  50951. this.type = Gamepad.GAMEPAD;
  50952. this._leftStickAxisX = leftStickX;
  50953. this._leftStickAxisY = leftStickY;
  50954. this._rightStickAxisX = rightStickX;
  50955. this._rightStickAxisY = rightStickY;
  50956. if (this.browserGamepad.axes.length >= 2) {
  50957. this._leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  50958. }
  50959. if (this.browserGamepad.axes.length >= 4) {
  50960. this._rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  50961. }
  50962. }
  50963. Gamepad.prototype.onleftstickchanged = function (callback) {
  50964. this._onleftstickchanged = callback;
  50965. };
  50966. Gamepad.prototype.onrightstickchanged = function (callback) {
  50967. this._onrightstickchanged = callback;
  50968. };
  50969. Object.defineProperty(Gamepad.prototype, "leftStick", {
  50970. get: function () {
  50971. return this._leftStick;
  50972. },
  50973. set: function (newValues) {
  50974. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  50975. this._onleftstickchanged(newValues);
  50976. }
  50977. this._leftStick = newValues;
  50978. },
  50979. enumerable: true,
  50980. configurable: true
  50981. });
  50982. Object.defineProperty(Gamepad.prototype, "rightStick", {
  50983. get: function () {
  50984. return this._rightStick;
  50985. },
  50986. set: function (newValues) {
  50987. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  50988. this._onrightstickchanged(newValues);
  50989. }
  50990. this._rightStick = newValues;
  50991. },
  50992. enumerable: true,
  50993. configurable: true
  50994. });
  50995. Gamepad.prototype.update = function () {
  50996. if (this._leftStick) {
  50997. this.leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  50998. }
  50999. if (this._rightStick) {
  51000. this.rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  51001. }
  51002. };
  51003. return Gamepad;
  51004. }());
  51005. Gamepad.GAMEPAD = 0;
  51006. Gamepad.GENERIC = 1;
  51007. Gamepad.XBOX = 2;
  51008. Gamepad.POSE_ENABLED = 3;
  51009. BABYLON.Gamepad = Gamepad;
  51010. var GenericPad = (function (_super) {
  51011. __extends(GenericPad, _super);
  51012. function GenericPad(id, index, gamepad) {
  51013. var _this = _super.call(this, id, index, gamepad) || this;
  51014. _this.id = id;
  51015. _this.index = index;
  51016. _this.gamepad = gamepad;
  51017. _this.type = Gamepad.GENERIC;
  51018. _this._buttons = new Array(gamepad.buttons.length);
  51019. return _this;
  51020. }
  51021. GenericPad.prototype.onbuttondown = function (callback) {
  51022. this._onbuttondown = callback;
  51023. };
  51024. GenericPad.prototype.onbuttonup = function (callback) {
  51025. this._onbuttonup = callback;
  51026. };
  51027. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  51028. if (newValue !== currentValue) {
  51029. if (this._onbuttondown && newValue === 1) {
  51030. this._onbuttondown(buttonIndex);
  51031. }
  51032. if (this._onbuttonup && newValue === 0) {
  51033. this._onbuttonup(buttonIndex);
  51034. }
  51035. }
  51036. return newValue;
  51037. };
  51038. GenericPad.prototype.update = function () {
  51039. _super.prototype.update.call(this);
  51040. for (var index = 0; index < this._buttons.length; index++) {
  51041. this._buttons[index] = this._setButtonValue(this.gamepad.buttons[index].value, this._buttons[index], index);
  51042. }
  51043. };
  51044. return GenericPad;
  51045. }(Gamepad));
  51046. BABYLON.GenericPad = GenericPad;
  51047. var Xbox360Button;
  51048. (function (Xbox360Button) {
  51049. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  51050. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  51051. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  51052. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  51053. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  51054. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  51055. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  51056. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  51057. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  51058. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  51059. })(Xbox360Button = BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  51060. var Xbox360Dpad;
  51061. (function (Xbox360Dpad) {
  51062. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  51063. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  51064. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  51065. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  51066. })(Xbox360Dpad = BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  51067. var Xbox360Pad = (function (_super) {
  51068. __extends(Xbox360Pad, _super);
  51069. function Xbox360Pad(id, index, gamepad, xboxOne) {
  51070. if (xboxOne === void 0) { xboxOne = false; }
  51071. var _this = _super.call(this, id, index, gamepad, 0, 1, (xboxOne ? 3 : 2), (xboxOne ? 4 : 3)) || this;
  51072. _this._leftTrigger = 0;
  51073. _this._rightTrigger = 0;
  51074. _this._buttonA = 0;
  51075. _this._buttonB = 0;
  51076. _this._buttonX = 0;
  51077. _this._buttonY = 0;
  51078. _this._buttonBack = 0;
  51079. _this._buttonStart = 0;
  51080. _this._buttonLB = 0;
  51081. _this._buttonRB = 0;
  51082. _this._buttonLeftStick = 0;
  51083. _this._buttonRightStick = 0;
  51084. _this._dPadUp = 0;
  51085. _this._dPadDown = 0;
  51086. _this._dPadLeft = 0;
  51087. _this._dPadRight = 0;
  51088. _this._isXboxOnePad = false;
  51089. _this.type = Gamepad.XBOX;
  51090. _this._isXboxOnePad = xboxOne;
  51091. return _this;
  51092. }
  51093. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  51094. this._onlefttriggerchanged = callback;
  51095. };
  51096. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  51097. this._onrighttriggerchanged = callback;
  51098. };
  51099. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  51100. get: function () {
  51101. return this._leftTrigger;
  51102. },
  51103. set: function (newValue) {
  51104. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  51105. this._onlefttriggerchanged(newValue);
  51106. }
  51107. this._leftTrigger = newValue;
  51108. },
  51109. enumerable: true,
  51110. configurable: true
  51111. });
  51112. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  51113. get: function () {
  51114. return this._rightTrigger;
  51115. },
  51116. set: function (newValue) {
  51117. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  51118. this._onrighttriggerchanged(newValue);
  51119. }
  51120. this._rightTrigger = newValue;
  51121. },
  51122. enumerable: true,
  51123. configurable: true
  51124. });
  51125. Xbox360Pad.prototype.onbuttondown = function (callback) {
  51126. this._onbuttondown = callback;
  51127. };
  51128. Xbox360Pad.prototype.onbuttonup = function (callback) {
  51129. this._onbuttonup = callback;
  51130. };
  51131. Xbox360Pad.prototype.ondpaddown = function (callback) {
  51132. this._ondpaddown = callback;
  51133. };
  51134. Xbox360Pad.prototype.ondpadup = function (callback) {
  51135. this._ondpadup = callback;
  51136. };
  51137. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  51138. if (newValue !== currentValue) {
  51139. if (this._onbuttondown && newValue === 1) {
  51140. this._onbuttondown(buttonType);
  51141. }
  51142. if (this._onbuttonup && newValue === 0) {
  51143. this._onbuttonup(buttonType);
  51144. }
  51145. }
  51146. return newValue;
  51147. };
  51148. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  51149. if (newValue !== currentValue) {
  51150. if (this._ondpaddown && newValue === 1) {
  51151. this._ondpaddown(buttonType);
  51152. }
  51153. if (this._ondpadup && newValue === 0) {
  51154. this._ondpadup(buttonType);
  51155. }
  51156. }
  51157. return newValue;
  51158. };
  51159. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  51160. get: function () {
  51161. return this._buttonA;
  51162. },
  51163. set: function (value) {
  51164. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  51165. },
  51166. enumerable: true,
  51167. configurable: true
  51168. });
  51169. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  51170. get: function () {
  51171. return this._buttonB;
  51172. },
  51173. set: function (value) {
  51174. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  51175. },
  51176. enumerable: true,
  51177. configurable: true
  51178. });
  51179. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  51180. get: function () {
  51181. return this._buttonX;
  51182. },
  51183. set: function (value) {
  51184. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  51185. },
  51186. enumerable: true,
  51187. configurable: true
  51188. });
  51189. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  51190. get: function () {
  51191. return this._buttonY;
  51192. },
  51193. set: function (value) {
  51194. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  51195. },
  51196. enumerable: true,
  51197. configurable: true
  51198. });
  51199. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  51200. get: function () {
  51201. return this._buttonStart;
  51202. },
  51203. set: function (value) {
  51204. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  51205. },
  51206. enumerable: true,
  51207. configurable: true
  51208. });
  51209. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  51210. get: function () {
  51211. return this._buttonBack;
  51212. },
  51213. set: function (value) {
  51214. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  51215. },
  51216. enumerable: true,
  51217. configurable: true
  51218. });
  51219. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  51220. get: function () {
  51221. return this._buttonLB;
  51222. },
  51223. set: function (value) {
  51224. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  51225. },
  51226. enumerable: true,
  51227. configurable: true
  51228. });
  51229. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  51230. get: function () {
  51231. return this._buttonRB;
  51232. },
  51233. set: function (value) {
  51234. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  51235. },
  51236. enumerable: true,
  51237. configurable: true
  51238. });
  51239. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  51240. get: function () {
  51241. return this._buttonLeftStick;
  51242. },
  51243. set: function (value) {
  51244. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  51245. },
  51246. enumerable: true,
  51247. configurable: true
  51248. });
  51249. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  51250. get: function () {
  51251. return this._buttonRightStick;
  51252. },
  51253. set: function (value) {
  51254. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  51255. },
  51256. enumerable: true,
  51257. configurable: true
  51258. });
  51259. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  51260. get: function () {
  51261. return this._dPadUp;
  51262. },
  51263. set: function (value) {
  51264. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  51265. },
  51266. enumerable: true,
  51267. configurable: true
  51268. });
  51269. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  51270. get: function () {
  51271. return this._dPadDown;
  51272. },
  51273. set: function (value) {
  51274. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  51275. },
  51276. enumerable: true,
  51277. configurable: true
  51278. });
  51279. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  51280. get: function () {
  51281. return this._dPadLeft;
  51282. },
  51283. set: function (value) {
  51284. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  51285. },
  51286. enumerable: true,
  51287. configurable: true
  51288. });
  51289. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  51290. get: function () {
  51291. return this._dPadRight;
  51292. },
  51293. set: function (value) {
  51294. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  51295. },
  51296. enumerable: true,
  51297. configurable: true
  51298. });
  51299. Xbox360Pad.prototype.update = function () {
  51300. _super.prototype.update.call(this);
  51301. if (this._isXboxOnePad) {
  51302. this.buttonA = this.browserGamepad.buttons[0].value;
  51303. this.buttonB = this.browserGamepad.buttons[1].value;
  51304. this.buttonX = this.browserGamepad.buttons[2].value;
  51305. this.buttonY = this.browserGamepad.buttons[3].value;
  51306. this.buttonLB = this.browserGamepad.buttons[4].value;
  51307. this.buttonRB = this.browserGamepad.buttons[5].value;
  51308. this.leftTrigger = this.browserGamepad.axes[2];
  51309. this.rightTrigger = this.browserGamepad.axes[5];
  51310. this.buttonBack = this.browserGamepad.buttons[9].value;
  51311. this.buttonStart = this.browserGamepad.buttons[8].value;
  51312. this.buttonLeftStick = this.browserGamepad.buttons[6].value;
  51313. this.buttonRightStick = this.browserGamepad.buttons[7].value;
  51314. this.dPadUp = this.browserGamepad.buttons[11].value;
  51315. this.dPadDown = this.browserGamepad.buttons[12].value;
  51316. this.dPadLeft = this.browserGamepad.buttons[13].value;
  51317. this.dPadRight = this.browserGamepad.buttons[14].value;
  51318. }
  51319. else {
  51320. this.buttonA = this.browserGamepad.buttons[0].value;
  51321. this.buttonB = this.browserGamepad.buttons[1].value;
  51322. this.buttonX = this.browserGamepad.buttons[2].value;
  51323. this.buttonY = this.browserGamepad.buttons[3].value;
  51324. this.buttonLB = this.browserGamepad.buttons[4].value;
  51325. this.buttonRB = this.browserGamepad.buttons[5].value;
  51326. this.leftTrigger = this.browserGamepad.buttons[6].value;
  51327. this.rightTrigger = this.browserGamepad.buttons[7].value;
  51328. this.buttonBack = this.browserGamepad.buttons[8].value;
  51329. this.buttonStart = this.browserGamepad.buttons[9].value;
  51330. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  51331. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  51332. this.dPadUp = this.browserGamepad.buttons[12].value;
  51333. this.dPadDown = this.browserGamepad.buttons[13].value;
  51334. this.dPadLeft = this.browserGamepad.buttons[14].value;
  51335. this.dPadRight = this.browserGamepad.buttons[15].value;
  51336. }
  51337. };
  51338. return Xbox360Pad;
  51339. }(Gamepad));
  51340. BABYLON.Xbox360Pad = Xbox360Pad;
  51341. })(BABYLON || (BABYLON = {}));
  51342. //# sourceMappingURL=babylon.gamepads.js.map
  51343. var BABYLON;
  51344. (function (BABYLON) {
  51345. var PoseEnabledControllerType;
  51346. (function (PoseEnabledControllerType) {
  51347. PoseEnabledControllerType[PoseEnabledControllerType["VIVE"] = 0] = "VIVE";
  51348. PoseEnabledControllerType[PoseEnabledControllerType["OCULUS"] = 1] = "OCULUS";
  51349. PoseEnabledControllerType[PoseEnabledControllerType["GENERIC"] = 2] = "GENERIC";
  51350. })(PoseEnabledControllerType = BABYLON.PoseEnabledControllerType || (BABYLON.PoseEnabledControllerType = {}));
  51351. var PoseEnabledControllerHelper = (function () {
  51352. function PoseEnabledControllerHelper() {
  51353. }
  51354. PoseEnabledControllerHelper.InitiateController = function (vrGamepad) {
  51355. // for now, only Oculus and Vive are supported
  51356. if (vrGamepad.id.indexOf('Oculus Touch') !== -1) {
  51357. return new OculusTouchController(vrGamepad);
  51358. }
  51359. else {
  51360. return new ViveController(vrGamepad);
  51361. }
  51362. };
  51363. return PoseEnabledControllerHelper;
  51364. }());
  51365. BABYLON.PoseEnabledControllerHelper = PoseEnabledControllerHelper;
  51366. var PoseEnabledController = (function (_super) {
  51367. __extends(PoseEnabledController, _super);
  51368. function PoseEnabledController(vrGamepad) {
  51369. var _this = _super.call(this, vrGamepad.id, vrGamepad.index, vrGamepad) || this;
  51370. _this.vrGamepad = vrGamepad;
  51371. _this.deviceScaleFactor = 1;
  51372. _this._leftHandSystemQuaternion = new BABYLON.Quaternion();
  51373. _this.type = BABYLON.Gamepad.POSE_ENABLED;
  51374. _this.controllerType = PoseEnabledControllerType.GENERIC;
  51375. _this.position = BABYLON.Vector3.Zero();
  51376. _this.rotationQuaternion = new BABYLON.Quaternion();
  51377. _this.devicePosition = BABYLON.Vector3.Zero();
  51378. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  51379. _this._calculatedPosition = BABYLON.Vector3.Zero();
  51380. _this._calculatedRotation = new BABYLON.Quaternion();
  51381. BABYLON.Quaternion.RotationYawPitchRollToRef(Math.PI, 0, 0, _this._leftHandSystemQuaternion);
  51382. return _this;
  51383. }
  51384. PoseEnabledController.prototype.update = function () {
  51385. _super.prototype.update.call(this);
  51386. // update this device's offset position from the attached camera, if provided
  51387. //if (this._poseControlledCamera && this._poseControlledCamera.deviceScaleFactor) {
  51388. //this.position.copyFrom(this._poseControlledCamera.position);
  51389. //this.rotationQuaternion.copyFrom(this._poseControlledCamera.rotationQuaternion);
  51390. //this.deviceScaleFactor = this._poseControlledCamera.deviceScaleFactor;
  51391. //}
  51392. var pose = this.vrGamepad.pose;
  51393. this.updateFromDevice(pose);
  51394. if (this._mesh) {
  51395. this._mesh.position.copyFrom(this._calculatedPosition);
  51396. this._mesh.rotationQuaternion.copyFrom(this._calculatedRotation);
  51397. }
  51398. };
  51399. PoseEnabledController.prototype.updateFromDevice = function (poseData) {
  51400. if (poseData) {
  51401. this.rawPose = poseData;
  51402. if (poseData.position) {
  51403. this.devicePosition.copyFromFloats(poseData.position[0], poseData.position[1], -poseData.position[2]);
  51404. if (this._mesh && this._mesh.getScene().useRightHandedSystem) {
  51405. this.devicePosition.z *= -1;
  51406. }
  51407. this.devicePosition.scaleToRef(this.deviceScaleFactor, this._calculatedPosition);
  51408. this._calculatedPosition.addInPlace(this.position);
  51409. }
  51410. if (poseData.orientation) {
  51411. this.deviceRotationQuaternion.copyFromFloats(this.rawPose.orientation[0], this.rawPose.orientation[1], -this.rawPose.orientation[2], -this.rawPose.orientation[3]);
  51412. if (this._mesh) {
  51413. if (this._mesh.getScene().useRightHandedSystem) {
  51414. this.deviceRotationQuaternion.z *= -1;
  51415. this.deviceRotationQuaternion.w *= -1;
  51416. }
  51417. else {
  51418. this.deviceRotationQuaternion.multiplyToRef(this._leftHandSystemQuaternion, this.deviceRotationQuaternion);
  51419. }
  51420. }
  51421. // if the camera is set, rotate to the camera's rotation
  51422. this.deviceRotationQuaternion.multiplyToRef(this.rotationQuaternion, this._calculatedRotation);
  51423. }
  51424. }
  51425. };
  51426. PoseEnabledController.prototype.attachToMesh = function (mesh) {
  51427. if (this._mesh) {
  51428. this._mesh.parent = undefined;
  51429. }
  51430. this._mesh = mesh;
  51431. if (this._poseControlledCamera) {
  51432. this._mesh.parent = this._poseControlledCamera;
  51433. }
  51434. if (!this._mesh.rotationQuaternion) {
  51435. this._mesh.rotationQuaternion = new BABYLON.Quaternion();
  51436. }
  51437. };
  51438. PoseEnabledController.prototype.attachToPoseControlledCamera = function (camera) {
  51439. this._poseControlledCamera = camera;
  51440. if (this._mesh) {
  51441. this._mesh.parent = this._poseControlledCamera;
  51442. }
  51443. };
  51444. PoseEnabledController.prototype.detachMesh = function () {
  51445. this._mesh = undefined;
  51446. };
  51447. return PoseEnabledController;
  51448. }(BABYLON.Gamepad));
  51449. BABYLON.PoseEnabledController = PoseEnabledController;
  51450. var WebVRController = (function (_super) {
  51451. __extends(WebVRController, _super);
  51452. function WebVRController(vrGamepad) {
  51453. var _this = _super.call(this, vrGamepad) || this;
  51454. //public onTriggerStateChangedObservable = new Observable<{ state: ExtendedGamepadButton, changes: GamepadButtonChanges }>();
  51455. _this.onTriggerStateChangedObservable = new BABYLON.Observable();
  51456. _this.onMainButtonStateChangedObservable = new BABYLON.Observable();
  51457. _this.onSecondaryButtonStateChangedObservable = new BABYLON.Observable();
  51458. _this.onPadStateChangedObservable = new BABYLON.Observable();
  51459. _this.onPadValuesChangedObservable = new BABYLON.Observable();
  51460. _this.pad = { x: 0, y: 0 };
  51461. // avoid GC, store state in a tmp object
  51462. _this._changes = {
  51463. pressChanged: false,
  51464. touchChanged: false,
  51465. valueChanged: false,
  51466. changed: false
  51467. };
  51468. _this._buttons = new Array(vrGamepad.buttons.length);
  51469. _this.hand = vrGamepad.hand;
  51470. return _this;
  51471. }
  51472. WebVRController.prototype.onButtonStateChange = function (callback) {
  51473. this._onButtonStateChange = callback;
  51474. };
  51475. WebVRController.prototype.update = function () {
  51476. _super.prototype.update.call(this);
  51477. for (var index = 0; index < this._buttons.length; index++) {
  51478. this._setButtonValue(this.vrGamepad.buttons[index], this._buttons[index], index);
  51479. }
  51480. ;
  51481. if (this.leftStick.x !== this.pad.x || this.leftStick.y !== this.pad.y) {
  51482. this.pad.x = this.leftStick.x;
  51483. this.pad.y = this.leftStick.y;
  51484. this.onPadValuesChangedObservable.notifyObservers(this.pad);
  51485. }
  51486. };
  51487. WebVRController.prototype._setButtonValue = function (newState, currentState, buttonIndex) {
  51488. if (!currentState) {
  51489. this._buttons[buttonIndex] = {
  51490. pressed: newState.pressed,
  51491. touched: newState.touched,
  51492. value: newState.value
  51493. };
  51494. return;
  51495. }
  51496. this._checkChanges(newState, currentState);
  51497. if (this._changes.changed) {
  51498. this._onButtonStateChange && this._onButtonStateChange(this.index, buttonIndex, newState);
  51499. this.handleButtonChange(buttonIndex, newState, this._changes);
  51500. }
  51501. this._buttons[buttonIndex].pressed = newState.pressed;
  51502. this._buttons[buttonIndex].touched = newState.touched;
  51503. // oculus triggers are never 0, thou not touched.
  51504. this._buttons[buttonIndex].value = newState.value < 0.00000001 ? 0 : newState.value;
  51505. };
  51506. WebVRController.prototype._checkChanges = function (newState, currentState) {
  51507. this._changes.pressChanged = newState.pressed !== currentState.pressed;
  51508. this._changes.touchChanged = newState.touched !== currentState.touched;
  51509. this._changes.valueChanged = newState.value !== currentState.value;
  51510. this._changes.changed = this._changes.pressChanged || this._changes.touchChanged || this._changes.valueChanged;
  51511. return this._changes;
  51512. };
  51513. return WebVRController;
  51514. }(PoseEnabledController));
  51515. BABYLON.WebVRController = WebVRController;
  51516. var OculusTouchController = (function (_super) {
  51517. __extends(OculusTouchController, _super);
  51518. function OculusTouchController(vrGamepad) {
  51519. var _this = _super.call(this, vrGamepad) || this;
  51520. _this.onSecondaryTriggerStateChangedObservable = new BABYLON.Observable();
  51521. _this.onThumbRestChangedObservable = new BABYLON.Observable();
  51522. _this.controllerType = PoseEnabledControllerType.OCULUS;
  51523. return _this;
  51524. }
  51525. OculusTouchController.prototype.initControllerMesh = function (scene) {
  51526. var _this = this;
  51527. var meshName = this.hand === 'right' ? 'RightTouch.babylon' : 'LeftTouch.babylon';
  51528. BABYLON.SceneLoader.ImportMesh("", "http://yoda.blob.core.windows.net/models/", meshName, scene, function (newMeshes) {
  51529. /*
  51530. Parent Mesh name: oculus_touch_left
  51531. - body
  51532. - trigger
  51533. - thumbstick
  51534. - grip
  51535. - button_y
  51536. - button_x
  51537. - button_enter
  51538. */
  51539. _this._defaultModel = newMeshes[1];
  51540. _this._hlButtonA = new BABYLON.HighlightLayer("hlButtonA", scene);
  51541. _this._hlButtonB = new BABYLON.HighlightLayer("hlButtonB", scene);
  51542. _this.attachToMesh(_this._defaultModel);
  51543. });
  51544. };
  51545. Object.defineProperty(OculusTouchController.prototype, "onAButtonStateChangedObservable", {
  51546. // helper getters for left and right hand.
  51547. get: function () {
  51548. if (this.hand === 'right') {
  51549. return this.onMainButtonStateChangedObservable;
  51550. }
  51551. else {
  51552. throw new Error('No A button on left hand');
  51553. }
  51554. },
  51555. enumerable: true,
  51556. configurable: true
  51557. });
  51558. Object.defineProperty(OculusTouchController.prototype, "onBButtonStateChangedObservable", {
  51559. get: function () {
  51560. if (this.hand === 'right') {
  51561. return this.onSecondaryButtonStateChangedObservable;
  51562. }
  51563. else {
  51564. throw new Error('No B button on left hand');
  51565. }
  51566. },
  51567. enumerable: true,
  51568. configurable: true
  51569. });
  51570. Object.defineProperty(OculusTouchController.prototype, "onXButtonStateChangedObservable", {
  51571. get: function () {
  51572. if (this.hand === 'left') {
  51573. return this.onMainButtonStateChangedObservable;
  51574. }
  51575. else {
  51576. throw new Error('No X button on right hand');
  51577. }
  51578. },
  51579. enumerable: true,
  51580. configurable: true
  51581. });
  51582. Object.defineProperty(OculusTouchController.prototype, "onYButtonStateChangedObservable", {
  51583. get: function () {
  51584. if (this.hand === 'left') {
  51585. return this.onSecondaryButtonStateChangedObservable;
  51586. }
  51587. else {
  51588. throw new Error('No Y button on right hand');
  51589. }
  51590. },
  51591. enumerable: true,
  51592. configurable: true
  51593. });
  51594. /*
  51595. 0) thumb stick (touch, press, value = pressed (0,1)). value is in this.leftStick
  51596. 1) index trigger (touch (?), press (only when value > 0.1), value 0 to 1)
  51597. 2) secondary trigger (same)
  51598. 3) A (right) X (left), touch, pressed = value
  51599. 4) B / Y
  51600. 5) thumb rest
  51601. */
  51602. OculusTouchController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  51603. var notifyObject = state; //{ state: state, changes: changes };
  51604. switch (buttonIdx) {
  51605. case 0:
  51606. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  51607. return;
  51608. case 1:
  51609. if (this._defaultModel) {
  51610. (this._defaultModel.getChildren()[3]).rotation.x = -notifyObject.value * 0.20;
  51611. (this._defaultModel.getChildren()[3]).position.y = -notifyObject.value * 0.005;
  51612. (this._defaultModel.getChildren()[3]).position.z = -notifyObject.value * 0.005;
  51613. }
  51614. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  51615. return;
  51616. case 2:
  51617. this.onSecondaryTriggerStateChangedObservable.notifyObservers(notifyObject);
  51618. return;
  51619. case 3:
  51620. if (this._defaultModel) {
  51621. if (notifyObject.pressed) {
  51622. (this._defaultModel.getChildren()[1]).position.y = -0.001;
  51623. }
  51624. else {
  51625. (this._defaultModel.getChildren()[1]).position.y = 0;
  51626. }
  51627. if (notifyObject.touched) {
  51628. this._hlButtonA.addMesh(this._defaultModel.getChildren()[1], BABYLON.Color3.White());
  51629. }
  51630. else {
  51631. this._hlButtonA.removeMesh(this._defaultModel.getChildren()[1]);
  51632. }
  51633. }
  51634. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  51635. return;
  51636. case 4:
  51637. if (this._defaultModel) {
  51638. if (notifyObject.pressed) {
  51639. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  51640. }
  51641. else {
  51642. (this._defaultModel.getChildren()[2]).position.y = 0;
  51643. }
  51644. if (notifyObject.touched) {
  51645. this._hlButtonB.addMesh(this._defaultModel.getChildren()[2], BABYLON.Color3.White());
  51646. }
  51647. else {
  51648. this._hlButtonB.removeMesh(this._defaultModel.getChildren()[2]);
  51649. }
  51650. }
  51651. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  51652. return;
  51653. case 5:
  51654. this.onThumbRestChangedObservable.notifyObservers(notifyObject);
  51655. return;
  51656. }
  51657. };
  51658. return OculusTouchController;
  51659. }(WebVRController));
  51660. BABYLON.OculusTouchController = OculusTouchController;
  51661. var ViveController = (function (_super) {
  51662. __extends(ViveController, _super);
  51663. function ViveController(vrGamepad) {
  51664. var _this = _super.call(this, vrGamepad) || this;
  51665. _this.controllerType = PoseEnabledControllerType.VIVE;
  51666. return _this;
  51667. }
  51668. ViveController.prototype.initControllerMesh = function (scene) {
  51669. var _this = this;
  51670. BABYLON.SceneLoader.ImportMesh("", "http://yoda.blob.core.windows.net/models/", "ViveWand.babylon", scene, function (newMeshes) {
  51671. /*
  51672. Parent Mesh name: ViveWand
  51673. - body
  51674. - r_gripper
  51675. - l_gripper
  51676. - menu_button
  51677. - system_button
  51678. - trackpad
  51679. - trigger
  51680. - LED
  51681. */
  51682. _this._defaultModel = newMeshes[1];
  51683. _this._hlButtonMenu = new BABYLON.HighlightLayer("hlButtonMenu", scene);
  51684. _this.attachToMesh(_this._defaultModel);
  51685. });
  51686. };
  51687. Object.defineProperty(ViveController.prototype, "onLeftButtonStateChangedObservable", {
  51688. get: function () {
  51689. return this.onMainButtonStateChangedObservable;
  51690. },
  51691. enumerable: true,
  51692. configurable: true
  51693. });
  51694. Object.defineProperty(ViveController.prototype, "onRightButtonStateChangedObservable", {
  51695. get: function () {
  51696. return this.onMainButtonStateChangedObservable;
  51697. },
  51698. enumerable: true,
  51699. configurable: true
  51700. });
  51701. Object.defineProperty(ViveController.prototype, "onMenuButtonStateChangedObservable", {
  51702. get: function () {
  51703. return this.onSecondaryButtonStateChangedObservable;
  51704. },
  51705. enumerable: true,
  51706. configurable: true
  51707. });
  51708. /**
  51709. * Vive mapping:
  51710. * 0: touchpad
  51711. * 1: trigger
  51712. * 2: left AND right buttons
  51713. * 3: menu button
  51714. */
  51715. ViveController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  51716. var notifyObject = state; //{ state: state, changes: changes };
  51717. switch (buttonIdx) {
  51718. case 0:
  51719. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  51720. return;
  51721. case 1:
  51722. if (this._defaultModel) {
  51723. (this._defaultModel.getChildren()[6]).rotation.x = -notifyObject.value * 0.15;
  51724. }
  51725. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  51726. return;
  51727. case 2:
  51728. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  51729. return;
  51730. case 3:
  51731. if (this._defaultModel) {
  51732. if (notifyObject.pressed) {
  51733. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  51734. this._hlButtonMenu.addMesh(this._defaultModel.getChildren()[2], BABYLON.Color3.White());
  51735. }
  51736. else {
  51737. (this._defaultModel.getChildren()[2]).position.y = 0;
  51738. this._hlButtonMenu.removeMesh(this._defaultModel.getChildren()[2]);
  51739. }
  51740. }
  51741. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  51742. return;
  51743. }
  51744. };
  51745. return ViveController;
  51746. }(WebVRController));
  51747. BABYLON.ViveController = ViveController;
  51748. })(BABYLON || (BABYLON = {}));
  51749. //# sourceMappingURL=babylon.extendedGamepad.js.map
  51750. /// <reference path="babylon.universalCamera.ts" />
  51751. var BABYLON;
  51752. (function (BABYLON) {
  51753. // We're mainly based on the logic defined into the FreeCamera code
  51754. var GamepadCamera = (function (_super) {
  51755. __extends(GamepadCamera, _super);
  51756. //-- end properties for backward compatibility for inputs
  51757. function GamepadCamera(name, position, scene) {
  51758. return _super.call(this, name, position, scene) || this;
  51759. }
  51760. Object.defineProperty(GamepadCamera.prototype, "gamepadAngularSensibility", {
  51761. //-- Begin properties for backward compatibility for inputs
  51762. get: function () {
  51763. var gamepad = this.inputs.attached["gamepad"];
  51764. if (gamepad)
  51765. return gamepad.gamepadAngularSensibility;
  51766. },
  51767. set: function (value) {
  51768. var gamepad = this.inputs.attached["gamepad"];
  51769. if (gamepad)
  51770. gamepad.gamepadAngularSensibility = value;
  51771. },
  51772. enumerable: true,
  51773. configurable: true
  51774. });
  51775. Object.defineProperty(GamepadCamera.prototype, "gamepadMoveSensibility", {
  51776. get: function () {
  51777. var gamepad = this.inputs.attached["gamepad"];
  51778. if (gamepad)
  51779. return gamepad.gamepadMoveSensibility;
  51780. },
  51781. set: function (value) {
  51782. var gamepad = this.inputs.attached["gamepad"];
  51783. if (gamepad)
  51784. gamepad.gamepadMoveSensibility = value;
  51785. },
  51786. enumerable: true,
  51787. configurable: true
  51788. });
  51789. GamepadCamera.prototype.getClassName = function () {
  51790. return "GamepadCamera";
  51791. };
  51792. return GamepadCamera;
  51793. }(BABYLON.UniversalCamera));
  51794. BABYLON.GamepadCamera = GamepadCamera;
  51795. })(BABYLON || (BABYLON = {}));
  51796. //# sourceMappingURL=babylon.gamepadCamera.js.map
  51797. var BABYLON;
  51798. (function (BABYLON) {
  51799. var Analyser = (function () {
  51800. function Analyser(scene) {
  51801. this.SMOOTHING = 0.75;
  51802. this.FFT_SIZE = 512;
  51803. this.BARGRAPHAMPLITUDE = 256;
  51804. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  51805. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  51806. this._scene = scene;
  51807. this._audioEngine = BABYLON.Engine.audioEngine;
  51808. if (this._audioEngine.canUseWebAudio) {
  51809. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  51810. this._webAudioAnalyser.minDecibels = -140;
  51811. this._webAudioAnalyser.maxDecibels = 0;
  51812. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  51813. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  51814. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  51815. }
  51816. }
  51817. Analyser.prototype.getFrequencyBinCount = function () {
  51818. if (this._audioEngine.canUseWebAudio) {
  51819. return this._webAudioAnalyser.frequencyBinCount;
  51820. }
  51821. else {
  51822. return 0;
  51823. }
  51824. };
  51825. Analyser.prototype.getByteFrequencyData = function () {
  51826. if (this._audioEngine.canUseWebAudio) {
  51827. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  51828. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  51829. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  51830. }
  51831. return this._byteFreqs;
  51832. };
  51833. Analyser.prototype.getByteTimeDomainData = function () {
  51834. if (this._audioEngine.canUseWebAudio) {
  51835. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  51836. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  51837. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  51838. }
  51839. return this._byteTime;
  51840. };
  51841. Analyser.prototype.getFloatFrequencyData = function () {
  51842. if (this._audioEngine.canUseWebAudio) {
  51843. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  51844. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  51845. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  51846. }
  51847. return this._floatFreqs;
  51848. };
  51849. Analyser.prototype.drawDebugCanvas = function () {
  51850. var _this = this;
  51851. if (this._audioEngine.canUseWebAudio) {
  51852. if (!this._debugCanvas) {
  51853. this._debugCanvas = document.createElement("canvas");
  51854. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  51855. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  51856. this._debugCanvas.style.position = "absolute";
  51857. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  51858. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  51859. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  51860. document.body.appendChild(this._debugCanvas);
  51861. this._registerFunc = function () {
  51862. _this.drawDebugCanvas();
  51863. };
  51864. this._scene.registerBeforeRender(this._registerFunc);
  51865. }
  51866. if (this._registerFunc) {
  51867. var workingArray = this.getByteFrequencyData();
  51868. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  51869. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  51870. // Draw the frequency domain chart.
  51871. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  51872. var value = workingArray[i];
  51873. var percent = value / this.BARGRAPHAMPLITUDE;
  51874. var height = this.DEBUGCANVASSIZE.height * percent;
  51875. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  51876. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  51877. var hue = i / this.getFrequencyBinCount() * 360;
  51878. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  51879. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  51880. }
  51881. }
  51882. }
  51883. };
  51884. Analyser.prototype.stopDebugCanvas = function () {
  51885. if (this._debugCanvas) {
  51886. this._scene.unregisterBeforeRender(this._registerFunc);
  51887. this._registerFunc = null;
  51888. document.body.removeChild(this._debugCanvas);
  51889. this._debugCanvas = null;
  51890. this._debugCanvasContext = null;
  51891. }
  51892. };
  51893. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  51894. if (this._audioEngine.canUseWebAudio) {
  51895. inputAudioNode.connect(this._webAudioAnalyser);
  51896. this._webAudioAnalyser.connect(outputAudioNode);
  51897. }
  51898. };
  51899. Analyser.prototype.dispose = function () {
  51900. if (this._audioEngine.canUseWebAudio) {
  51901. this._webAudioAnalyser.disconnect();
  51902. }
  51903. };
  51904. return Analyser;
  51905. }());
  51906. BABYLON.Analyser = Analyser;
  51907. })(BABYLON || (BABYLON = {}));
  51908. //# sourceMappingURL=babylon.analyser.js.map
  51909. var BABYLON;
  51910. (function (BABYLON) {
  51911. var DepthRenderer = (function () {
  51912. function DepthRenderer(scene, type) {
  51913. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  51914. var _this = this;
  51915. this._viewMatrix = BABYLON.Matrix.Zero();
  51916. this._projectionMatrix = BABYLON.Matrix.Zero();
  51917. this._transformMatrix = BABYLON.Matrix.Zero();
  51918. this._worldViewProjection = BABYLON.Matrix.Zero();
  51919. this._scene = scene;
  51920. var engine = scene.getEngine();
  51921. // Render target
  51922. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  51923. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  51924. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  51925. this._depthMap.refreshRate = 1;
  51926. this._depthMap.renderParticles = false;
  51927. this._depthMap.renderList = null;
  51928. // set default depth value to 1.0 (far away)
  51929. this._depthMap.onClearObservable.add(function (engine) {
  51930. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  51931. });
  51932. // Custom render function
  51933. var renderSubMesh = function (subMesh) {
  51934. var mesh = subMesh.getRenderingMesh();
  51935. var scene = _this._scene;
  51936. var engine = scene.getEngine();
  51937. // Culling
  51938. engine.setState(subMesh.getMaterial().backFaceCulling);
  51939. // Managing instances
  51940. var batch = mesh._getInstancesRenderList(subMesh._id);
  51941. if (batch.mustReturn) {
  51942. return;
  51943. }
  51944. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  51945. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  51946. engine.enableEffect(_this._effect);
  51947. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  51948. var material = subMesh.getMaterial();
  51949. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  51950. _this._effect.setFloat("far", scene.activeCamera.maxZ);
  51951. // Alpha test
  51952. if (material && material.needAlphaTesting()) {
  51953. var alphaTexture = material.getAlphaTestTexture();
  51954. _this._effect.setTexture("diffuseSampler", alphaTexture);
  51955. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  51956. }
  51957. // Bones
  51958. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  51959. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  51960. }
  51961. // Draw
  51962. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  51963. }
  51964. };
  51965. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes) {
  51966. var index;
  51967. for (index = 0; index < opaqueSubMeshes.length; index++) {
  51968. renderSubMesh(opaqueSubMeshes.data[index]);
  51969. }
  51970. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  51971. renderSubMesh(alphaTestSubMeshes.data[index]);
  51972. }
  51973. };
  51974. }
  51975. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  51976. var material = subMesh.getMaterial();
  51977. if (material.disableDepthWrite) {
  51978. return false;
  51979. }
  51980. var defines = [];
  51981. var attribs = [BABYLON.VertexBuffer.PositionKind];
  51982. var mesh = subMesh.getMesh();
  51983. var scene = mesh.getScene();
  51984. // Alpha test
  51985. if (material && material.needAlphaTesting()) {
  51986. defines.push("#define ALPHATEST");
  51987. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  51988. attribs.push(BABYLON.VertexBuffer.UVKind);
  51989. defines.push("#define UV1");
  51990. }
  51991. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  51992. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  51993. defines.push("#define UV2");
  51994. }
  51995. }
  51996. // Bones
  51997. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  51998. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  51999. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  52000. if (mesh.numBoneInfluencers > 4) {
  52001. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  52002. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  52003. }
  52004. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  52005. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  52006. }
  52007. else {
  52008. defines.push("#define NUM_BONE_INFLUENCERS 0");
  52009. }
  52010. // Instances
  52011. if (useInstances) {
  52012. defines.push("#define INSTANCES");
  52013. attribs.push("world0");
  52014. attribs.push("world1");
  52015. attribs.push("world2");
  52016. attribs.push("world3");
  52017. }
  52018. // Get correct effect
  52019. var join = defines.join("\n");
  52020. if (this._cachedDefines !== join) {
  52021. this._cachedDefines = join;
  52022. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "far"], ["diffuseSampler"], join);
  52023. }
  52024. return this._effect.isReady();
  52025. };
  52026. DepthRenderer.prototype.getDepthMap = function () {
  52027. return this._depthMap;
  52028. };
  52029. // Methods
  52030. DepthRenderer.prototype.dispose = function () {
  52031. this._depthMap.dispose();
  52032. };
  52033. return DepthRenderer;
  52034. }());
  52035. BABYLON.DepthRenderer = DepthRenderer;
  52036. })(BABYLON || (BABYLON = {}));
  52037. //# sourceMappingURL=babylon.depthRenderer.js.map
  52038. var BABYLON;
  52039. (function (BABYLON) {
  52040. var SSAORenderingPipeline = (function (_super) {
  52041. __extends(SSAORenderingPipeline, _super);
  52042. /**
  52043. * @constructor
  52044. * @param {string} name - The rendering pipeline name
  52045. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  52046. * @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 }
  52047. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  52048. */
  52049. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  52050. var _this = _super.call(this, scene.getEngine(), name) || this;
  52051. // Members
  52052. /**
  52053. * The PassPostProcess id in the pipeline that contains the original scene color
  52054. * @type {string}
  52055. */
  52056. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  52057. /**
  52058. * The SSAO PostProcess id in the pipeline
  52059. * @type {string}
  52060. */
  52061. _this.SSAORenderEffect = "SSAORenderEffect";
  52062. /**
  52063. * The horizontal blur PostProcess id in the pipeline
  52064. * @type {string}
  52065. */
  52066. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  52067. /**
  52068. * The vertical blur PostProcess id in the pipeline
  52069. * @type {string}
  52070. */
  52071. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  52072. /**
  52073. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  52074. * @type {string}
  52075. */
  52076. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  52077. /**
  52078. * The output strength of the SSAO post-process. Default value is 1.0.
  52079. * @type {number}
  52080. */
  52081. _this.totalStrength = 1.0;
  52082. /**
  52083. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  52084. * @type {number}
  52085. */
  52086. _this.radius = 0.0001;
  52087. /**
  52088. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  52089. * Must not be equal to fallOff and superior to fallOff.
  52090. * Default value is 0.975
  52091. * @type {number}
  52092. */
  52093. _this.area = 0.0075;
  52094. /**
  52095. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  52096. * Must not be equal to area and inferior to area.
  52097. * Default value is 0.0
  52098. * @type {number}
  52099. */
  52100. _this.fallOff = 0.000001;
  52101. /**
  52102. * The base color of the SSAO post-process
  52103. * The final result is "base + ssao" between [0, 1]
  52104. * @type {number}
  52105. */
  52106. _this.base = 0.5;
  52107. _this._firstUpdate = true;
  52108. _this._scene = scene;
  52109. // Set up assets
  52110. _this._createRandomTexture();
  52111. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  52112. var ssaoRatio = ratio.ssaoRatio || ratio;
  52113. var combineRatio = ratio.combineRatio || ratio;
  52114. _this._ratio = {
  52115. ssaoRatio: ssaoRatio,
  52116. combineRatio: combineRatio
  52117. };
  52118. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  52119. _this._createSSAOPostProcess(ssaoRatio);
  52120. _this._createBlurPostProcess(ssaoRatio);
  52121. _this._createSSAOCombinePostProcess(combineRatio);
  52122. // Set up pipeline
  52123. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  52124. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  52125. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  52126. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  52127. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  52128. // Finish
  52129. scene.postProcessRenderPipelineManager.addPipeline(_this);
  52130. if (cameras)
  52131. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  52132. return _this;
  52133. }
  52134. // Public Methods
  52135. /**
  52136. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  52137. */
  52138. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  52139. if (disableDepthRender === void 0) { disableDepthRender = false; }
  52140. for (var i = 0; i < this._scene.cameras.length; i++) {
  52141. var camera = this._scene.cameras[i];
  52142. this._originalColorPostProcess.dispose(camera);
  52143. this._ssaoPostProcess.dispose(camera);
  52144. this._blurHPostProcess.dispose(camera);
  52145. this._blurVPostProcess.dispose(camera);
  52146. this._ssaoCombinePostProcess.dispose(camera);
  52147. }
  52148. this._randomTexture.dispose();
  52149. if (disableDepthRender)
  52150. this._scene.disableDepthRenderer();
  52151. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  52152. _super.prototype.dispose.call(this);
  52153. };
  52154. // Private Methods
  52155. SSAORenderingPipeline.prototype._createBlurPostProcess = function (ratio) {
  52156. var _this = this;
  52157. /*
  52158. var samplerOffsets = [
  52159. -8.0, -6.0, -4.0, -2.0,
  52160. 0.0,
  52161. 2.0, 4.0, 6.0, 8.0
  52162. ];
  52163. */
  52164. var samples = 16;
  52165. var samplerOffsets = [];
  52166. for (var i = -8; i < 8; i++) {
  52167. samplerOffsets.push(i * 2);
  52168. }
  52169. 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");
  52170. this._blurHPostProcess.onApply = function (effect) {
  52171. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width);
  52172. effect.setTexture("depthSampler", _this._depthTexture);
  52173. if (_this._firstUpdate) {
  52174. effect.setArray("samplerOffsets", samplerOffsets);
  52175. }
  52176. };
  52177. 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");
  52178. this._blurVPostProcess.onApply = function (effect) {
  52179. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height);
  52180. effect.setTexture("depthSampler", _this._depthTexture);
  52181. if (_this._firstUpdate) {
  52182. effect.setArray("samplerOffsets", samplerOffsets);
  52183. _this._firstUpdate = false;
  52184. }
  52185. };
  52186. };
  52187. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  52188. var _this = this;
  52189. var numSamples = 16;
  52190. var sampleSphere = [
  52191. 0.5381, 0.1856, -0.4319,
  52192. 0.1379, 0.2486, 0.4430,
  52193. 0.3371, 0.5679, -0.0057,
  52194. -0.6999, -0.0451, -0.0019,
  52195. 0.0689, -0.1598, -0.8547,
  52196. 0.0560, 0.0069, -0.1843,
  52197. -0.0146, 0.1402, 0.0762,
  52198. 0.0100, -0.1924, -0.0344,
  52199. -0.3577, -0.5301, -0.4358,
  52200. -0.3169, 0.1063, 0.0158,
  52201. 0.0103, -0.5869, 0.0046,
  52202. -0.0897, -0.4940, 0.3287,
  52203. 0.7119, -0.0154, -0.0918,
  52204. -0.0533, 0.0596, -0.5411,
  52205. 0.0352, -0.0631, 0.5460,
  52206. -0.4776, 0.2847, -0.0271
  52207. ];
  52208. var samplesFactor = 1.0 / numSamples;
  52209. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  52210. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  52211. "area", "fallOff", "base", "range", "viewport"
  52212. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  52213. var viewport = new BABYLON.Vector2(0, 0);
  52214. this._ssaoPostProcess.onApply = function (effect) {
  52215. if (_this._firstUpdate) {
  52216. effect.setArray3("sampleSphere", sampleSphere);
  52217. effect.setFloat("samplesFactor", samplesFactor);
  52218. effect.setFloat("randTextureTiles", 4.0);
  52219. }
  52220. effect.setFloat("totalStrength", _this.totalStrength);
  52221. effect.setFloat("radius", _this.radius);
  52222. effect.setFloat("area", _this.area);
  52223. effect.setFloat("fallOff", _this.fallOff);
  52224. effect.setFloat("base", _this.base);
  52225. effect.setTexture("textureSampler", _this._depthTexture);
  52226. effect.setTexture("randomSampler", _this._randomTexture);
  52227. };
  52228. };
  52229. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  52230. var _this = this;
  52231. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  52232. this._ssaoCombinePostProcess.onApply = function (effect) {
  52233. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  52234. };
  52235. };
  52236. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  52237. var size = 512;
  52238. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  52239. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  52240. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  52241. var context = this._randomTexture.getContext();
  52242. var rand = function (min, max) {
  52243. return Math.random() * (max - min) + min;
  52244. };
  52245. var randVector = BABYLON.Vector3.Zero();
  52246. for (var x = 0; x < size; x++) {
  52247. for (var y = 0; y < size; y++) {
  52248. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  52249. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  52250. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  52251. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  52252. context.fillRect(x, y, 1, 1);
  52253. }
  52254. }
  52255. this._randomTexture.update(false);
  52256. };
  52257. return SSAORenderingPipeline;
  52258. }(BABYLON.PostProcessRenderPipeline));
  52259. __decorate([
  52260. BABYLON.serialize()
  52261. ], SSAORenderingPipeline.prototype, "totalStrength", void 0);
  52262. __decorate([
  52263. BABYLON.serialize()
  52264. ], SSAORenderingPipeline.prototype, "radius", void 0);
  52265. __decorate([
  52266. BABYLON.serialize()
  52267. ], SSAORenderingPipeline.prototype, "area", void 0);
  52268. __decorate([
  52269. BABYLON.serialize()
  52270. ], SSAORenderingPipeline.prototype, "fallOff", void 0);
  52271. __decorate([
  52272. BABYLON.serialize()
  52273. ], SSAORenderingPipeline.prototype, "base", void 0);
  52274. __decorate([
  52275. BABYLON.serialize()
  52276. ], SSAORenderingPipeline.prototype, "_ratio", void 0);
  52277. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  52278. })(BABYLON || (BABYLON = {}));
  52279. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  52280. var BABYLON;
  52281. (function (BABYLON) {
  52282. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  52283. var VolumetricLightScatteringPostProcess = (function (_super) {
  52284. __extends(VolumetricLightScatteringPostProcess, _super);
  52285. /**
  52286. * @constructor
  52287. * @param {string} name - The post-process name
  52288. * @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)
  52289. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  52290. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  52291. * @param {number} samples - The post-process quality, default 100
  52292. * @param {number} samplingMode - The post-process filtering mode
  52293. * @param {BABYLON.Engine} engine - The babylon engine
  52294. * @param {boolean} reusable - If the post-process is reusable
  52295. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  52296. */
  52297. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  52298. if (samples === void 0) { samples = 100; }
  52299. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  52300. 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;
  52301. _this._screenCoordinates = BABYLON.Vector2.Zero();
  52302. /**
  52303. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  52304. * @type {Vector3}
  52305. */
  52306. _this.customMeshPosition = BABYLON.Vector3.Zero();
  52307. /**
  52308. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  52309. * @type {boolean}
  52310. */
  52311. _this.useCustomMeshPosition = false;
  52312. /**
  52313. * If the post-process should inverse the light scattering direction
  52314. * @type {boolean}
  52315. */
  52316. _this.invert = true;
  52317. /**
  52318. * Array containing the excluded meshes not rendered in the internal pass
  52319. */
  52320. _this.excludedMeshes = new Array();
  52321. /**
  52322. * Controls the overall intensity of the post-process
  52323. * @type {number}
  52324. */
  52325. _this.exposure = 0.3;
  52326. /**
  52327. * Dissipates each sample's contribution in range [0, 1]
  52328. * @type {number}
  52329. */
  52330. _this.decay = 0.96815;
  52331. /**
  52332. * Controls the overall intensity of each sample
  52333. * @type {number}
  52334. */
  52335. _this.weight = 0.58767;
  52336. /**
  52337. * Controls the density of each sample
  52338. * @type {number}
  52339. */
  52340. _this.density = 0.926;
  52341. scene = (camera === null) ? scene : camera.getScene(); // parameter "scene" can be null.
  52342. var engine = scene.getEngine();
  52343. _this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  52344. // Configure mesh
  52345. _this.mesh = (mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene);
  52346. // Configure
  52347. _this._createPass(scene, ratio.passRatio || ratio);
  52348. _this.onActivate = function (camera) {
  52349. if (!_this.isSupported) {
  52350. _this.dispose(camera);
  52351. }
  52352. _this.onActivate = null;
  52353. };
  52354. _this.onApplyObservable.add(function (effect) {
  52355. _this._updateMeshScreenCoordinates(scene);
  52356. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  52357. effect.setFloat("exposure", _this.exposure);
  52358. effect.setFloat("decay", _this.decay);
  52359. effect.setFloat("weight", _this.weight);
  52360. effect.setFloat("density", _this.density);
  52361. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  52362. });
  52363. return _this;
  52364. }
  52365. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  52366. get: function () {
  52367. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  52368. return false;
  52369. },
  52370. set: function (useDiffuseColor) {
  52371. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  52372. },
  52373. enumerable: true,
  52374. configurable: true
  52375. });
  52376. VolumetricLightScatteringPostProcess.prototype.isReady = function (subMesh, useInstances) {
  52377. var mesh = subMesh.getMesh();
  52378. // Render this.mesh as default
  52379. if (mesh === this.mesh) {
  52380. return mesh.material.isReady(mesh);
  52381. }
  52382. var defines = [];
  52383. var attribs = [BABYLON.VertexBuffer.PositionKind];
  52384. var material = subMesh.getMaterial();
  52385. var needUV = false;
  52386. // Alpha test
  52387. if (material) {
  52388. if (material.needAlphaTesting()) {
  52389. defines.push("#define ALPHATEST");
  52390. }
  52391. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  52392. attribs.push(BABYLON.VertexBuffer.UVKind);
  52393. defines.push("#define UV1");
  52394. }
  52395. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  52396. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  52397. defines.push("#define UV2");
  52398. }
  52399. }
  52400. // Bones
  52401. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  52402. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  52403. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  52404. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  52405. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  52406. }
  52407. else {
  52408. defines.push("#define NUM_BONE_INFLUENCERS 0");
  52409. }
  52410. // Instances
  52411. if (useInstances) {
  52412. defines.push("#define INSTANCES");
  52413. attribs.push("world0");
  52414. attribs.push("world1");
  52415. attribs.push("world2");
  52416. attribs.push("world3");
  52417. }
  52418. // Get correct effect
  52419. var join = defines.join("\n");
  52420. if (this._cachedDefines !== join) {
  52421. this._cachedDefines = join;
  52422. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  52423. }
  52424. return this._volumetricLightScatteringPass.isReady();
  52425. };
  52426. /**
  52427. * Sets the new light position for light scattering effect
  52428. * @param {BABYLON.Vector3} The new custom light position
  52429. */
  52430. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  52431. this.customMeshPosition = position;
  52432. };
  52433. /**
  52434. * Returns the light position for light scattering effect
  52435. * @return {BABYLON.Vector3} The custom light position
  52436. */
  52437. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  52438. return this.customMeshPosition;
  52439. };
  52440. /**
  52441. * Disposes the internal assets and detaches the post-process from the camera
  52442. */
  52443. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  52444. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  52445. if (rttIndex !== -1) {
  52446. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  52447. }
  52448. this._volumetricLightScatteringRTT.dispose();
  52449. _super.prototype.dispose.call(this, camera);
  52450. };
  52451. /**
  52452. * Returns the render target texture used by the post-process
  52453. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  52454. */
  52455. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  52456. return this._volumetricLightScatteringRTT;
  52457. };
  52458. // Private methods
  52459. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  52460. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  52461. return true;
  52462. }
  52463. return false;
  52464. };
  52465. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  52466. var _this = this;
  52467. var engine = scene.getEngine();
  52468. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  52469. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  52470. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  52471. this._volumetricLightScatteringRTT.renderList = null;
  52472. this._volumetricLightScatteringRTT.renderParticles = false;
  52473. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  52474. // Custom render function for submeshes
  52475. var renderSubMesh = function (subMesh) {
  52476. var mesh = subMesh.getRenderingMesh();
  52477. if (_this._meshExcluded(mesh)) {
  52478. return;
  52479. }
  52480. var scene = mesh.getScene();
  52481. var engine = scene.getEngine();
  52482. // Culling
  52483. engine.setState(subMesh.getMaterial().backFaceCulling);
  52484. // Managing instances
  52485. var batch = mesh._getInstancesRenderList(subMesh._id);
  52486. if (batch.mustReturn) {
  52487. return;
  52488. }
  52489. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  52490. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  52491. var effect = _this._volumetricLightScatteringPass;
  52492. if (mesh === _this.mesh) {
  52493. effect = subMesh.getMaterial().getEffect();
  52494. }
  52495. engine.enableEffect(effect);
  52496. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  52497. if (mesh === _this.mesh) {
  52498. subMesh.getMaterial().bind(mesh.getWorldMatrix(), mesh);
  52499. }
  52500. else {
  52501. var material = subMesh.getMaterial();
  52502. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  52503. // Alpha test
  52504. if (material && material.needAlphaTesting()) {
  52505. var alphaTexture = material.getAlphaTestTexture();
  52506. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  52507. if (alphaTexture) {
  52508. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  52509. }
  52510. }
  52511. // Bones
  52512. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  52513. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  52514. }
  52515. }
  52516. // Draw
  52517. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  52518. }
  52519. };
  52520. // Render target texture callbacks
  52521. var savedSceneClearColor;
  52522. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  52523. this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function () {
  52524. savedSceneClearColor = scene.clearColor;
  52525. scene.clearColor = sceneClearColor;
  52526. });
  52527. this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function () {
  52528. scene.clearColor = savedSceneClearColor;
  52529. });
  52530. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  52531. var engine = scene.getEngine();
  52532. var index;
  52533. for (index = 0; index < opaqueSubMeshes.length; index++) {
  52534. renderSubMesh(opaqueSubMeshes.data[index]);
  52535. }
  52536. engine.setAlphaTesting(true);
  52537. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  52538. renderSubMesh(alphaTestSubMeshes.data[index]);
  52539. }
  52540. engine.setAlphaTesting(false);
  52541. if (transparentSubMeshes.length) {
  52542. // Sort sub meshes
  52543. for (index = 0; index < transparentSubMeshes.length; index++) {
  52544. var submesh = transparentSubMeshes.data[index];
  52545. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  52546. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  52547. }
  52548. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  52549. sortedArray.sort(function (a, b) {
  52550. // Alpha index first
  52551. if (a._alphaIndex > b._alphaIndex) {
  52552. return 1;
  52553. }
  52554. if (a._alphaIndex < b._alphaIndex) {
  52555. return -1;
  52556. }
  52557. // Then distance to camera
  52558. if (a._distanceToCamera < b._distanceToCamera) {
  52559. return 1;
  52560. }
  52561. if (a._distanceToCamera > b._distanceToCamera) {
  52562. return -1;
  52563. }
  52564. return 0;
  52565. });
  52566. // Render sub meshes
  52567. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  52568. for (index = 0; index < sortedArray.length; index++) {
  52569. renderSubMesh(sortedArray[index]);
  52570. }
  52571. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  52572. }
  52573. };
  52574. };
  52575. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  52576. var transform = scene.getTransformMatrix();
  52577. var meshPosition;
  52578. if (this.useCustomMeshPosition) {
  52579. meshPosition = this.customMeshPosition;
  52580. }
  52581. else if (this.attachedNode) {
  52582. meshPosition = this.attachedNode.position;
  52583. }
  52584. else {
  52585. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  52586. }
  52587. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  52588. this._screenCoordinates.x = pos.x / this._viewPort.width;
  52589. this._screenCoordinates.y = pos.y / this._viewPort.height;
  52590. if (this.invert)
  52591. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  52592. };
  52593. // Static methods
  52594. /**
  52595. * Creates a default mesh for the Volumeric Light Scattering post-process
  52596. * @param {string} The mesh name
  52597. * @param {BABYLON.Scene} The scene where to create the mesh
  52598. * @return {BABYLON.Mesh} the default mesh
  52599. */
  52600. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  52601. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  52602. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  52603. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  52604. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  52605. mesh.material = material;
  52606. return mesh;
  52607. };
  52608. return VolumetricLightScatteringPostProcess;
  52609. }(BABYLON.PostProcess));
  52610. __decorate([
  52611. BABYLON.serializeAsVector3()
  52612. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  52613. __decorate([
  52614. BABYLON.serialize()
  52615. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  52616. __decorate([
  52617. BABYLON.serialize()
  52618. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  52619. __decorate([
  52620. BABYLON.serializeAsMeshReference()
  52621. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  52622. __decorate([
  52623. BABYLON.serialize()
  52624. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  52625. __decorate([
  52626. BABYLON.serialize()
  52627. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  52628. __decorate([
  52629. BABYLON.serialize()
  52630. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  52631. __decorate([
  52632. BABYLON.serialize()
  52633. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  52634. __decorate([
  52635. BABYLON.serialize()
  52636. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  52637. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  52638. })(BABYLON || (BABYLON = {}));
  52639. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  52640. // BABYLON.JS Chromatic Aberration GLSL Shader
  52641. // Author: Olivier Guyot
  52642. // Separates very slightly R, G and B colors on the edges of the screen
  52643. // Inspired by Francois Tarlier & Martins Upitis
  52644. var BABYLON;
  52645. (function (BABYLON) {
  52646. var LensRenderingPipeline = (function (_super) {
  52647. __extends(LensRenderingPipeline, _super);
  52648. /**
  52649. * @constructor
  52650. *
  52651. * Effect parameters are as follow:
  52652. * {
  52653. * chromatic_aberration: number; // from 0 to x (1 for realism)
  52654. * edge_blur: number; // from 0 to x (1 for realism)
  52655. * distortion: number; // from 0 to x (1 for realism)
  52656. * grain_amount: number; // from 0 to 1
  52657. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  52658. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  52659. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  52660. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  52661. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  52662. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  52663. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  52664. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  52665. * }
  52666. * Note: if an effect parameter is unset, effect is disabled
  52667. *
  52668. * @param {string} name - The rendering pipeline name
  52669. * @param {object} parameters - An object containing all parameters (see above)
  52670. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  52671. * @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)
  52672. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  52673. */
  52674. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  52675. if (ratio === void 0) { ratio = 1.0; }
  52676. var _this = _super.call(this, scene.getEngine(), name) || this;
  52677. // Lens effects can be of the following:
  52678. // - chromatic aberration (slight shift of RGB colors)
  52679. // - blur on the edge of the lens
  52680. // - lens distortion
  52681. // - depth-of-field blur & highlights enhancing
  52682. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  52683. // - grain effect (noise or custom texture)
  52684. // Two additional texture samplers are needed:
  52685. // - depth map (for depth-of-field)
  52686. // - grain texture
  52687. /**
  52688. * The chromatic aberration PostProcess id in the pipeline
  52689. * @type {string}
  52690. */
  52691. _this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  52692. /**
  52693. * The highlights enhancing PostProcess id in the pipeline
  52694. * @type {string}
  52695. */
  52696. _this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  52697. /**
  52698. * The depth-of-field PostProcess id in the pipeline
  52699. * @type {string}
  52700. */
  52701. _this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  52702. _this._scene = scene;
  52703. // Fetch texture samplers
  52704. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  52705. if (parameters.grain_texture) {
  52706. _this._grainTexture = parameters.grain_texture;
  52707. }
  52708. else {
  52709. _this._createGrainTexture();
  52710. }
  52711. // save parameters
  52712. _this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  52713. _this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  52714. _this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  52715. _this._distortion = parameters.distortion ? parameters.distortion : 0;
  52716. _this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  52717. _this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  52718. _this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  52719. _this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  52720. _this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  52721. _this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  52722. _this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  52723. // Create effects
  52724. _this._createChromaticAberrationPostProcess(ratio);
  52725. _this._createHighlightsPostProcess(ratio);
  52726. _this._createDepthOfFieldPostProcess(ratio / 4);
  52727. // Set up pipeline
  52728. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  52729. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  52730. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  52731. if (_this._highlightsGain === -1) {
  52732. _this._disableEffect(_this.HighlightsEnhancingEffect, null);
  52733. }
  52734. // Finish
  52735. scene.postProcessRenderPipelineManager.addPipeline(_this);
  52736. if (cameras) {
  52737. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  52738. }
  52739. return _this;
  52740. }
  52741. // public methods (self explanatory)
  52742. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  52743. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  52744. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  52745. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  52746. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  52747. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  52748. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  52749. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  52750. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  52751. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  52752. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  52753. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  52754. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  52755. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  52756. };
  52757. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  52758. this._highlightsPostProcess.updateEffect();
  52759. };
  52760. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  52761. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  52762. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  52763. this._highlightsGain = amount;
  52764. };
  52765. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  52766. if (this._highlightsGain === -1) {
  52767. this._highlightsGain = 1.0;
  52768. }
  52769. this._highlightsThreshold = amount;
  52770. };
  52771. LensRenderingPipeline.prototype.disableHighlights = function () {
  52772. this._highlightsGain = -1;
  52773. };
  52774. /**
  52775. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  52776. */
  52777. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  52778. if (disableDepthRender === void 0) { disableDepthRender = false; }
  52779. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  52780. this._chromaticAberrationPostProcess = undefined;
  52781. this._highlightsPostProcess = undefined;
  52782. this._depthOfFieldPostProcess = undefined;
  52783. this._grainTexture.dispose();
  52784. if (disableDepthRender)
  52785. this._scene.disableDepthRenderer();
  52786. };
  52787. // colors shifting and distortion
  52788. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  52789. var _this = this;
  52790. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height"], // uniforms
  52791. [], // samplers
  52792. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  52793. this._chromaticAberrationPostProcess.onApply = function (effect) {
  52794. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  52795. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  52796. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  52797. };
  52798. };
  52799. // highlights enhancing
  52800. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  52801. var _this = this;
  52802. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  52803. [], // samplers
  52804. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  52805. this._highlightsPostProcess.onApply = function (effect) {
  52806. effect.setFloat('gain', _this._highlightsGain);
  52807. effect.setFloat('threshold', _this._highlightsThreshold);
  52808. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  52809. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  52810. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  52811. };
  52812. };
  52813. // colors shifting and distortion
  52814. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  52815. var _this = this;
  52816. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  52817. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  52818. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  52819. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  52820. this._depthOfFieldPostProcess.onApply = function (effect) {
  52821. effect.setTexture("depthSampler", _this._depthTexture);
  52822. effect.setTexture("grainSampler", _this._grainTexture);
  52823. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  52824. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  52825. effect.setFloat('grain_amount', _this._grainAmount);
  52826. effect.setBool('blur_noise', _this._blurNoise);
  52827. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  52828. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  52829. effect.setFloat('distortion', _this._distortion);
  52830. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  52831. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  52832. effect.setFloat('aperture', _this._dofAperture);
  52833. effect.setFloat('darken', _this._dofDarken);
  52834. effect.setFloat('edge_blur', _this._edgeBlur);
  52835. effect.setBool('highlights', (_this._highlightsGain !== -1));
  52836. effect.setFloat('near', _this._scene.activeCamera.minZ);
  52837. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  52838. };
  52839. };
  52840. // creates a black and white random noise texture, 512x512
  52841. LensRenderingPipeline.prototype._createGrainTexture = function () {
  52842. var size = 512;
  52843. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  52844. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  52845. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  52846. var context = this._grainTexture.getContext();
  52847. var rand = function (min, max) {
  52848. return Math.random() * (max - min) + min;
  52849. };
  52850. var value;
  52851. for (var x = 0; x < size; x++) {
  52852. for (var y = 0; y < size; y++) {
  52853. value = Math.floor(rand(0.42, 0.58) * 255);
  52854. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  52855. context.fillRect(x, y, 1, 1);
  52856. }
  52857. }
  52858. this._grainTexture.update(false);
  52859. };
  52860. return LensRenderingPipeline;
  52861. }(BABYLON.PostProcessRenderPipeline));
  52862. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  52863. })(BABYLON || (BABYLON = {}));
  52864. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map
  52865. //
  52866. // This post-process allows the modification of rendered colors by using
  52867. // a 'look-up table' (LUT). This effect is also called Color Grading.
  52868. //
  52869. // The object needs to be provided an url to a texture containing the color
  52870. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  52871. // Use an image editing software to tweak the LUT to match your needs.
  52872. //
  52873. // For an example of a color LUT, see here:
  52874. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  52875. // For explanations on color grading, see here:
  52876. // http://udn.epicgames.com/Three/ColorGrading.html
  52877. //
  52878. var BABYLON;
  52879. (function (BABYLON) {
  52880. var ColorCorrectionPostProcess = (function (_super) {
  52881. __extends(ColorCorrectionPostProcess, _super);
  52882. function ColorCorrectionPostProcess(name, colorTableUrl, options, camera, samplingMode, engine, reusable) {
  52883. var _this = _super.call(this, name, 'colorCorrection', null, ['colorTable'], options, camera, samplingMode, engine, reusable) || this;
  52884. _this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  52885. _this._colorTableTexture.anisotropicFilteringLevel = 1;
  52886. _this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  52887. _this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  52888. _this.onApply = function (effect) {
  52889. effect.setTexture("colorTable", _this._colorTableTexture);
  52890. };
  52891. return _this;
  52892. }
  52893. return ColorCorrectionPostProcess;
  52894. }(BABYLON.PostProcess));
  52895. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  52896. })(BABYLON || (BABYLON = {}));
  52897. //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.map
  52898. /// <reference path="babylon.freeCamera.ts" />
  52899. /// <reference path="babylon.arcRotateCamera.ts" />
  52900. /// <reference path="babylon.gamepadCamera.ts" />
  52901. /// <reference path="babylon.universalCamera.ts" />
  52902. var BABYLON;
  52903. (function (BABYLON) {
  52904. var AnaglyphFreeCamera = (function (_super) {
  52905. __extends(AnaglyphFreeCamera, _super);
  52906. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  52907. var _this = _super.call(this, name, position, scene) || this;
  52908. _this.interaxialDistance = interaxialDistance;
  52909. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  52910. return _this;
  52911. }
  52912. AnaglyphFreeCamera.prototype.getClassName = function () {
  52913. return "AnaglyphFreeCamera";
  52914. };
  52915. return AnaglyphFreeCamera;
  52916. }(BABYLON.FreeCamera));
  52917. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  52918. var AnaglyphArcRotateCamera = (function (_super) {
  52919. __extends(AnaglyphArcRotateCamera, _super);
  52920. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  52921. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  52922. _this.interaxialDistance = interaxialDistance;
  52923. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  52924. return _this;
  52925. }
  52926. AnaglyphArcRotateCamera.prototype.getClassName = function () {
  52927. return "AnaglyphArcRotateCamera";
  52928. };
  52929. return AnaglyphArcRotateCamera;
  52930. }(BABYLON.ArcRotateCamera));
  52931. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  52932. var AnaglyphGamepadCamera = (function (_super) {
  52933. __extends(AnaglyphGamepadCamera, _super);
  52934. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  52935. var _this = _super.call(this, name, position, scene) || this;
  52936. _this.interaxialDistance = interaxialDistance;
  52937. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  52938. return _this;
  52939. }
  52940. AnaglyphGamepadCamera.prototype.getClassName = function () {
  52941. return "AnaglyphGamepadCamera";
  52942. };
  52943. return AnaglyphGamepadCamera;
  52944. }(BABYLON.GamepadCamera));
  52945. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  52946. var AnaglyphUniversalCamera = (function (_super) {
  52947. __extends(AnaglyphUniversalCamera, _super);
  52948. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  52949. var _this = _super.call(this, name, position, scene) || this;
  52950. _this.interaxialDistance = interaxialDistance;
  52951. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  52952. return _this;
  52953. }
  52954. AnaglyphUniversalCamera.prototype.getClassName = function () {
  52955. return "AnaglyphUniversalCamera";
  52956. };
  52957. return AnaglyphUniversalCamera;
  52958. }(BABYLON.UniversalCamera));
  52959. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  52960. var StereoscopicFreeCamera = (function (_super) {
  52961. __extends(StereoscopicFreeCamera, _super);
  52962. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  52963. var _this = _super.call(this, name, position, scene) || this;
  52964. _this.interaxialDistance = interaxialDistance;
  52965. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  52966. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  52967. return _this;
  52968. }
  52969. StereoscopicFreeCamera.prototype.getClassName = function () {
  52970. return "StereoscopicFreeCamera";
  52971. };
  52972. return StereoscopicFreeCamera;
  52973. }(BABYLON.FreeCamera));
  52974. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  52975. var StereoscopicArcRotateCamera = (function (_super) {
  52976. __extends(StereoscopicArcRotateCamera, _super);
  52977. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  52978. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  52979. _this.interaxialDistance = interaxialDistance;
  52980. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  52981. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  52982. return _this;
  52983. }
  52984. StereoscopicArcRotateCamera.prototype.getClassName = function () {
  52985. return "StereoscopicArcRotateCamera";
  52986. };
  52987. return StereoscopicArcRotateCamera;
  52988. }(BABYLON.ArcRotateCamera));
  52989. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  52990. var StereoscopicGamepadCamera = (function (_super) {
  52991. __extends(StereoscopicGamepadCamera, _super);
  52992. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  52993. var _this = _super.call(this, name, position, scene) || this;
  52994. _this.interaxialDistance = interaxialDistance;
  52995. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  52996. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  52997. return _this;
  52998. }
  52999. StereoscopicGamepadCamera.prototype.getClassName = function () {
  53000. return "StereoscopicGamepadCamera";
  53001. };
  53002. return StereoscopicGamepadCamera;
  53003. }(BABYLON.GamepadCamera));
  53004. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  53005. var StereoscopicUniversalCamera = (function (_super) {
  53006. __extends(StereoscopicUniversalCamera, _super);
  53007. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  53008. var _this = _super.call(this, name, position, scene) || this;
  53009. _this.interaxialDistance = interaxialDistance;
  53010. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  53011. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  53012. return _this;
  53013. }
  53014. StereoscopicUniversalCamera.prototype.getClassName = function () {
  53015. return "StereoscopicUniversalCamera";
  53016. };
  53017. return StereoscopicUniversalCamera;
  53018. }(BABYLON.UniversalCamera));
  53019. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  53020. })(BABYLON || (BABYLON = {}));
  53021. //# sourceMappingURL=babylon.stereoscopicCameras.js.map
  53022. /// <reference path="RenderPipeline\babylon.postProcessRenderPipeline.ts" />
  53023. var BABYLON;
  53024. (function (BABYLON) {
  53025. var HDRRenderingPipeline = (function (_super) {
  53026. __extends(HDRRenderingPipeline, _super);
  53027. /**
  53028. * @constructor
  53029. * @param {string} name - The rendering pipeline name
  53030. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  53031. * @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)
  53032. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  53033. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  53034. */
  53035. function HDRRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  53036. if (originalPostProcess === void 0) { originalPostProcess = null; }
  53037. var _this = _super.call(this, scene.getEngine(), name) || this;
  53038. /**
  53039. * Public members
  53040. */
  53041. // Gaussian Blur
  53042. /**
  53043. * Gaussian blur coefficient
  53044. * @type {number}
  53045. */
  53046. _this.gaussCoeff = 0.3;
  53047. /**
  53048. * Gaussian blur mean
  53049. * @type {number}
  53050. */
  53051. _this.gaussMean = 1.0;
  53052. /**
  53053. * Gaussian blur standard deviation
  53054. * @type {number}
  53055. */
  53056. _this.gaussStandDev = 0.8;
  53057. /**
  53058. * Gaussian blur multiplier. Multiplies the blur effect
  53059. * @type {number}
  53060. */
  53061. _this.gaussMultiplier = 4.0;
  53062. // HDR
  53063. /**
  53064. * Exposure, controls the overall intensity of the pipeline
  53065. * @type {number}
  53066. */
  53067. _this.exposure = 1.0;
  53068. /**
  53069. * Minimum luminance that the post-process can output. Luminance is >= 0
  53070. * @type {number}
  53071. */
  53072. _this.minimumLuminance = 1.0;
  53073. /**
  53074. * Maximum luminance that the post-process can output. Must be suprerior to minimumLuminance
  53075. * @type {number}
  53076. */
  53077. _this.maximumLuminance = 1e20;
  53078. /**
  53079. * Increase rate for luminance: eye adaptation speed to dark
  53080. * @type {number}
  53081. */
  53082. _this.luminanceIncreaserate = 0.5;
  53083. /**
  53084. * Decrease rate for luminance: eye adaptation speed to bright
  53085. * @type {number}
  53086. */
  53087. _this.luminanceDecreaseRate = 0.5;
  53088. // Bright pass
  53089. /**
  53090. * Minimum luminance needed to compute HDR
  53091. * @type {number}
  53092. */
  53093. _this.brightThreshold = 0.8;
  53094. _this._needUpdate = true;
  53095. _this._scene = scene;
  53096. // Bright pass
  53097. _this._createBrightPassPostProcess(scene, ratio);
  53098. // Down sample X4
  53099. _this._createDownSampleX4PostProcess(scene, ratio);
  53100. // Create gaussian blur post-processes
  53101. _this._createGaussianBlurPostProcess(scene, ratio);
  53102. // Texture adder
  53103. _this._createTextureAdderPostProcess(scene, ratio);
  53104. // Luminance generator
  53105. _this._createLuminanceGeneratorPostProcess(scene);
  53106. // HDR
  53107. _this._createHDRPostProcess(scene, ratio);
  53108. // Pass postprocess
  53109. if (originalPostProcess === null) {
  53110. _this._originalPostProcess = new BABYLON.PassPostProcess("hdr", ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  53111. }
  53112. else {
  53113. _this._originalPostProcess = originalPostProcess;
  53114. }
  53115. // Configure pipeline
  53116. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this._originalPostProcess; }, true));
  53117. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this._brightPassPostProcess; }, true));
  53118. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this._downSampleX4PostProcess; }, true));
  53119. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurH", function () { return _this._guassianBlurHPostProcess; }, true));
  53120. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurV", function () { return _this._guassianBlurVPostProcess; }, true));
  53121. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this._textureAdderPostProcess; }, true));
  53122. var addDownSamplerPostProcess = function (id) {
  53123. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampler" + id, function () { return _this._downSamplePostProcesses[id]; }, true));
  53124. };
  53125. for (var i = HDRRenderingPipeline.LUM_STEPS - 1; i >= 0; i--) {
  53126. addDownSamplerPostProcess(i);
  53127. }
  53128. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this._hdrPostProcess; }, true));
  53129. // Finish
  53130. scene.postProcessRenderPipelineManager.addPipeline(_this);
  53131. if (cameras !== null) {
  53132. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  53133. }
  53134. _this.update();
  53135. return _this;
  53136. }
  53137. /**
  53138. * Tells the pipeline to update its post-processes
  53139. */
  53140. HDRRenderingPipeline.prototype.update = function () {
  53141. this._needUpdate = true;
  53142. };
  53143. /**
  53144. * Returns the current calculated luminance
  53145. */
  53146. HDRRenderingPipeline.prototype.getCurrentLuminance = function () {
  53147. return this._hdrCurrentLuminance;
  53148. };
  53149. /**
  53150. * Returns the currently drawn luminance
  53151. */
  53152. HDRRenderingPipeline.prototype.getOutputLuminance = function () {
  53153. return this._hdrOutputLuminance;
  53154. };
  53155. /**
  53156. * Releases the rendering pipeline and its internal effects. Detaches pipeline from cameras
  53157. */
  53158. HDRRenderingPipeline.prototype.dispose = function () {
  53159. for (var i = 0; i < this._scene.cameras.length; i++) {
  53160. var camera = this._scene.cameras[i];
  53161. this._originalPostProcess.dispose(camera);
  53162. this._brightPassPostProcess.dispose(camera);
  53163. this._downSampleX4PostProcess.dispose(camera);
  53164. this._guassianBlurHPostProcess.dispose(camera);
  53165. this._guassianBlurVPostProcess.dispose(camera);
  53166. this._textureAdderPostProcess.dispose(camera);
  53167. for (var j = HDRRenderingPipeline.LUM_STEPS - 1; j >= 0; j--) {
  53168. this._downSamplePostProcesses[j].dispose(camera);
  53169. }
  53170. this._hdrPostProcess.dispose(camera);
  53171. }
  53172. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  53173. _super.prototype.dispose.call(this);
  53174. };
  53175. /**
  53176. * Creates the HDR post-process and computes the luminance adaptation
  53177. */
  53178. HDRRenderingPipeline.prototype._createHDRPostProcess = function (scene, ratio) {
  53179. var _this = this;
  53180. var hdrLastLuminance = 0.0;
  53181. this._hdrOutputLuminance = -1.0;
  53182. this._hdrCurrentLuminance = 1.0;
  53183. this._hdrPostProcess = new BABYLON.PostProcess("hdr", "hdr", ["exposure", "avgLuminance"], ["otherSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define HDR");
  53184. this._hdrPostProcess.onApply = function (effect) {
  53185. if (_this._hdrOutputLuminance < 0.0) {
  53186. _this._hdrOutputLuminance = _this._hdrCurrentLuminance;
  53187. }
  53188. else {
  53189. var dt = (hdrLastLuminance - (hdrLastLuminance + scene.getEngine().getDeltaTime())) / 1000.0;
  53190. if (_this._hdrCurrentLuminance < _this._hdrOutputLuminance + _this.luminanceDecreaseRate * dt) {
  53191. _this._hdrOutputLuminance += _this.luminanceDecreaseRate * dt;
  53192. }
  53193. else if (_this._hdrCurrentLuminance > _this._hdrOutputLuminance - _this.luminanceIncreaserate * dt) {
  53194. _this._hdrOutputLuminance -= _this.luminanceIncreaserate * dt;
  53195. }
  53196. else {
  53197. _this._hdrOutputLuminance = _this._hdrCurrentLuminance;
  53198. }
  53199. }
  53200. _this._hdrOutputLuminance = BABYLON.MathTools.Clamp(_this._hdrOutputLuminance, _this.minimumLuminance, _this.maximumLuminance);
  53201. hdrLastLuminance += scene.getEngine().getDeltaTime();
  53202. effect.setTextureFromPostProcess("textureSampler", _this._textureAdderPostProcess);
  53203. effect.setTextureFromPostProcess("otherSampler", _this._originalPostProcess);
  53204. effect.setFloat("exposure", _this.exposure);
  53205. effect.setFloat("avgLuminance", _this._hdrOutputLuminance);
  53206. _this._needUpdate = false;
  53207. };
  53208. };
  53209. /**
  53210. * Texture Adder post-process
  53211. */
  53212. HDRRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  53213. var _this = this;
  53214. this._textureAdderPostProcess = new BABYLON.PostProcess("hdr", "hdr", [], ["otherSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define TEXTURE_ADDER");
  53215. this._textureAdderPostProcess.onApply = function (effect) {
  53216. effect.setTextureFromPostProcess("otherSampler", _this._originalPostProcess);
  53217. };
  53218. };
  53219. /**
  53220. * Down sample X4 post-process
  53221. */
  53222. HDRRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  53223. var _this = this;
  53224. var downSampleX4Offsets = new Array(32);
  53225. this._downSampleX4PostProcess = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets"], [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define DOWN_SAMPLE_X4");
  53226. this._downSampleX4PostProcess.onApply = function (effect) {
  53227. if (_this._needUpdate) {
  53228. var id = 0;
  53229. for (var i = -2; i < 2; i++) {
  53230. for (var j = -2; j < 2; j++) {
  53231. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / _this._downSampleX4PostProcess.width);
  53232. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / _this._downSampleX4PostProcess.height);
  53233. id += 2;
  53234. }
  53235. }
  53236. }
  53237. effect.setArray2("dsOffsets", downSampleX4Offsets);
  53238. };
  53239. };
  53240. /**
  53241. * Bright pass post-process
  53242. */
  53243. HDRRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  53244. var _this = this;
  53245. var brightOffsets = new Array(8);
  53246. var brightPassCallback = function (effect) {
  53247. if (_this._needUpdate) {
  53248. var sU = (1.0 / _this._brightPassPostProcess.width);
  53249. var sV = (1.0 / _this._brightPassPostProcess.height);
  53250. brightOffsets[0] = -0.5 * sU;
  53251. brightOffsets[1] = 0.5 * sV;
  53252. brightOffsets[2] = 0.5 * sU;
  53253. brightOffsets[3] = 0.5 * sV;
  53254. brightOffsets[4] = -0.5 * sU;
  53255. brightOffsets[5] = -0.5 * sV;
  53256. brightOffsets[6] = 0.5 * sU;
  53257. brightOffsets[7] = -0.5 * sV;
  53258. }
  53259. effect.setArray2("dsOffsets", brightOffsets);
  53260. effect.setFloat("brightThreshold", _this.brightThreshold);
  53261. };
  53262. this._brightPassPostProcess = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets", "brightThreshold"], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define BRIGHT_PASS");
  53263. this._brightPassPostProcess.onApply = brightPassCallback;
  53264. };
  53265. /**
  53266. * Luminance generator. Creates the luminance post-process and down sample post-processes
  53267. */
  53268. HDRRenderingPipeline.prototype._createLuminanceGeneratorPostProcess = function (scene) {
  53269. var _this = this;
  53270. var lumSteps = HDRRenderingPipeline.LUM_STEPS;
  53271. var luminanceOffsets = new Array(8);
  53272. var downSampleOffsets = new Array(18);
  53273. var halfDestPixelSize;
  53274. this._downSamplePostProcesses = new Array(lumSteps);
  53275. // Utils for luminance
  53276. var luminanceUpdateSourceOffsets = function (width, height) {
  53277. var sU = (1.0 / width);
  53278. var sV = (1.0 / height);
  53279. luminanceOffsets[0] = -0.5 * sU;
  53280. luminanceOffsets[1] = 0.5 * sV;
  53281. luminanceOffsets[2] = 0.5 * sU;
  53282. luminanceOffsets[3] = 0.5 * sV;
  53283. luminanceOffsets[4] = -0.5 * sU;
  53284. luminanceOffsets[5] = -0.5 * sV;
  53285. luminanceOffsets[6] = 0.5 * sU;
  53286. luminanceOffsets[7] = -0.5 * sV;
  53287. };
  53288. var luminanceUpdateDestOffsets = function (width, height) {
  53289. var id = 0;
  53290. for (var x = -1; x < 2; x++) {
  53291. for (var y = -1; y < 2; y++) {
  53292. downSampleOffsets[id] = (x) / width;
  53293. downSampleOffsets[id + 1] = (y) / height;
  53294. id += 2;
  53295. }
  53296. }
  53297. };
  53298. // Luminance callback
  53299. var luminanceCallback = function (effect) {
  53300. if (_this._needUpdate) {
  53301. luminanceUpdateSourceOffsets(_this._textureAdderPostProcess.width, _this._textureAdderPostProcess.height);
  53302. }
  53303. effect.setTextureFromPostProcess("textureSampler", _this._textureAdderPostProcess);
  53304. effect.setArray2("lumOffsets", luminanceOffsets);
  53305. };
  53306. // Down sample callbacks
  53307. var downSampleCallback = function (indice) {
  53308. var i = indice;
  53309. return function (effect) {
  53310. luminanceUpdateSourceOffsets(_this._downSamplePostProcesses[i].width, _this._downSamplePostProcesses[i].height);
  53311. luminanceUpdateDestOffsets(_this._downSamplePostProcesses[i].width, _this._downSamplePostProcesses[i].height);
  53312. halfDestPixelSize = 0.5 / _this._downSamplePostProcesses[i].width;
  53313. effect.setTextureFromPostProcess("textureSampler", _this._downSamplePostProcesses[i + 1]);
  53314. effect.setFloat("halfDestPixelSize", halfDestPixelSize);
  53315. effect.setArray2("dsOffsets", downSampleOffsets);
  53316. };
  53317. };
  53318. var downSampleAfterRenderCallback = function (effect) {
  53319. // Unpack result
  53320. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  53321. 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);
  53322. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  53323. };
  53324. // Create luminance post-process
  53325. var ratio = { width: Math.pow(3, lumSteps - 1), height: Math.pow(3, lumSteps - 1) };
  53326. 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);
  53327. this._downSamplePostProcesses[lumSteps - 1].onApply = luminanceCallback;
  53328. // Create down sample post-processes
  53329. for (var i = lumSteps - 2; i >= 0; i--) {
  53330. var length = Math.pow(3, i);
  53331. ratio = { width: length, height: length };
  53332. var defines = "#define DOWN_SAMPLE\n";
  53333. if (i === 0) {
  53334. defines += "#define FINAL_DOWN_SAMPLE\n"; // To pack the result
  53335. }
  53336. this._downSamplePostProcesses[i] = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets", "halfDestPixelSize"], [], ratio, null, BABYLON.Texture.NEAREST_SAMPLINGMODE, scene.getEngine(), false, defines, BABYLON.Engine.TEXTURETYPE_FLOAT);
  53337. this._downSamplePostProcesses[i].onApply = downSampleCallback(i);
  53338. if (i === 0) {
  53339. this._downSamplePostProcesses[i].onAfterRender = downSampleAfterRenderCallback;
  53340. }
  53341. }
  53342. };
  53343. /**
  53344. * Gaussian blur post-processes. Horizontal and Vertical
  53345. */
  53346. HDRRenderingPipeline.prototype._createGaussianBlurPostProcess = function (scene, ratio) {
  53347. var _this = this;
  53348. var blurOffsetsW = new Array(9);
  53349. var blurOffsetsH = new Array(9);
  53350. var blurWeights = new Array(9);
  53351. var uniforms = ["blurOffsets", "blurWeights", "multiplier"];
  53352. // Utils for gaussian blur
  53353. var calculateBlurOffsets = function (height) {
  53354. var lastOutputDimensions = {
  53355. width: scene.getEngine().getRenderWidth(),
  53356. height: scene.getEngine().getRenderHeight()
  53357. };
  53358. for (var i = 0; i < 9; i++) {
  53359. var value = (i - 4.0) * (1.0 / (height === true ? lastOutputDimensions.height : lastOutputDimensions.width));
  53360. if (height) {
  53361. blurOffsetsH[i] = value;
  53362. }
  53363. else {
  53364. blurOffsetsW[i] = value;
  53365. }
  53366. }
  53367. };
  53368. var calculateWeights = function () {
  53369. var x = 0.0;
  53370. for (var i = 0; i < 9; i++) {
  53371. x = (i - 4.0) / 4.0;
  53372. 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));
  53373. }
  53374. };
  53375. // Callback
  53376. var gaussianBlurCallback = function (height) {
  53377. return function (effect) {
  53378. if (_this._needUpdate) {
  53379. calculateWeights();
  53380. calculateBlurOffsets(height);
  53381. }
  53382. effect.setArray("blurOffsets", height ? blurOffsetsH : blurOffsetsW);
  53383. effect.setArray("blurWeights", blurWeights);
  53384. effect.setFloat("multiplier", _this.gaussMultiplier);
  53385. };
  53386. };
  53387. // Create horizontal gaussian blur post-processes
  53388. this._guassianBlurHPostProcess = new BABYLON.PostProcess("hdr", "hdr", uniforms, [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define GAUSSIAN_BLUR_H");
  53389. this._guassianBlurHPostProcess.onApply = gaussianBlurCallback(false);
  53390. // Create vertical gaussian blur post-process
  53391. this._guassianBlurVPostProcess = new BABYLON.PostProcess("hdr", "hdr", uniforms, [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define GAUSSIAN_BLUR_V");
  53392. this._guassianBlurVPostProcess.onApply = gaussianBlurCallback(true);
  53393. };
  53394. return HDRRenderingPipeline;
  53395. }(BABYLON.PostProcessRenderPipeline));
  53396. // Luminance generator
  53397. HDRRenderingPipeline.LUM_STEPS = 6;
  53398. BABYLON.HDRRenderingPipeline = HDRRenderingPipeline;
  53399. })(BABYLON || (BABYLON = {}));
  53400. //# sourceMappingURL=babylon.hdrRenderingPipeline.js.map
  53401. var BABYLON;
  53402. (function (BABYLON) {
  53403. var FaceAdjacencies = (function () {
  53404. function FaceAdjacencies() {
  53405. this.edges = new Array();
  53406. this.edgesConnectedCount = 0;
  53407. }
  53408. return FaceAdjacencies;
  53409. }());
  53410. var EdgesRenderer = (function () {
  53411. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  53412. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  53413. if (epsilon === void 0) { epsilon = 0.95; }
  53414. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  53415. this.edgesWidthScalerForOrthographic = 1000.0;
  53416. this.edgesWidthScalerForPerspective = 50.0;
  53417. this._linesPositions = new Array();
  53418. this._linesNormals = new Array();
  53419. this._linesIndices = new Array();
  53420. this._buffers = {};
  53421. this._checkVerticesInsteadOfIndices = false;
  53422. this._source = source;
  53423. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  53424. this._epsilon = epsilon;
  53425. this._prepareRessources();
  53426. this._generateEdgesLines();
  53427. }
  53428. EdgesRenderer.prototype._prepareRessources = function () {
  53429. if (this._lineShader) {
  53430. return;
  53431. }
  53432. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  53433. attributes: ["position", "normal"],
  53434. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  53435. });
  53436. this._lineShader.disableDepthWrite = true;
  53437. this._lineShader.backFaceCulling = false;
  53438. };
  53439. EdgesRenderer.prototype.dispose = function () {
  53440. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  53441. if (buffer) {
  53442. buffer.dispose();
  53443. this._buffers[BABYLON.VertexBuffer.PositionKind] = null;
  53444. }
  53445. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  53446. if (buffer) {
  53447. buffer.dispose();
  53448. this._buffers[BABYLON.VertexBuffer.NormalKind] = null;
  53449. }
  53450. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  53451. this._lineShader.dispose();
  53452. };
  53453. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  53454. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  53455. return 0;
  53456. }
  53457. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  53458. return 1;
  53459. }
  53460. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  53461. return 2;
  53462. }
  53463. return -1;
  53464. };
  53465. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  53466. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  53467. return 0;
  53468. }
  53469. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  53470. return 1;
  53471. }
  53472. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  53473. return 2;
  53474. }
  53475. return -1;
  53476. };
  53477. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  53478. var needToCreateLine;
  53479. if (edge === undefined) {
  53480. needToCreateLine = true;
  53481. }
  53482. else {
  53483. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  53484. needToCreateLine = dotProduct < this._epsilon;
  53485. }
  53486. if (needToCreateLine) {
  53487. var offset = this._linesPositions.length / 3;
  53488. var normal = p0.subtract(p1);
  53489. normal.normalize();
  53490. // Positions
  53491. this._linesPositions.push(p0.x);
  53492. this._linesPositions.push(p0.y);
  53493. this._linesPositions.push(p0.z);
  53494. this._linesPositions.push(p0.x);
  53495. this._linesPositions.push(p0.y);
  53496. this._linesPositions.push(p0.z);
  53497. this._linesPositions.push(p1.x);
  53498. this._linesPositions.push(p1.y);
  53499. this._linesPositions.push(p1.z);
  53500. this._linesPositions.push(p1.x);
  53501. this._linesPositions.push(p1.y);
  53502. this._linesPositions.push(p1.z);
  53503. // Normals
  53504. this._linesNormals.push(p1.x);
  53505. this._linesNormals.push(p1.y);
  53506. this._linesNormals.push(p1.z);
  53507. this._linesNormals.push(-1);
  53508. this._linesNormals.push(p1.x);
  53509. this._linesNormals.push(p1.y);
  53510. this._linesNormals.push(p1.z);
  53511. this._linesNormals.push(1);
  53512. this._linesNormals.push(p0.x);
  53513. this._linesNormals.push(p0.y);
  53514. this._linesNormals.push(p0.z);
  53515. this._linesNormals.push(-1);
  53516. this._linesNormals.push(p0.x);
  53517. this._linesNormals.push(p0.y);
  53518. this._linesNormals.push(p0.z);
  53519. this._linesNormals.push(1);
  53520. // Indices
  53521. this._linesIndices.push(offset);
  53522. this._linesIndices.push(offset + 1);
  53523. this._linesIndices.push(offset + 2);
  53524. this._linesIndices.push(offset);
  53525. this._linesIndices.push(offset + 2);
  53526. this._linesIndices.push(offset + 3);
  53527. }
  53528. };
  53529. EdgesRenderer.prototype._generateEdgesLines = function () {
  53530. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  53531. var indices = this._source.getIndices();
  53532. // First let's find adjacencies
  53533. var adjacencies = new Array();
  53534. var faceNormals = new Array();
  53535. var index;
  53536. var faceAdjacencies;
  53537. // Prepare faces
  53538. for (index = 0; index < indices.length; index += 3) {
  53539. faceAdjacencies = new FaceAdjacencies();
  53540. var p0Index = indices[index];
  53541. var p1Index = indices[index + 1];
  53542. var p2Index = indices[index + 2];
  53543. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  53544. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  53545. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  53546. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  53547. faceNormal.normalize();
  53548. faceNormals.push(faceNormal);
  53549. adjacencies.push(faceAdjacencies);
  53550. }
  53551. // Scan
  53552. for (index = 0; index < adjacencies.length; index++) {
  53553. faceAdjacencies = adjacencies[index];
  53554. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  53555. var otherFaceAdjacencies = adjacencies[otherIndex];
  53556. if (faceAdjacencies.edgesConnectedCount === 3) {
  53557. break;
  53558. }
  53559. if (otherFaceAdjacencies.edgesConnectedCount === 3) {
  53560. continue;
  53561. }
  53562. var otherP0 = indices[otherIndex * 3];
  53563. var otherP1 = indices[otherIndex * 3 + 1];
  53564. var otherP2 = indices[otherIndex * 3 + 2];
  53565. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  53566. var otherEdgeIndex;
  53567. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  53568. continue;
  53569. }
  53570. switch (edgeIndex) {
  53571. case 0:
  53572. if (this._checkVerticesInsteadOfIndices) {
  53573. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  53574. }
  53575. else {
  53576. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  53577. }
  53578. break;
  53579. case 1:
  53580. if (this._checkVerticesInsteadOfIndices) {
  53581. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  53582. }
  53583. else {
  53584. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  53585. }
  53586. break;
  53587. case 2:
  53588. if (this._checkVerticesInsteadOfIndices) {
  53589. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  53590. }
  53591. else {
  53592. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  53593. }
  53594. break;
  53595. }
  53596. if (otherEdgeIndex === -1) {
  53597. continue;
  53598. }
  53599. faceAdjacencies.edges[edgeIndex] = otherIndex;
  53600. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  53601. faceAdjacencies.edgesConnectedCount++;
  53602. otherFaceAdjacencies.edgesConnectedCount++;
  53603. if (faceAdjacencies.edgesConnectedCount === 3) {
  53604. break;
  53605. }
  53606. }
  53607. }
  53608. }
  53609. // Create lines
  53610. for (index = 0; index < adjacencies.length; index++) {
  53611. // 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
  53612. var current = adjacencies[index];
  53613. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  53614. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  53615. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  53616. }
  53617. // Merge into a single mesh
  53618. var engine = this._source.getScene().getEngine();
  53619. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  53620. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  53621. this._ib = engine.createIndexBuffer(this._linesIndices);
  53622. this._indicesCount = this._linesIndices.length;
  53623. };
  53624. EdgesRenderer.prototype.render = function () {
  53625. if (!this._lineShader.isReady()) {
  53626. return;
  53627. }
  53628. var scene = this._source.getScene();
  53629. var engine = scene.getEngine();
  53630. this._lineShader._preBind();
  53631. // VBOs
  53632. engine.bindBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  53633. scene.resetCachedMaterial();
  53634. this._lineShader.setColor4("color", this._source.edgesColor);
  53635. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  53636. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  53637. }
  53638. else {
  53639. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  53640. }
  53641. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  53642. this._lineShader.bind(this._source.getWorldMatrix());
  53643. // Draw order
  53644. engine.draw(true, 0, this._indicesCount);
  53645. this._lineShader.unbind();
  53646. engine.setDepthWrite(true);
  53647. };
  53648. return EdgesRenderer;
  53649. }());
  53650. BABYLON.EdgesRenderer = EdgesRenderer;
  53651. })(BABYLON || (BABYLON = {}));
  53652. //# sourceMappingURL=babylon.edgesRenderer.js.map
  53653. var BABYLON;
  53654. (function (BABYLON) {
  53655. var TonemappingOperator;
  53656. (function (TonemappingOperator) {
  53657. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  53658. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  53659. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  53660. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  53661. })(TonemappingOperator = BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  53662. ;
  53663. var TonemapPostProcess = (function (_super) {
  53664. __extends(TonemapPostProcess, _super);
  53665. function TonemapPostProcess(name, _operator, exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  53666. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  53667. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  53668. var _this = _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, defines, textureFormat) || this;
  53669. _this._operator = _operator;
  53670. _this.exposureAdjustment = exposureAdjustment;
  53671. var defines = "#define ";
  53672. if (_this._operator === TonemappingOperator.Hable)
  53673. defines += "HABLE_TONEMAPPING";
  53674. else if (_this._operator === TonemappingOperator.Reinhard)
  53675. defines += "REINHARD_TONEMAPPING";
  53676. else if (_this._operator === TonemappingOperator.HejiDawson)
  53677. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  53678. else if (_this._operator === TonemappingOperator.Photographic)
  53679. defines += "PHOTOGRAPHIC_TONEMAPPING";
  53680. //sadly a second call to create the effect.
  53681. _this.updateEffect(defines);
  53682. _this.onApply = function (effect) {
  53683. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  53684. };
  53685. return _this;
  53686. }
  53687. return TonemapPostProcess;
  53688. }(BABYLON.PostProcess));
  53689. BABYLON.TonemapPostProcess = TonemapPostProcess;
  53690. })(BABYLON || (BABYLON = {}));
  53691. //# sourceMappingURL=babylon.tonemapPostProcess.js.map
  53692. var BABYLON;
  53693. (function (BABYLON) {
  53694. var ReflectionProbe = (function () {
  53695. function ReflectionProbe(name, size, scene, generateMipMaps) {
  53696. if (generateMipMaps === void 0) { generateMipMaps = true; }
  53697. var _this = this;
  53698. this.name = name;
  53699. this._viewMatrix = BABYLON.Matrix.Identity();
  53700. this._target = BABYLON.Vector3.Zero();
  53701. this._add = BABYLON.Vector3.Zero();
  53702. this.invertYAxis = false;
  53703. this.position = BABYLON.Vector3.Zero();
  53704. this._scene = scene;
  53705. this._scene.reflectionProbes.push(this);
  53706. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  53707. this._renderTargetTexture.onBeforeRenderObservable.add(function (faceIndex) {
  53708. switch (faceIndex) {
  53709. case 0:
  53710. _this._add.copyFromFloats(1, 0, 0);
  53711. break;
  53712. case 1:
  53713. _this._add.copyFromFloats(-1, 0, 0);
  53714. break;
  53715. case 2:
  53716. _this._add.copyFromFloats(0, _this.invertYAxis ? 1 : -1, 0);
  53717. break;
  53718. case 3:
  53719. _this._add.copyFromFloats(0, _this.invertYAxis ? -1 : 1, 0);
  53720. break;
  53721. case 4:
  53722. _this._add.copyFromFloats(0, 0, 1);
  53723. break;
  53724. case 5:
  53725. _this._add.copyFromFloats(0, 0, -1);
  53726. break;
  53727. }
  53728. if (_this._attachedMesh) {
  53729. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  53730. }
  53731. _this.position.addToRef(_this._add, _this._target);
  53732. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  53733. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  53734. });
  53735. this._renderTargetTexture.onAfterUnbindObservable.add(function () {
  53736. scene.updateTransformMatrix(true);
  53737. });
  53738. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  53739. }
  53740. Object.defineProperty(ReflectionProbe.prototype, "samples", {
  53741. get: function () {
  53742. return this._renderTargetTexture.samples;
  53743. },
  53744. set: function (value) {
  53745. this._renderTargetTexture.samples = value;
  53746. },
  53747. enumerable: true,
  53748. configurable: true
  53749. });
  53750. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  53751. get: function () {
  53752. return this._renderTargetTexture.refreshRate;
  53753. },
  53754. set: function (value) {
  53755. this._renderTargetTexture.refreshRate = value;
  53756. },
  53757. enumerable: true,
  53758. configurable: true
  53759. });
  53760. ReflectionProbe.prototype.getScene = function () {
  53761. return this._scene;
  53762. };
  53763. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  53764. get: function () {
  53765. return this._renderTargetTexture;
  53766. },
  53767. enumerable: true,
  53768. configurable: true
  53769. });
  53770. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  53771. get: function () {
  53772. return this._renderTargetTexture.renderList;
  53773. },
  53774. enumerable: true,
  53775. configurable: true
  53776. });
  53777. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  53778. this._attachedMesh = mesh;
  53779. };
  53780. ReflectionProbe.prototype.dispose = function () {
  53781. var index = this._scene.reflectionProbes.indexOf(this);
  53782. if (index !== -1) {
  53783. // Remove from the scene if found
  53784. this._scene.reflectionProbes.splice(index, 1);
  53785. }
  53786. if (this._renderTargetTexture) {
  53787. this._renderTargetTexture.dispose();
  53788. this._renderTargetTexture = null;
  53789. }
  53790. };
  53791. return ReflectionProbe;
  53792. }());
  53793. BABYLON.ReflectionProbe = ReflectionProbe;
  53794. })(BABYLON || (BABYLON = {}));
  53795. //# sourceMappingURL=babylon.reflectionProbe.js.map
  53796. var BABYLON;
  53797. (function (BABYLON) {
  53798. var SolidParticle = (function () {
  53799. /**
  53800. * Creates a Solid Particle object.
  53801. * Don't create particles manually, use instead the Solid Particle System internal tools like _addParticle()
  53802. * `particleIndex` (integer) is the particle index in the Solid Particle System pool. It's also the particle identifier.
  53803. * `positionIndex` (integer) is the starting index of the particle vertices in the SPS "positions" array.
  53804. * `model` (ModelShape) is a reference to the model shape on what the particle is designed.
  53805. * `shapeId` (integer) is the model shape identifier in the SPS.
  53806. * `idxInShape` (integer) is the index of the particle in the current model (ex: the 10th box of addShape(box, 30))
  53807. * `modelBoundingInfo` is the reference to the model BoundingInfo used for intersection computations.
  53808. */
  53809. function SolidParticle(particleIndex, positionIndex, model, shapeId, idxInShape, sps, modelBoundingInfo) {
  53810. this.idx = 0; // particle global index
  53811. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0); // color
  53812. this.position = BABYLON.Vector3.Zero(); // position
  53813. this.rotation = BABYLON.Vector3.Zero(); // rotation
  53814. this.scaling = new BABYLON.Vector3(1.0, 1.0, 1.0); // scaling
  53815. this.uvs = new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0); // uvs
  53816. this.velocity = BABYLON.Vector3.Zero(); // velocity
  53817. this.alive = true; // alive
  53818. this.isVisible = true; // visibility
  53819. this._pos = 0; // index of this particle in the global "positions" array
  53820. this.shapeId = 0; // model shape id
  53821. this.idxInShape = 0; // index of the particle in its shape id
  53822. this.idx = particleIndex;
  53823. this._pos = positionIndex;
  53824. this._model = model;
  53825. this.shapeId = shapeId;
  53826. this.idxInShape = idxInShape;
  53827. this._sps = sps;
  53828. if (modelBoundingInfo) {
  53829. this._modelBoundingInfo = modelBoundingInfo;
  53830. this._boundingInfo = new BABYLON.BoundingInfo(modelBoundingInfo.minimum, modelBoundingInfo.maximum);
  53831. }
  53832. }
  53833. Object.defineProperty(SolidParticle.prototype, "scale", {
  53834. /**
  53835. * legacy support, changed scale to scaling
  53836. */
  53837. get: function () {
  53838. return this.scaling;
  53839. },
  53840. set: function (scale) {
  53841. this.scaling = scale;
  53842. },
  53843. enumerable: true,
  53844. configurable: true
  53845. });
  53846. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  53847. /**
  53848. * legacy support, changed quaternion to rotationQuaternion
  53849. */
  53850. get: function () {
  53851. return this.rotationQuaternion;
  53852. },
  53853. set: function (q) {
  53854. this.rotationQuaternion = q;
  53855. },
  53856. enumerable: true,
  53857. configurable: true
  53858. });
  53859. /**
  53860. * Returns a boolean. True if the particle intersects another particle or another mesh, else false.
  53861. * The intersection is computed on the particle bounding sphere and Axis Aligned Bounding Box (AABB)
  53862. * `target` is the object (solid particle or mesh) what the intersection is computed against.
  53863. */
  53864. SolidParticle.prototype.intersectsMesh = function (target) {
  53865. if (!this._boundingInfo || !target._boundingInfo) {
  53866. return false;
  53867. }
  53868. if (this._sps._bSphereOnly) {
  53869. return BABYLON.BoundingSphere.Intersects(this._boundingInfo.boundingSphere, target._boundingInfo.boundingSphere);
  53870. }
  53871. return this._boundingInfo.intersects(target._boundingInfo, false);
  53872. };
  53873. return SolidParticle;
  53874. }());
  53875. BABYLON.SolidParticle = SolidParticle;
  53876. var ModelShape = (function () {
  53877. /**
  53878. * 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.
  53879. * SPS internal tool, don't use it manually.
  53880. */
  53881. function ModelShape(id, shape, shapeUV, posFunction, vtxFunction) {
  53882. this.shapeID = id;
  53883. this._shape = shape;
  53884. this._shapeUV = shapeUV;
  53885. this._positionFunction = posFunction;
  53886. this._vertexFunction = vtxFunction;
  53887. }
  53888. return ModelShape;
  53889. }());
  53890. BABYLON.ModelShape = ModelShape;
  53891. })(BABYLON || (BABYLON = {}));
  53892. //# sourceMappingURL=babylon.solidParticle.js.map
  53893. var BABYLON;
  53894. (function (BABYLON) {
  53895. /**
  53896. * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System
  53897. */
  53898. var SolidParticleSystem = (function () {
  53899. /**
  53900. * Creates a SPS (Solid Particle System) object.
  53901. * `name` (String) is the SPS name, this will be the underlying mesh name.
  53902. * `scene` (Scene) is the scene in which the SPS is added.
  53903. * `updatable` (optional boolean, default true) : if the SPS must be updatable or immutable.
  53904. * `isPickable` (optional boolean, default false) : if the solid particles must be pickable.
  53905. * `particleIntersection` (optional boolean, default false) : if the solid particle intersections must be computed.
  53906. * `boundingSphereOnly` (optional boolean, default false) : if the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster).
  53907. * `bSphereRadiusFactor` (optional float, default 1.0) : a number to multiply the boundind sphere radius by in order to reduce it for instance.
  53908. * Example : bSphereRadiusFactor = 1.0 / Math.sqrt(3.0) => the bounding sphere exactly matches a spherical mesh.
  53909. */
  53910. function SolidParticleSystem(name, scene, options) {
  53911. // public members
  53912. /**
  53913. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  53914. * Example : var p = SPS.particles[i];
  53915. */
  53916. this.particles = new Array();
  53917. /**
  53918. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  53919. */
  53920. this.nbParticles = 0;
  53921. /**
  53922. * If the particles must ever face the camera (default false). Useful for planar particles.
  53923. */
  53924. this.billboard = false;
  53925. /**
  53926. * Recompute normals when adding a shape
  53927. */
  53928. this.recomputeNormals = true;
  53929. /**
  53930. * This a counter ofr your own usage. It's not set by any SPS functions.
  53931. */
  53932. this.counter = 0;
  53933. /**
  53934. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  53935. * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns
  53936. */
  53937. this.vars = {};
  53938. this._positions = new Array();
  53939. this._indices = new Array();
  53940. this._normals = new Array();
  53941. this._colors = new Array();
  53942. this._uvs = new Array();
  53943. this._index = 0; // indices index
  53944. this._updatable = true;
  53945. this._pickable = false;
  53946. this._isVisibilityBoxLocked = false;
  53947. this._alwaysVisible = false;
  53948. this._shapeCounter = 0;
  53949. this._copy = new BABYLON.SolidParticle(null, null, null, null, null, null);
  53950. this._color = new BABYLON.Color4(0, 0, 0, 0);
  53951. this._computeParticleColor = true;
  53952. this._computeParticleTexture = true;
  53953. this._computeParticleRotation = true;
  53954. this._computeParticleVertex = false;
  53955. this._computeBoundingBox = false;
  53956. this._cam_axisZ = BABYLON.Vector3.Zero();
  53957. this._cam_axisY = BABYLON.Vector3.Zero();
  53958. this._cam_axisX = BABYLON.Vector3.Zero();
  53959. this._axisX = BABYLON.Axis.X;
  53960. this._axisY = BABYLON.Axis.Y;
  53961. this._axisZ = BABYLON.Axis.Z;
  53962. this._camDir = BABYLON.Vector3.Zero();
  53963. this._rotMatrix = new BABYLON.Matrix();
  53964. this._invertMatrix = new BABYLON.Matrix();
  53965. this._rotated = BABYLON.Vector3.Zero();
  53966. this._quaternion = new BABYLON.Quaternion();
  53967. this._vertex = BABYLON.Vector3.Zero();
  53968. this._normal = BABYLON.Vector3.Zero();
  53969. this._yaw = 0.0;
  53970. this._pitch = 0.0;
  53971. this._roll = 0.0;
  53972. this._halfroll = 0.0;
  53973. this._halfpitch = 0.0;
  53974. this._halfyaw = 0.0;
  53975. this._sinRoll = 0.0;
  53976. this._cosRoll = 0.0;
  53977. this._sinPitch = 0.0;
  53978. this._cosPitch = 0.0;
  53979. this._sinYaw = 0.0;
  53980. this._cosYaw = 0.0;
  53981. this._w = 0.0;
  53982. this._mustUnrotateFixedNormals = false;
  53983. this._minimum = BABYLON.Tmp.Vector3[0];
  53984. this._maximum = BABYLON.Tmp.Vector3[1];
  53985. this._scale = BABYLON.Tmp.Vector3[2];
  53986. this._translation = BABYLON.Tmp.Vector3[3];
  53987. this._minBbox = BABYLON.Tmp.Vector3[4];
  53988. this._maxBbox = BABYLON.Tmp.Vector3[5];
  53989. this._particlesIntersect = false;
  53990. this._bSphereOnly = false;
  53991. this._bSphereRadiusFactor = 1.0;
  53992. this.name = name;
  53993. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  53994. this._camera = scene.activeCamera;
  53995. this._pickable = options ? options.isPickable : false;
  53996. this._particlesIntersect = options ? options.particleIntersection : false;
  53997. this._bSphereOnly = options ? options.boundingSphereOnly : false;
  53998. this._bSphereRadiusFactor = (options && options.bSphereRadiusFactor) ? options.bSphereRadiusFactor : 1.0;
  53999. if (options && options.updatable) {
  54000. this._updatable = options.updatable;
  54001. }
  54002. else {
  54003. this._updatable = true;
  54004. }
  54005. if (this._pickable) {
  54006. this.pickedParticles = [];
  54007. }
  54008. }
  54009. /**
  54010. * Builds the SPS underlying mesh. Returns a standard Mesh.
  54011. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  54012. */
  54013. SolidParticleSystem.prototype.buildMesh = function () {
  54014. if (this.nbParticles === 0) {
  54015. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  54016. this.addShape(triangle, 1);
  54017. triangle.dispose();
  54018. }
  54019. this._positions32 = new Float32Array(this._positions);
  54020. this._uvs32 = new Float32Array(this._uvs);
  54021. this._colors32 = new Float32Array(this._colors);
  54022. if (this.recomputeNormals) {
  54023. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices, this._normals);
  54024. }
  54025. this._normals32 = new Float32Array(this._normals);
  54026. this._fixedNormal32 = new Float32Array(this._normals);
  54027. if (this._mustUnrotateFixedNormals) {
  54028. this._unrotateFixedNormals();
  54029. }
  54030. var vertexData = new BABYLON.VertexData();
  54031. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  54032. vertexData.indices = this._indices;
  54033. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  54034. if (this._uvs32) {
  54035. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  54036. ;
  54037. }
  54038. if (this._colors32) {
  54039. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  54040. }
  54041. var mesh = new BABYLON.Mesh(this.name, this._scene);
  54042. vertexData.applyToMesh(mesh, this._updatable);
  54043. this.mesh = mesh;
  54044. this.mesh.isPickable = this._pickable;
  54045. // free memory
  54046. this._positions = null;
  54047. this._normals = null;
  54048. this._uvs = null;
  54049. this._colors = null;
  54050. if (!this._updatable) {
  54051. this.particles.length = 0;
  54052. }
  54053. return mesh;
  54054. };
  54055. /**
  54056. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  54057. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  54058. * Thus the particles generated from `digest()` have their property `position` set yet.
  54059. * `mesh` ( Mesh ) is the mesh to be digested
  54060. * `facetNb` (optional integer, default 1) is the number of mesh facets per particle, this parameter is overriden by the parameter `number` if any
  54061. * `delta` (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  54062. * `number` (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  54063. */
  54064. SolidParticleSystem.prototype.digest = function (mesh, options) {
  54065. var size = (options && options.facetNb) || 1;
  54066. var number = (options && options.number);
  54067. var delta = (options && options.delta) || 0;
  54068. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  54069. var meshInd = mesh.getIndices();
  54070. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  54071. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  54072. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  54073. var f = 0; // facet counter
  54074. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  54075. // compute size from number
  54076. if (number) {
  54077. number = (number > totalFacets) ? totalFacets : number;
  54078. size = Math.round(totalFacets / number);
  54079. delta = 0;
  54080. }
  54081. else {
  54082. size = (size > totalFacets) ? totalFacets : size;
  54083. }
  54084. var facetPos = []; // submesh positions
  54085. var facetInd = []; // submesh indices
  54086. var facetUV = []; // submesh UV
  54087. var facetCol = []; // submesh colors
  54088. var barycenter = BABYLON.Tmp.Vector3[0];
  54089. var rand;
  54090. var sizeO = size;
  54091. while (f < totalFacets) {
  54092. size = sizeO + Math.floor((1 + delta) * Math.random());
  54093. if (f > totalFacets - size) {
  54094. size = totalFacets - f;
  54095. }
  54096. // reset temp arrays
  54097. facetPos.length = 0;
  54098. facetInd.length = 0;
  54099. facetUV.length = 0;
  54100. facetCol.length = 0;
  54101. // iterate over "size" facets
  54102. var fi = 0;
  54103. for (var j = f * 3; j < (f + size) * 3; j++) {
  54104. facetInd.push(fi);
  54105. var i = meshInd[j];
  54106. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  54107. if (meshUV) {
  54108. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  54109. }
  54110. if (meshCol) {
  54111. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  54112. }
  54113. fi++;
  54114. }
  54115. // create a model shape for each single particle
  54116. var idx = this.nbParticles;
  54117. var shape = this._posToShape(facetPos);
  54118. var shapeUV = this._uvsToShapeUV(facetUV);
  54119. // compute the barycenter of the shape
  54120. var v;
  54121. for (v = 0; v < shape.length; v++) {
  54122. barycenter.addInPlace(shape[v]);
  54123. }
  54124. barycenter.scaleInPlace(1 / shape.length);
  54125. // shift the shape from its barycenter to the origin
  54126. for (v = 0; v < shape.length; v++) {
  54127. shape[v].subtractInPlace(barycenter);
  54128. }
  54129. var bInfo;
  54130. if (this._particlesIntersect) {
  54131. bInfo = new BABYLON.BoundingInfo(barycenter, barycenter);
  54132. }
  54133. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, shapeUV, null, null);
  54134. // add the particle in the SPS
  54135. var currentPos = this._positions.length;
  54136. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, meshNor, this._normals, idx, 0, null);
  54137. this._addParticle(idx, currentPos, modelShape, this._shapeCounter, 0, bInfo);
  54138. // initialize the particle position
  54139. this.particles[this.nbParticles].position.addInPlace(barycenter);
  54140. this._index += shape.length;
  54141. idx++;
  54142. this.nbParticles++;
  54143. this._shapeCounter++;
  54144. f += size;
  54145. }
  54146. return this;
  54147. };
  54148. // unrotate the fixed normals in case the mesh was built with pre-rotated particles, ex : use of positionFunction in addShape()
  54149. SolidParticleSystem.prototype._unrotateFixedNormals = function () {
  54150. var index = 0;
  54151. var idx = 0;
  54152. for (var p = 0; p < this.particles.length; p++) {
  54153. this._particle = this.particles[p];
  54154. this._shape = this._particle._model._shape;
  54155. if (this._particle.rotationQuaternion) {
  54156. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  54157. }
  54158. else {
  54159. this._yaw = this._particle.rotation.y;
  54160. this._pitch = this._particle.rotation.x;
  54161. this._roll = this._particle.rotation.z;
  54162. this._quaternionRotationYPR();
  54163. }
  54164. this._quaternionToRotationMatrix();
  54165. this._rotMatrix.invertToRef(this._invertMatrix);
  54166. for (var pt = 0; pt < this._shape.length; pt++) {
  54167. idx = index + pt * 3;
  54168. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._normals32[idx], this._normals32[idx + 1], this._normals32[idx + 2], this._invertMatrix, this._normal);
  54169. this._fixedNormal32[idx] = this._normal.x;
  54170. this._fixedNormal32[idx + 1] = this._normal.y;
  54171. this._fixedNormal32[idx + 2] = this._normal.z;
  54172. }
  54173. index = idx + 3;
  54174. }
  54175. };
  54176. //reset copy
  54177. SolidParticleSystem.prototype._resetCopy = function () {
  54178. this._copy.position.x = 0;
  54179. this._copy.position.y = 0;
  54180. this._copy.position.z = 0;
  54181. this._copy.rotation.x = 0;
  54182. this._copy.rotation.y = 0;
  54183. this._copy.rotation.z = 0;
  54184. this._copy.rotationQuaternion = null;
  54185. this._copy.scaling.x = 1;
  54186. this._copy.scaling.y = 1;
  54187. this._copy.scaling.z = 1;
  54188. this._copy.uvs.x = 0;
  54189. this._copy.uvs.y = 0;
  54190. this._copy.uvs.z = 1;
  54191. this._copy.uvs.w = 1;
  54192. this._copy.color = null;
  54193. };
  54194. // _meshBuilder : inserts the shape model in the global SPS mesh
  54195. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, meshNor, normals, idx, idxInShape, options) {
  54196. var i;
  54197. var u = 0;
  54198. var c = 0;
  54199. var n = 0;
  54200. this._resetCopy();
  54201. if (options && options.positionFunction) {
  54202. options.positionFunction(this._copy, idx, idxInShape);
  54203. this._mustUnrotateFixedNormals = true;
  54204. }
  54205. if (this._copy.rotationQuaternion) {
  54206. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  54207. }
  54208. else {
  54209. this._yaw = this._copy.rotation.y;
  54210. this._pitch = this._copy.rotation.x;
  54211. this._roll = this._copy.rotation.z;
  54212. this._quaternionRotationYPR();
  54213. }
  54214. this._quaternionToRotationMatrix();
  54215. for (i = 0; i < shape.length; i++) {
  54216. this._vertex.x = shape[i].x;
  54217. this._vertex.y = shape[i].y;
  54218. this._vertex.z = shape[i].z;
  54219. if (options && options.vertexFunction) {
  54220. options.vertexFunction(this._copy, this._vertex, i);
  54221. }
  54222. this._vertex.x *= this._copy.scaling.x;
  54223. this._vertex.y *= this._copy.scaling.y;
  54224. this._vertex.z *= this._copy.scaling.z;
  54225. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  54226. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  54227. if (meshUV) {
  54228. 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);
  54229. u += 2;
  54230. }
  54231. if (this._copy.color) {
  54232. this._color = this._copy.color;
  54233. }
  54234. else if (meshCol && meshCol[c] !== undefined) {
  54235. this._color.r = meshCol[c];
  54236. this._color.g = meshCol[c + 1];
  54237. this._color.b = meshCol[c + 2];
  54238. this._color.a = meshCol[c + 3];
  54239. }
  54240. else {
  54241. this._color.r = 1;
  54242. this._color.g = 1;
  54243. this._color.b = 1;
  54244. this._color.a = 1;
  54245. }
  54246. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  54247. c += 4;
  54248. if (!this.recomputeNormals && meshNor) {
  54249. this._normal.x = meshNor[n];
  54250. this._normal.y = meshNor[n + 1];
  54251. this._normal.z = meshNor[n + 2];
  54252. BABYLON.Vector3.TransformNormalToRef(this._normal, this._rotMatrix, this._normal);
  54253. normals.push(this._normal.x, this._normal.y, this._normal.z);
  54254. n += 3;
  54255. }
  54256. }
  54257. for (i = 0; i < meshInd.length; i++) {
  54258. indices.push(p + meshInd[i]);
  54259. }
  54260. if (this._pickable) {
  54261. var nbfaces = meshInd.length / 3;
  54262. for (i = 0; i < nbfaces; i++) {
  54263. this.pickedParticles.push({ idx: idx, faceId: i });
  54264. }
  54265. }
  54266. return this._copy;
  54267. };
  54268. // returns a shape array from positions array
  54269. SolidParticleSystem.prototype._posToShape = function (positions) {
  54270. var shape = [];
  54271. for (var i = 0; i < positions.length; i += 3) {
  54272. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  54273. }
  54274. return shape;
  54275. };
  54276. // returns a shapeUV array from a Vector4 uvs
  54277. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  54278. var shapeUV = [];
  54279. if (uvs) {
  54280. for (var i = 0; i < uvs.length; i++)
  54281. shapeUV.push(uvs[i]);
  54282. }
  54283. return shapeUV;
  54284. };
  54285. // adds a new particle object in the particles array
  54286. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, model, shapeId, idxInShape, bInfo) {
  54287. var sp = new BABYLON.SolidParticle(idx, idxpos, model, shapeId, idxInShape, this, bInfo);
  54288. this.particles.push(sp);
  54289. return sp;
  54290. };
  54291. /**
  54292. * Adds some particles to the SPS from the model shape. Returns the shape id.
  54293. * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps
  54294. * `mesh` is any Mesh object that will be used as a model for the solid particles.
  54295. * `nb` (positive integer) the number of particles to be created from this model
  54296. * `positionFunction` is an optional javascript function to called for each particle on SPS creation.
  54297. * `vertexFunction` is an optional javascript function to called for each vertex of each particle on SPS creation
  54298. */
  54299. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  54300. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  54301. var meshInd = mesh.getIndices();
  54302. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  54303. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  54304. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  54305. var bbInfo;
  54306. if (this._particlesIntersect) {
  54307. bbInfo = mesh.getBoundingInfo();
  54308. }
  54309. var shape = this._posToShape(meshPos);
  54310. var shapeUV = this._uvsToShapeUV(meshUV);
  54311. var posfunc = options ? options.positionFunction : null;
  54312. var vtxfunc = options ? options.vertexFunction : null;
  54313. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, shapeUV, posfunc, vtxfunc);
  54314. // particles
  54315. var sp;
  54316. var currentCopy;
  54317. var idx = this.nbParticles;
  54318. for (var i = 0; i < nb; i++) {
  54319. var currentPos = this._positions.length;
  54320. currentCopy = this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, meshNor, this._normals, idx, i, options);
  54321. if (this._updatable) {
  54322. sp = this._addParticle(idx, currentPos, modelShape, this._shapeCounter, i, bbInfo);
  54323. sp.position.copyFrom(currentCopy.position);
  54324. sp.rotation.copyFrom(currentCopy.rotation);
  54325. if (currentCopy.rotationQuaternion) {
  54326. sp.rotationQuaternion.copyFrom(currentCopy.rotationQuaternion);
  54327. }
  54328. if (currentCopy.color) {
  54329. sp.color.copyFrom(currentCopy.color);
  54330. }
  54331. sp.scaling.copyFrom(currentCopy.scaling);
  54332. sp.uvs.copyFrom(currentCopy.uvs);
  54333. }
  54334. this._index += shape.length;
  54335. idx++;
  54336. }
  54337. this.nbParticles += nb;
  54338. this._shapeCounter++;
  54339. return this._shapeCounter - 1;
  54340. };
  54341. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  54342. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  54343. this._resetCopy();
  54344. if (particle._model._positionFunction) {
  54345. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  54346. }
  54347. if (this._copy.rotationQuaternion) {
  54348. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  54349. }
  54350. else {
  54351. this._yaw = this._copy.rotation.y;
  54352. this._pitch = this._copy.rotation.x;
  54353. this._roll = this._copy.rotation.z;
  54354. this._quaternionRotationYPR();
  54355. }
  54356. this._quaternionToRotationMatrix();
  54357. this._shape = particle._model._shape;
  54358. for (var pt = 0; pt < this._shape.length; pt++) {
  54359. this._vertex.x = this._shape[pt].x;
  54360. this._vertex.y = this._shape[pt].y;
  54361. this._vertex.z = this._shape[pt].z;
  54362. if (particle._model._vertexFunction) {
  54363. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  54364. }
  54365. this._vertex.x *= this._copy.scaling.x;
  54366. this._vertex.y *= this._copy.scaling.y;
  54367. this._vertex.z *= this._copy.scaling.z;
  54368. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  54369. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  54370. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  54371. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  54372. }
  54373. particle.position.x = 0.0;
  54374. particle.position.y = 0.0;
  54375. particle.position.z = 0.0;
  54376. particle.rotation.x = 0.0;
  54377. particle.rotation.y = 0.0;
  54378. particle.rotation.z = 0.0;
  54379. particle.rotationQuaternion = null;
  54380. particle.scaling.x = 1.0;
  54381. particle.scaling.y = 1.0;
  54382. particle.scaling.z = 1.0;
  54383. };
  54384. /**
  54385. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  54386. * Returns the SPS.
  54387. */
  54388. SolidParticleSystem.prototype.rebuildMesh = function () {
  54389. for (var p = 0; p < this.particles.length; p++) {
  54390. this._rebuildParticle(this.particles[p]);
  54391. }
  54392. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  54393. return this;
  54394. };
  54395. /**
  54396. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  54397. * This method calls `updateParticle()` for each particle of the SPS.
  54398. * For an animated SPS, it is usually called within the render loop.
  54399. * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_
  54400. * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_
  54401. * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_
  54402. * Returns the SPS.
  54403. */
  54404. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  54405. if (start === void 0) { start = 0; }
  54406. if (end === void 0) { end = this.nbParticles - 1; }
  54407. if (update === void 0) { update = true; }
  54408. if (!this._updatable) {
  54409. return;
  54410. }
  54411. // custom beforeUpdate
  54412. this.beforeUpdateParticles(start, end, update);
  54413. this._cam_axisX.x = 1.0;
  54414. this._cam_axisX.y = 0.0;
  54415. this._cam_axisX.z = 0.0;
  54416. this._cam_axisY.x = 0.0;
  54417. this._cam_axisY.y = 1.0;
  54418. this._cam_axisY.z = 0.0;
  54419. this._cam_axisZ.x = 0.0;
  54420. this._cam_axisZ.y = 0.0;
  54421. this._cam_axisZ.z = 1.0;
  54422. // if the particles will always face the camera
  54423. if (this.billboard) {
  54424. this.mesh.computeWorldMatrix(true);
  54425. // compute the camera position and un-rotate it by the current mesh rotation
  54426. if (this.mesh._worldMatrix.decompose(this._scale, this._quaternion, this._translation)) {
  54427. this._quaternionToRotationMatrix();
  54428. this._rotMatrix.invertToRef(this._invertMatrix);
  54429. this._camera._currentTarget.subtractToRef(this._camera.globalPosition, this._camDir);
  54430. BABYLON.Vector3.TransformNormalToRef(this._camDir, this._invertMatrix, this._cam_axisZ);
  54431. this._cam_axisZ.normalize();
  54432. // same for camera up vector extracted from the cam view matrix
  54433. var view = this._camera.getViewMatrix(true);
  54434. BABYLON.Vector3.TransformNormalFromFloatsToRef(view.m[1], view.m[5], view.m[9], this._invertMatrix, this._cam_axisY);
  54435. BABYLON.Vector3.CrossToRef(this._cam_axisY, this._cam_axisZ, this._cam_axisX);
  54436. this._cam_axisY.normalize();
  54437. this._cam_axisX.normalize();
  54438. }
  54439. }
  54440. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  54441. var idx = 0; // current position index in the global array positions32
  54442. var index = 0; // position start index in the global array positions32 of the current particle
  54443. var colidx = 0; // current color index in the global array colors32
  54444. var colorIndex = 0; // color start index in the global array colors32 of the current particle
  54445. var uvidx = 0; // current uv index in the global array uvs32
  54446. var uvIndex = 0; // uv start index in the global array uvs32 of the current particle
  54447. var pt = 0; // current index in the particle model shape
  54448. if (this.mesh.isFacetDataEnabled) {
  54449. this._computeBoundingBox = true;
  54450. }
  54451. end = (end >= this.nbParticles) ? this.nbParticles - 1 : end;
  54452. if (this._computeBoundingBox) {
  54453. if (start == 0 && end == this.nbParticles - 1) {
  54454. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  54455. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  54456. }
  54457. else {
  54458. this._minimum.copyFrom(this.mesh._boundingInfo.boundingBox.minimum);
  54459. this._maximum.copyFrom(this.mesh._boundingInfo.boundingBox.maximum);
  54460. }
  54461. }
  54462. // particle loop
  54463. index = this.particles[start]._pos;
  54464. var vpos = (index / 3) | 0;
  54465. colorIndex = vpos * 4;
  54466. uvIndex = vpos * 2;
  54467. for (var p = start; p <= end; p++) {
  54468. this._particle = this.particles[p];
  54469. this._shape = this._particle._model._shape;
  54470. this._shapeUV = this._particle._model._shapeUV;
  54471. // call to custom user function to update the particle properties
  54472. this.updateParticle(this._particle);
  54473. if (this._particle.isVisible) {
  54474. // particle rotation matrix
  54475. if (this.billboard) {
  54476. this._particle.rotation.x = 0.0;
  54477. this._particle.rotation.y = 0.0;
  54478. }
  54479. if (this._computeParticleRotation || this.billboard) {
  54480. if (this._particle.rotationQuaternion) {
  54481. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  54482. }
  54483. else {
  54484. this._yaw = this._particle.rotation.y;
  54485. this._pitch = this._particle.rotation.x;
  54486. this._roll = this._particle.rotation.z;
  54487. this._quaternionRotationYPR();
  54488. }
  54489. this._quaternionToRotationMatrix();
  54490. }
  54491. // particle vertex loop
  54492. for (pt = 0; pt < this._shape.length; pt++) {
  54493. idx = index + pt * 3;
  54494. colidx = colorIndex + pt * 4;
  54495. uvidx = uvIndex + pt * 2;
  54496. this._vertex.x = this._shape[pt].x;
  54497. this._vertex.y = this._shape[pt].y;
  54498. this._vertex.z = this._shape[pt].z;
  54499. if (this._computeParticleVertex) {
  54500. this.updateParticleVertex(this._particle, this._vertex, pt);
  54501. }
  54502. // positions
  54503. this._vertex.x *= this._particle.scaling.x;
  54504. this._vertex.y *= this._particle.scaling.y;
  54505. this._vertex.z *= this._particle.scaling.z;
  54506. 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];
  54507. 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;
  54508. 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;
  54509. 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;
  54510. 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;
  54511. 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;
  54512. 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;
  54513. if (this._computeBoundingBox) {
  54514. if (this._positions32[idx] < this._minimum.x) {
  54515. this._minimum.x = this._positions32[idx];
  54516. }
  54517. if (this._positions32[idx] > this._maximum.x) {
  54518. this._maximum.x = this._positions32[idx];
  54519. }
  54520. if (this._positions32[idx + 1] < this._minimum.y) {
  54521. this._minimum.y = this._positions32[idx + 1];
  54522. }
  54523. if (this._positions32[idx + 1] > this._maximum.y) {
  54524. this._maximum.y = this._positions32[idx + 1];
  54525. }
  54526. if (this._positions32[idx + 2] < this._minimum.z) {
  54527. this._minimum.z = this._positions32[idx + 2];
  54528. }
  54529. if (this._positions32[idx + 2] > this._maximum.z) {
  54530. this._maximum.z = this._positions32[idx + 2];
  54531. }
  54532. }
  54533. // normals : if the particles can't be morphed then just rotate the normals, what is much more faster than ComputeNormals()
  54534. if (!this._computeParticleVertex) {
  54535. this._normal.x = this._fixedNormal32[idx];
  54536. this._normal.y = this._fixedNormal32[idx + 1];
  54537. this._normal.z = this._fixedNormal32[idx + 2];
  54538. 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]);
  54539. 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]);
  54540. 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]);
  54541. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  54542. 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;
  54543. 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;
  54544. }
  54545. if (this._computeParticleColor) {
  54546. this._colors32[colidx] = this._particle.color.r;
  54547. this._colors32[colidx + 1] = this._particle.color.g;
  54548. this._colors32[colidx + 2] = this._particle.color.b;
  54549. this._colors32[colidx + 3] = this._particle.color.a;
  54550. }
  54551. if (this._computeParticleTexture) {
  54552. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  54553. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  54554. }
  54555. }
  54556. }
  54557. else {
  54558. for (pt = 0; pt < this._shape.length; pt++) {
  54559. idx = index + pt * 3;
  54560. colidx = colorIndex + pt * 4;
  54561. uvidx = uvIndex + pt * 2;
  54562. this._positions32[idx] = this._camera.position.x;
  54563. this._positions32[idx + 1] = this._camera.position.y;
  54564. this._positions32[idx + 2] = this._camera.position.z;
  54565. this._normals32[idx] = 0.0;
  54566. this._normals32[idx + 1] = 0.0;
  54567. this._normals32[idx + 2] = 0.0;
  54568. if (this._computeParticleColor) {
  54569. this._colors32[colidx] = this._particle.color.r;
  54570. this._colors32[colidx + 1] = this._particle.color.g;
  54571. this._colors32[colidx + 2] = this._particle.color.b;
  54572. this._colors32[colidx + 3] = this._particle.color.a;
  54573. }
  54574. if (this._computeParticleTexture) {
  54575. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  54576. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  54577. }
  54578. }
  54579. }
  54580. // if the particle intersections must be computed : update the bbInfo
  54581. if (this._particlesIntersect) {
  54582. var bInfo = this._particle._boundingInfo;
  54583. var bBox = bInfo.boundingBox;
  54584. var bSphere = bInfo.boundingSphere;
  54585. if (!this._bSphereOnly) {
  54586. // place, scale and rotate the particle bbox within the SPS local system, then update it
  54587. for (var b = 0; b < bBox.vectors.length; b++) {
  54588. this._vertex.x = this._particle._modelBoundingInfo.boundingBox.vectors[b].x * this._particle.scaling.x;
  54589. this._vertex.y = this._particle._modelBoundingInfo.boundingBox.vectors[b].y * this._particle.scaling.y;
  54590. this._vertex.z = this._particle._modelBoundingInfo.boundingBox.vectors[b].z * this._particle.scaling.z;
  54591. 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];
  54592. 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;
  54593. 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;
  54594. 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;
  54595. 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;
  54596. 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;
  54597. 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;
  54598. }
  54599. bBox._update(this.mesh._worldMatrix);
  54600. }
  54601. // place and scale the particle bouding sphere in the SPS local system, then update it
  54602. this._minBbox.x = this._particle._modelBoundingInfo.minimum.x * this._particle.scaling.x;
  54603. this._minBbox.y = this._particle._modelBoundingInfo.minimum.y * this._particle.scaling.y;
  54604. this._minBbox.z = this._particle._modelBoundingInfo.minimum.z * this._particle.scaling.z;
  54605. this._maxBbox.x = this._particle._modelBoundingInfo.maximum.x * this._particle.scaling.x;
  54606. this._maxBbox.y = this._particle._modelBoundingInfo.maximum.y * this._particle.scaling.y;
  54607. this._maxBbox.z = this._particle._modelBoundingInfo.maximum.z * this._particle.scaling.z;
  54608. bSphere.center.x = this._particle.position.x + (this._minBbox.x + this._maxBbox.x) * 0.5;
  54609. bSphere.center.y = this._particle.position.y + (this._minBbox.y + this._maxBbox.y) * 0.5;
  54610. bSphere.center.z = this._particle.position.z + (this._minBbox.z + this._maxBbox.z) * 0.5;
  54611. 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));
  54612. bSphere._update(this.mesh._worldMatrix);
  54613. }
  54614. // increment indexes for the next particle
  54615. index = idx + 3;
  54616. colorIndex = colidx + 4;
  54617. uvIndex = uvidx + 2;
  54618. }
  54619. // if the VBO must be updated
  54620. if (update) {
  54621. if (this._computeParticleColor) {
  54622. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  54623. }
  54624. if (this._computeParticleTexture) {
  54625. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  54626. }
  54627. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  54628. if (!this.mesh.areNormalsFrozen || this.mesh.isFacetDataEnabled) {
  54629. if (this._computeParticleVertex || this.mesh.isFacetDataEnabled) {
  54630. // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]
  54631. var params = this.mesh.isFacetDataEnabled ? this.mesh.getFacetDataParameters() : null;
  54632. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices, this._normals32, params);
  54633. for (var i = 0; i < this._normals32.length; i++) {
  54634. this._fixedNormal32[i] = this._normals32[i];
  54635. }
  54636. }
  54637. if (!this.mesh.areNormalsFrozen) {
  54638. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  54639. }
  54640. }
  54641. }
  54642. if (this._computeBoundingBox) {
  54643. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  54644. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  54645. }
  54646. this.afterUpdateParticles(start, end, update);
  54647. return this;
  54648. };
  54649. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  54650. this._halfroll = this._roll * 0.5;
  54651. this._halfpitch = this._pitch * 0.5;
  54652. this._halfyaw = this._yaw * 0.5;
  54653. this._sinRoll = Math.sin(this._halfroll);
  54654. this._cosRoll = Math.cos(this._halfroll);
  54655. this._sinPitch = Math.sin(this._halfpitch);
  54656. this._cosPitch = Math.cos(this._halfpitch);
  54657. this._sinYaw = Math.sin(this._halfyaw);
  54658. this._cosYaw = Math.cos(this._halfyaw);
  54659. this._quaternion.x = (this._cosYaw * this._sinPitch * this._cosRoll) + (this._sinYaw * this._cosPitch * this._sinRoll);
  54660. this._quaternion.y = (this._sinYaw * this._cosPitch * this._cosRoll) - (this._cosYaw * this._sinPitch * this._sinRoll);
  54661. this._quaternion.z = (this._cosYaw * this._cosPitch * this._sinRoll) - (this._sinYaw * this._sinPitch * this._cosRoll);
  54662. this._quaternion.w = (this._cosYaw * this._cosPitch * this._cosRoll) + (this._sinYaw * this._sinPitch * this._sinRoll);
  54663. };
  54664. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  54665. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  54666. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  54667. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  54668. this._rotMatrix.m[3] = 0;
  54669. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  54670. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  54671. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  54672. this._rotMatrix.m[7] = 0;
  54673. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  54674. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  54675. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  54676. this._rotMatrix.m[11] = 0;
  54677. this._rotMatrix.m[12] = 0;
  54678. this._rotMatrix.m[13] = 0;
  54679. this._rotMatrix.m[14] = 0;
  54680. this._rotMatrix.m[15] = 1.0;
  54681. };
  54682. /**
  54683. * Disposes the SPS.
  54684. * Returns nothing.
  54685. */
  54686. SolidParticleSystem.prototype.dispose = function () {
  54687. this.mesh.dispose();
  54688. this.vars = null;
  54689. // drop references to internal big arrays for the GC
  54690. this._positions = null;
  54691. this._indices = null;
  54692. this._normals = null;
  54693. this._uvs = null;
  54694. this._colors = null;
  54695. this._positions32 = null;
  54696. this._normals32 = null;
  54697. this._fixedNormal32 = null;
  54698. this._uvs32 = null;
  54699. this._colors32 = null;
  54700. this.pickedParticles = null;
  54701. };
  54702. /**
  54703. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  54704. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  54705. * Returns the SPS.
  54706. */
  54707. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  54708. if (!this._isVisibilityBoxLocked) {
  54709. this.mesh.refreshBoundingInfo();
  54710. }
  54711. return this;
  54712. };
  54713. /**
  54714. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  54715. * @param size the size (float) of the visibility box
  54716. * note : this doesn't lock the SPS mesh bounding box.
  54717. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  54718. */
  54719. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  54720. var vis = size / 2;
  54721. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  54722. };
  54723. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  54724. // getter and setter
  54725. get: function () {
  54726. return this._alwaysVisible;
  54727. },
  54728. /**
  54729. * Sets the SPS as always visible or not
  54730. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  54731. */
  54732. set: function (val) {
  54733. this._alwaysVisible = val;
  54734. this.mesh.alwaysSelectAsActiveMesh = val;
  54735. },
  54736. enumerable: true,
  54737. configurable: true
  54738. });
  54739. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  54740. get: function () {
  54741. return this._isVisibilityBoxLocked;
  54742. },
  54743. /**
  54744. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  54745. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  54746. */
  54747. set: function (val) {
  54748. this._isVisibilityBoxLocked = val;
  54749. this.mesh.getBoundingInfo().isLocked = val;
  54750. },
  54751. enumerable: true,
  54752. configurable: true
  54753. });
  54754. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  54755. // getters
  54756. get: function () {
  54757. return this._computeParticleRotation;
  54758. },
  54759. // Optimizer setters
  54760. /**
  54761. * Tells to `setParticles()` to compute the particle rotations or not.
  54762. * Default value : true. The SPS is faster when it's set to false.
  54763. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  54764. */
  54765. set: function (val) {
  54766. this._computeParticleRotation = val;
  54767. },
  54768. enumerable: true,
  54769. configurable: true
  54770. });
  54771. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  54772. get: function () {
  54773. return this._computeParticleColor;
  54774. },
  54775. /**
  54776. * Tells to `setParticles()` to compute the particle colors or not.
  54777. * Default value : true. The SPS is faster when it's set to false.
  54778. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  54779. */
  54780. set: function (val) {
  54781. this._computeParticleColor = val;
  54782. },
  54783. enumerable: true,
  54784. configurable: true
  54785. });
  54786. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  54787. get: function () {
  54788. return this._computeParticleTexture;
  54789. },
  54790. /**
  54791. * Tells to `setParticles()` to compute the particle textures or not.
  54792. * Default value : true. The SPS is faster when it's set to false.
  54793. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  54794. */
  54795. set: function (val) {
  54796. this._computeParticleTexture = val;
  54797. },
  54798. enumerable: true,
  54799. configurable: true
  54800. });
  54801. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  54802. get: function () {
  54803. return this._computeParticleVertex;
  54804. },
  54805. /**
  54806. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  54807. * Default value : false. The SPS is faster when it's set to false.
  54808. * Note : the particle custom vertex positions aren't stored values.
  54809. */
  54810. set: function (val) {
  54811. this._computeParticleVertex = val;
  54812. },
  54813. enumerable: true,
  54814. configurable: true
  54815. });
  54816. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  54817. get: function () {
  54818. return this._computeBoundingBox;
  54819. },
  54820. /**
  54821. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  54822. */
  54823. set: function (val) {
  54824. this._computeBoundingBox = val;
  54825. },
  54826. enumerable: true,
  54827. configurable: true
  54828. });
  54829. // =======================================================================
  54830. // Particle behavior logic
  54831. // these following methods may be overwritten by the user to fit his needs
  54832. /**
  54833. * This function does nothing. It may be overwritten to set all the particle first values.
  54834. * The SPS doesn't call this function, you may have to call it by your own.
  54835. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  54836. */
  54837. SolidParticleSystem.prototype.initParticles = function () {
  54838. };
  54839. /**
  54840. * This function does nothing. It may be overwritten to recycle a particle.
  54841. * The SPS doesn't call this function, you may have to call it by your own.
  54842. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  54843. */
  54844. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  54845. return particle;
  54846. };
  54847. /**
  54848. * Updates a particle : this function should be overwritten by the user.
  54849. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  54850. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  54851. * ex : just set a particle position or velocity and recycle conditions
  54852. */
  54853. SolidParticleSystem.prototype.updateParticle = function (particle) {
  54854. return particle;
  54855. };
  54856. /**
  54857. * Updates a vertex of a particle : it can be overwritten by the user.
  54858. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  54859. * @param particle the current particle
  54860. * @param vertex the current index of the current particle
  54861. * @param pt the index of the current vertex in the particle shape
  54862. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape
  54863. * ex : just set a vertex particle position
  54864. */
  54865. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  54866. return vertex;
  54867. };
  54868. /**
  54869. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  54870. * This does nothing and may be overwritten by the user.
  54871. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  54872. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  54873. * @param update the boolean update value actually passed to setParticles()
  54874. */
  54875. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  54876. };
  54877. /**
  54878. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  54879. * This will be passed three parameters.
  54880. * This does nothing and may be overwritten by the user.
  54881. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  54882. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  54883. * @param update the boolean update value actually passed to setParticles()
  54884. */
  54885. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  54886. };
  54887. return SolidParticleSystem;
  54888. }());
  54889. BABYLON.SolidParticleSystem = SolidParticleSystem;
  54890. })(BABYLON || (BABYLON = {}));
  54891. //# sourceMappingURL=babylon.solidParticleSystem.js.map
  54892. var BABYLON;
  54893. (function (BABYLON) {
  54894. var Internals;
  54895. (function (Internals) {
  54896. var FileFaceOrientation = (function () {
  54897. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  54898. this.name = name;
  54899. this.worldAxisForNormal = worldAxisForNormal;
  54900. this.worldAxisForFileX = worldAxisForFileX;
  54901. this.worldAxisForFileY = worldAxisForFileY;
  54902. }
  54903. return FileFaceOrientation;
  54904. }());
  54905. ;
  54906. /**
  54907. * Helper class dealing with the extraction of spherical polynomial dataArray
  54908. * from a cube map.
  54909. */
  54910. var CubeMapToSphericalPolynomialTools = (function () {
  54911. function CubeMapToSphericalPolynomialTools() {
  54912. }
  54913. /**
  54914. * Converts a cubemap to the according Spherical Polynomial data.
  54915. * This extracts the first 3 orders only as they are the only one used in the lighting.
  54916. *
  54917. * @param cubeInfo The Cube map to extract the information from.
  54918. * @return The Spherical Polynomial data.
  54919. */
  54920. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  54921. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  54922. var totalSolidAngle = 0.0;
  54923. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  54924. var du = 2.0 / cubeInfo.size;
  54925. var dv = du;
  54926. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  54927. var minUV = du * 0.5 - 1.0;
  54928. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  54929. var fileFace = this.FileFaces[faceIndex];
  54930. var dataArray = cubeInfo[fileFace.name];
  54931. var v = minUV;
  54932. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  54933. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  54934. // Because SP is still linear, so summation is fine in that basis.
  54935. for (var y = 0; y < cubeInfo.size; y++) {
  54936. var u = minUV;
  54937. for (var x = 0; x < cubeInfo.size; x++) {
  54938. // World direction (not normalised)
  54939. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  54940. worldDirection.normalize();
  54941. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  54942. if (1) {
  54943. var r = dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0];
  54944. var g = dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1];
  54945. var b = dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2];
  54946. var color = new BABYLON.Color3(r, g, b);
  54947. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  54948. }
  54949. else {
  54950. if (faceIndex == 0) {
  54951. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 1;
  54952. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 0;
  54953. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 0;
  54954. }
  54955. else if (faceIndex == 1) {
  54956. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 0;
  54957. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 1;
  54958. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 0;
  54959. }
  54960. else if (faceIndex == 2) {
  54961. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 0;
  54962. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 0;
  54963. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 1;
  54964. }
  54965. else if (faceIndex == 3) {
  54966. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 1;
  54967. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 1;
  54968. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 0;
  54969. }
  54970. else if (faceIndex == 4) {
  54971. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 1;
  54972. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 0;
  54973. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 1;
  54974. }
  54975. else if (faceIndex == 5) {
  54976. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 0;
  54977. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 1;
  54978. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 1;
  54979. }
  54980. 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]);
  54981. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  54982. }
  54983. totalSolidAngle += deltaSolidAngle;
  54984. u += du;
  54985. }
  54986. v += dv;
  54987. }
  54988. }
  54989. var correctSolidAngle = 4.0 * Math.PI; // Solid angle for entire sphere is 4*pi
  54990. var correction = correctSolidAngle / totalSolidAngle;
  54991. sphericalHarmonics.scale(correction);
  54992. // Additionally scale by pi -- audit needed
  54993. sphericalHarmonics.scale(1.0 / Math.PI);
  54994. return BABYLON.SphericalPolynomial.getSphericalPolynomialFromHarmonics(sphericalHarmonics);
  54995. };
  54996. return CubeMapToSphericalPolynomialTools;
  54997. }());
  54998. CubeMapToSphericalPolynomialTools.FileFaces = [
  54999. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  55000. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  55001. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  55002. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  55003. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  55004. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  55005. ];
  55006. Internals.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  55007. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  55008. })(BABYLON || (BABYLON = {}));
  55009. //# sourceMappingURL=babylon.tools.cubemapToSphericalPolynomial.js.map
  55010. var BABYLON;
  55011. (function (BABYLON) {
  55012. var Internals;
  55013. (function (Internals) {
  55014. /**
  55015. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  55016. */
  55017. var PanoramaToCubeMapTools = (function () {
  55018. function PanoramaToCubeMapTools() {
  55019. }
  55020. /**
  55021. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  55022. *
  55023. * @param float32Array The source data.
  55024. * @param inputWidth The width of the input panorama.
  55025. * @param inputhHeight The height of the input panorama.
  55026. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  55027. * @return The cubemap data
  55028. */
  55029. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  55030. if (!float32Array) {
  55031. throw "ConvertPanoramaToCubemap: input cannot be null";
  55032. }
  55033. if (float32Array.length != inputWidth * inputHeight * 3) {
  55034. throw "ConvertPanoramaToCubemap: input size is wrong";
  55035. }
  55036. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  55037. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  55038. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  55039. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  55040. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  55041. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  55042. return {
  55043. front: textureFront,
  55044. back: textureBack,
  55045. left: textureLeft,
  55046. right: textureRight,
  55047. up: textureUp,
  55048. down: textureDown,
  55049. size: size
  55050. };
  55051. };
  55052. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  55053. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  55054. var textureArray = new Float32Array(buffer);
  55055. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  55056. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  55057. var dy = 1 / texSize;
  55058. var fy = 0;
  55059. for (var y = 0; y < texSize; y++) {
  55060. var xv1 = faceData[0];
  55061. var xv2 = faceData[2];
  55062. for (var x = 0; x < texSize; x++) {
  55063. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  55064. v.normalize();
  55065. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  55066. // 3 channels per pixels
  55067. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  55068. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  55069. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  55070. xv1 = xv1.add(rotDX1);
  55071. xv2 = xv2.add(rotDX2);
  55072. }
  55073. fy += dy;
  55074. }
  55075. return textureArray;
  55076. };
  55077. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  55078. var theta = Math.atan2(vDir.z, vDir.x);
  55079. var phi = Math.acos(vDir.y);
  55080. while (theta < -Math.PI)
  55081. theta += 2 * Math.PI;
  55082. while (theta > Math.PI)
  55083. theta -= 2 * Math.PI;
  55084. var dx = theta / Math.PI;
  55085. var dy = phi / Math.PI;
  55086. // recenter.
  55087. dx = dx * 0.5 + 0.5;
  55088. var px = Math.round(dx * inputWidth);
  55089. if (px < 0)
  55090. px = 0;
  55091. else if (px >= inputWidth)
  55092. px = inputWidth - 1;
  55093. var py = Math.round(dy * inputHeight);
  55094. if (py < 0)
  55095. py = 0;
  55096. else if (py >= inputHeight)
  55097. py = inputHeight - 1;
  55098. var inputY = (inputHeight - py - 1);
  55099. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  55100. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  55101. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  55102. return {
  55103. r: r,
  55104. g: g,
  55105. b: b
  55106. };
  55107. };
  55108. return PanoramaToCubeMapTools;
  55109. }());
  55110. PanoramaToCubeMapTools.FACE_FRONT = [
  55111. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  55112. new BABYLON.Vector3(1.0, -1.0, -1.0),
  55113. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  55114. new BABYLON.Vector3(1.0, 1.0, -1.0)
  55115. ];
  55116. PanoramaToCubeMapTools.FACE_BACK = [
  55117. new BABYLON.Vector3(1.0, -1.0, 1.0),
  55118. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  55119. new BABYLON.Vector3(1.0, 1.0, 1.0),
  55120. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  55121. ];
  55122. PanoramaToCubeMapTools.FACE_RIGHT = [
  55123. new BABYLON.Vector3(1.0, -1.0, -1.0),
  55124. new BABYLON.Vector3(1.0, -1.0, 1.0),
  55125. new BABYLON.Vector3(1.0, 1.0, -1.0),
  55126. new BABYLON.Vector3(1.0, 1.0, 1.0)
  55127. ];
  55128. PanoramaToCubeMapTools.FACE_LEFT = [
  55129. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  55130. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  55131. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  55132. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  55133. ];
  55134. PanoramaToCubeMapTools.FACE_DOWN = [
  55135. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  55136. new BABYLON.Vector3(1.0, 1.0, -1.0),
  55137. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  55138. new BABYLON.Vector3(1.0, 1.0, 1.0)
  55139. ];
  55140. PanoramaToCubeMapTools.FACE_UP = [
  55141. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  55142. new BABYLON.Vector3(1.0, -1.0, 1.0),
  55143. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  55144. new BABYLON.Vector3(1.0, -1.0, -1.0)
  55145. ];
  55146. Internals.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  55147. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  55148. })(BABYLON || (BABYLON = {}));
  55149. //# sourceMappingURL=babylon.tools.panoramaToCubemap.js.map
  55150. var BABYLON;
  55151. (function (BABYLON) {
  55152. var Internals;
  55153. (function (Internals) {
  55154. ;
  55155. /**
  55156. * This groups tools to convert HDR texture to native colors array.
  55157. */
  55158. var HDRTools = (function () {
  55159. function HDRTools() {
  55160. }
  55161. HDRTools.Ldexp = function (mantissa, exponent) {
  55162. if (exponent > 1023) {
  55163. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  55164. }
  55165. if (exponent < -1074) {
  55166. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  55167. }
  55168. return mantissa * Math.pow(2, exponent);
  55169. };
  55170. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  55171. if (exponent > 0) {
  55172. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  55173. float32array[index + 0] = red * exponent;
  55174. float32array[index + 1] = green * exponent;
  55175. float32array[index + 2] = blue * exponent;
  55176. }
  55177. else {
  55178. float32array[index + 0] = 0;
  55179. float32array[index + 1] = 0;
  55180. float32array[index + 2] = 0;
  55181. }
  55182. };
  55183. HDRTools.readStringLine = function (uint8array, startIndex) {
  55184. var line = "";
  55185. var character = "";
  55186. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  55187. character = String.fromCharCode(uint8array[i]);
  55188. if (character == "\n") {
  55189. break;
  55190. }
  55191. line += character;
  55192. }
  55193. return line;
  55194. };
  55195. /**
  55196. * Reads header information from an RGBE texture stored in a native array.
  55197. * More information on this format are available here:
  55198. * https://en.wikipedia.org/wiki/RGBE_image_format
  55199. *
  55200. * @param uint8array The binary file stored in native array.
  55201. * @return The header information.
  55202. */
  55203. HDRTools.RGBE_ReadHeader = function (uint8array) {
  55204. var height = 0;
  55205. var width = 0;
  55206. var line = this.readStringLine(uint8array, 0);
  55207. if (line[0] != '#' || line[1] != '?') {
  55208. throw "Bad HDR Format.";
  55209. }
  55210. var endOfHeader = false;
  55211. var findFormat = false;
  55212. var lineIndex = 0;
  55213. do {
  55214. lineIndex += (line.length + 1);
  55215. line = this.readStringLine(uint8array, lineIndex);
  55216. if (line == "FORMAT=32-bit_rle_rgbe") {
  55217. findFormat = true;
  55218. }
  55219. else if (line.length == 0) {
  55220. endOfHeader = true;
  55221. }
  55222. } while (!endOfHeader);
  55223. if (!findFormat) {
  55224. throw "HDR Bad header format, unsupported FORMAT";
  55225. }
  55226. lineIndex += (line.length + 1);
  55227. line = this.readStringLine(uint8array, lineIndex);
  55228. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  55229. var match = sizeRegexp.exec(line);
  55230. // TODO. Support +Y and -X if needed.
  55231. if (match.length < 3) {
  55232. throw "HDR Bad header format, no size";
  55233. }
  55234. width = parseInt(match[2]);
  55235. height = parseInt(match[1]);
  55236. if (width < 8 || width > 0x7fff) {
  55237. throw "HDR Bad header format, unsupported size";
  55238. }
  55239. lineIndex += (line.length + 1);
  55240. return {
  55241. height: height,
  55242. width: width,
  55243. dataPosition: lineIndex
  55244. };
  55245. };
  55246. /**
  55247. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  55248. * This RGBE texture needs to store the information as a panorama.
  55249. *
  55250. * More information on this format are available here:
  55251. * https://en.wikipedia.org/wiki/RGBE_image_format
  55252. *
  55253. * @param buffer The binary file stored in an array buffer.
  55254. * @param size The expected size of the extracted cubemap.
  55255. * @return The Cube Map information.
  55256. */
  55257. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  55258. var uint8array = new Uint8Array(buffer);
  55259. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  55260. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  55261. var cubeMapData = Internals.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  55262. return cubeMapData;
  55263. };
  55264. /**
  55265. * Returns the pixels data extracted from an RGBE texture.
  55266. * This pixels will be stored left to right up to down in the R G B order in one array.
  55267. *
  55268. * More information on this format are available here:
  55269. * https://en.wikipedia.org/wiki/RGBE_image_format
  55270. *
  55271. * @param uint8array The binary file stored in an array buffer.
  55272. * @param hdrInfo The header information of the file.
  55273. * @return The pixels data in RGB right to left up to down order.
  55274. */
  55275. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  55276. // Keep for multi format supports.
  55277. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  55278. };
  55279. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  55280. var num_scanlines = hdrInfo.height;
  55281. var scanline_width = hdrInfo.width;
  55282. var a, b, c, d, count;
  55283. var dataIndex = hdrInfo.dataPosition;
  55284. var index = 0, endIndex = 0, i = 0;
  55285. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  55286. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  55287. // 3 channels of 4 bytes per pixel in float.
  55288. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  55289. var resultArray = new Float32Array(resultBuffer);
  55290. // read in each successive scanline
  55291. while (num_scanlines > 0) {
  55292. a = uint8array[dataIndex++];
  55293. b = uint8array[dataIndex++];
  55294. c = uint8array[dataIndex++];
  55295. d = uint8array[dataIndex++];
  55296. if (a != 2 || b != 2 || (c & 0x80)) {
  55297. // this file is not run length encoded
  55298. throw "HDR Bad header format, not RLE";
  55299. }
  55300. if (((c << 8) | d) != scanline_width) {
  55301. throw "HDR Bad header format, wrong scan line width";
  55302. }
  55303. index = 0;
  55304. // read each of the four channels for the scanline into the buffer
  55305. for (i = 0; i < 4; i++) {
  55306. endIndex = (i + 1) * scanline_width;
  55307. while (index < endIndex) {
  55308. a = uint8array[dataIndex++];
  55309. b = uint8array[dataIndex++];
  55310. if (a > 128) {
  55311. // a run of the same value
  55312. count = a - 128;
  55313. if ((count == 0) || (count > endIndex - index)) {
  55314. throw "HDR Bad Format, bad scanline data (run)";
  55315. }
  55316. while (count-- > 0) {
  55317. scanLineArray[index++] = b;
  55318. }
  55319. }
  55320. else {
  55321. // a non-run
  55322. count = a;
  55323. if ((count == 0) || (count > endIndex - index)) {
  55324. throw "HDR Bad Format, bad scanline data (non-run)";
  55325. }
  55326. scanLineArray[index++] = b;
  55327. if (--count > 0) {
  55328. for (var j = 0; j < count; j++) {
  55329. scanLineArray[index++] = uint8array[dataIndex++];
  55330. }
  55331. }
  55332. }
  55333. }
  55334. }
  55335. // now convert data from buffer into floats
  55336. for (i = 0; i < scanline_width; i++) {
  55337. a = scanLineArray[i];
  55338. b = scanLineArray[i + scanline_width];
  55339. c = scanLineArray[i + 2 * scanline_width];
  55340. d = scanLineArray[i + 3 * scanline_width];
  55341. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  55342. }
  55343. num_scanlines--;
  55344. }
  55345. return resultArray;
  55346. };
  55347. return HDRTools;
  55348. }());
  55349. Internals.HDRTools = HDRTools;
  55350. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  55351. })(BABYLON || (BABYLON = {}));
  55352. //# sourceMappingURL=babylon.tools.hdr.js.map
  55353. //_______________________________________________________________
  55354. // Extracted from CubeMapGen:
  55355. // https://code.google.com/archive/p/cubemapgen/
  55356. //
  55357. // Following https://seblagarde.wordpress.com/2012/06/10/amd-cubemapgen-for-physically-based-rendering/
  55358. //_______________________________________________________________
  55359. var BABYLON;
  55360. (function (BABYLON) {
  55361. var Internals;
  55362. (function (Internals) {
  55363. /**
  55364. * The bounding box information used during the conversion process.
  55365. */
  55366. var CMGBoundinBox = (function () {
  55367. function CMGBoundinBox() {
  55368. this.min = new BABYLON.Vector3(0, 0, 0);
  55369. this.max = new BABYLON.Vector3(0, 0, 0);
  55370. this.clear();
  55371. }
  55372. CMGBoundinBox.prototype.clear = function () {
  55373. this.min.x = CMGBoundinBox.MAX;
  55374. this.min.y = CMGBoundinBox.MAX;
  55375. this.min.z = CMGBoundinBox.MAX;
  55376. this.max.x = CMGBoundinBox.MIN;
  55377. this.max.y = CMGBoundinBox.MIN;
  55378. this.max.z = CMGBoundinBox.MIN;
  55379. };
  55380. CMGBoundinBox.prototype.augment = function (x, y, z) {
  55381. this.min.x = Math.min(this.min.x, x);
  55382. this.min.y = Math.min(this.min.y, y);
  55383. this.min.z = Math.min(this.min.z, z);
  55384. this.max.x = Math.max(this.max.x, x);
  55385. this.max.y = Math.max(this.max.y, y);
  55386. this.max.z = Math.max(this.max.z, z);
  55387. };
  55388. CMGBoundinBox.prototype.clampMin = function (x, y, z) {
  55389. this.min.x = Math.max(this.min.x, x);
  55390. this.min.y = Math.max(this.min.y, y);
  55391. this.min.z = Math.max(this.min.z, z);
  55392. };
  55393. CMGBoundinBox.prototype.clampMax = function (x, y, z) {
  55394. this.max.x = Math.min(this.max.x, x);
  55395. this.max.y = Math.min(this.max.y, y);
  55396. this.max.z = Math.min(this.max.z, z);
  55397. };
  55398. CMGBoundinBox.prototype.empty = function () {
  55399. if ((this.min.x > this.max.y) ||
  55400. (this.min.y > this.max.y) ||
  55401. (this.min.z > this.max.y)) {
  55402. return true;
  55403. }
  55404. else {
  55405. return false;
  55406. }
  55407. };
  55408. return CMGBoundinBox;
  55409. }());
  55410. CMGBoundinBox.MAX = Number.MAX_VALUE;
  55411. CMGBoundinBox.MIN = Number.MIN_VALUE;
  55412. /**
  55413. * Helper class to PreProcess a cubemap in order to generate mipmap according to the level of blur
  55414. * required by the glossinees of a material.
  55415. *
  55416. * This only supports the cosine drop power as well as Warp fixup generation method.
  55417. *
  55418. * This is using the process from CubeMapGen described here:
  55419. * https://seblagarde.wordpress.com/2012/06/10/amd-cubemapgen-for-physically-based-rendering/
  55420. */
  55421. var PMREMGenerator = (function () {
  55422. /**
  55423. * Constructor of the generator.
  55424. *
  55425. * @param input The different faces data from the original cubemap in the order X+ X- Y+ Y- Z+ Z-
  55426. * @param inputSize The size of the cubemap faces
  55427. * @param outputSize The size of the output cubemap faces
  55428. * @param maxNumMipLevels The max number of mip map to generate (0 means all)
  55429. * @param numChannels The number of channels stored in the cubemap (3 for RBGE for instance)
  55430. * @param isFloat Specifies if the input texture is in float or int (hdr is usually in float)
  55431. * @param specularPower The max specular level of the desired cubemap
  55432. * @param cosinePowerDropPerMip The amount of drop the specular power will follow on each mip
  55433. * @param excludeBase Specifies wether to process the level 0 (original level) or not
  55434. * @param fixup Specifies wether to apply the edge fixup algorythm or not
  55435. */
  55436. function PMREMGenerator(input, inputSize, outputSize, maxNumMipLevels, numChannels, isFloat, specularPower, cosinePowerDropPerMip, excludeBase, fixup) {
  55437. this.input = input;
  55438. this.inputSize = inputSize;
  55439. this.outputSize = outputSize;
  55440. this.maxNumMipLevels = maxNumMipLevels;
  55441. this.numChannels = numChannels;
  55442. this.isFloat = isFloat;
  55443. this.specularPower = specularPower;
  55444. this.cosinePowerDropPerMip = cosinePowerDropPerMip;
  55445. this.excludeBase = excludeBase;
  55446. this.fixup = fixup;
  55447. this._outputSurface = [];
  55448. this._numMipLevels = 0;
  55449. }
  55450. /**
  55451. * Launches the filter process and return the result.
  55452. *
  55453. * @return the filter cubemap in the form mip0 [faces1..6] .. mipN [faces1..6]
  55454. */
  55455. PMREMGenerator.prototype.filterCubeMap = function () {
  55456. // Init cubemap processor
  55457. this.init();
  55458. // Filters the cubemap
  55459. this.filterCubeMapMipChain();
  55460. // Returns the filtered mips.
  55461. return this._outputSurface;
  55462. };
  55463. PMREMGenerator.prototype.init = function () {
  55464. var i;
  55465. var j;
  55466. var mipLevelSize;
  55467. //if nax num mip levels is set to 0, set it to generate the entire mip chain
  55468. if (this.maxNumMipLevels == 0) {
  55469. this.maxNumMipLevels = PMREMGenerator.CP_MAX_MIPLEVELS;
  55470. }
  55471. //first miplevel size
  55472. mipLevelSize = this.outputSize;
  55473. //Iterate over mip chain, and init ArrayBufferView for mip-chain
  55474. for (j = 0; j < this.maxNumMipLevels; j++) {
  55475. this._outputSurface.length++;
  55476. this._outputSurface[j] = [];
  55477. //Iterate over faces for output images
  55478. for (i = 0; i < 6; i++) {
  55479. this._outputSurface[j].length++;
  55480. // Initializes a new array for the output.
  55481. if (this.isFloat) {
  55482. this._outputSurface[j][i] = new Float32Array(mipLevelSize * mipLevelSize * this.numChannels);
  55483. }
  55484. else {
  55485. this._outputSurface[j][i] = new Uint32Array(mipLevelSize * mipLevelSize * this.numChannels);
  55486. }
  55487. }
  55488. //next mip level is half size
  55489. mipLevelSize >>= 1;
  55490. this._numMipLevels++;
  55491. //terminate if mip chain becomes too small
  55492. if (mipLevelSize == 0) {
  55493. this.maxNumMipLevels = j;
  55494. return;
  55495. }
  55496. }
  55497. };
  55498. //--------------------------------------------------------------------------------------
  55499. //Cube map filtering and mip chain generation.
  55500. // the cube map filtereing is specified using a number of parameters:
  55501. // Filtering per miplevel is specified using 2D cone angle (in degrees) that
  55502. // indicates the region of the hemisphere to filter over for each tap.
  55503. //
  55504. // Note that the top mip level is also a filtered version of the original input images
  55505. // as well in order to create mip chains for diffuse environment illumination.
  55506. // The cone angle for the top level is specified by a_BaseAngle. This can be used to
  55507. // generate mipchains used to store the resutls of preintegration across the hemisphere.
  55508. //
  55509. // Then the mip angle used to genreate the next level of the mip chain from the first level
  55510. // is a_InitialMipAngle
  55511. //
  55512. // The angle for the subsequent levels of the mip chain are specified by their parents
  55513. // filtering angle and a per-level scale and bias
  55514. // newAngle = oldAngle * a_MipAnglePerLevelScale;
  55515. //
  55516. //--------------------------------------------------------------------------------------
  55517. PMREMGenerator.prototype.filterCubeMapMipChain = function () {
  55518. // First, take count of the lighting model to modify SpecularPower
  55519. // 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;
  55520. // var refSpecularPower = this.specularPower; // Only Phong BRDF yet. This explains the line below using this.specularpower.
  55521. //Cone angle start (for generating subsequent mip levels)
  55522. var currentSpecularPower = this.specularPower;
  55523. //Build filter lookup tables based on the source miplevel size
  55524. this.precomputeFilterLookupTables(this.inputSize);
  55525. // Note that we need to filter the first level before generating mipmap
  55526. // So LevelIndex == 0 is base filtering hen LevelIndex > 0 is mipmap generation
  55527. for (var levelIndex = 0; levelIndex < this._numMipLevels; levelIndex++) {
  55528. // TODO : Write a function to copy and scale the base mipmap in output
  55529. // I am just lazy here and just put a high specular power value, and do some if.
  55530. if (this.excludeBase && (levelIndex == 0)) {
  55531. // 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).
  55532. currentSpecularPower = 100000.0;
  55533. }
  55534. // Special case for cosine power mipmap chain. For quality requirement, we always process the current mipmap from the top mipmap
  55535. var srcCubeImage = this.input;
  55536. var dstCubeImage = this._outputSurface[levelIndex];
  55537. var dstSize = this.outputSize >> levelIndex;
  55538. // Compute required angle.
  55539. var angle = this.getBaseFilterAngle(currentSpecularPower);
  55540. // filter cube surfaces
  55541. this.filterCubeSurfaces(srcCubeImage, this.inputSize, dstCubeImage, dstSize, angle, currentSpecularPower);
  55542. // fix seams
  55543. if (this.fixup) {
  55544. this.fixupCubeEdges(dstCubeImage, dstSize);
  55545. }
  55546. // Decrease the specular power to generate the mipmap chain
  55547. // TODO : Use another method for Exclude (see first comment at start of the function
  55548. if (this.excludeBase && (levelIndex == 0)) {
  55549. currentSpecularPower = this.specularPower;
  55550. }
  55551. currentSpecularPower *= this.cosinePowerDropPerMip;
  55552. }
  55553. };
  55554. //--------------------------------------------------------------------------------------
  55555. // This function return the BaseFilterAngle require by PMREMGenerator to its FilterExtends
  55556. // It allow to optimize the texel to access base on the specular power.
  55557. //--------------------------------------------------------------------------------------
  55558. PMREMGenerator.prototype.getBaseFilterAngle = function (cosinePower) {
  55559. // We want to find the alpha such that:
  55560. // cos(alpha)^cosinePower = epsilon
  55561. // That's: acos(epsilon^(1/cosinePower))
  55562. var threshold = 0.000001; // Empirical threshold (Work perfectly, didn't check for a more big number, may get some performance and still god approximation)
  55563. var angle = 180.0;
  55564. angle = Math.acos(Math.pow(threshold, 1.0 / cosinePower));
  55565. angle *= 180.0 / Math.PI; // Convert to degree
  55566. angle *= 2.0; // * 2.0f because PMREMGenerator divide by 2 later
  55567. return angle;
  55568. };
  55569. //--------------------------------------------------------------------------------------
  55570. //Builds the following lookup tables prior to filtering:
  55571. // -normalizer cube map
  55572. // -tap weight lookup table
  55573. //
  55574. //--------------------------------------------------------------------------------------
  55575. PMREMGenerator.prototype.precomputeFilterLookupTables = function (srcCubeMapWidth) {
  55576. var srcTexelAngle;
  55577. var iCubeFace;
  55578. //clear pre-existing normalizer cube map
  55579. this._normCubeMap = [];
  55580. //Normalized vectors per cubeface and per-texel solid angle
  55581. this.buildNormalizerSolidAngleCubemap(srcCubeMapWidth);
  55582. };
  55583. //--------------------------------------------------------------------------------------
  55584. //Builds a normalizer cubemap, with the texels solid angle stored in the fourth component
  55585. //
  55586. //Takes in a cube face size, and an array of 6 surfaces to write the cube faces into
  55587. //
  55588. //Note that this normalizer cube map stores the vectors in unbiased -1 to 1 range.
  55589. // if _bx2 style scaled and biased vectors are needed, uncomment the SCALE and BIAS
  55590. // below
  55591. //--------------------------------------------------------------------------------------
  55592. PMREMGenerator.prototype.buildNormalizerSolidAngleCubemap = function (size) {
  55593. var iCubeFace;
  55594. var u;
  55595. var v;
  55596. //iterate over cube faces
  55597. for (iCubeFace = 0; iCubeFace < 6; iCubeFace++) {
  55598. //First three channels for norm cube, and last channel for solid angle
  55599. this._normCubeMap.push(new Float32Array(size * size * 4));
  55600. //fast texture walk, build normalizer cube map
  55601. var facesData = this.input[iCubeFace];
  55602. for (v = 0; v < size; v++) {
  55603. for (u = 0; u < size; u++) {
  55604. var vect = this.texelCoordToVect(iCubeFace, u, v, size, this.fixup);
  55605. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 0] = vect.x;
  55606. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 1] = vect.y;
  55607. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 2] = vect.z;
  55608. var solidAngle = this.texelCoordSolidAngle(iCubeFace, u, v, size);
  55609. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 4] = solidAngle;
  55610. }
  55611. }
  55612. }
  55613. };
  55614. //--------------------------------------------------------------------------------------
  55615. // Convert cubemap face texel coordinates and face idx to 3D vector
  55616. // note the U and V coords are integer coords and range from 0 to size-1
  55617. // this routine can be used to generate a normalizer cube map
  55618. //--------------------------------------------------------------------------------------
  55619. // SL BEGIN
  55620. PMREMGenerator.prototype.texelCoordToVect = function (faceIdx, u, v, size, fixup) {
  55621. var nvcU;
  55622. var nvcV;
  55623. var tempVec;
  55624. // Change from original AMD code
  55625. // transform from [0..res - 1] to [- (1 - 1 / res) .. (1 - 1 / res)]
  55626. // + 0.5f is for texel center addressing
  55627. nvcU = (2.0 * (u + 0.5) / size) - 1.0;
  55628. nvcV = (2.0 * (v + 0.5) / size) - 1.0;
  55629. // warp fixup
  55630. if (fixup && size > 1) {
  55631. // Code from Nvtt : http://code.google.com/p/nvidia-texture-tools/source/browse/trunk/src/nvtt/CubeSurface.cpp
  55632. var a = Math.pow(size, 2.0) / Math.pow(size - 1, 3.0);
  55633. nvcU = a * Math.pow(nvcU, 3) + nvcU;
  55634. nvcV = a * Math.pow(nvcV, 3) + nvcV;
  55635. }
  55636. // Get current vector
  55637. // generate x,y,z vector (xform 2d NVC coord to 3D vector)
  55638. // U contribution
  55639. var UVec = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_UDIR];
  55640. PMREMGenerator._vectorTemp.x = UVec[0] * nvcU;
  55641. PMREMGenerator._vectorTemp.y = UVec[1] * nvcU;
  55642. PMREMGenerator._vectorTemp.z = UVec[2] * nvcU;
  55643. // V contribution and Sum
  55644. var VVec = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_VDIR];
  55645. PMREMGenerator._vectorTemp.x += VVec[0] * nvcV;
  55646. PMREMGenerator._vectorTemp.y += VVec[1] * nvcV;
  55647. PMREMGenerator._vectorTemp.z += VVec[2] * nvcV;
  55648. //add face axis
  55649. var faceAxis = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_FACEAXIS];
  55650. PMREMGenerator._vectorTemp.x += faceAxis[0];
  55651. PMREMGenerator._vectorTemp.y += faceAxis[1];
  55652. PMREMGenerator._vectorTemp.z += faceAxis[2];
  55653. //normalize vector
  55654. PMREMGenerator._vectorTemp.normalize();
  55655. return PMREMGenerator._vectorTemp;
  55656. };
  55657. //--------------------------------------------------------------------------------------
  55658. // Convert 3D vector to cubemap face texel coordinates and face idx
  55659. // note the U and V coords are integer coords and range from 0 to size-1
  55660. // this routine can be used to generate a normalizer cube map
  55661. //
  55662. // returns face IDX and texel coords
  55663. //--------------------------------------------------------------------------------------
  55664. // SL BEGIN
  55665. /*
  55666. Mapping Texture Coordinates to Cube Map Faces
  55667. Because there are multiple faces, the mapping of texture coordinates to positions on cube map faces
  55668. is more complicated than the other texturing targets. The EXT_texture_cube_map extension is purposefully
  55669. designed to be consistent with DirectX 7's cube map arrangement. This is also consistent with the cube
  55670. map arrangement in Pixar's RenderMan package.
  55671. For cube map texturing, the (s,t,r) texture coordinates are treated as a direction vector (rx,ry,rz)
  55672. emanating from the center of a cube. (The q coordinate can be ignored since it merely scales the vector
  55673. without affecting the direction.) At texture application time, the interpolated per-fragment (s,t,r)
  55674. selects one of the cube map face's 2D mipmap sets based on the largest magnitude coordinate direction
  55675. the major axis direction). The target column in the table below explains how the major axis direction
  55676. maps to the 2D image of a particular cube map target.
  55677. major axis
  55678. direction target sc tc ma
  55679. ---------- --------------------------------- --- --- ---
  55680. +rx GL_TEXTURE_CUBE_MAP_POSITIVE_X_EXT -rz -ry rx
  55681. -rx GL_TEXTURE_CUBE_MAP_NEGATIVE_X_EXT +rz -ry rx
  55682. +ry GL_TEXTURE_CUBE_MAP_POSITIVE_Y_EXT +rx +rz ry
  55683. -ry GL_TEXTURE_CUBE_MAP_NEGATIVE_Y_EXT +rx -rz ry
  55684. +rz GL_TEXTURE_CUBE_MAP_POSITIVE_Z_EXT +rx -ry rz
  55685. -rz GL_TEXTURE_CUBE_MAP_NEGATIVE_Z_EXT -rx -ry rz
  55686. Using the sc, tc, and ma determined by the major axis direction as specified in the table above,
  55687. an updated (s,t) is calculated as follows
  55688. s = ( sc/|ma| + 1 ) / 2
  55689. t = ( tc/|ma| + 1 ) / 2
  55690. If |ma| is zero or very nearly zero, the results of the above two equations need not be defined
  55691. (though the result may not lead to GL interruption or termination). Once the cube map face's 2D mipmap
  55692. set and (s,t) is determined, texture fetching and filtering proceeds like standard OpenGL 2D texturing.
  55693. */
  55694. // Note this method return U and V in range from 0 to size-1
  55695. // SL END
  55696. // Store the information in vector3 for convenience (faceindex, u, v)
  55697. PMREMGenerator.prototype.vectToTexelCoord = function (x, y, z, size) {
  55698. var maxCoord;
  55699. var faceIdx;
  55700. //absolute value 3
  55701. var absX = Math.abs(x);
  55702. var absY = Math.abs(y);
  55703. var absZ = Math.abs(z);
  55704. if (absX >= absY && absX >= absZ) {
  55705. maxCoord = absX;
  55706. if (x >= 0) {
  55707. faceIdx = PMREMGenerator.CP_FACE_X_POS;
  55708. }
  55709. else {
  55710. faceIdx = PMREMGenerator.CP_FACE_X_NEG;
  55711. }
  55712. }
  55713. else if (absY >= absX && absY >= absZ) {
  55714. maxCoord = absY;
  55715. if (y >= 0) {
  55716. faceIdx = PMREMGenerator.CP_FACE_Y_POS;
  55717. }
  55718. else {
  55719. faceIdx = PMREMGenerator.CP_FACE_Y_NEG;
  55720. }
  55721. }
  55722. else {
  55723. maxCoord = absZ;
  55724. if (z >= 0) {
  55725. faceIdx = PMREMGenerator.CP_FACE_Z_POS;
  55726. }
  55727. else {
  55728. faceIdx = PMREMGenerator.CP_FACE_Z_NEG;
  55729. }
  55730. }
  55731. //divide through by max coord so face vector lies on cube face
  55732. var scale = 1 / maxCoord;
  55733. x *= scale;
  55734. y *= scale;
  55735. z *= scale;
  55736. var temp = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_UDIR];
  55737. var nvcU = temp[0] * x + temp[1] * y + temp[2] * z;
  55738. temp = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_VDIR];
  55739. var nvcV = temp[0] * x + temp[1] * y + temp[2] * z;
  55740. // Modify original AMD code to return value from 0 to Size - 1
  55741. var u = Math.floor((size - 1) * 0.5 * (nvcU + 1.0));
  55742. var v = Math.floor((size - 1) * 0.5 * (nvcV + 1.0));
  55743. PMREMGenerator._vectorTemp.x = faceIdx;
  55744. PMREMGenerator._vectorTemp.y = u;
  55745. PMREMGenerator._vectorTemp.z = v;
  55746. return PMREMGenerator._vectorTemp;
  55747. };
  55748. //--------------------------------------------------------------------------------------
  55749. //Original code from Ignacio CastaÒo
  55750. // This formula is from Manne ÷hrstrˆm's thesis.
  55751. // Take two coordiantes in the range [-1, 1] that define a portion of a
  55752. // cube face and return the area of the projection of that portion on the
  55753. // surface of the sphere.
  55754. //--------------------------------------------------------------------------------------
  55755. PMREMGenerator.prototype.areaElement = function (x, y) {
  55756. return Math.atan2(x * y, Math.sqrt(x * x + y * y + 1));
  55757. };
  55758. PMREMGenerator.prototype.texelCoordSolidAngle = function (faceIdx, u, v, size) {
  55759. // transform from [0..res - 1] to [- (1 - 1 / res) .. (1 - 1 / res)]
  55760. // (+ 0.5f is for texel center addressing)
  55761. u = (2.0 * (u + 0.5) / size) - 1.0;
  55762. v = (2.0 * (v + 0.5) / size) - 1.0;
  55763. // Shift from a demi texel, mean 1.0f / a_Size with U and V in [-1..1]
  55764. var invResolution = 1.0 / size;
  55765. // U and V are the -1..1 texture coordinate on the current face.
  55766. // Get projected area for this texel
  55767. var x0 = u - invResolution;
  55768. var y0 = v - invResolution;
  55769. var x1 = u + invResolution;
  55770. var y1 = v + invResolution;
  55771. var solidAngle = this.areaElement(x0, y0) - this.areaElement(x0, y1) - this.areaElement(x1, y0) + this.areaElement(x1, y1);
  55772. return solidAngle;
  55773. };
  55774. //--------------------------------------------------------------------------------------
  55775. //The key to the speed of these filtering routines is to quickly define a per-face
  55776. // bounding box of pixels which enclose all the taps in the filter kernel efficiently.
  55777. // Later these pixels are selectively processed based on their dot products to see if
  55778. // they reside within the filtering cone.
  55779. //
  55780. //This is done by computing the smallest per-texel angle to get a conservative estimate
  55781. // of the number of texels needed to be covered in width and height order to filter the
  55782. // region. the bounding box for the center taps face is defined first, and if the
  55783. // filtereing region bleeds onto the other faces, bounding boxes for the other faces are
  55784. // defined next
  55785. //--------------------------------------------------------------------------------------
  55786. PMREMGenerator.prototype.filterCubeSurfaces = function (srcCubeMap, srcSize, dstCubeMap, dstSize, filterConeAngle, specularPower) {
  55787. // note that pixels within these regions may be rejected
  55788. // based on the anlge
  55789. var iCubeFace;
  55790. var u;
  55791. var v;
  55792. // bounding box per face to specify region to process
  55793. var filterExtents = [];
  55794. for (iCubeFace = 0; iCubeFace < 6; iCubeFace++) {
  55795. filterExtents.push(new CMGBoundinBox());
  55796. }
  55797. // min angle a src texel can cover (in degrees)
  55798. var srcTexelAngle = (180.0 / (Math.PI) * Math.atan2(1.0, srcSize));
  55799. // angle about center tap to define filter cone
  55800. // filter angle is 1/2 the cone angle
  55801. var filterAngle = filterConeAngle / 2.0;
  55802. //ensure filter angle is larger than a texel
  55803. if (filterAngle < srcTexelAngle) {
  55804. filterAngle = srcTexelAngle;
  55805. }
  55806. //ensure filter cone is always smaller than the hemisphere
  55807. if (filterAngle > 90.0) {
  55808. filterAngle = 90.0;
  55809. }
  55810. // the maximum number of texels in 1D the filter cone angle will cover
  55811. // used to determine bounding box size for filter extents
  55812. var filterSize = Math.ceil(filterAngle / srcTexelAngle);
  55813. // ensure conservative region always covers at least one texel
  55814. if (filterSize < 1) {
  55815. filterSize = 1;
  55816. }
  55817. // dotProdThresh threshold based on cone angle to determine whether or not taps
  55818. // reside within the cone angle
  55819. var dotProdThresh = Math.cos((Math.PI / 180.0) * filterAngle);
  55820. // process required faces
  55821. for (iCubeFace = 0; iCubeFace < 6; iCubeFace++) {
  55822. //iterate over dst cube map face texel
  55823. for (v = 0; v < dstSize; v++) {
  55824. for (u = 0; u < dstSize; u++) {
  55825. //get center tap direction
  55826. var centerTapDir = this.texelCoordToVect(iCubeFace, u, v, dstSize, this.fixup).clone();
  55827. //clear old per-face filter extents
  55828. this.clearFilterExtents(filterExtents);
  55829. //define per-face filter extents
  55830. this.determineFilterExtents(centerTapDir, srcSize, filterSize, filterExtents);
  55831. //perform filtering of src faces using filter extents
  55832. var vect = this.processFilterExtents(centerTapDir, dotProdThresh, filterExtents, srcCubeMap, srcSize, specularPower);
  55833. dstCubeMap[iCubeFace][(v * dstSize + u) * this.numChannels + 0] = vect.x;
  55834. dstCubeMap[iCubeFace][(v * dstSize + u) * this.numChannels + 1] = vect.y;
  55835. dstCubeMap[iCubeFace][(v * dstSize + u) * this.numChannels + 2] = vect.z;
  55836. }
  55837. }
  55838. }
  55839. };
  55840. //--------------------------------------------------------------------------------------
  55841. //Clear filter extents for the 6 cube map faces
  55842. //--------------------------------------------------------------------------------------
  55843. PMREMGenerator.prototype.clearFilterExtents = function (filterExtents) {
  55844. for (var iCubeFaces = 0; iCubeFaces < 6; iCubeFaces++) {
  55845. filterExtents[iCubeFaces].clear();
  55846. }
  55847. };
  55848. //--------------------------------------------------------------------------------------
  55849. //Define per-face bounding box filter extents
  55850. //
  55851. // These define conservative texel regions in each of the faces the filter can possibly
  55852. // process. When the pixels in the regions are actually processed, the dot product
  55853. // between the tap vector and the center tap vector is used to determine the weight of
  55854. // the tap and whether or not the tap is within the cone.
  55855. //
  55856. //--------------------------------------------------------------------------------------
  55857. PMREMGenerator.prototype.determineFilterExtents = function (centerTapDir, srcSize, bboxSize, filterExtents) {
  55858. //neighboring face and bleed over amount, and width of BBOX for
  55859. // left, right, top, and bottom edges of this face
  55860. var bleedOverAmount = [0, 0, 0, 0];
  55861. var bleedOverBBoxMin = [0, 0, 0, 0];
  55862. var bleedOverBBoxMax = [0, 0, 0, 0];
  55863. var neighborFace;
  55864. var neighborEdge;
  55865. var oppositeFaceIdx;
  55866. //get face idx, and u, v info from center tap dir
  55867. var result = this.vectToTexelCoord(centerTapDir.x, centerTapDir.y, centerTapDir.z, srcSize);
  55868. var faceIdx = result.x;
  55869. var u = result.y;
  55870. var v = result.z;
  55871. //define bbox size within face
  55872. filterExtents[faceIdx].augment(u - bboxSize, v - bboxSize, 0);
  55873. filterExtents[faceIdx].augment(u + bboxSize, v + bboxSize, 0);
  55874. filterExtents[faceIdx].clampMin(0, 0, 0);
  55875. filterExtents[faceIdx].clampMax(srcSize - 1, srcSize - 1, 0);
  55876. //u and v extent in face corresponding to center tap
  55877. var minU = filterExtents[faceIdx].min.x;
  55878. var minV = filterExtents[faceIdx].min.y;
  55879. var maxU = filterExtents[faceIdx].max.x;
  55880. var maxV = filterExtents[faceIdx].max.y;
  55881. //bleed over amounts for face across u=0 edge (left)
  55882. bleedOverAmount[0] = (bboxSize - u);
  55883. bleedOverBBoxMin[0] = minV;
  55884. bleedOverBBoxMax[0] = maxV;
  55885. //bleed over amounts for face across u=1 edge (right)
  55886. bleedOverAmount[1] = (u + bboxSize) - (srcSize - 1);
  55887. bleedOverBBoxMin[1] = minV;
  55888. bleedOverBBoxMax[1] = maxV;
  55889. //bleed over to face across v=0 edge (up)
  55890. bleedOverAmount[2] = (bboxSize - v);
  55891. bleedOverBBoxMin[2] = minU;
  55892. bleedOverBBoxMax[2] = maxU;
  55893. //bleed over to face across v=1 edge (down)
  55894. bleedOverAmount[3] = (v + bboxSize) - (srcSize - 1);
  55895. bleedOverBBoxMin[3] = minU;
  55896. bleedOverBBoxMax[3] = maxU;
  55897. //compute bleed over regions in neighboring faces
  55898. for (var i = 0; i < 4; i++) {
  55899. if (bleedOverAmount[i] > 0) {
  55900. neighborFace = PMREMGenerator._sgCubeNgh[faceIdx][i][0];
  55901. neighborEdge = PMREMGenerator._sgCubeNgh[faceIdx][i][1];
  55902. //For certain types of edge abutments, the bleedOverBBoxMin, and bleedOverBBoxMax need to
  55903. // be flipped: the cases are
  55904. // if a left edge mates with a left or bottom edge on the neighbor
  55905. // if a top edge mates with a top or right edge on the neighbor
  55906. // if a right edge mates with a right or top edge on the neighbor
  55907. // if a bottom edge mates with a bottom or left edge on the neighbor
  55908. //Seeing as the edges are enumerated as follows
  55909. // left =0
  55910. // right =1
  55911. // top =2
  55912. // bottom =3
  55913. //
  55914. // so if the edge enums are the same, or the sum of the enums == 3,
  55915. // the bbox needs to be flipped
  55916. if ((i == neighborEdge) || ((i + neighborEdge) == 3)) {
  55917. bleedOverBBoxMin[i] = (srcSize - 1) - bleedOverBBoxMin[i];
  55918. bleedOverBBoxMax[i] = (srcSize - 1) - bleedOverBBoxMax[i];
  55919. }
  55920. //The way the bounding box is extended onto the neighboring face
  55921. // depends on which edge of neighboring face abuts with this one
  55922. switch (PMREMGenerator._sgCubeNgh[faceIdx][i][1]) {
  55923. case PMREMGenerator.CP_EDGE_LEFT:
  55924. filterExtents[neighborFace].augment(0, bleedOverBBoxMin[i], 0);
  55925. filterExtents[neighborFace].augment(bleedOverAmount[i], bleedOverBBoxMax[i], 0);
  55926. break;
  55927. case PMREMGenerator.CP_EDGE_RIGHT:
  55928. filterExtents[neighborFace].augment((srcSize - 1), bleedOverBBoxMin[i], 0);
  55929. filterExtents[neighborFace].augment((srcSize - 1) - bleedOverAmount[i], bleedOverBBoxMax[i], 0);
  55930. break;
  55931. case PMREMGenerator.CP_EDGE_TOP:
  55932. filterExtents[neighborFace].augment(bleedOverBBoxMin[i], 0, 0);
  55933. filterExtents[neighborFace].augment(bleedOverBBoxMax[i], bleedOverAmount[i], 0);
  55934. break;
  55935. case PMREMGenerator.CP_EDGE_BOTTOM:
  55936. filterExtents[neighborFace].augment(bleedOverBBoxMin[i], (srcSize - 1), 0);
  55937. filterExtents[neighborFace].augment(bleedOverBBoxMax[i], (srcSize - 1) - bleedOverAmount[i], 0);
  55938. break;
  55939. }
  55940. //clamp filter extents in non-center tap faces to remain within surface
  55941. filterExtents[neighborFace].clampMin(0, 0, 0);
  55942. filterExtents[neighborFace].clampMax(srcSize - 1, srcSize - 1, 0);
  55943. }
  55944. //If the bleed over amount bleeds past the adjacent face onto the opposite face
  55945. // from the center tap face, then process the opposite face entirely for now.
  55946. //Note that the cases in which this happens, what usually happens is that
  55947. // more than one edge bleeds onto the opposite face, and the bounding box
  55948. // encompasses the entire cube map face.
  55949. if (bleedOverAmount[i] > srcSize) {
  55950. //determine opposite face
  55951. switch (faceIdx) {
  55952. case PMREMGenerator.CP_FACE_X_POS:
  55953. oppositeFaceIdx = PMREMGenerator.CP_FACE_X_NEG;
  55954. break;
  55955. case PMREMGenerator.CP_FACE_X_NEG:
  55956. oppositeFaceIdx = PMREMGenerator.CP_FACE_X_POS;
  55957. break;
  55958. case PMREMGenerator.CP_FACE_Y_POS:
  55959. oppositeFaceIdx = PMREMGenerator.CP_FACE_Y_NEG;
  55960. break;
  55961. case PMREMGenerator.CP_FACE_Y_NEG:
  55962. oppositeFaceIdx = PMREMGenerator.CP_FACE_Y_POS;
  55963. break;
  55964. case PMREMGenerator.CP_FACE_Z_POS:
  55965. oppositeFaceIdx = PMREMGenerator.CP_FACE_Z_NEG;
  55966. break;
  55967. case PMREMGenerator.CP_FACE_Z_NEG:
  55968. oppositeFaceIdx = PMREMGenerator.CP_FACE_Z_POS;
  55969. break;
  55970. default:
  55971. break;
  55972. }
  55973. //just encompass entire face for now
  55974. filterExtents[oppositeFaceIdx].augment(0, 0, 0);
  55975. filterExtents[oppositeFaceIdx].augment((srcSize - 1), (srcSize - 1), 0);
  55976. }
  55977. }
  55978. };
  55979. //--------------------------------------------------------------------------------------
  55980. //ProcessFilterExtents
  55981. // Process bounding box in each cube face
  55982. //
  55983. //--------------------------------------------------------------------------------------
  55984. PMREMGenerator.prototype.processFilterExtents = function (centerTapDir, dotProdThresh, filterExtents, srcCubeMap, srcSize, specularPower) {
  55985. //accumulators are 64-bit floats in order to have the precision needed
  55986. // over a summation of a large number of pixels
  55987. var dstAccum = [0, 0, 0, 0];
  55988. var weightAccum = 0;
  55989. var k = 0;
  55990. var nSrcChannels = this.numChannels;
  55991. // norm cube map and srcCubeMap have same face width
  55992. var faceWidth = srcSize;
  55993. //amount to add to pointer to move to next scanline in images
  55994. var normCubePitch = faceWidth * 4; // 4 channels in normCubeMap.
  55995. var srcCubePitch = faceWidth * this.numChannels; // numChannels correponds to the cubemap number of channel
  55996. var IsPhongBRDF = 1; // Only works in Phong BRDF yet.
  55997. //(a_LightingModel == CP_LIGHTINGMODEL_PHONG_BRDF || a_LightingModel == CP_LIGHTINGMODEL_BLINN_BRDF) ? 1 : 0; // This value will be added to the specular power
  55998. // iterate over cubefaces
  55999. for (var iFaceIdx = 0; iFaceIdx < 6; iFaceIdx++) {
  56000. //if bbox is non empty
  56001. if (!filterExtents[iFaceIdx].empty()) {
  56002. var uStart = filterExtents[iFaceIdx].min.x;
  56003. var vStart = filterExtents[iFaceIdx].min.y;
  56004. var uEnd = filterExtents[iFaceIdx].max.x;
  56005. var vEnd = filterExtents[iFaceIdx].max.y;
  56006. var startIndexNormCubeMap = (4 * ((vStart * faceWidth) + uStart));
  56007. var startIndexSrcCubeMap = (this.numChannels * ((vStart * faceWidth) + uStart));
  56008. //note that <= is used to ensure filter extents always encompass at least one pixel if bbox is non empty
  56009. for (var v = vStart; v <= vEnd; v++) {
  56010. var normCubeRowWalk = 0;
  56011. var srcCubeRowWalk = 0;
  56012. for (var u = uStart; u <= uEnd; u++) {
  56013. //pointer to direction in cube map associated with texel
  56014. var texelVectX = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 0];
  56015. var texelVectY = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 1];
  56016. var texelVectZ = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 2];
  56017. //check dot product to see if texel is within cone
  56018. var tapDotProd = texelVectX * centerTapDir.x +
  56019. texelVectY * centerTapDir.y +
  56020. texelVectZ * centerTapDir.z;
  56021. if (tapDotProd >= dotProdThresh && tapDotProd > 0.0) {
  56022. //solid angle stored in 4th channel of normalizer/solid angle cube map
  56023. var weight = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 3];
  56024. // Here we decide if we use a Phong/Blinn or a Phong/Blinn BRDF.
  56025. // Phong/Blinn BRDF is just the Phong/Blinn model multiply by the cosine of the lambert law
  56026. // so just adding one to specularpower do the trick.
  56027. weight *= Math.pow(tapDotProd, (specularPower + IsPhongBRDF));
  56028. //iterate over channels
  56029. for (k = 0; k < nSrcChannels; k++) {
  56030. dstAccum[k] += weight * srcCubeMap[iFaceIdx][startIndexSrcCubeMap + srcCubeRowWalk];
  56031. srcCubeRowWalk++;
  56032. }
  56033. weightAccum += weight; //accumulate weight
  56034. }
  56035. else {
  56036. //step across source pixel
  56037. srcCubeRowWalk += nSrcChannels;
  56038. }
  56039. normCubeRowWalk += 4; // 4 channels per norm cube map.
  56040. }
  56041. startIndexNormCubeMap += normCubePitch;
  56042. startIndexSrcCubeMap += srcCubePitch;
  56043. }
  56044. }
  56045. }
  56046. //divide through by weights if weight is non zero
  56047. if (weightAccum != 0.0) {
  56048. PMREMGenerator._vectorTemp.x = (dstAccum[0] / weightAccum);
  56049. PMREMGenerator._vectorTemp.y = (dstAccum[1] / weightAccum);
  56050. PMREMGenerator._vectorTemp.z = (dstAccum[2] / weightAccum);
  56051. if (this.numChannels > 3) {
  56052. PMREMGenerator._vectorTemp.w = (dstAccum[3] / weightAccum);
  56053. }
  56054. }
  56055. else {
  56056. // otherwise sample nearest
  56057. // get face idx and u, v texel coordinate in face
  56058. var coord = this.vectToTexelCoord(centerTapDir.x, centerTapDir.y, centerTapDir.z, srcSize).clone();
  56059. PMREMGenerator._vectorTemp.x = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 0];
  56060. PMREMGenerator._vectorTemp.y = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 1];
  56061. PMREMGenerator._vectorTemp.z = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 2];
  56062. if (this.numChannels > 3) {
  56063. PMREMGenerator._vectorTemp.z = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 3];
  56064. }
  56065. }
  56066. return PMREMGenerator._vectorTemp;
  56067. };
  56068. //--------------------------------------------------------------------------------------
  56069. // Fixup cube edges
  56070. //
  56071. // average texels on cube map faces across the edges
  56072. // WARP/BENT Method Only.
  56073. //--------------------------------------------------------------------------------------
  56074. PMREMGenerator.prototype.fixupCubeEdges = function (cubeMap, cubeMapSize) {
  56075. var k;
  56076. var j;
  56077. var i;
  56078. var iFace;
  56079. var iCorner = 0;
  56080. var cornerNumPtrs = [0, 0, 0, 0, 0, 0, 0, 0]; //indexed by corner and face idx
  56081. var faceCornerStartIndicies = [[], [], [], []]; //corner pointers for face keeping track of the face they belong to.
  56082. // note that if functionality to filter across the three texels for each corner, then
  56083. //indexed by corner and face idx. the array contains the face the start points belongs to.
  56084. var cornerPtr = [
  56085. [[], [], []],
  56086. [[], [], []],
  56087. [[], [], []],
  56088. [[], [], []],
  56089. [[], [], []],
  56090. [[], [], []],
  56091. [[], [], []],
  56092. [[], [], []]
  56093. ];
  56094. //if there is no fixup, or fixup width = 0, do nothing
  56095. if (cubeMapSize < 1) {
  56096. return;
  56097. }
  56098. //special case 1x1 cubemap, average face colors
  56099. if (cubeMapSize == 1) {
  56100. //iterate over channels
  56101. for (k = 0; k < this.numChannels; k++) {
  56102. var accum = 0.0;
  56103. //iterate over faces to accumulate face colors
  56104. for (iFace = 0; iFace < 6; iFace++) {
  56105. accum += cubeMap[iFace][k];
  56106. }
  56107. //compute average over 6 face colors
  56108. accum /= 6.0;
  56109. //iterate over faces to distribute face colors
  56110. for (iFace = 0; iFace < 6; iFace++) {
  56111. cubeMap[iFace][k] = accum;
  56112. }
  56113. }
  56114. return;
  56115. }
  56116. //iterate over faces to collect list of corner texel pointers
  56117. for (iFace = 0; iFace < 6; iFace++) {
  56118. //the 4 corner pointers for this face
  56119. faceCornerStartIndicies[0] = [iFace, 0];
  56120. faceCornerStartIndicies[1] = [iFace, ((cubeMapSize - 1) * this.numChannels)];
  56121. faceCornerStartIndicies[2] = [iFace, ((cubeMapSize) * (cubeMapSize - 1) * this.numChannels)];
  56122. faceCornerStartIndicies[3] = [iFace, ((((cubeMapSize) * (cubeMapSize - 1)) + (cubeMapSize - 1)) * this.numChannels)];
  56123. //iterate over face corners to collect cube corner pointers
  56124. for (iCorner = 0; iCorner < 4; iCorner++) {
  56125. var corner = PMREMGenerator._sgCubeCornerList[iFace][iCorner];
  56126. cornerPtr[corner][cornerNumPtrs[corner]] = faceCornerStartIndicies[iCorner];
  56127. cornerNumPtrs[corner]++;
  56128. }
  56129. }
  56130. //iterate over corners to average across corner tap values
  56131. for (iCorner = 0; iCorner < 8; iCorner++) {
  56132. for (k = 0; k < this.numChannels; k++) {
  56133. var cornerTapAccum = 0.0;
  56134. //iterate over corner texels and average results
  56135. for (i = 0; i < 3; i++) {
  56136. cornerTapAccum += cubeMap[cornerPtr[iCorner][i][0]][cornerPtr[iCorner][i][1] + k]; // Get in the cube map face the start point + channel.
  56137. }
  56138. //divide by 3 to compute average of corner tap values
  56139. cornerTapAccum *= (1.0 / 3.0);
  56140. //iterate over corner texels and average results
  56141. for (i = 0; i < 3; i++) {
  56142. cubeMap[cornerPtr[iCorner][i][0]][cornerPtr[iCorner][i][1] + k] = cornerTapAccum;
  56143. }
  56144. }
  56145. }
  56146. //iterate over the twelve edges of the cube to average across edges
  56147. for (i = 0; i < 12; i++) {
  56148. var face = PMREMGenerator._sgCubeEdgeList[i][0];
  56149. var edge = PMREMGenerator._sgCubeEdgeList[i][1];
  56150. var neighborFace = PMREMGenerator._sgCubeNgh[face][edge][0];
  56151. var neighborEdge = PMREMGenerator._sgCubeNgh[face][edge][1];
  56152. var edgeStartIndex = 0; // a_CubeMap[face].m_ImgData;
  56153. var neighborEdgeStartIndex = 0; // a_CubeMap[neighborFace].m_ImgData;
  56154. var edgeWalk = 0;
  56155. var neighborEdgeWalk = 0;
  56156. //Determine walking pointers based on edge type
  56157. // e.g. CP_EDGE_LEFT, CP_EDGE_RIGHT, CP_EDGE_TOP, CP_EDGE_BOTTOM
  56158. switch (edge) {
  56159. case PMREMGenerator.CP_EDGE_LEFT:
  56160. // no change to faceEdgeStartPtr
  56161. edgeWalk = this.numChannels * cubeMapSize;
  56162. break;
  56163. case PMREMGenerator.CP_EDGE_RIGHT:
  56164. edgeStartIndex += (cubeMapSize - 1) * this.numChannels;
  56165. edgeWalk = this.numChannels * cubeMapSize;
  56166. break;
  56167. case PMREMGenerator.CP_EDGE_TOP:
  56168. // no change to faceEdgeStartPtr
  56169. edgeWalk = this.numChannels;
  56170. break;
  56171. case PMREMGenerator.CP_EDGE_BOTTOM:
  56172. edgeStartIndex += (cubeMapSize) * (cubeMapSize - 1) * this.numChannels;
  56173. edgeWalk = this.numChannels;
  56174. break;
  56175. }
  56176. //For certain types of edge abutments, the neighbor edge walk needs to
  56177. // be flipped: the cases are
  56178. // if a left edge mates with a left or bottom edge on the neighbor
  56179. // if a top edge mates with a top or right edge on the neighbor
  56180. // if a right edge mates with a right or top edge on the neighbor
  56181. // if a bottom edge mates with a bottom or left edge on the neighbor
  56182. //Seeing as the edges are enumerated as follows
  56183. // left =0
  56184. // right =1
  56185. // top =2
  56186. // bottom =3
  56187. //
  56188. //If the edge enums are the same, or the sum of the enums == 3,
  56189. // the neighbor edge walk needs to be flipped
  56190. if ((edge == neighborEdge) || ((edge + neighborEdge) == 3)) {
  56191. switch (neighborEdge) {
  56192. case PMREMGenerator.CP_EDGE_LEFT:
  56193. neighborEdgeStartIndex += (cubeMapSize - 1) * (cubeMapSize) * this.numChannels;
  56194. neighborEdgeWalk = -(this.numChannels * cubeMapSize);
  56195. break;
  56196. case PMREMGenerator.CP_EDGE_RIGHT:
  56197. neighborEdgeStartIndex += ((cubeMapSize - 1) * (cubeMapSize) + (cubeMapSize - 1)) * this.numChannels;
  56198. neighborEdgeWalk = -(this.numChannels * cubeMapSize);
  56199. break;
  56200. case PMREMGenerator.CP_EDGE_TOP:
  56201. neighborEdgeStartIndex += (cubeMapSize - 1) * this.numChannels;
  56202. neighborEdgeWalk = -this.numChannels;
  56203. break;
  56204. case PMREMGenerator.CP_EDGE_BOTTOM:
  56205. neighborEdgeStartIndex += ((cubeMapSize - 1) * (cubeMapSize) + (cubeMapSize - 1)) * this.numChannels;
  56206. neighborEdgeWalk = -this.numChannels;
  56207. break;
  56208. }
  56209. }
  56210. else {
  56211. //swapped direction neighbor edge walk
  56212. switch (neighborEdge) {
  56213. case PMREMGenerator.CP_EDGE_LEFT:
  56214. //no change to neighborEdgeStartPtr for this case since it points
  56215. // to the upper left corner already
  56216. neighborEdgeWalk = this.numChannels * cubeMapSize;
  56217. break;
  56218. case PMREMGenerator.CP_EDGE_RIGHT:
  56219. neighborEdgeStartIndex += (cubeMapSize - 1) * this.numChannels;
  56220. neighborEdgeWalk = this.numChannels * cubeMapSize;
  56221. break;
  56222. case PMREMGenerator.CP_EDGE_TOP:
  56223. //no change to neighborEdgeStartPtr for this case since it points
  56224. // to the upper left corner already
  56225. neighborEdgeWalk = this.numChannels;
  56226. break;
  56227. case PMREMGenerator.CP_EDGE_BOTTOM:
  56228. neighborEdgeStartIndex += (cubeMapSize) * (cubeMapSize - 1) * this.numChannels;
  56229. neighborEdgeWalk = this.numChannels;
  56230. break;
  56231. }
  56232. }
  56233. //Perform edge walk, to average across the 12 edges and smoothly propagate change to
  56234. //nearby neighborhood
  56235. //step ahead one texel on edge
  56236. edgeStartIndex += edgeWalk;
  56237. neighborEdgeStartIndex += neighborEdgeWalk;
  56238. // note that this loop does not process the corner texels, since they have already been
  56239. // averaged across faces across earlier
  56240. for (j = 1; j < (cubeMapSize - 1); j++) {
  56241. //for each set of taps along edge, average them
  56242. // and rewrite the results into the edges
  56243. for (k = 0; k < this.numChannels; k++) {
  56244. var edgeTap = cubeMap[face][edgeStartIndex + k];
  56245. var neighborEdgeTap = cubeMap[neighborFace][neighborEdgeStartIndex + k];
  56246. //compute average of tap intensity values
  56247. var avgTap = 0.5 * (edgeTap + neighborEdgeTap);
  56248. //propagate average of taps to edge taps
  56249. cubeMap[face][edgeStartIndex + k] = avgTap;
  56250. cubeMap[neighborFace][neighborEdgeStartIndex + k] = avgTap;
  56251. }
  56252. edgeStartIndex += edgeWalk;
  56253. neighborEdgeStartIndex += neighborEdgeWalk;
  56254. }
  56255. }
  56256. };
  56257. return PMREMGenerator;
  56258. }());
  56259. PMREMGenerator.CP_MAX_MIPLEVELS = 16;
  56260. PMREMGenerator.CP_UDIR = 0;
  56261. PMREMGenerator.CP_VDIR = 1;
  56262. PMREMGenerator.CP_FACEAXIS = 2;
  56263. //used to index cube faces
  56264. PMREMGenerator.CP_FACE_X_POS = 0;
  56265. PMREMGenerator.CP_FACE_X_NEG = 1;
  56266. PMREMGenerator.CP_FACE_Y_POS = 2;
  56267. PMREMGenerator.CP_FACE_Y_NEG = 3;
  56268. PMREMGenerator.CP_FACE_Z_POS = 4;
  56269. PMREMGenerator.CP_FACE_Z_NEG = 5;
  56270. //used to index image edges
  56271. // NOTE.. the actual number corresponding to the edge is important
  56272. // do not change these, or the code will break
  56273. //
  56274. // CP_EDGE_LEFT is u = 0
  56275. // CP_EDGE_RIGHT is u = width-1
  56276. // CP_EDGE_TOP is v = 0
  56277. // CP_EDGE_BOTTOM is v = height-1
  56278. PMREMGenerator.CP_EDGE_LEFT = 0;
  56279. PMREMGenerator.CP_EDGE_RIGHT = 1;
  56280. PMREMGenerator.CP_EDGE_TOP = 2;
  56281. PMREMGenerator.CP_EDGE_BOTTOM = 3;
  56282. //corners of CUBE map (P or N specifys if it corresponds to the
  56283. // positive or negative direction each of X, Y, and Z
  56284. PMREMGenerator.CP_CORNER_NNN = 0;
  56285. PMREMGenerator.CP_CORNER_NNP = 1;
  56286. PMREMGenerator.CP_CORNER_NPN = 2;
  56287. PMREMGenerator.CP_CORNER_NPP = 3;
  56288. PMREMGenerator.CP_CORNER_PNN = 4;
  56289. PMREMGenerator.CP_CORNER_PNP = 5;
  56290. PMREMGenerator.CP_CORNER_PPN = 6;
  56291. PMREMGenerator.CP_CORNER_PPP = 7;
  56292. PMREMGenerator._vectorTemp = new BABYLON.Vector4(0, 0, 0, 0);
  56293. //3x2 matrices that map cube map indexing vectors in 3d
  56294. // (after face selection and divide through by the
  56295. // _ABSOLUTE VALUE_ of the max coord)
  56296. // into NVC space
  56297. //Note this currently assumes the D3D cube face ordering and orientation
  56298. PMREMGenerator._sgFace2DMapping = [
  56299. //XPOS face
  56300. [[0, 0, -1],
  56301. [0, -1, 0],
  56302. [1, 0, 0]],
  56303. //XNEG face
  56304. [[0, 0, 1],
  56305. [0, -1, 0],
  56306. [-1, 0, 0]],
  56307. //YPOS face
  56308. [[1, 0, 0],
  56309. [0, 0, 1],
  56310. [0, 1, 0]],
  56311. //YNEG face
  56312. [[1, 0, 0],
  56313. [0, 0, -1],
  56314. [0, -1, 0]],
  56315. //ZPOS face
  56316. [[1, 0, 0],
  56317. [0, -1, 0],
  56318. [0, 0, 1]],
  56319. //ZNEG face
  56320. [[-1, 0, 0],
  56321. [0, -1, 0],
  56322. [0, 0, -1]],
  56323. ];
  56324. //------------------------------------------------------------------------------
  56325. // D3D cube map face specification
  56326. // mapping from 3D x,y,z cube map lookup coordinates
  56327. // to 2D within face u,v coordinates
  56328. //
  56329. // --------------------> U direction
  56330. // | (within-face texture space)
  56331. // | _____
  56332. // | | |
  56333. // | | +Y |
  56334. // | _____|_____|_____ _____
  56335. // | | | | | |
  56336. // | | -X | +Z | +X | -Z |
  56337. // | |_____|_____|_____|_____|
  56338. // | | |
  56339. // | | -Y |
  56340. // | |_____|
  56341. // |
  56342. // v V direction
  56343. // (within-face texture space)
  56344. //------------------------------------------------------------------------------
  56345. //Information about neighbors and how texture coorrdinates change across faces
  56346. // in ORDER of left, right, top, bottom (e.g. edges corresponding to u=0,
  56347. // u=1, v=0, v=1 in the 2D coordinate system of the particular face.
  56348. //Note this currently assumes the D3D cube face ordering and orientation
  56349. PMREMGenerator._sgCubeNgh = [
  56350. //XPOS face
  56351. [[PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_RIGHT],
  56352. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_LEFT],
  56353. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_RIGHT],
  56354. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_RIGHT]],
  56355. //XNEG face
  56356. [[PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_RIGHT],
  56357. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_LEFT],
  56358. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_LEFT],
  56359. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_LEFT]],
  56360. //YPOS face
  56361. [[PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_TOP],
  56362. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_TOP],
  56363. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_TOP],
  56364. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_TOP]],
  56365. //YNEG face
  56366. [[PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_BOTTOM],
  56367. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  56368. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  56369. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_BOTTOM]],
  56370. //ZPOS face
  56371. [[PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_RIGHT],
  56372. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_LEFT],
  56373. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  56374. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_TOP]],
  56375. //ZNEG face
  56376. [[PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_RIGHT],
  56377. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_LEFT],
  56378. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_TOP],
  56379. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_BOTTOM]]
  56380. ];
  56381. //The 12 edges of the cubemap, (entries are used to index into the neighbor table)
  56382. // this table is used to average over the edges.
  56383. PMREMGenerator._sgCubeEdgeList = [
  56384. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_LEFT],
  56385. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_RIGHT],
  56386. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_TOP],
  56387. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  56388. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_LEFT],
  56389. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_RIGHT],
  56390. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_TOP],
  56391. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_BOTTOM],
  56392. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_TOP],
  56393. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  56394. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_TOP],
  56395. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_BOTTOM]
  56396. ];
  56397. //Information about which of the 8 cube corners are correspond to the
  56398. // the 4 corners in each cube face
  56399. // the order is upper left, upper right, lower left, lower right
  56400. PMREMGenerator._sgCubeCornerList = [
  56401. [PMREMGenerator.CP_CORNER_PPP, PMREMGenerator.CP_CORNER_PPN, PMREMGenerator.CP_CORNER_PNP, PMREMGenerator.CP_CORNER_PNN],
  56402. [PMREMGenerator.CP_CORNER_NPN, PMREMGenerator.CP_CORNER_NPP, PMREMGenerator.CP_CORNER_NNN, PMREMGenerator.CP_CORNER_NNP],
  56403. [PMREMGenerator.CP_CORNER_NPN, PMREMGenerator.CP_CORNER_PPN, PMREMGenerator.CP_CORNER_NPP, PMREMGenerator.CP_CORNER_PPP],
  56404. [PMREMGenerator.CP_CORNER_NNP, PMREMGenerator.CP_CORNER_PNP, PMREMGenerator.CP_CORNER_NNN, PMREMGenerator.CP_CORNER_PNN],
  56405. [PMREMGenerator.CP_CORNER_NPP, PMREMGenerator.CP_CORNER_PPP, PMREMGenerator.CP_CORNER_NNP, PMREMGenerator.CP_CORNER_PNP],
  56406. [PMREMGenerator.CP_CORNER_PPN, PMREMGenerator.CP_CORNER_NPN, PMREMGenerator.CP_CORNER_PNN, PMREMGenerator.CP_CORNER_NNN] // ZNEG face
  56407. ];
  56408. Internals.PMREMGenerator = PMREMGenerator;
  56409. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  56410. })(BABYLON || (BABYLON = {}));
  56411. //# sourceMappingURL=babylon.tools.pmremGenerator.js.map
  56412. var BABYLON;
  56413. (function (BABYLON) {
  56414. /**
  56415. * This represents a texture coming from an HDR input.
  56416. *
  56417. * The only supported format is currently panorama picture stored in RGBE format.
  56418. * Example of such files can be found on HDRLib: http://hdrlib.com/
  56419. */
  56420. var HDRCubeTexture = (function (_super) {
  56421. __extends(HDRCubeTexture, _super);
  56422. /**
  56423. * Instantiates an HDRTexture from the following parameters.
  56424. *
  56425. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  56426. * @param scene The scene the texture will be used in
  56427. * @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.
  56428. * @param noMipmap Forces to not generate the mipmap if true
  56429. * @param generateHarmonics Specifies wether you want to extract the polynomial harmonics during the generation process
  56430. * @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)
  56431. * @param usePMREMGenerator Specifies wether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time.
  56432. */
  56433. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator, onLoad, onError) {
  56434. if (noMipmap === void 0) { noMipmap = false; }
  56435. if (generateHarmonics === void 0) { generateHarmonics = true; }
  56436. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  56437. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  56438. if (onLoad === void 0) { onLoad = null; }
  56439. if (onError === void 0) { onError = null; }
  56440. var _this = _super.call(this, scene) || this;
  56441. _this._useInGammaSpace = false;
  56442. _this._generateHarmonics = true;
  56443. _this._isBABYLONPreprocessed = false;
  56444. _this._onLoad = null;
  56445. _this._onError = null;
  56446. /**
  56447. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  56448. */
  56449. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  56450. /**
  56451. * The spherical polynomial data extracted from the texture.
  56452. */
  56453. _this.sphericalPolynomial = null;
  56454. /**
  56455. * Specifies wether the texture has been generated through the PMREMGenerator tool.
  56456. * This is usefull at run time to apply the good shader.
  56457. */
  56458. _this.isPMREM = false;
  56459. if (!url) {
  56460. return _this;
  56461. }
  56462. _this.name = url;
  56463. _this.url = url;
  56464. _this.hasAlpha = false;
  56465. _this.isCube = true;
  56466. _this._textureMatrix = BABYLON.Matrix.Identity();
  56467. _this._onLoad = onLoad;
  56468. _this._onError = onError;
  56469. if (size) {
  56470. _this._isBABYLONPreprocessed = false;
  56471. _this._noMipmap = noMipmap;
  56472. _this._size = size;
  56473. _this._useInGammaSpace = useInGammaSpace;
  56474. _this._usePMREMGenerator = usePMREMGenerator &&
  56475. scene.getEngine().getCaps().textureLOD &&
  56476. _this.getScene().getEngine().getCaps().textureFloat &&
  56477. !_this._useInGammaSpace;
  56478. }
  56479. else {
  56480. _this._isBABYLONPreprocessed = true;
  56481. _this._noMipmap = false;
  56482. _this._useInGammaSpace = false;
  56483. _this._usePMREMGenerator = scene.getEngine().getCaps().textureLOD &&
  56484. _this.getScene().getEngine().getCaps().textureFloat &&
  56485. !_this._useInGammaSpace;
  56486. }
  56487. _this.isPMREM = _this._usePMREMGenerator;
  56488. _this._texture = _this._getFromCache(url, _this._noMipmap);
  56489. if (!_this._texture) {
  56490. if (!scene.useDelayedTextureLoading) {
  56491. _this.loadTexture();
  56492. }
  56493. else {
  56494. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  56495. }
  56496. }
  56497. return _this;
  56498. }
  56499. /**
  56500. * Occurs when the file is a preprocessed .babylon.hdr file.
  56501. */
  56502. HDRCubeTexture.prototype.loadBabylonTexture = function () {
  56503. var _this = this;
  56504. var mipLevels = 0;
  56505. var floatArrayView = null;
  56506. var mipmapGenerator = (!this._useInGammaSpace && this.getScene().getEngine().getCaps().textureFloat) ? function (data) {
  56507. var mips = [];
  56508. var startIndex = 30;
  56509. for (var level = 0; level < mipLevels; level++) {
  56510. mips.push([]);
  56511. // Fill each pixel of the mip level.
  56512. var faceSize = Math.pow(_this._size >> level, 2) * 3;
  56513. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  56514. var faceData = floatArrayView.subarray(startIndex, startIndex + faceSize);
  56515. mips[level].push(faceData);
  56516. startIndex += faceSize;
  56517. }
  56518. }
  56519. return mips;
  56520. } : null;
  56521. var callback = function (buffer) {
  56522. // Create Native Array Views
  56523. var intArrayView = new Int32Array(buffer);
  56524. floatArrayView = new Float32Array(buffer);
  56525. // Fill header.
  56526. var version = intArrayView[0]; // Version 1. (MAy be use in case of format changes for backward compaibility)
  56527. _this._size = intArrayView[1]; // CubeMap max mip face size.
  56528. // Update Texture Information.
  56529. _this.getScene().getEngine().updateTextureSize(_this._texture, _this._size, _this._size);
  56530. // Fill polynomial information.
  56531. _this.sphericalPolynomial = new BABYLON.SphericalPolynomial();
  56532. _this.sphericalPolynomial.x.copyFromFloats(floatArrayView[2], floatArrayView[3], floatArrayView[4]);
  56533. _this.sphericalPolynomial.y.copyFromFloats(floatArrayView[5], floatArrayView[6], floatArrayView[7]);
  56534. _this.sphericalPolynomial.z.copyFromFloats(floatArrayView[8], floatArrayView[9], floatArrayView[10]);
  56535. _this.sphericalPolynomial.xx.copyFromFloats(floatArrayView[11], floatArrayView[12], floatArrayView[13]);
  56536. _this.sphericalPolynomial.yy.copyFromFloats(floatArrayView[14], floatArrayView[15], floatArrayView[16]);
  56537. _this.sphericalPolynomial.zz.copyFromFloats(floatArrayView[17], floatArrayView[18], floatArrayView[19]);
  56538. _this.sphericalPolynomial.xy.copyFromFloats(floatArrayView[20], floatArrayView[21], floatArrayView[22]);
  56539. _this.sphericalPolynomial.yz.copyFromFloats(floatArrayView[23], floatArrayView[24], floatArrayView[25]);
  56540. _this.sphericalPolynomial.zx.copyFromFloats(floatArrayView[26], floatArrayView[27], floatArrayView[28]);
  56541. // Fill pixel data.
  56542. mipLevels = intArrayView[29]; // Number of mip levels.
  56543. var startIndex = 30;
  56544. var data = [];
  56545. var faceSize = Math.pow(_this._size, 2) * 3;
  56546. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  56547. data.push(floatArrayView.subarray(startIndex, startIndex + faceSize));
  56548. startIndex += faceSize;
  56549. }
  56550. var results = [];
  56551. var byteArray = null;
  56552. // Push each faces.
  56553. for (var k = 0; k < 6; k++) {
  56554. var dataFace = null;
  56555. // If special cases.
  56556. if (!mipmapGenerator) {
  56557. var j = ([0, 2, 4, 1, 3, 5])[k]; // Transforms +X+Y+Z... to +X-X+Y-Y... if no mipmapgenerator...
  56558. dataFace = data[j];
  56559. if (!_this.getScene().getEngine().getCaps().textureFloat) {
  56560. // 3 channels of 1 bytes per pixel in bytes.
  56561. var byteBuffer = new ArrayBuffer(faceSize);
  56562. byteArray = new Uint8Array(byteBuffer);
  56563. }
  56564. for (var i = 0; i < _this._size * _this._size; i++) {
  56565. // Put in gamma space if requested.
  56566. if (_this._useInGammaSpace) {
  56567. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  56568. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  56569. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  56570. }
  56571. // Convert to int texture for fallback.
  56572. if (byteArray) {
  56573. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  56574. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  56575. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  56576. // May use luminance instead if the result is not accurate.
  56577. var max = Math.max(Math.max(r, g), b);
  56578. if (max > 255) {
  56579. var scale = 255 / max;
  56580. r *= scale;
  56581. g *= scale;
  56582. b *= scale;
  56583. }
  56584. byteArray[(i * 3) + 0] = r;
  56585. byteArray[(i * 3) + 1] = g;
  56586. byteArray[(i * 3) + 2] = b;
  56587. }
  56588. }
  56589. }
  56590. else {
  56591. dataFace = data[k];
  56592. }
  56593. // Fill the array accordingly.
  56594. if (byteArray) {
  56595. results.push(byteArray);
  56596. }
  56597. else {
  56598. results.push(dataFace);
  56599. }
  56600. }
  56601. return results;
  56602. };
  56603. 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, this._onLoad, this._onError);
  56604. };
  56605. /**
  56606. * Occurs when the file is raw .hdr file.
  56607. */
  56608. HDRCubeTexture.prototype.loadHDRTexture = function () {
  56609. var _this = this;
  56610. var callback = function (buffer) {
  56611. // Extract the raw linear data.
  56612. var data = BABYLON.Internals.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  56613. // Generate harmonics if needed.
  56614. if (_this._generateHarmonics) {
  56615. _this.sphericalPolynomial = BABYLON.Internals.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  56616. }
  56617. var results = [];
  56618. var byteArray = null;
  56619. // Push each faces.
  56620. for (var j = 0; j < 6; j++) {
  56621. // Create uintarray fallback.
  56622. if (!_this.getScene().getEngine().getCaps().textureFloat) {
  56623. // 3 channels of 1 bytes per pixel in bytes.
  56624. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  56625. byteArray = new Uint8Array(byteBuffer);
  56626. }
  56627. var dataFace = data[HDRCubeTexture._facesMapping[j]];
  56628. // If special cases.
  56629. if (_this._useInGammaSpace || byteArray) {
  56630. for (var i = 0; i < _this._size * _this._size; i++) {
  56631. // Put in gamma space if requested.
  56632. if (_this._useInGammaSpace) {
  56633. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  56634. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  56635. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  56636. }
  56637. // Convert to int texture for fallback.
  56638. if (byteArray) {
  56639. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  56640. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  56641. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  56642. // May use luminance instead if the result is not accurate.
  56643. var max = Math.max(Math.max(r, g), b);
  56644. if (max > 255) {
  56645. var scale = 255 / max;
  56646. r *= scale;
  56647. g *= scale;
  56648. b *= scale;
  56649. }
  56650. byteArray[(i * 3) + 0] = r;
  56651. byteArray[(i * 3) + 1] = g;
  56652. byteArray[(i * 3) + 2] = b;
  56653. }
  56654. }
  56655. }
  56656. if (byteArray) {
  56657. results.push(byteArray);
  56658. }
  56659. else {
  56660. results.push(dataFace);
  56661. }
  56662. }
  56663. return results;
  56664. };
  56665. var mipmapGenerator = null;
  56666. if (!this._noMipmap &&
  56667. this._usePMREMGenerator) {
  56668. mipmapGenerator = function (data) {
  56669. // Custom setup of the generator matching with the PBR shader values.
  56670. var generator = new BABYLON.Internals.PMREMGenerator(data, _this._size, _this._size, 0, 3, _this.getScene().getEngine().getCaps().textureFloat, 2048, 0.25, false, true);
  56671. return generator.filterCubeMap();
  56672. };
  56673. }
  56674. 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, this._onLoad, this._onError);
  56675. };
  56676. /**
  56677. * Starts the loading process of the texture.
  56678. */
  56679. HDRCubeTexture.prototype.loadTexture = function () {
  56680. if (this._isBABYLONPreprocessed) {
  56681. this.loadBabylonTexture();
  56682. }
  56683. else {
  56684. this.loadHDRTexture();
  56685. }
  56686. };
  56687. HDRCubeTexture.prototype.clone = function () {
  56688. var size = this._isBABYLONPreprocessed ? null : this._size;
  56689. var newTexture = new HDRCubeTexture(this.url, this.getScene(), size, this._noMipmap, this._generateHarmonics, this._useInGammaSpace, this._usePMREMGenerator);
  56690. // Base texture
  56691. newTexture.level = this.level;
  56692. newTexture.wrapU = this.wrapU;
  56693. newTexture.wrapV = this.wrapV;
  56694. newTexture.coordinatesIndex = this.coordinatesIndex;
  56695. newTexture.coordinatesMode = this.coordinatesMode;
  56696. return newTexture;
  56697. };
  56698. // Methods
  56699. HDRCubeTexture.prototype.delayLoad = function () {
  56700. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  56701. return;
  56702. }
  56703. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  56704. this._texture = this._getFromCache(this.url, this._noMipmap);
  56705. if (!this._texture) {
  56706. this.loadTexture();
  56707. }
  56708. };
  56709. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  56710. return this._textureMatrix;
  56711. };
  56712. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  56713. var texture = null;
  56714. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  56715. var size = parsedTexture.isBABYLONPreprocessed ? null : parsedTexture.size;
  56716. texture = new BABYLON.HDRCubeTexture(rootUrl + parsedTexture.name, scene, size, parsedTexture.noMipmap, parsedTexture.generateHarmonics, parsedTexture.useInGammaSpace, parsedTexture.usePMREMGenerator);
  56717. texture.name = parsedTexture.name;
  56718. texture.hasAlpha = parsedTexture.hasAlpha;
  56719. texture.level = parsedTexture.level;
  56720. texture.coordinatesMode = parsedTexture.coordinatesMode;
  56721. }
  56722. return texture;
  56723. };
  56724. HDRCubeTexture.prototype.serialize = function () {
  56725. if (!this.name) {
  56726. return null;
  56727. }
  56728. var serializationObject = {};
  56729. serializationObject.name = this.name;
  56730. serializationObject.hasAlpha = this.hasAlpha;
  56731. serializationObject.isCube = true;
  56732. serializationObject.level = this.level;
  56733. serializationObject.size = this._size;
  56734. serializationObject.coordinatesMode = this.coordinatesMode;
  56735. serializationObject.useInGammaSpace = this._useInGammaSpace;
  56736. serializationObject.generateHarmonics = this._generateHarmonics;
  56737. serializationObject.usePMREMGenerator = this._usePMREMGenerator;
  56738. serializationObject.isBABYLONPreprocessed = this._isBABYLONPreprocessed;
  56739. serializationObject.customType = "BABYLON.HDRCubeTexture";
  56740. serializationObject.noMipmap = this._noMipmap;
  56741. return serializationObject;
  56742. };
  56743. /**
  56744. * Saves as a file the data contained in the texture in a binary format.
  56745. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  56746. * as the spherical used in the lighting.
  56747. * @param url The HDR file url.
  56748. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  56749. * @param onError Method called if any error happens during download.
  56750. * @return The packed binary data.
  56751. */
  56752. HDRCubeTexture.generateBabylonHDROnDisk = function (url, size, onError) {
  56753. if (onError === void 0) { onError = null; }
  56754. var callback = function (buffer) {
  56755. var data = new Blob([buffer], { type: 'application/octet-stream' });
  56756. // Returns a URL you can use as a href.
  56757. var objUrl = window.URL.createObjectURL(data);
  56758. // Simulates a link to it and click to dowload.
  56759. var a = document.createElement("a");
  56760. document.body.appendChild(a);
  56761. a.style.display = "none";
  56762. a.href = objUrl;
  56763. a.download = "envmap.babylon.hdr";
  56764. a.click();
  56765. };
  56766. HDRCubeTexture.generateBabylonHDR(url, size, callback, onError);
  56767. };
  56768. /**
  56769. * Serializes the data contained in the texture in a binary format.
  56770. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  56771. * as the spherical used in the lighting.
  56772. * @param url The HDR file url.
  56773. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  56774. * @param onError Method called if any error happens during download.
  56775. * @return The packed binary data.
  56776. */
  56777. HDRCubeTexture.generateBabylonHDR = function (url, size, callback, onError) {
  56778. if (onError === void 0) { onError = null; }
  56779. // Needs the url tho create the texture.
  56780. if (!url) {
  56781. return null;
  56782. }
  56783. // Check Power of two size.
  56784. if (!BABYLON.Tools.IsExponentOfTwo(size)) {
  56785. return null;
  56786. }
  56787. var getDataCallback = function (dataBuffer) {
  56788. // Extract the raw linear data.
  56789. var cubeData = BABYLON.Internals.HDRTools.GetCubeMapTextureData(dataBuffer, size);
  56790. // Generate harmonics if needed.
  56791. var sphericalPolynomial = BABYLON.Internals.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(cubeData);
  56792. // Generate seamless faces
  56793. var mipGeneratorArray = [];
  56794. // Data are known to be in +X +Y +Z -X -Y -Z
  56795. // mipmmapGenerator data is expected to be order in +X -X +Y -Y +Z -Z
  56796. mipGeneratorArray.push(cubeData.right); // +X
  56797. mipGeneratorArray.push(cubeData.left); // -X
  56798. mipGeneratorArray.push(cubeData.up); // +Y
  56799. mipGeneratorArray.push(cubeData.down); // -Y
  56800. mipGeneratorArray.push(cubeData.front); // +Z
  56801. mipGeneratorArray.push(cubeData.back); // -Z
  56802. // Custom setup of the generator matching with the PBR shader values.
  56803. var generator = new BABYLON.Internals.PMREMGenerator(mipGeneratorArray, size, size, 0, 3, true, 2048, 0.25, false, true);
  56804. var mippedData = generator.filterCubeMap();
  56805. // Compute required byte length.
  56806. var byteLength = 1 * 4; // Raw Data Version int32.
  56807. byteLength += 4; // CubeMap max mip face size int32.
  56808. byteLength += (9 * 3 * 4); // Spherical polynomial byte length 9 Vector 3 of floats.
  56809. // Add data size.
  56810. byteLength += 4; // Number of mip levels int32.
  56811. for (var level = 0; level < mippedData.length; level++) {
  56812. var mipSize = size >> level;
  56813. byteLength += (6 * mipSize * mipSize * 3 * 4); // 6 faces of size squared rgb float pixels.
  56814. }
  56815. // Prepare binary structure.
  56816. var buffer = new ArrayBuffer(byteLength);
  56817. var intArrayView = new Int32Array(buffer);
  56818. var floatArrayView = new Float32Array(buffer);
  56819. // Fill header.
  56820. intArrayView[0] = 1; // Version 1.
  56821. intArrayView[1] = size; // CubeMap max mip face size.
  56822. // Fill polynomial information.
  56823. sphericalPolynomial.x.toArray(floatArrayView, 2);
  56824. sphericalPolynomial.y.toArray(floatArrayView, 5);
  56825. sphericalPolynomial.z.toArray(floatArrayView, 8);
  56826. sphericalPolynomial.xx.toArray(floatArrayView, 11);
  56827. sphericalPolynomial.yy.toArray(floatArrayView, 14);
  56828. sphericalPolynomial.zz.toArray(floatArrayView, 17);
  56829. sphericalPolynomial.xy.toArray(floatArrayView, 20);
  56830. sphericalPolynomial.yz.toArray(floatArrayView, 23);
  56831. sphericalPolynomial.zx.toArray(floatArrayView, 26);
  56832. // Fill pixel data.
  56833. intArrayView[29] = mippedData.length; // Number of mip levels.
  56834. var startIndex = 30;
  56835. for (var level = 0; level < mippedData.length; level++) {
  56836. // Fill each pixel of the mip level.
  56837. var faceSize = Math.pow(size >> level, 2) * 3;
  56838. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  56839. floatArrayView.set(mippedData[level][faceIndex], startIndex);
  56840. startIndex += faceSize;
  56841. }
  56842. }
  56843. // Callback.
  56844. callback(buffer);
  56845. };
  56846. // Download and process.
  56847. BABYLON.Tools.LoadFile(url, function (data) {
  56848. getDataCallback(data);
  56849. }, null, null, true, onError);
  56850. };
  56851. return HDRCubeTexture;
  56852. }(BABYLON.BaseTexture));
  56853. HDRCubeTexture._facesMapping = [
  56854. "right",
  56855. "up",
  56856. "front",
  56857. "left",
  56858. "down",
  56859. "back"
  56860. ];
  56861. BABYLON.HDRCubeTexture = HDRCubeTexture;
  56862. })(BABYLON || (BABYLON = {}));
  56863. //# sourceMappingURL=babylon.hdrCubeTexture.js.map
  56864. var BABYLON;
  56865. (function (BABYLON) {
  56866. var Debug;
  56867. (function (Debug) {
  56868. /**
  56869. * Demo available here: http://www.babylonjs-playground.com/#1BZJVJ#8
  56870. */
  56871. var SkeletonViewer = (function () {
  56872. function SkeletonViewer(skeleton, mesh, scene, autoUpdateBonesMatrices, renderingGroupId) {
  56873. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  56874. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  56875. this.skeleton = skeleton;
  56876. this.mesh = mesh;
  56877. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  56878. this.renderingGroupId = renderingGroupId;
  56879. this.color = BABYLON.Color3.White();
  56880. this._debugLines = [];
  56881. this._isEnabled = false;
  56882. this._scene = scene;
  56883. this.update();
  56884. this._renderFunction = this.update.bind(this);
  56885. }
  56886. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  56887. get: function () {
  56888. return this._isEnabled;
  56889. },
  56890. set: function (value) {
  56891. if (this._isEnabled === value) {
  56892. return;
  56893. }
  56894. this._isEnabled = value;
  56895. if (value) {
  56896. this._scene.registerBeforeRender(this._renderFunction);
  56897. }
  56898. else {
  56899. this._scene.unregisterBeforeRender(this._renderFunction);
  56900. }
  56901. },
  56902. enumerable: true,
  56903. configurable: true
  56904. });
  56905. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  56906. if (x === void 0) { x = 0; }
  56907. if (y === void 0) { y = 0; }
  56908. if (z === void 0) { z = 0; }
  56909. var tmat = BABYLON.Tmp.Matrix[0];
  56910. var parentBone = bone.getParent();
  56911. tmat.copyFrom(bone.getLocalMatrix());
  56912. if (x !== 0 || y !== 0 || z !== 0) {
  56913. var tmat2 = BABYLON.Tmp.Matrix[1];
  56914. BABYLON.Matrix.IdentityToRef(tmat2);
  56915. tmat2.m[12] = x;
  56916. tmat2.m[13] = y;
  56917. tmat2.m[14] = z;
  56918. tmat2.multiplyToRef(tmat, tmat);
  56919. }
  56920. if (parentBone) {
  56921. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  56922. }
  56923. tmat.multiplyToRef(meshMat, tmat);
  56924. position.x = tmat.m[12];
  56925. position.y = tmat.m[13];
  56926. position.z = tmat.m[14];
  56927. };
  56928. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  56929. var len = bones.length;
  56930. for (var i = 0; i < len; i++) {
  56931. var bone = bones[i];
  56932. var points = this._debugLines[i];
  56933. if (!points) {
  56934. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  56935. this._debugLines[i] = points;
  56936. }
  56937. this._getBonePosition(points[0], bone, meshMat);
  56938. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  56939. }
  56940. };
  56941. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  56942. var len = bones.length;
  56943. var boneNum = 0;
  56944. for (var i = len - 1; i >= 0; i--) {
  56945. var childBone = bones[i];
  56946. var parentBone = childBone.getParent();
  56947. if (!parentBone) {
  56948. continue;
  56949. }
  56950. var points = this._debugLines[boneNum];
  56951. if (!points) {
  56952. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  56953. this._debugLines[boneNum] = points;
  56954. }
  56955. childBone.getAbsolutePositionToRef(this.mesh, points[0]);
  56956. parentBone.getAbsolutePositionToRef(this.mesh, points[1]);
  56957. boneNum++;
  56958. }
  56959. };
  56960. SkeletonViewer.prototype.update = function () {
  56961. if (this.autoUpdateBonesMatrices) {
  56962. this.skeleton.computeAbsoluteTransforms();
  56963. }
  56964. if (this.skeleton.bones[0].length === undefined) {
  56965. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  56966. }
  56967. else {
  56968. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  56969. }
  56970. if (!this._debugMesh) {
  56971. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem(null, { lines: this._debugLines, updatable: true }, this._scene);
  56972. this._debugMesh.renderingGroupId = this.renderingGroupId;
  56973. }
  56974. else {
  56975. BABYLON.MeshBuilder.CreateLineSystem(null, { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  56976. }
  56977. this._debugMesh.color = this.color;
  56978. };
  56979. SkeletonViewer.prototype.dispose = function () {
  56980. if (this._debugMesh) {
  56981. this.isEnabled = false;
  56982. this._debugMesh.dispose();
  56983. this._debugMesh = null;
  56984. }
  56985. };
  56986. return SkeletonViewer;
  56987. }());
  56988. Debug.SkeletonViewer = SkeletonViewer;
  56989. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  56990. })(BABYLON || (BABYLON = {}));
  56991. //# sourceMappingURL=babylon.skeletonViewer.js.map
  56992. var BABYLON;
  56993. (function (BABYLON) {
  56994. var Debug;
  56995. (function (Debug) {
  56996. var AxesViewer = (function () {
  56997. function AxesViewer(scene, scaleLines) {
  56998. if (scaleLines === void 0) { scaleLines = 1; }
  56999. this._xline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  57000. this._yline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  57001. this._zline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  57002. this.scaleLines = 1;
  57003. this.scaleLines = scaleLines;
  57004. this._xmesh = BABYLON.Mesh.CreateLines("xline", this._xline, scene, true);
  57005. this._ymesh = BABYLON.Mesh.CreateLines("yline", this._yline, scene, true);
  57006. this._zmesh = BABYLON.Mesh.CreateLines("zline", this._zline, scene, true);
  57007. this._xmesh.renderingGroupId = 2;
  57008. this._ymesh.renderingGroupId = 2;
  57009. this._zmesh.renderingGroupId = 2;
  57010. this._xmesh.material.checkReadyOnlyOnce = true;
  57011. this._xmesh.color = new BABYLON.Color3(1, 0, 0);
  57012. this._ymesh.material.checkReadyOnlyOnce = true;
  57013. this._ymesh.color = new BABYLON.Color3(0, 1, 0);
  57014. this._zmesh.material.checkReadyOnlyOnce = true;
  57015. this._zmesh.color = new BABYLON.Color3(0, 0, 1);
  57016. this.scene = scene;
  57017. }
  57018. AxesViewer.prototype.update = function (position, xaxis, yaxis, zaxis) {
  57019. var scaleLines = this.scaleLines;
  57020. var point1 = this._xline[0];
  57021. var point2 = this._xline[1];
  57022. point1.x = position.x;
  57023. point1.y = position.y;
  57024. point1.z = position.z;
  57025. point2.x = point1.x + xaxis.x * scaleLines;
  57026. point2.y = point1.y + xaxis.y * scaleLines;
  57027. point2.z = point1.z + xaxis.z * scaleLines;
  57028. BABYLON.Mesh.CreateLines(null, this._xline, null, null, this._xmesh);
  57029. point1 = this._yline[0];
  57030. point2 = this._yline[1];
  57031. point1.x = position.x;
  57032. point1.y = position.y;
  57033. point1.z = position.z;
  57034. point2.x = point1.x + yaxis.x * scaleLines;
  57035. point2.y = point1.y + yaxis.y * scaleLines;
  57036. point2.z = point1.z + yaxis.z * scaleLines;
  57037. BABYLON.Mesh.CreateLines(null, this._yline, null, null, this._ymesh);
  57038. point1 = this._zline[0];
  57039. point2 = this._zline[1];
  57040. point1.x = position.x;
  57041. point1.y = position.y;
  57042. point1.z = position.z;
  57043. point2.x = point1.x + zaxis.x * scaleLines;
  57044. point2.y = point1.y + zaxis.y * scaleLines;
  57045. point2.z = point1.z + zaxis.z * scaleLines;
  57046. BABYLON.Mesh.CreateLines(null, this._zline, null, null, this._zmesh);
  57047. };
  57048. AxesViewer.prototype.dispose = function () {
  57049. if (this._xmesh) {
  57050. this._xmesh.dispose();
  57051. this._ymesh.dispose();
  57052. this._zmesh.dispose();
  57053. this._xmesh = null;
  57054. this._ymesh = null;
  57055. this._zmesh = null;
  57056. this._xline = null;
  57057. this._yline = null;
  57058. this._zline = null;
  57059. this.scene = null;
  57060. }
  57061. };
  57062. return AxesViewer;
  57063. }());
  57064. Debug.AxesViewer = AxesViewer;
  57065. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  57066. })(BABYLON || (BABYLON = {}));
  57067. //# sourceMappingURL=babylon.axesViewer.js.map
  57068. var BABYLON;
  57069. (function (BABYLON) {
  57070. var Debug;
  57071. (function (Debug) {
  57072. var BoneAxesViewer = (function (_super) {
  57073. __extends(BoneAxesViewer, _super);
  57074. function BoneAxesViewer(scene, bone, mesh, scaleLines) {
  57075. if (scaleLines === void 0) { scaleLines = 1; }
  57076. var _this = _super.call(this, scene, scaleLines) || this;
  57077. _this.pos = BABYLON.Vector3.Zero();
  57078. _this.xaxis = BABYLON.Vector3.Zero();
  57079. _this.yaxis = BABYLON.Vector3.Zero();
  57080. _this.zaxis = BABYLON.Vector3.Zero();
  57081. _this.mesh = mesh;
  57082. _this.bone = bone;
  57083. return _this;
  57084. }
  57085. BoneAxesViewer.prototype.update = function () {
  57086. var bone = this.bone;
  57087. bone.getAbsolutePositionToRef(this.mesh, this.pos);
  57088. bone.getDirectionToRef(BABYLON.Axis.X, this.mesh, this.xaxis);
  57089. bone.getDirectionToRef(BABYLON.Axis.Y, this.mesh, this.yaxis);
  57090. bone.getDirectionToRef(BABYLON.Axis.Z, this.mesh, this.zaxis);
  57091. _super.prototype.update.call(this, this.pos, this.xaxis, this.yaxis, this.zaxis);
  57092. };
  57093. BoneAxesViewer.prototype.dispose = function () {
  57094. if (this.pos) {
  57095. this.pos = null;
  57096. this.xaxis = null;
  57097. this.yaxis = null;
  57098. this.zaxis = null;
  57099. this.mesh = null;
  57100. this.bone = null;
  57101. _super.prototype.dispose.call(this);
  57102. }
  57103. };
  57104. return BoneAxesViewer;
  57105. }(Debug.AxesViewer));
  57106. Debug.BoneAxesViewer = BoneAxesViewer;
  57107. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  57108. })(BABYLON || (BABYLON = {}));
  57109. //# sourceMappingURL=babylon.boneAxesViewer.js.map
  57110. var BABYLON;
  57111. (function (BABYLON) {
  57112. /**
  57113. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  57114. * It can help converting any input color in a desired output one. This can then be used to create effects
  57115. * from sepia, black and white to sixties or futuristic rendering...
  57116. *
  57117. * The only supported format is currently 3dl.
  57118. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
  57119. */
  57120. var ColorGradingTexture = (function (_super) {
  57121. __extends(ColorGradingTexture, _super);
  57122. /**
  57123. * Instantiates a ColorGradingTexture from the following parameters.
  57124. *
  57125. * @param url The location of the color gradind data (currently only supporting 3dl)
  57126. * @param scene The scene the texture will be used in
  57127. */
  57128. function ColorGradingTexture(url, scene) {
  57129. var _this = _super.call(this, scene) || this;
  57130. if (!url) {
  57131. return _this;
  57132. }
  57133. _this._textureMatrix = BABYLON.Matrix.Identity();
  57134. _this.name = url;
  57135. _this.url = url;
  57136. _this.hasAlpha = false;
  57137. _this.isCube = false;
  57138. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  57139. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  57140. _this.anisotropicFilteringLevel = 1;
  57141. _this._texture = _this._getFromCache(url, true);
  57142. if (!_this._texture) {
  57143. if (!scene.useDelayedTextureLoading) {
  57144. _this.loadTexture();
  57145. }
  57146. else {
  57147. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  57148. }
  57149. }
  57150. return _this;
  57151. }
  57152. /**
  57153. * Returns the texture matrix used in most of the material.
  57154. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  57155. */
  57156. ColorGradingTexture.prototype.getTextureMatrix = function () {
  57157. return this._textureMatrix;
  57158. };
  57159. /**
  57160. * Occurs when the file being loaded is a .3dl LUT file.
  57161. */
  57162. ColorGradingTexture.prototype.load3dlTexture = function () {
  57163. var _this = this;
  57164. var mipLevels = 0;
  57165. var floatArrayView = null;
  57166. var texture = this.getScene().getEngine().createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  57167. this._texture = texture;
  57168. var callback = function (text) {
  57169. var data;
  57170. var tempData;
  57171. var line;
  57172. var lines = text.split('\n');
  57173. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  57174. var maxColor = 0;
  57175. for (var i = 0; i < lines.length; i++) {
  57176. line = lines[i];
  57177. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  57178. continue;
  57179. if (line.indexOf('#') === 0)
  57180. continue;
  57181. var words = line.split(" ");
  57182. if (size === 0) {
  57183. // Number of space + one
  57184. size = words.length;
  57185. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  57186. tempData = new Float32Array(size * size * size * 4);
  57187. continue;
  57188. }
  57189. if (size != 0) {
  57190. var r = Math.max(parseInt(words[0]), 0);
  57191. var g = Math.max(parseInt(words[1]), 0);
  57192. var b = Math.max(parseInt(words[2]), 0);
  57193. maxColor = Math.max(r, maxColor);
  57194. maxColor = Math.max(g, maxColor);
  57195. maxColor = Math.max(b, maxColor);
  57196. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  57197. tempData[pixelStorageIndex + 0] = r;
  57198. tempData[pixelStorageIndex + 1] = g;
  57199. tempData[pixelStorageIndex + 2] = b;
  57200. tempData[pixelStorageIndex + 3] = 0;
  57201. pixelIndexSlice++;
  57202. if (pixelIndexSlice % size == 0) {
  57203. pixelIndexH++;
  57204. pixelIndexSlice = 0;
  57205. if (pixelIndexH % size == 0) {
  57206. pixelIndexW++;
  57207. pixelIndexH = 0;
  57208. }
  57209. }
  57210. }
  57211. }
  57212. for (var i = 0; i < tempData.length; i++) {
  57213. var value = tempData[i];
  57214. data[i] = (value / maxColor * 255);
  57215. }
  57216. _this.getScene().getEngine().updateTextureSize(texture, size * size, size);
  57217. _this.getScene().getEngine().updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  57218. };
  57219. BABYLON.Tools.LoadFile(this.url, callback);
  57220. return this._texture;
  57221. };
  57222. /**
  57223. * Starts the loading process of the texture.
  57224. */
  57225. ColorGradingTexture.prototype.loadTexture = function () {
  57226. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  57227. this.load3dlTexture();
  57228. }
  57229. };
  57230. /**
  57231. * Clones the color gradind texture.
  57232. */
  57233. ColorGradingTexture.prototype.clone = function () {
  57234. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  57235. // Base texture
  57236. newTexture.level = this.level;
  57237. return newTexture;
  57238. };
  57239. /**
  57240. * Called during delayed load for textures.
  57241. */
  57242. ColorGradingTexture.prototype.delayLoad = function () {
  57243. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  57244. return;
  57245. }
  57246. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  57247. this._texture = this._getFromCache(this.url, true);
  57248. if (!this._texture) {
  57249. this.loadTexture();
  57250. }
  57251. };
  57252. /**
  57253. * Binds the color grading to the shader.
  57254. * @param colorGrading The texture to bind
  57255. * @param effect The effect to bind to
  57256. */
  57257. ColorGradingTexture.Bind = function (colorGrading, effect) {
  57258. effect.setTexture("cameraColorGrading2DSampler", colorGrading);
  57259. var x = colorGrading.level; // Texture Level
  57260. var y = colorGrading.getSize().height; // Texture Size example with 8
  57261. var z = y - 1.0; // SizeMinusOne 8 - 1
  57262. var w = 1 / y; // Space of 1 slice 1 / 8
  57263. effect.setFloat4("vCameraColorGradingInfos", x, y, z, w);
  57264. var slicePixelSizeU = w / y; // Space of 1 pixel in U direction, e.g. 1/64
  57265. 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
  57266. 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
  57267. 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
  57268. var z2 = 0.5 * slicePixelSizeU; // Offset of lookup range in U to align sample position with texel centre, for example 0.5/64
  57269. var w2 = 0.5 * slicePixelSizeV; // Offset of lookup range in V to align sample position with texel centre, for example 0.5/8
  57270. effect.setFloat4("vCameraColorGradingScaleOffset", x2, y2, z2, w2);
  57271. };
  57272. /**
  57273. * Prepare the list of uniforms associated with the ColorGrading effects.
  57274. * @param uniformsList The list of uniforms used in the effect
  57275. * @param samplersList The list of samplers used in the effect
  57276. */
  57277. ColorGradingTexture.PrepareUniformsAndSamplers = function (uniformsList, samplersList) {
  57278. uniformsList.push("vCameraColorGradingInfos", "vCameraColorGradingScaleOffset");
  57279. samplersList.push("cameraColorGrading2DSampler");
  57280. };
  57281. /**
  57282. * Parses a color grading texture serialized by Babylon.
  57283. * @param parsedTexture The texture information being parsedTexture
  57284. * @param scene The scene to load the texture in
  57285. * @param rootUrl The root url of the data assets to load
  57286. * @return A color gradind texture
  57287. */
  57288. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  57289. var texture = null;
  57290. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  57291. texture = new BABYLON.ColorGradingTexture(parsedTexture.name, scene);
  57292. texture.name = parsedTexture.name;
  57293. texture.level = parsedTexture.level;
  57294. }
  57295. return texture;
  57296. };
  57297. /**
  57298. * Serializes the LUT texture to json format.
  57299. */
  57300. ColorGradingTexture.prototype.serialize = function () {
  57301. if (!this.name) {
  57302. return null;
  57303. }
  57304. var serializationObject = {};
  57305. serializationObject.name = this.name;
  57306. serializationObject.level = this.level;
  57307. serializationObject.customType = "BABYLON.ColorGradingTexture";
  57308. return serializationObject;
  57309. };
  57310. return ColorGradingTexture;
  57311. }(BABYLON.BaseTexture));
  57312. /**
  57313. * Empty line regex stored for GC.
  57314. */
  57315. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  57316. BABYLON.ColorGradingTexture = ColorGradingTexture;
  57317. })(BABYLON || (BABYLON = {}));
  57318. //# sourceMappingURL=babylon.colorGradingTexture.js.map
  57319. var BABYLON;
  57320. (function (BABYLON) {
  57321. /**
  57322. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  57323. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  57324. * 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;
  57325. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  57326. */
  57327. var ColorCurves = (function () {
  57328. function ColorCurves() {
  57329. this._dirty = true;
  57330. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  57331. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  57332. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  57333. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  57334. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  57335. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  57336. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  57337. this._globalHue = 30;
  57338. this._globalDensity = 0;
  57339. this._globalSaturation = 0;
  57340. this._globalExposure = 0;
  57341. this._highlightsHue = 30;
  57342. this._highlightsDensity = 0;
  57343. this._highlightsSaturation = 0;
  57344. this._highlightsExposure = 0;
  57345. this._midtonesHue = 30;
  57346. this._midtonesDensity = 0;
  57347. this._midtonesSaturation = 0;
  57348. this._midtonesExposure = 0;
  57349. this._shadowsHue = 30;
  57350. this._shadowsDensity = 0;
  57351. this._shadowsSaturation = 0;
  57352. this._shadowsExposure = 0;
  57353. }
  57354. Object.defineProperty(ColorCurves.prototype, "GlobalHue", {
  57355. /**
  57356. * Gets the global Hue value.
  57357. * 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).
  57358. */
  57359. get: function () {
  57360. return this._globalHue;
  57361. },
  57362. /**
  57363. * Sets the global Hue value.
  57364. * 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).
  57365. */
  57366. set: function (value) {
  57367. this._globalHue = value;
  57368. this._dirty = true;
  57369. },
  57370. enumerable: true,
  57371. configurable: true
  57372. });
  57373. Object.defineProperty(ColorCurves.prototype, "GlobalDensity", {
  57374. /**
  57375. * Gets the global Density value.
  57376. * 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.
  57377. * Values less than zero provide a filter of opposite hue.
  57378. */
  57379. get: function () {
  57380. return this._globalDensity;
  57381. },
  57382. /**
  57383. * Sets the global Density value.
  57384. * 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.
  57385. * Values less than zero provide a filter of opposite hue.
  57386. */
  57387. set: function (value) {
  57388. this._globalDensity = value;
  57389. this._dirty = true;
  57390. },
  57391. enumerable: true,
  57392. configurable: true
  57393. });
  57394. Object.defineProperty(ColorCurves.prototype, "GlobalSaturation", {
  57395. /**
  57396. * Gets the global Saturation value.
  57397. * 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.
  57398. */
  57399. get: function () {
  57400. return this._globalSaturation;
  57401. },
  57402. /**
  57403. * Sets the global Saturation value.
  57404. * 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.
  57405. */
  57406. set: function (value) {
  57407. this._globalSaturation = value;
  57408. this._dirty = true;
  57409. },
  57410. enumerable: true,
  57411. configurable: true
  57412. });
  57413. Object.defineProperty(ColorCurves.prototype, "HighlightsHue", {
  57414. /**
  57415. * Gets the highlights Hue value.
  57416. * 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).
  57417. */
  57418. get: function () {
  57419. return this._highlightsHue;
  57420. },
  57421. /**
  57422. * Sets the highlights Hue value.
  57423. * 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).
  57424. */
  57425. set: function (value) {
  57426. this._highlightsHue = value;
  57427. this._dirty = true;
  57428. },
  57429. enumerable: true,
  57430. configurable: true
  57431. });
  57432. Object.defineProperty(ColorCurves.prototype, "HighlightsDensity", {
  57433. /**
  57434. * Gets the highlights Density value.
  57435. * 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.
  57436. * Values less than zero provide a filter of opposite hue.
  57437. */
  57438. get: function () {
  57439. return this._highlightsDensity;
  57440. },
  57441. /**
  57442. * Sets the highlights Density value.
  57443. * 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.
  57444. * Values less than zero provide a filter of opposite hue.
  57445. */
  57446. set: function (value) {
  57447. this._highlightsDensity = value;
  57448. this._dirty = true;
  57449. },
  57450. enumerable: true,
  57451. configurable: true
  57452. });
  57453. Object.defineProperty(ColorCurves.prototype, "HighlightsSaturation", {
  57454. /**
  57455. * Gets the highlights Saturation value.
  57456. * 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.
  57457. */
  57458. get: function () {
  57459. return this._highlightsSaturation;
  57460. },
  57461. /**
  57462. * Sets the highlights Saturation value.
  57463. * 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.
  57464. */
  57465. set: function (value) {
  57466. this._highlightsSaturation = value;
  57467. this._dirty = true;
  57468. },
  57469. enumerable: true,
  57470. configurable: true
  57471. });
  57472. Object.defineProperty(ColorCurves.prototype, "HighlightsExposure", {
  57473. /**
  57474. * Gets the highlights Exposure value.
  57475. * 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.
  57476. */
  57477. get: function () {
  57478. return this._highlightsExposure;
  57479. },
  57480. /**
  57481. * Sets the highlights Exposure value.
  57482. * 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.
  57483. */
  57484. set: function (value) {
  57485. this._highlightsExposure = value;
  57486. this._dirty = true;
  57487. },
  57488. enumerable: true,
  57489. configurable: true
  57490. });
  57491. Object.defineProperty(ColorCurves.prototype, "MidtonesHue", {
  57492. /**
  57493. * Gets the midtones Hue value.
  57494. * 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).
  57495. */
  57496. get: function () {
  57497. return this._midtonesHue;
  57498. },
  57499. /**
  57500. * Sets the midtones Hue value.
  57501. * 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).
  57502. */
  57503. set: function (value) {
  57504. this._midtonesHue = value;
  57505. this._dirty = true;
  57506. },
  57507. enumerable: true,
  57508. configurable: true
  57509. });
  57510. Object.defineProperty(ColorCurves.prototype, "MidtonesDensity", {
  57511. /**
  57512. * Gets the midtones Density value.
  57513. * 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.
  57514. * Values less than zero provide a filter of opposite hue.
  57515. */
  57516. get: function () {
  57517. return this._midtonesDensity;
  57518. },
  57519. /**
  57520. * Sets the midtones Density value.
  57521. * 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.
  57522. * Values less than zero provide a filter of opposite hue.
  57523. */
  57524. set: function (value) {
  57525. this._midtonesDensity = value;
  57526. this._dirty = true;
  57527. },
  57528. enumerable: true,
  57529. configurable: true
  57530. });
  57531. Object.defineProperty(ColorCurves.prototype, "MidtonesSaturation", {
  57532. /**
  57533. * Gets the midtones Saturation value.
  57534. * 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.
  57535. */
  57536. get: function () {
  57537. return this._midtonesSaturation;
  57538. },
  57539. /**
  57540. * Sets the midtones Saturation value.
  57541. * 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.
  57542. */
  57543. set: function (value) {
  57544. this._midtonesSaturation = value;
  57545. this._dirty = true;
  57546. },
  57547. enumerable: true,
  57548. configurable: true
  57549. });
  57550. Object.defineProperty(ColorCurves.prototype, "MidtonesExposure", {
  57551. /**
  57552. * Gets the midtones Exposure value.
  57553. * 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.
  57554. */
  57555. get: function () {
  57556. return this._midtonesExposure;
  57557. },
  57558. /**
  57559. * Sets the midtones Exposure value.
  57560. * 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.
  57561. */
  57562. set: function (value) {
  57563. this._midtonesExposure = value;
  57564. this._dirty = true;
  57565. },
  57566. enumerable: true,
  57567. configurable: true
  57568. });
  57569. Object.defineProperty(ColorCurves.prototype, "ShadowsHue", {
  57570. /**
  57571. * Gets the shadows Hue value.
  57572. * 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).
  57573. */
  57574. get: function () {
  57575. return this._shadowsHue;
  57576. },
  57577. /**
  57578. * Sets the shadows Hue value.
  57579. * 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).
  57580. */
  57581. set: function (value) {
  57582. this._shadowsHue = value;
  57583. this._dirty = true;
  57584. },
  57585. enumerable: true,
  57586. configurable: true
  57587. });
  57588. Object.defineProperty(ColorCurves.prototype, "ShadowsDensity", {
  57589. /**
  57590. * Gets the shadows Density value.
  57591. * 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.
  57592. * Values less than zero provide a filter of opposite hue.
  57593. */
  57594. get: function () {
  57595. return this._shadowsDensity;
  57596. },
  57597. /**
  57598. * Sets the shadows Density value.
  57599. * 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.
  57600. * Values less than zero provide a filter of opposite hue.
  57601. */
  57602. set: function (value) {
  57603. this._shadowsDensity = value;
  57604. this._dirty = true;
  57605. },
  57606. enumerable: true,
  57607. configurable: true
  57608. });
  57609. Object.defineProperty(ColorCurves.prototype, "ShadowsSaturation", {
  57610. /**
  57611. * Gets the shadows Saturation value.
  57612. * 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.
  57613. */
  57614. get: function () {
  57615. return this._shadowsSaturation;
  57616. },
  57617. /**
  57618. * Sets the shadows Saturation value.
  57619. * 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.
  57620. */
  57621. set: function (value) {
  57622. this._shadowsSaturation = value;
  57623. this._dirty = true;
  57624. },
  57625. enumerable: true,
  57626. configurable: true
  57627. });
  57628. Object.defineProperty(ColorCurves.prototype, "ShadowsExposure", {
  57629. /**
  57630. * Gets the shadows Exposure value.
  57631. * 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.
  57632. */
  57633. get: function () {
  57634. return this._shadowsExposure;
  57635. },
  57636. /**
  57637. * Sets the shadows Exposure value.
  57638. * 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.
  57639. */
  57640. set: function (value) {
  57641. this._shadowsExposure = value;
  57642. this._dirty = true;
  57643. },
  57644. enumerable: true,
  57645. configurable: true
  57646. });
  57647. /**
  57648. * Binds the color curves to the shader.
  57649. * @param colorCurves The color curve to bind
  57650. * @param effect The effect to bind to
  57651. */
  57652. ColorCurves.Bind = function (colorCurves, effect) {
  57653. if (colorCurves._dirty) {
  57654. colorCurves._dirty = false;
  57655. // Fill in global info.
  57656. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  57657. // Compute highlights info.
  57658. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  57659. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  57660. // Compute midtones info.
  57661. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  57662. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  57663. // Compute shadows info.
  57664. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  57665. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  57666. // Compute deltas (neutral is midtones).
  57667. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  57668. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  57669. }
  57670. effect.setFloat4("vCameraColorCurvePositive", colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  57671. effect.setFloat4("vCameraColorCurveNeutral", colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  57672. effect.setFloat4("vCameraColorCurveNegative", colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  57673. };
  57674. /**
  57675. * Prepare the list of uniforms associated with the ColorCurves effects.
  57676. * @param uniformsList The list of uniforms used in the effect
  57677. */
  57678. ColorCurves.PrepareUniforms = function (uniformsList) {
  57679. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  57680. };
  57681. /**
  57682. * Returns color grading data based on a hue, density, saturation and exposure value.
  57683. * @param filterHue The hue of the color filter.
  57684. * @param filterDensity The density of the color filter.
  57685. * @param saturation The saturation.
  57686. * @param exposure The exposure.
  57687. * @param result The result data container.
  57688. */
  57689. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  57690. if (hue == null) {
  57691. return;
  57692. }
  57693. hue = ColorCurves.clamp(hue, 0, 360);
  57694. density = ColorCurves.clamp(density, -100, 100);
  57695. saturation = ColorCurves.clamp(saturation, -100, 100);
  57696. exposure = ColorCurves.clamp(exposure, -100, 100);
  57697. // Remap the slider/config filter density with non-linear mapping and also scale by half
  57698. // so that the maximum filter density is only 50% control. This provides fine control
  57699. // for small values and reasonable range.
  57700. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  57701. density *= 0.5;
  57702. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  57703. if (density < 0) {
  57704. density *= -1;
  57705. hue = (hue + 180) % 360;
  57706. }
  57707. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  57708. result.scaleToRef(2, result);
  57709. result.a = 1 + 0.01 * saturation;
  57710. };
  57711. /**
  57712. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  57713. * @param value The input slider value in range [-100,100].
  57714. * @returns Adjusted value.
  57715. */
  57716. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  57717. value /= 100;
  57718. var x = Math.abs(value);
  57719. x = Math.pow(x, 2);
  57720. if (value < 0) {
  57721. x *= -1;
  57722. }
  57723. x *= 100;
  57724. return x;
  57725. };
  57726. /**
  57727. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  57728. * @param hue The hue (H) input.
  57729. * @param saturation The saturation (S) input.
  57730. * @param brightness The brightness (B) input.
  57731. * @result An RGBA color represented as Vector4.
  57732. */
  57733. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  57734. var h = ColorCurves.clamp(hue, 0, 360);
  57735. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  57736. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  57737. if (s === 0) {
  57738. result.r = v;
  57739. result.g = v;
  57740. result.b = v;
  57741. }
  57742. else {
  57743. // sector 0 to 5
  57744. h /= 60;
  57745. var i = Math.floor(h);
  57746. // fractional part of h
  57747. var f = h - i;
  57748. var p = v * (1 - s);
  57749. var q = v * (1 - s * f);
  57750. var t = v * (1 - s * (1 - f));
  57751. switch (i) {
  57752. case 0:
  57753. result.r = v;
  57754. result.g = t;
  57755. result.b = p;
  57756. break;
  57757. case 1:
  57758. result.r = q;
  57759. result.g = v;
  57760. result.b = p;
  57761. break;
  57762. case 2:
  57763. result.r = p;
  57764. result.g = v;
  57765. result.b = t;
  57766. break;
  57767. case 3:
  57768. result.r = p;
  57769. result.g = q;
  57770. result.b = v;
  57771. break;
  57772. case 4:
  57773. result.r = t;
  57774. result.g = p;
  57775. result.b = v;
  57776. break;
  57777. default:
  57778. result.r = v;
  57779. result.g = p;
  57780. result.b = q;
  57781. break;
  57782. }
  57783. }
  57784. result.a = 1;
  57785. };
  57786. /**
  57787. * Returns a value clamped between min and max
  57788. * @param value The value to clamp
  57789. * @param min The minimum of value
  57790. * @param max The maximum of value
  57791. * @returns The clamped value.
  57792. */
  57793. ColorCurves.clamp = function (value, min, max) {
  57794. return Math.min(Math.max(value, min), max);
  57795. };
  57796. /**
  57797. * Clones the current color curve instance.
  57798. * @return The cloned curves
  57799. */
  57800. ColorCurves.prototype.clone = function () {
  57801. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  57802. };
  57803. /**
  57804. * Serializes the current color curve instance to a json representation.
  57805. * @return a JSON representation
  57806. */
  57807. ColorCurves.prototype.serialize = function () {
  57808. return BABYLON.SerializationHelper.Serialize(this);
  57809. };
  57810. /**
  57811. * Parses the color curve from a json representation.
  57812. * @param source the JSON source to parse
  57813. * @return The parsed curves
  57814. */
  57815. ColorCurves.Parse = function (source) {
  57816. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  57817. };
  57818. return ColorCurves;
  57819. }());
  57820. __decorate([
  57821. BABYLON.serialize()
  57822. ], ColorCurves.prototype, "_globalHue", void 0);
  57823. __decorate([
  57824. BABYLON.serialize()
  57825. ], ColorCurves.prototype, "_globalDensity", void 0);
  57826. __decorate([
  57827. BABYLON.serialize()
  57828. ], ColorCurves.prototype, "_globalSaturation", void 0);
  57829. __decorate([
  57830. BABYLON.serialize()
  57831. ], ColorCurves.prototype, "_globalExposure", void 0);
  57832. __decorate([
  57833. BABYLON.serialize()
  57834. ], ColorCurves.prototype, "_highlightsHue", void 0);
  57835. __decorate([
  57836. BABYLON.serialize()
  57837. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  57838. __decorate([
  57839. BABYLON.serialize()
  57840. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  57841. __decorate([
  57842. BABYLON.serialize()
  57843. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  57844. __decorate([
  57845. BABYLON.serialize()
  57846. ], ColorCurves.prototype, "_midtonesHue", void 0);
  57847. __decorate([
  57848. BABYLON.serialize()
  57849. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  57850. __decorate([
  57851. BABYLON.serialize()
  57852. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  57853. __decorate([
  57854. BABYLON.serialize()
  57855. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  57856. BABYLON.ColorCurves = ColorCurves;
  57857. })(BABYLON || (BABYLON = {}));
  57858. //# sourceMappingURL=babylon.colorCurves.js.map
  57859. var BABYLON;
  57860. (function (BABYLON) {
  57861. var PBRMaterialDefines = (function (_super) {
  57862. __extends(PBRMaterialDefines, _super);
  57863. function PBRMaterialDefines() {
  57864. var _this = _super.call(this) || this;
  57865. _this.ALBEDO = false;
  57866. _this.AMBIENT = false;
  57867. _this.OPACITY = false;
  57868. _this.OPACITYRGB = false;
  57869. _this.REFLECTION = false;
  57870. _this.EMISSIVE = false;
  57871. _this.REFLECTIVITY = false;
  57872. _this.BUMP = false;
  57873. _this.PARALLAX = false;
  57874. _this.PARALLAXOCCLUSION = false;
  57875. _this.SPECULAROVERALPHA = false;
  57876. _this.CLIPPLANE = false;
  57877. _this.ALPHATEST = false;
  57878. _this.ALPHAFROMALBEDO = false;
  57879. _this.POINTSIZE = false;
  57880. _this.FOG = false;
  57881. _this.SPECULARTERM = false;
  57882. _this.OPACITYFRESNEL = false;
  57883. _this.EMISSIVEFRESNEL = false;
  57884. _this.FRESNEL = false;
  57885. _this.NORMAL = false;
  57886. _this.TANGENT = false;
  57887. _this.UV1 = false;
  57888. _this.UV2 = false;
  57889. _this.VERTEXCOLOR = false;
  57890. _this.VERTEXALPHA = false;
  57891. _this.NUM_BONE_INFLUENCERS = 0;
  57892. _this.BonesPerMesh = 0;
  57893. _this.INSTANCES = false;
  57894. _this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  57895. _this.MICROSURFACEAUTOMATIC = false;
  57896. _this.EMISSIVEASILLUMINATION = false;
  57897. _this.LINKEMISSIVEWITHALBEDO = false;
  57898. _this.LIGHTMAP = false;
  57899. _this.USELIGHTMAPASSHADOWMAP = false;
  57900. _this.REFLECTIONMAP_3D = false;
  57901. _this.REFLECTIONMAP_SPHERICAL = false;
  57902. _this.REFLECTIONMAP_PLANAR = false;
  57903. _this.REFLECTIONMAP_CUBIC = false;
  57904. _this.REFLECTIONMAP_PROJECTION = false;
  57905. _this.REFLECTIONMAP_SKYBOX = false;
  57906. _this.REFLECTIONMAP_EXPLICIT = false;
  57907. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  57908. _this.INVERTCUBICMAP = false;
  57909. _this.LOGARITHMICDEPTH = false;
  57910. _this.CAMERATONEMAP = false;
  57911. _this.CAMERACONTRAST = false;
  57912. _this.CAMERACOLORGRADING = false;
  57913. _this.CAMERACOLORCURVES = false;
  57914. _this.OVERLOADEDVALUES = false;
  57915. _this.OVERLOADEDSHADOWVALUES = false;
  57916. _this.USESPHERICALFROMREFLECTIONMAP = false;
  57917. _this.REFRACTION = false;
  57918. _this.REFRACTIONMAP_3D = false;
  57919. _this.LINKREFRACTIONTOTRANSPARENCY = false;
  57920. _this.REFRACTIONMAPINLINEARSPACE = false;
  57921. _this.LODBASEDMICROSFURACE = false;
  57922. _this.USEPHYSICALLIGHTFALLOFF = false;
  57923. _this.RADIANCEOVERALPHA = false;
  57924. _this.USEPMREMREFLECTION = false;
  57925. _this.USEPMREMREFRACTION = false;
  57926. _this.OPENGLNORMALMAP = false;
  57927. _this.INVERTNORMALMAPX = false;
  57928. _this.INVERTNORMALMAPY = false;
  57929. _this.SHADOWFULLFLOAT = false;
  57930. _this.METALLICWORKFLOW = false;
  57931. _this.METALLICROUGHNESSMAP = false;
  57932. _this.METALLICROUGHNESSGSTOREINALPHA = false;
  57933. _this.METALLICROUGHNESSGSTOREINGREEN = false;
  57934. _this.rebuild();
  57935. return _this;
  57936. }
  57937. return PBRMaterialDefines;
  57938. }(BABYLON.MaterialDefines));
  57939. /**
  57940. * The Physically based material of BJS.
  57941. *
  57942. * This offers the main features of a standard PBR material.
  57943. * For more information, please refer to the documentation :
  57944. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  57945. */
  57946. var PBRMaterial = (function (_super) {
  57947. __extends(PBRMaterial, _super);
  57948. /**
  57949. * Instantiates a new PBRMaterial instance.
  57950. *
  57951. * @param name The material name
  57952. * @param scene The scene the material will be use in.
  57953. */
  57954. function PBRMaterial(name, scene) {
  57955. var _this = _super.call(this, name, scene) || this;
  57956. /**
  57957. * Intensity of the direct lights e.g. the four lights available in your scene.
  57958. * This impacts both the direct diffuse and specular highlights.
  57959. */
  57960. _this.directIntensity = 1.0;
  57961. /**
  57962. * Intensity of the emissive part of the material.
  57963. * This helps controlling the emissive effect without modifying the emissive color.
  57964. */
  57965. _this.emissiveIntensity = 1.0;
  57966. /**
  57967. * Intensity of the environment e.g. how much the environment will light the object
  57968. * either through harmonics for rough material or through the refelction for shiny ones.
  57969. */
  57970. _this.environmentIntensity = 1.0;
  57971. /**
  57972. * This is a special control allowing the reduction of the specular highlights coming from the
  57973. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  57974. */
  57975. _this.specularIntensity = 1.0;
  57976. _this._lightingInfos = new BABYLON.Vector4(_this.directIntensity, _this.emissiveIntensity, _this.environmentIntensity, _this.specularIntensity);
  57977. /**
  57978. * Debug Control allowing disabling the bump map on this material.
  57979. */
  57980. _this.disableBumpMap = false;
  57981. /**
  57982. * Debug Control helping enforcing or dropping the darkness of shadows.
  57983. * 1.0 means the shadows have their normal darkness, 0.0 means the shadows are not visible.
  57984. */
  57985. _this.overloadedShadowIntensity = 1.0;
  57986. /**
  57987. * Debug Control helping dropping the shading effect coming from the diffuse lighting.
  57988. * 1.0 means the shade have their normal impact, 0.0 means no shading at all.
  57989. */
  57990. _this.overloadedShadeIntensity = 1.0;
  57991. _this._overloadedShadowInfos = new BABYLON.Vector4(_this.overloadedShadowIntensity, _this.overloadedShadeIntensity, 0.0, 0.0);
  57992. /**
  57993. * The camera exposure used on this material.
  57994. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  57995. * This corresponds to a photographic exposure.
  57996. */
  57997. _this.cameraExposure = 1.0;
  57998. /**
  57999. * The camera contrast used on this material.
  58000. * This property is here and not in the camera to allow controlling contrast without full screen post process.
  58001. */
  58002. _this.cameraContrast = 1.0;
  58003. /**
  58004. * Color Grading 2D Lookup Texture.
  58005. * This allows special effects like sepia, black and white to sixties rendering style.
  58006. */
  58007. _this.cameraColorGradingTexture = null;
  58008. /**
  58009. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  58010. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  58011. * 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;
  58012. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  58013. */
  58014. _this.cameraColorCurves = null;
  58015. _this._cameraInfos = new BABYLON.Vector4(1.0, 1.0, 0.0, 0.0);
  58016. _this._microsurfaceTextureLods = new BABYLON.Vector2(0.0, 0.0);
  58017. /**
  58018. * Debug Control allowing to overload the ambient color.
  58019. * This as to be use with the overloadedAmbientIntensity parameter.
  58020. */
  58021. _this.overloadedAmbient = BABYLON.Color3.White();
  58022. /**
  58023. * Debug Control indicating how much the overloaded ambient color is used against the default one.
  58024. */
  58025. _this.overloadedAmbientIntensity = 0.0;
  58026. /**
  58027. * Debug Control allowing to overload the albedo color.
  58028. * This as to be use with the overloadedAlbedoIntensity parameter.
  58029. */
  58030. _this.overloadedAlbedo = BABYLON.Color3.White();
  58031. /**
  58032. * Debug Control indicating how much the overloaded albedo color is used against the default one.
  58033. */
  58034. _this.overloadedAlbedoIntensity = 0.0;
  58035. /**
  58036. * Debug Control allowing to overload the reflectivity color.
  58037. * This as to be use with the overloadedReflectivityIntensity parameter.
  58038. */
  58039. _this.overloadedReflectivity = new BABYLON.Color3(0.3, 0.3, 0.3);
  58040. /**
  58041. * Debug Control indicating how much the overloaded reflectivity color is used against the default one.
  58042. */
  58043. _this.overloadedReflectivityIntensity = 0.0;
  58044. /**
  58045. * Debug Control allowing to overload the emissive color.
  58046. * This as to be use with the overloadedEmissiveIntensity parameter.
  58047. */
  58048. _this.overloadedEmissive = BABYLON.Color3.White();
  58049. /**
  58050. * Debug Control indicating how much the overloaded emissive color is used against the default one.
  58051. */
  58052. _this.overloadedEmissiveIntensity = 0.0;
  58053. _this._overloadedIntensity = new BABYLON.Vector4(_this.overloadedAmbientIntensity, _this.overloadedAlbedoIntensity, _this.overloadedReflectivityIntensity, _this.overloadedEmissiveIntensity);
  58054. /**
  58055. * Debug Control allowing to overload the reflection color.
  58056. * This as to be use with the overloadedReflectionIntensity parameter.
  58057. */
  58058. _this.overloadedReflection = BABYLON.Color3.White();
  58059. /**
  58060. * Debug Control indicating how much the overloaded reflection color is used against the default one.
  58061. */
  58062. _this.overloadedReflectionIntensity = 0.0;
  58063. /**
  58064. * Debug Control allowing to overload the microsurface.
  58065. * This as to be use with the overloadedMicroSurfaceIntensity parameter.
  58066. */
  58067. _this.overloadedMicroSurface = 0.0;
  58068. /**
  58069. * Debug Control indicating how much the overloaded microsurface is used against the default one.
  58070. */
  58071. _this.overloadedMicroSurfaceIntensity = 0.0;
  58072. _this._overloadedMicroSurface = new BABYLON.Vector3(_this.overloadedMicroSurface, _this.overloadedMicroSurfaceIntensity, _this.overloadedReflectionIntensity);
  58073. /**
  58074. * AKA Occlusion Texture Intensity in other nomenclature.
  58075. */
  58076. _this.ambientTextureStrength = 1.0;
  58077. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  58078. /**
  58079. * AKA Diffuse Color in other nomenclature.
  58080. */
  58081. _this.albedoColor = new BABYLON.Color3(1, 1, 1);
  58082. /**
  58083. * AKA Specular Color in other nomenclature.
  58084. */
  58085. _this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  58086. _this.reflectionColor = new BABYLON.Color3(0.5, 0.5, 0.5);
  58087. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  58088. /**
  58089. * AKA Glossiness in other nomenclature.
  58090. */
  58091. _this.microSurface = 0.9;
  58092. /**
  58093. * source material index of refraction (IOR)' / 'destination material IOR.
  58094. */
  58095. _this.indexOfRefraction = 0.66;
  58096. /**
  58097. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  58098. */
  58099. _this.invertRefractionY = false;
  58100. /**
  58101. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  58102. * Materials half opaque for instance using refraction could benefit from this control.
  58103. */
  58104. _this.linkRefractionWithTransparency = false;
  58105. /**
  58106. * The emissive and albedo are linked to never be more than one (Energy conservation).
  58107. */
  58108. _this.linkEmissiveWithAlbedo = false;
  58109. _this.useLightmapAsShadowmap = false;
  58110. /**
  58111. * In this mode, the emissive informtaion will always be added to the lighting once.
  58112. * A light for instance can be thought as emissive.
  58113. */
  58114. _this.useEmissiveAsIllumination = false;
  58115. /**
  58116. * Secifies that the alpha is coming form the albedo channel alpha channel.
  58117. */
  58118. _this.useAlphaFromAlbedoTexture = false;
  58119. /**
  58120. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  58121. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  58122. */
  58123. _this.useSpecularOverAlpha = true;
  58124. /**
  58125. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  58126. */
  58127. _this.useMicroSurfaceFromReflectivityMapAlpha = false;
  58128. /**
  58129. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  58130. */
  58131. _this.useRoughnessFromMetallicTextureAlpha = true;
  58132. /**
  58133. * Specifies if the metallic texture contains the roughness information in its green channel.
  58134. */
  58135. _this.useRoughnessFromMetallicTextureGreen = false;
  58136. /**
  58137. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  58138. * The material will try to infer what glossiness each pixel should be.
  58139. */
  58140. _this.useAutoMicroSurfaceFromReflectivityMap = false;
  58141. /**
  58142. * Allows to work with scalar in linear mode. This is definitely a matter of preferences and tools used during
  58143. * the creation of the material.
  58144. */
  58145. _this.useScalarInLinearSpace = false;
  58146. /**
  58147. * BJS is using an harcoded light falloff based on a manually sets up range.
  58148. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  58149. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  58150. */
  58151. _this.usePhysicalLightFalloff = true;
  58152. /**
  58153. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  58154. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  58155. */
  58156. _this.useRadianceOverAlpha = true;
  58157. /**
  58158. * Allows using the bump map in parallax mode.
  58159. */
  58160. _this.useParallax = false;
  58161. /**
  58162. * Allows using the bump map in parallax occlusion mode.
  58163. */
  58164. _this.useParallaxOcclusion = false;
  58165. /**
  58166. * Controls the scale bias of the parallax mode.
  58167. */
  58168. _this.parallaxScaleBias = 0.05;
  58169. /**
  58170. * If sets to true, disables all the lights affecting the material.
  58171. */
  58172. _this.disableLighting = false;
  58173. /**
  58174. * Number of Simultaneous lights allowed on the material.
  58175. */
  58176. _this.maxSimultaneousLights = 4;
  58177. /**
  58178. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  58179. */
  58180. _this.invertNormalMapX = false;
  58181. /**
  58182. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  58183. */
  58184. _this.invertNormalMapY = false;
  58185. _this._renderTargets = new BABYLON.SmartArray(16);
  58186. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  58187. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  58188. _this._tempColor = new BABYLON.Color3();
  58189. _this._defines = new PBRMaterialDefines();
  58190. _this._cachedDefines = new PBRMaterialDefines();
  58191. _this._myScene = null;
  58192. _this._myShadowGenerator = null;
  58193. _this._cachedDefines.BonesPerMesh = -1;
  58194. _this.getRenderTargetTextures = function () {
  58195. _this._renderTargets.reset();
  58196. if (_this.reflectionTexture && _this.reflectionTexture.isRenderTarget) {
  58197. _this._renderTargets.push(_this.reflectionTexture);
  58198. }
  58199. if (_this.refractionTexture && _this.refractionTexture.isRenderTarget) {
  58200. _this._renderTargets.push(_this.refractionTexture);
  58201. }
  58202. return _this._renderTargets;
  58203. };
  58204. return _this;
  58205. }
  58206. PBRMaterial.prototype.getClassName = function () {
  58207. return "PBRMaterial";
  58208. };
  58209. Object.defineProperty(PBRMaterial.prototype, "useLogarithmicDepth", {
  58210. get: function () {
  58211. return this._useLogarithmicDepth;
  58212. },
  58213. set: function (value) {
  58214. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  58215. },
  58216. enumerable: true,
  58217. configurable: true
  58218. });
  58219. PBRMaterial.prototype.needAlphaBlending = function () {
  58220. if (this.linkRefractionWithTransparency) {
  58221. return false;
  58222. }
  58223. return (this.alpha < 1.0) || (this.opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture() || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled;
  58224. };
  58225. PBRMaterial.prototype.needAlphaTesting = function () {
  58226. if (this.linkRefractionWithTransparency) {
  58227. return false;
  58228. }
  58229. return this.albedoTexture != null && this.albedoTexture.hasAlpha;
  58230. };
  58231. PBRMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  58232. return this.albedoTexture != null && this.albedoTexture.hasAlpha && this.useAlphaFromAlbedoTexture;
  58233. };
  58234. PBRMaterial.prototype.getAlphaTestTexture = function () {
  58235. return this.albedoTexture;
  58236. };
  58237. PBRMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  58238. if (!mesh) {
  58239. return true;
  58240. }
  58241. if (this._defines.INSTANCES !== useInstances) {
  58242. return false;
  58243. }
  58244. if (mesh._materialDefines && mesh._materialDefines.isEqual(this._defines)) {
  58245. return true;
  58246. }
  58247. return false;
  58248. };
  58249. PBRMaterial.prototype.convertColorToLinearSpaceToRef = function (color, ref) {
  58250. PBRMaterial.convertColorToLinearSpaceToRef(color, ref, this.useScalarInLinearSpace);
  58251. };
  58252. PBRMaterial.convertColorToLinearSpaceToRef = function (color, ref, useScalarInLinear) {
  58253. if (!useScalarInLinear) {
  58254. color.toLinearSpaceToRef(ref);
  58255. }
  58256. else {
  58257. ref.r = color.r;
  58258. ref.g = color.g;
  58259. ref.b = color.b;
  58260. }
  58261. };
  58262. PBRMaterial.BindLights = function (scene, mesh, effect, defines, useScalarInLinearSpace, maxSimultaneousLights, usePhysicalLightFalloff) {
  58263. var lightIndex = 0;
  58264. var depthValuesAlreadySet = false;
  58265. for (var index = 0; index < scene.lights.length; index++) {
  58266. var light = scene.lights[index];
  58267. if (!light.isEnabled()) {
  58268. continue;
  58269. }
  58270. if (!light.canAffectMesh(mesh)) {
  58271. continue;
  58272. }
  58273. BABYLON.MaterialHelper.BindLightProperties(light, effect, lightIndex);
  58274. // GAMMA CORRECTION.
  58275. this.convertColorToLinearSpaceToRef(light.diffuse, PBRMaterial._scaledAlbedo, useScalarInLinearSpace);
  58276. PBRMaterial._scaledAlbedo.scaleToRef(light.intensity, PBRMaterial._scaledAlbedo);
  58277. effect.setColor4("vLightDiffuse" + lightIndex, PBRMaterial._scaledAlbedo, usePhysicalLightFalloff ? light.radius : light.range);
  58278. if (defines["SPECULARTERM"]) {
  58279. this.convertColorToLinearSpaceToRef(light.specular, PBRMaterial._scaledReflectivity, useScalarInLinearSpace);
  58280. PBRMaterial._scaledReflectivity.scaleToRef(light.intensity, PBRMaterial._scaledReflectivity);
  58281. effect.setColor3("vLightSpecular" + lightIndex, PBRMaterial._scaledReflectivity);
  58282. }
  58283. // Shadows
  58284. if (scene.shadowsEnabled) {
  58285. depthValuesAlreadySet = BABYLON.MaterialHelper.BindLightShadow(light, scene, mesh, lightIndex, effect, depthValuesAlreadySet);
  58286. }
  58287. lightIndex++;
  58288. if (lightIndex === maxSimultaneousLights)
  58289. break;
  58290. }
  58291. };
  58292. PBRMaterial.prototype.isReady = function (mesh, useInstances) {
  58293. if (this.isFrozen) {
  58294. if (this._wasPreviouslyReady) {
  58295. return true;
  58296. }
  58297. }
  58298. var scene = this.getScene();
  58299. var engine = scene.getEngine();
  58300. var needNormals = false;
  58301. var needUVs = false;
  58302. this._defines.reset();
  58303. if (scene.lightsEnabled && !this.disableLighting) {
  58304. needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, this._defines, this.maxSimultaneousLights) || needNormals;
  58305. }
  58306. if (!this.checkReadyOnEveryCall) {
  58307. if (this._renderId === scene.getRenderId()) {
  58308. if (this._checkCache(scene, mesh, useInstances)) {
  58309. return true;
  58310. }
  58311. }
  58312. }
  58313. if (scene.texturesEnabled) {
  58314. if (scene.getEngine().getCaps().textureLOD) {
  58315. this._defines.LODBASEDMICROSFURACE = true;
  58316. }
  58317. if (this.albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  58318. if (!this.albedoTexture.isReady()) {
  58319. return false;
  58320. }
  58321. else {
  58322. needUVs = true;
  58323. this._defines.ALBEDO = true;
  58324. }
  58325. }
  58326. if (this.ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  58327. if (!this.ambientTexture.isReady()) {
  58328. return false;
  58329. }
  58330. else {
  58331. needUVs = true;
  58332. this._defines.AMBIENT = true;
  58333. }
  58334. }
  58335. if (this.opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  58336. if (!this.opacityTexture.isReady()) {
  58337. return false;
  58338. }
  58339. else {
  58340. needUVs = true;
  58341. this._defines.OPACITY = true;
  58342. if (this.opacityTexture.getAlphaFromRGB) {
  58343. this._defines.OPACITYRGB = true;
  58344. }
  58345. }
  58346. }
  58347. if (this.reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  58348. if (!this.reflectionTexture.isReady()) {
  58349. return false;
  58350. }
  58351. else {
  58352. needNormals = true;
  58353. this._defines.REFLECTION = true;
  58354. if (this.reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  58355. this._defines.INVERTCUBICMAP = true;
  58356. }
  58357. this._defines.REFLECTIONMAP_3D = this.reflectionTexture.isCube;
  58358. switch (this.reflectionTexture.coordinatesMode) {
  58359. case BABYLON.Texture.CUBIC_MODE:
  58360. case BABYLON.Texture.INVCUBIC_MODE:
  58361. this._defines.REFLECTIONMAP_CUBIC = true;
  58362. break;
  58363. case BABYLON.Texture.EXPLICIT_MODE:
  58364. this._defines.REFLECTIONMAP_EXPLICIT = true;
  58365. break;
  58366. case BABYLON.Texture.PLANAR_MODE:
  58367. this._defines.REFLECTIONMAP_PLANAR = true;
  58368. break;
  58369. case BABYLON.Texture.PROJECTION_MODE:
  58370. this._defines.REFLECTIONMAP_PROJECTION = true;
  58371. break;
  58372. case BABYLON.Texture.SKYBOX_MODE:
  58373. this._defines.REFLECTIONMAP_SKYBOX = true;
  58374. break;
  58375. case BABYLON.Texture.SPHERICAL_MODE:
  58376. this._defines.REFLECTIONMAP_SPHERICAL = true;
  58377. break;
  58378. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  58379. this._defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  58380. break;
  58381. }
  58382. if (this.reflectionTexture instanceof BABYLON.HDRCubeTexture && this.reflectionTexture) {
  58383. this._defines.USESPHERICALFROMREFLECTIONMAP = true;
  58384. needNormals = true;
  58385. if (this.reflectionTexture.isPMREM) {
  58386. this._defines.USEPMREMREFLECTION = true;
  58387. }
  58388. }
  58389. }
  58390. }
  58391. if (this.lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  58392. if (!this.lightmapTexture.isReady()) {
  58393. return false;
  58394. }
  58395. else {
  58396. needUVs = true;
  58397. this._defines.LIGHTMAP = true;
  58398. this._defines.USELIGHTMAPASSHADOWMAP = this.useLightmapAsShadowmap;
  58399. }
  58400. }
  58401. if (this.emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  58402. if (!this.emissiveTexture.isReady()) {
  58403. return false;
  58404. }
  58405. else {
  58406. needUVs = true;
  58407. this._defines.EMISSIVE = true;
  58408. }
  58409. }
  58410. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  58411. if (this.metallicTexture) {
  58412. if (!this.metallicTexture.isReady()) {
  58413. return false;
  58414. }
  58415. else {
  58416. needUVs = true;
  58417. this._defines.METALLICWORKFLOW = true;
  58418. this._defines.METALLICROUGHNESSMAP = true;
  58419. this._defines.METALLICROUGHNESSGSTOREINALPHA = this.useRoughnessFromMetallicTextureAlpha;
  58420. this._defines.METALLICROUGHNESSGSTOREINGREEN = !this.useRoughnessFromMetallicTextureAlpha && this.useRoughnessFromMetallicTextureGreen;
  58421. }
  58422. }
  58423. else if (this.reflectivityTexture) {
  58424. if (!this.reflectivityTexture.isReady()) {
  58425. return false;
  58426. }
  58427. else {
  58428. needUVs = true;
  58429. this._defines.REFLECTIVITY = true;
  58430. this._defines.MICROSURFACEFROMREFLECTIVITYMAP = this.useMicroSurfaceFromReflectivityMapAlpha;
  58431. this._defines.MICROSURFACEAUTOMATIC = this.useAutoMicroSurfaceFromReflectivityMap;
  58432. }
  58433. }
  58434. }
  58435. if (scene.getEngine().getCaps().standardDerivatives && this.bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this.disableBumpMap) {
  58436. if (!this.bumpTexture.isReady()) {
  58437. return false;
  58438. }
  58439. else {
  58440. needUVs = true;
  58441. this._defines.BUMP = true;
  58442. if (this.useParallax && this.albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  58443. this._defines.PARALLAX = true;
  58444. if (this.useParallaxOcclusion) {
  58445. this._defines.PARALLAXOCCLUSION = true;
  58446. }
  58447. }
  58448. if (this.invertNormalMapX) {
  58449. this._defines.INVERTNORMALMAPX = true;
  58450. }
  58451. if (this.invertNormalMapY) {
  58452. this._defines.INVERTNORMALMAPY = true;
  58453. }
  58454. if (scene._mirroredCameraPosition) {
  58455. this._defines.INVERTNORMALMAPX = !this._defines.INVERTNORMALMAPX;
  58456. this._defines.INVERTNORMALMAPY = !this._defines.INVERTNORMALMAPY;
  58457. }
  58458. }
  58459. }
  58460. if (this.refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  58461. if (!this.refractionTexture.isReady()) {
  58462. return false;
  58463. }
  58464. else {
  58465. needUVs = true;
  58466. this._defines.REFRACTION = true;
  58467. this._defines.REFRACTIONMAP_3D = this.refractionTexture.isCube;
  58468. if (this.linkRefractionWithTransparency) {
  58469. this._defines.LINKREFRACTIONTOTRANSPARENCY = true;
  58470. }
  58471. if (this.refractionTexture instanceof BABYLON.HDRCubeTexture) {
  58472. this._defines.REFRACTIONMAPINLINEARSPACE = true;
  58473. if (this.refractionTexture.isPMREM) {
  58474. this._defines.USEPMREMREFRACTION = true;
  58475. }
  58476. }
  58477. }
  58478. }
  58479. if (this.cameraColorGradingTexture && BABYLON.StandardMaterial.ColorGradingTextureEnabled) {
  58480. if (!this.cameraColorGradingTexture.isReady()) {
  58481. return false;
  58482. }
  58483. else {
  58484. this._defines.CAMERACOLORGRADING = true;
  58485. }
  58486. }
  58487. }
  58488. // Effect
  58489. if (scene.clipPlane) {
  58490. this._defines.CLIPPLANE = true;
  58491. }
  58492. if (engine.getAlphaTesting()) {
  58493. this._defines.ALPHATEST = true;
  58494. }
  58495. if (this._shouldUseAlphaFromAlbedoTexture()) {
  58496. this._defines.ALPHAFROMALBEDO = true;
  58497. }
  58498. if (this.useEmissiveAsIllumination) {
  58499. this._defines.EMISSIVEASILLUMINATION = true;
  58500. }
  58501. if (this.linkEmissiveWithAlbedo) {
  58502. this._defines.LINKEMISSIVEWITHALBEDO = true;
  58503. }
  58504. if (this.useLogarithmicDepth) {
  58505. this._defines.LOGARITHMICDEPTH = true;
  58506. }
  58507. if (this.cameraContrast != 1) {
  58508. this._defines.CAMERACONTRAST = true;
  58509. }
  58510. if (this.cameraExposure != 1) {
  58511. this._defines.CAMERATONEMAP = true;
  58512. }
  58513. if (this.cameraColorCurves) {
  58514. this._defines.CAMERACOLORCURVES = true;
  58515. }
  58516. if (this.overloadedShadeIntensity != 1 ||
  58517. this.overloadedShadowIntensity != 1) {
  58518. this._defines.OVERLOADEDSHADOWVALUES = true;
  58519. }
  58520. if (this.overloadedMicroSurfaceIntensity > 0 ||
  58521. this.overloadedEmissiveIntensity > 0 ||
  58522. this.overloadedReflectivityIntensity > 0 ||
  58523. this.overloadedAlbedoIntensity > 0 ||
  58524. this.overloadedAmbientIntensity > 0 ||
  58525. this.overloadedReflectionIntensity > 0) {
  58526. this._defines.OVERLOADEDVALUES = true;
  58527. }
  58528. // Point size
  58529. if (this.pointsCloud || scene.forcePointsCloud) {
  58530. this._defines.POINTSIZE = true;
  58531. }
  58532. // Fog
  58533. if (scene.fogEnabled && mesh && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  58534. this._defines.FOG = true;
  58535. }
  58536. if (BABYLON.StandardMaterial.FresnelEnabled) {
  58537. // Fresnel
  58538. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled ||
  58539. this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  58540. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  58541. this._defines.OPACITYFRESNEL = true;
  58542. }
  58543. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  58544. this._defines.EMISSIVEFRESNEL = true;
  58545. }
  58546. needNormals = true;
  58547. this._defines.FRESNEL = true;
  58548. }
  58549. }
  58550. if (this._defines.SPECULARTERM && this.useSpecularOverAlpha) {
  58551. this._defines.SPECULAROVERALPHA = true;
  58552. }
  58553. if (this.usePhysicalLightFalloff) {
  58554. this._defines.USEPHYSICALLIGHTFALLOFF = true;
  58555. }
  58556. if (this.useRadianceOverAlpha) {
  58557. this._defines.RADIANCEOVERALPHA = true;
  58558. }
  58559. if ((this.metallic !== undefined && this.metallic !== null) || (this.roughness !== undefined && this.roughness !== null)) {
  58560. this._defines.METALLICWORKFLOW = true;
  58561. }
  58562. // Attribs
  58563. if (mesh) {
  58564. if (needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  58565. this._defines.NORMAL = true;
  58566. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  58567. this._defines.TANGENT = true;
  58568. }
  58569. }
  58570. if (needUVs) {
  58571. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  58572. this._defines.UV1 = true;
  58573. }
  58574. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  58575. this._defines.UV2 = true;
  58576. }
  58577. }
  58578. if (mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  58579. this._defines.VERTEXCOLOR = true;
  58580. if (mesh.hasVertexAlpha) {
  58581. this._defines.VERTEXALPHA = true;
  58582. }
  58583. }
  58584. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  58585. this._defines.NUM_BONE_INFLUENCERS = mesh.numBoneInfluencers;
  58586. this._defines.BonesPerMesh = (mesh.skeleton.bones.length + 1);
  58587. }
  58588. // Instances
  58589. if (useInstances) {
  58590. this._defines.INSTANCES = true;
  58591. }
  58592. }
  58593. // Get correct effect
  58594. if (!this._defines.isEqual(this._cachedDefines)) {
  58595. this._defines.cloneTo(this._cachedDefines);
  58596. scene.resetCachedMaterial();
  58597. // Fallbacks
  58598. var fallbacks = new BABYLON.EffectFallbacks();
  58599. if (this._defines.REFLECTION) {
  58600. fallbacks.addFallback(0, "REFLECTION");
  58601. }
  58602. if (this._defines.REFRACTION) {
  58603. fallbacks.addFallback(0, "REFRACTION");
  58604. }
  58605. if (this._defines.REFLECTIVITY) {
  58606. fallbacks.addFallback(0, "REFLECTIVITY");
  58607. }
  58608. if (this._defines.BUMP) {
  58609. fallbacks.addFallback(0, "BUMP");
  58610. }
  58611. if (this._defines.PARALLAX) {
  58612. fallbacks.addFallback(1, "PARALLAX");
  58613. }
  58614. if (this._defines.PARALLAXOCCLUSION) {
  58615. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  58616. }
  58617. if (this._defines.SPECULAROVERALPHA) {
  58618. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  58619. }
  58620. if (this._defines.FOG) {
  58621. fallbacks.addFallback(1, "FOG");
  58622. }
  58623. if (this._defines.POINTSIZE) {
  58624. fallbacks.addFallback(0, "POINTSIZE");
  58625. }
  58626. if (this._defines.LOGARITHMICDEPTH) {
  58627. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  58628. }
  58629. BABYLON.MaterialHelper.HandleFallbacksForShadows(this._defines, fallbacks, this.maxSimultaneousLights);
  58630. if (this._defines.SPECULARTERM) {
  58631. fallbacks.addFallback(0, "SPECULARTERM");
  58632. }
  58633. if (this._defines.OPACITYFRESNEL) {
  58634. fallbacks.addFallback(1, "OPACITYFRESNEL");
  58635. }
  58636. if (this._defines.EMISSIVEFRESNEL) {
  58637. fallbacks.addFallback(2, "EMISSIVEFRESNEL");
  58638. }
  58639. if (this._defines.FRESNEL) {
  58640. fallbacks.addFallback(3, "FRESNEL");
  58641. }
  58642. if (this._defines.NUM_BONE_INFLUENCERS > 0) {
  58643. fallbacks.addCPUSkinningFallback(0, mesh);
  58644. }
  58645. //Attributes
  58646. var attribs = [BABYLON.VertexBuffer.PositionKind];
  58647. if (this._defines.NORMAL) {
  58648. attribs.push(BABYLON.VertexBuffer.NormalKind);
  58649. }
  58650. if (this._defines.TANGENT) {
  58651. attribs.push(BABYLON.VertexBuffer.TangentKind);
  58652. }
  58653. if (this._defines.UV1) {
  58654. attribs.push(BABYLON.VertexBuffer.UVKind);
  58655. }
  58656. if (this._defines.UV2) {
  58657. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  58658. }
  58659. if (this._defines.VERTEXCOLOR) {
  58660. attribs.push(BABYLON.VertexBuffer.ColorKind);
  58661. }
  58662. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, this._defines, fallbacks);
  58663. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, this._defines);
  58664. // Legacy browser patch
  58665. var join = this._defines.toString();
  58666. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  58667. "vFogInfos", "vFogColor", "pointSize",
  58668. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vReflectivityInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  58669. "mBones",
  58670. "vClipPlane", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  58671. "depthValues",
  58672. "opacityParts", "emissiveLeftColor", "emissiveRightColor",
  58673. "vLightingIntensity", "vOverloadedShadowIntensity", "vOverloadedIntensity", "vOverloadedAlbedo", "vOverloadedReflection", "vOverloadedReflectivity", "vOverloadedEmissive", "vOverloadedMicroSurface",
  58674. "logarithmicDepthConstant",
  58675. "vSphericalX", "vSphericalY", "vSphericalZ",
  58676. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  58677. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  58678. "vMicrosurfaceTextureLods",
  58679. "vCameraInfos"
  58680. ];
  58681. var samplers = ["albedoSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "reflectivitySampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  58682. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  58683. BABYLON.ColorGradingTexture.PrepareUniformsAndSamplers(uniforms, samplers);
  58684. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList(uniforms, samplers, this._defines, this.maxSimultaneousLights);
  58685. this._effect = scene.getEngine().createEffect("pbr", attribs, uniforms, samplers, join, fallbacks, this.onCompiled, this.onError, { maxSimultaneousLights: this.maxSimultaneousLights });
  58686. }
  58687. if (!this._effect.isReady()) {
  58688. return false;
  58689. }
  58690. this._renderId = scene.getRenderId();
  58691. this._wasPreviouslyReady = true;
  58692. if (mesh) {
  58693. if (!mesh._materialDefines) {
  58694. mesh._materialDefines = new PBRMaterialDefines();
  58695. }
  58696. this._defines.cloneTo(mesh._materialDefines);
  58697. }
  58698. return true;
  58699. };
  58700. PBRMaterial.prototype.unbind = function () {
  58701. if (this.reflectionTexture && this.reflectionTexture.isRenderTarget) {
  58702. this._effect.setTexture("reflection2DSampler", null);
  58703. }
  58704. if (this.refractionTexture && this.refractionTexture.isRenderTarget) {
  58705. this._effect.setTexture("refraction2DSampler", null);
  58706. }
  58707. _super.prototype.unbind.call(this);
  58708. };
  58709. PBRMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  58710. this._effect.setMatrix("world", world);
  58711. };
  58712. PBRMaterial.prototype.bind = function (world, mesh) {
  58713. this._myScene = this.getScene();
  58714. // Matrices
  58715. this.bindOnlyWorldMatrix(world);
  58716. // Bones
  58717. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  58718. if (this._myScene.getCachedMaterial() !== this) {
  58719. this._effect.setMatrix("viewProjection", this._myScene.getTransformMatrix());
  58720. if (BABYLON.StandardMaterial.FresnelEnabled) {
  58721. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  58722. this._effect.setColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  58723. }
  58724. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  58725. this._effect.setColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  58726. this._effect.setColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  58727. }
  58728. }
  58729. // Textures
  58730. if (this._myScene.texturesEnabled) {
  58731. if (this.albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  58732. this._effect.setTexture("albedoSampler", this.albedoTexture);
  58733. this._effect.setFloat2("vAlbedoInfos", this.albedoTexture.coordinatesIndex, this.albedoTexture.level);
  58734. this._effect.setMatrix("albedoMatrix", this.albedoTexture.getTextureMatrix());
  58735. }
  58736. if (this.ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  58737. this._effect.setTexture("ambientSampler", this.ambientTexture);
  58738. this._effect.setFloat3("vAmbientInfos", this.ambientTexture.coordinatesIndex, this.ambientTexture.level, this.ambientTextureStrength);
  58739. this._effect.setMatrix("ambientMatrix", this.ambientTexture.getTextureMatrix());
  58740. }
  58741. if (this.opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  58742. this._effect.setTexture("opacitySampler", this.opacityTexture);
  58743. this._effect.setFloat2("vOpacityInfos", this.opacityTexture.coordinatesIndex, this.opacityTexture.level);
  58744. this._effect.setMatrix("opacityMatrix", this.opacityTexture.getTextureMatrix());
  58745. }
  58746. if (this.reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  58747. this._microsurfaceTextureLods.x = Math.round(Math.log(this.reflectionTexture.getSize().width) * Math.LOG2E);
  58748. if (this.reflectionTexture.isCube) {
  58749. this._effect.setTexture("reflectionCubeSampler", this.reflectionTexture);
  58750. }
  58751. else {
  58752. this._effect.setTexture("reflection2DSampler", this.reflectionTexture);
  58753. }
  58754. this._effect.setMatrix("reflectionMatrix", this.reflectionTexture.getReflectionTextureMatrix());
  58755. this._effect.setFloat2("vReflectionInfos", this.reflectionTexture.level, 0);
  58756. if (this._defines.USESPHERICALFROMREFLECTIONMAP) {
  58757. this._effect.setFloat3("vSphericalX", this.reflectionTexture.sphericalPolynomial.x.x, this.reflectionTexture.sphericalPolynomial.x.y, this.reflectionTexture.sphericalPolynomial.x.z);
  58758. this._effect.setFloat3("vSphericalY", this.reflectionTexture.sphericalPolynomial.y.x, this.reflectionTexture.sphericalPolynomial.y.y, this.reflectionTexture.sphericalPolynomial.y.z);
  58759. this._effect.setFloat3("vSphericalZ", this.reflectionTexture.sphericalPolynomial.z.x, this.reflectionTexture.sphericalPolynomial.z.y, this.reflectionTexture.sphericalPolynomial.z.z);
  58760. this._effect.setFloat3("vSphericalXX", this.reflectionTexture.sphericalPolynomial.xx.x, this.reflectionTexture.sphericalPolynomial.xx.y, this.reflectionTexture.sphericalPolynomial.xx.z);
  58761. this._effect.setFloat3("vSphericalYY", this.reflectionTexture.sphericalPolynomial.yy.x, this.reflectionTexture.sphericalPolynomial.yy.y, this.reflectionTexture.sphericalPolynomial.yy.z);
  58762. this._effect.setFloat3("vSphericalZZ", this.reflectionTexture.sphericalPolynomial.zz.x, this.reflectionTexture.sphericalPolynomial.zz.y, this.reflectionTexture.sphericalPolynomial.zz.z);
  58763. this._effect.setFloat3("vSphericalXY", this.reflectionTexture.sphericalPolynomial.xy.x, this.reflectionTexture.sphericalPolynomial.xy.y, this.reflectionTexture.sphericalPolynomial.xy.z);
  58764. this._effect.setFloat3("vSphericalYZ", this.reflectionTexture.sphericalPolynomial.yz.x, this.reflectionTexture.sphericalPolynomial.yz.y, this.reflectionTexture.sphericalPolynomial.yz.z);
  58765. this._effect.setFloat3("vSphericalZX", this.reflectionTexture.sphericalPolynomial.zx.x, this.reflectionTexture.sphericalPolynomial.zx.y, this.reflectionTexture.sphericalPolynomial.zx.z);
  58766. }
  58767. }
  58768. if (this.emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  58769. this._effect.setTexture("emissiveSampler", this.emissiveTexture);
  58770. this._effect.setFloat2("vEmissiveInfos", this.emissiveTexture.coordinatesIndex, this.emissiveTexture.level);
  58771. this._effect.setMatrix("emissiveMatrix", this.emissiveTexture.getTextureMatrix());
  58772. }
  58773. if (this.lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  58774. this._effect.setTexture("lightmapSampler", this.lightmapTexture);
  58775. this._effect.setFloat2("vLightmapInfos", this.lightmapTexture.coordinatesIndex, this.lightmapTexture.level);
  58776. this._effect.setMatrix("lightmapMatrix", this.lightmapTexture.getTextureMatrix());
  58777. }
  58778. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  58779. if (this.metallicTexture) {
  58780. this._effect.setTexture("reflectivitySampler", this.metallicTexture);
  58781. this._effect.setFloat2("vReflectivityInfos", this.metallicTexture.coordinatesIndex, this.metallicTexture.level);
  58782. this._effect.setMatrix("reflectivityMatrix", this.metallicTexture.getTextureMatrix());
  58783. }
  58784. else if (this.reflectivityTexture) {
  58785. this._effect.setTexture("reflectivitySampler", this.reflectivityTexture);
  58786. this._effect.setFloat2("vReflectivityInfos", this.reflectivityTexture.coordinatesIndex, this.reflectivityTexture.level);
  58787. this._effect.setMatrix("reflectivityMatrix", this.reflectivityTexture.getTextureMatrix());
  58788. }
  58789. }
  58790. if (this.bumpTexture && this._myScene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this.disableBumpMap) {
  58791. this._effect.setTexture("bumpSampler", this.bumpTexture);
  58792. this._effect.setFloat3("vBumpInfos", this.bumpTexture.coordinatesIndex, 1.0 / this.bumpTexture.level, this.parallaxScaleBias);
  58793. this._effect.setMatrix("bumpMatrix", this.bumpTexture.getTextureMatrix());
  58794. }
  58795. if (this.refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  58796. this._microsurfaceTextureLods.y = Math.round(Math.log(this.refractionTexture.getSize().width) * Math.LOG2E);
  58797. var depth = 1.0;
  58798. if (this.refractionTexture.isCube) {
  58799. this._effect.setTexture("refractionCubeSampler", this.refractionTexture);
  58800. }
  58801. else {
  58802. this._effect.setTexture("refraction2DSampler", this.refractionTexture);
  58803. this._effect.setMatrix("refractionMatrix", this.refractionTexture.getReflectionTextureMatrix());
  58804. if (this.refractionTexture.depth) {
  58805. depth = this.refractionTexture.depth;
  58806. }
  58807. }
  58808. this._effect.setFloat4("vRefractionInfos", this.refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  58809. }
  58810. if ((this.reflectionTexture || this.refractionTexture)) {
  58811. this._effect.setFloat2("vMicrosurfaceTextureLods", this._microsurfaceTextureLods.x, this._microsurfaceTextureLods.y);
  58812. }
  58813. if (this.cameraColorGradingTexture && BABYLON.StandardMaterial.ColorGradingTextureEnabled) {
  58814. BABYLON.ColorGradingTexture.Bind(this.cameraColorGradingTexture, this._effect);
  58815. }
  58816. }
  58817. // Clip plane
  58818. BABYLON.MaterialHelper.BindClipPlane(this._effect, this._myScene);
  58819. // Point size
  58820. if (this.pointsCloud) {
  58821. this._effect.setFloat("pointSize", this.pointSize);
  58822. }
  58823. // Colors
  58824. this._myScene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  58825. if (this._defines.METALLICWORKFLOW) {
  58826. PBRMaterial._scaledReflectivity.r = this.metallic === undefined ? 1 : this.metallic;
  58827. PBRMaterial._scaledReflectivity.g = this.roughness === undefined ? 1 : this.roughness;
  58828. this._effect.setColor4("vReflectivityColor", PBRMaterial._scaledReflectivity, 0);
  58829. }
  58830. else {
  58831. // GAMMA CORRECTION.
  58832. this.convertColorToLinearSpaceToRef(this.reflectivityColor, PBRMaterial._scaledReflectivity);
  58833. this._effect.setColor4("vReflectivityColor", PBRMaterial._scaledReflectivity, this.microSurface);
  58834. }
  58835. this._effect.setVector3("vEyePosition", this._myScene._mirroredCameraPosition ? this._myScene._mirroredCameraPosition : this._myScene.activeCamera.position);
  58836. this._effect.setColor3("vAmbientColor", this._globalAmbientColor);
  58837. // GAMMA CORRECTION.
  58838. this.convertColorToLinearSpaceToRef(this.emissiveColor, PBRMaterial._scaledEmissive);
  58839. this._effect.setColor3("vEmissiveColor", PBRMaterial._scaledEmissive);
  58840. // GAMMA CORRECTION.
  58841. this.convertColorToLinearSpaceToRef(this.reflectionColor, PBRMaterial._scaledReflection);
  58842. this._effect.setColor3("vReflectionColor", PBRMaterial._scaledReflection);
  58843. }
  58844. if (this._myScene.getCachedMaterial() !== this || !this.isFrozen) {
  58845. // GAMMA CORRECTION.
  58846. this.convertColorToLinearSpaceToRef(this.albedoColor, PBRMaterial._scaledAlbedo);
  58847. this._effect.setColor4("vAlbedoColor", PBRMaterial._scaledAlbedo, this.alpha * mesh.visibility);
  58848. // Lights
  58849. if (this._myScene.lightsEnabled && !this.disableLighting) {
  58850. PBRMaterial.BindLights(this._myScene, mesh, this._effect, this._defines, this.useScalarInLinearSpace, this.maxSimultaneousLights, this.usePhysicalLightFalloff);
  58851. }
  58852. // View
  58853. if (this._myScene.fogEnabled && mesh.applyFog && this._myScene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this.reflectionTexture) {
  58854. this._effect.setMatrix("view", this._myScene.getViewMatrix());
  58855. }
  58856. // Fog
  58857. BABYLON.MaterialHelper.BindFogParameters(this._myScene, mesh, this._effect);
  58858. this._lightingInfos.x = this.directIntensity;
  58859. this._lightingInfos.y = this.emissiveIntensity;
  58860. this._lightingInfos.z = this.environmentIntensity;
  58861. this._lightingInfos.w = this.specularIntensity;
  58862. this._effect.setVector4("vLightingIntensity", this._lightingInfos);
  58863. this._overloadedShadowInfos.x = this.overloadedShadowIntensity;
  58864. this._overloadedShadowInfos.y = this.overloadedShadeIntensity;
  58865. this._effect.setVector4("vOverloadedShadowIntensity", this._overloadedShadowInfos);
  58866. this._cameraInfos.x = this.cameraExposure;
  58867. this._cameraInfos.y = this.cameraContrast;
  58868. this._effect.setVector4("vCameraInfos", this._cameraInfos);
  58869. if (this.cameraColorCurves) {
  58870. BABYLON.ColorCurves.Bind(this.cameraColorCurves, this._effect);
  58871. }
  58872. this._overloadedIntensity.x = this.overloadedAmbientIntensity;
  58873. this._overloadedIntensity.y = this.overloadedAlbedoIntensity;
  58874. this._overloadedIntensity.z = this.overloadedReflectivityIntensity;
  58875. this._overloadedIntensity.w = this.overloadedEmissiveIntensity;
  58876. this._effect.setVector4("vOverloadedIntensity", this._overloadedIntensity);
  58877. this._effect.setColor3("vOverloadedAmbient", this.overloadedAmbient);
  58878. this.convertColorToLinearSpaceToRef(this.overloadedAlbedo, this._tempColor);
  58879. this._effect.setColor3("vOverloadedAlbedo", this._tempColor);
  58880. this.convertColorToLinearSpaceToRef(this.overloadedReflectivity, this._tempColor);
  58881. this._effect.setColor3("vOverloadedReflectivity", this._tempColor);
  58882. this.convertColorToLinearSpaceToRef(this.overloadedEmissive, this._tempColor);
  58883. this._effect.setColor3("vOverloadedEmissive", this._tempColor);
  58884. this.convertColorToLinearSpaceToRef(this.overloadedReflection, this._tempColor);
  58885. this._effect.setColor3("vOverloadedReflection", this._tempColor);
  58886. this._overloadedMicroSurface.x = this.overloadedMicroSurface;
  58887. this._overloadedMicroSurface.y = this.overloadedMicroSurfaceIntensity;
  58888. this._overloadedMicroSurface.z = this.overloadedReflectionIntensity;
  58889. this._effect.setVector3("vOverloadedMicroSurface", this._overloadedMicroSurface);
  58890. // Log. depth
  58891. BABYLON.MaterialHelper.BindLogDepth(this._defines, this._effect, this._myScene);
  58892. }
  58893. _super.prototype.bind.call(this, world, mesh);
  58894. this._myScene = null;
  58895. };
  58896. PBRMaterial.prototype.getAnimatables = function () {
  58897. var results = [];
  58898. if (this.albedoTexture && this.albedoTexture.animations && this.albedoTexture.animations.length > 0) {
  58899. results.push(this.albedoTexture);
  58900. }
  58901. if (this.ambientTexture && this.ambientTexture.animations && this.ambientTexture.animations.length > 0) {
  58902. results.push(this.ambientTexture);
  58903. }
  58904. if (this.opacityTexture && this.opacityTexture.animations && this.opacityTexture.animations.length > 0) {
  58905. results.push(this.opacityTexture);
  58906. }
  58907. if (this.reflectionTexture && this.reflectionTexture.animations && this.reflectionTexture.animations.length > 0) {
  58908. results.push(this.reflectionTexture);
  58909. }
  58910. if (this.emissiveTexture && this.emissiveTexture.animations && this.emissiveTexture.animations.length > 0) {
  58911. results.push(this.emissiveTexture);
  58912. }
  58913. if (this.metallicTexture && this.metallicTexture.animations && this.metallicTexture.animations.length > 0) {
  58914. results.push(this.metallicTexture);
  58915. }
  58916. else if (this.reflectivityTexture && this.reflectivityTexture.animations && this.reflectivityTexture.animations.length > 0) {
  58917. results.push(this.reflectivityTexture);
  58918. }
  58919. if (this.bumpTexture && this.bumpTexture.animations && this.bumpTexture.animations.length > 0) {
  58920. results.push(this.bumpTexture);
  58921. }
  58922. if (this.lightmapTexture && this.lightmapTexture.animations && this.lightmapTexture.animations.length > 0) {
  58923. results.push(this.lightmapTexture);
  58924. }
  58925. if (this.refractionTexture && this.refractionTexture.animations && this.refractionTexture.animations.length > 0) {
  58926. results.push(this.refractionTexture);
  58927. }
  58928. if (this.cameraColorGradingTexture && this.cameraColorGradingTexture.animations && this.cameraColorGradingTexture.animations.length > 0) {
  58929. results.push(this.cameraColorGradingTexture);
  58930. }
  58931. return results;
  58932. };
  58933. PBRMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  58934. if (forceDisposeTextures) {
  58935. if (this.albedoTexture) {
  58936. this.albedoTexture.dispose();
  58937. }
  58938. if (this.ambientTexture) {
  58939. this.ambientTexture.dispose();
  58940. }
  58941. if (this.opacityTexture) {
  58942. this.opacityTexture.dispose();
  58943. }
  58944. if (this.reflectionTexture) {
  58945. this.reflectionTexture.dispose();
  58946. }
  58947. if (this.emissiveTexture) {
  58948. this.emissiveTexture.dispose();
  58949. }
  58950. if (this.metallicTexture) {
  58951. this.metallicTexture.dispose();
  58952. }
  58953. if (this.reflectivityTexture) {
  58954. this.reflectivityTexture.dispose();
  58955. }
  58956. if (this.bumpTexture) {
  58957. this.bumpTexture.dispose();
  58958. }
  58959. if (this.lightmapTexture) {
  58960. this.lightmapTexture.dispose();
  58961. }
  58962. if (this.refractionTexture) {
  58963. this.refractionTexture.dispose();
  58964. }
  58965. if (this.cameraColorGradingTexture) {
  58966. this.cameraColorGradingTexture.dispose();
  58967. }
  58968. }
  58969. this._renderTargets.dispose();
  58970. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  58971. };
  58972. PBRMaterial.prototype.clone = function (name) {
  58973. var _this = this;
  58974. return BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  58975. };
  58976. PBRMaterial.prototype.serialize = function () {
  58977. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  58978. serializationObject.customType = "BABYLON.PBRMaterial";
  58979. return serializationObject;
  58980. };
  58981. // Statics
  58982. PBRMaterial.Parse = function (source, scene, rootUrl) {
  58983. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  58984. };
  58985. return PBRMaterial;
  58986. }(BABYLON.Material));
  58987. PBRMaterial._scaledAlbedo = new BABYLON.Color3();
  58988. PBRMaterial._scaledReflectivity = new BABYLON.Color3();
  58989. PBRMaterial._scaledEmissive = new BABYLON.Color3();
  58990. PBRMaterial._scaledReflection = new BABYLON.Color3();
  58991. __decorate([
  58992. BABYLON.serialize()
  58993. ], PBRMaterial.prototype, "directIntensity", void 0);
  58994. __decorate([
  58995. BABYLON.serialize()
  58996. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  58997. __decorate([
  58998. BABYLON.serialize()
  58999. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  59000. __decorate([
  59001. BABYLON.serialize()
  59002. ], PBRMaterial.prototype, "specularIntensity", void 0);
  59003. __decorate([
  59004. BABYLON.serialize()
  59005. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  59006. __decorate([
  59007. BABYLON.serialize()
  59008. ], PBRMaterial.prototype, "overloadedShadowIntensity", void 0);
  59009. __decorate([
  59010. BABYLON.serialize()
  59011. ], PBRMaterial.prototype, "overloadedShadeIntensity", void 0);
  59012. __decorate([
  59013. BABYLON.serialize()
  59014. ], PBRMaterial.prototype, "cameraExposure", void 0);
  59015. __decorate([
  59016. BABYLON.serialize()
  59017. ], PBRMaterial.prototype, "cameraContrast", void 0);
  59018. __decorate([
  59019. BABYLON.serializeAsTexture()
  59020. ], PBRMaterial.prototype, "cameraColorGradingTexture", void 0);
  59021. __decorate([
  59022. BABYLON.serializeAsColorCurves()
  59023. ], PBRMaterial.prototype, "cameraColorCurves", void 0);
  59024. __decorate([
  59025. BABYLON.serializeAsColor3()
  59026. ], PBRMaterial.prototype, "overloadedAmbient", void 0);
  59027. __decorate([
  59028. BABYLON.serialize()
  59029. ], PBRMaterial.prototype, "overloadedAmbientIntensity", void 0);
  59030. __decorate([
  59031. BABYLON.serializeAsColor3()
  59032. ], PBRMaterial.prototype, "overloadedAlbedo", void 0);
  59033. __decorate([
  59034. BABYLON.serialize()
  59035. ], PBRMaterial.prototype, "overloadedAlbedoIntensity", void 0);
  59036. __decorate([
  59037. BABYLON.serializeAsColor3()
  59038. ], PBRMaterial.prototype, "overloadedReflectivity", void 0);
  59039. __decorate([
  59040. BABYLON.serialize()
  59041. ], PBRMaterial.prototype, "overloadedReflectivityIntensity", void 0);
  59042. __decorate([
  59043. BABYLON.serializeAsColor3()
  59044. ], PBRMaterial.prototype, "overloadedEmissive", void 0);
  59045. __decorate([
  59046. BABYLON.serialize()
  59047. ], PBRMaterial.prototype, "overloadedEmissiveIntensity", void 0);
  59048. __decorate([
  59049. BABYLON.serializeAsColor3()
  59050. ], PBRMaterial.prototype, "overloadedReflection", void 0);
  59051. __decorate([
  59052. BABYLON.serialize()
  59053. ], PBRMaterial.prototype, "overloadedReflectionIntensity", void 0);
  59054. __decorate([
  59055. BABYLON.serialize()
  59056. ], PBRMaterial.prototype, "overloadedMicroSurface", void 0);
  59057. __decorate([
  59058. BABYLON.serialize()
  59059. ], PBRMaterial.prototype, "overloadedMicroSurfaceIntensity", void 0);
  59060. __decorate([
  59061. BABYLON.serializeAsTexture()
  59062. ], PBRMaterial.prototype, "albedoTexture", void 0);
  59063. __decorate([
  59064. BABYLON.serializeAsTexture()
  59065. ], PBRMaterial.prototype, "ambientTexture", void 0);
  59066. __decorate([
  59067. BABYLON.serialize()
  59068. ], PBRMaterial.prototype, "ambientTextureStrength", void 0);
  59069. __decorate([
  59070. BABYLON.serializeAsTexture()
  59071. ], PBRMaterial.prototype, "opacityTexture", void 0);
  59072. __decorate([
  59073. BABYLON.serializeAsTexture()
  59074. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  59075. __decorate([
  59076. BABYLON.serializeAsTexture()
  59077. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  59078. __decorate([
  59079. BABYLON.serializeAsTexture()
  59080. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  59081. __decorate([
  59082. BABYLON.serializeAsTexture()
  59083. ], PBRMaterial.prototype, "metallicTexture", void 0);
  59084. __decorate([
  59085. BABYLON.serialize()
  59086. ], PBRMaterial.prototype, "metallic", void 0);
  59087. __decorate([
  59088. BABYLON.serialize()
  59089. ], PBRMaterial.prototype, "roughness", void 0);
  59090. __decorate([
  59091. BABYLON.serializeAsTexture()
  59092. ], PBRMaterial.prototype, "bumpTexture", void 0);
  59093. __decorate([
  59094. BABYLON.serializeAsTexture()
  59095. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  59096. __decorate([
  59097. BABYLON.serializeAsTexture()
  59098. ], PBRMaterial.prototype, "refractionTexture", void 0);
  59099. __decorate([
  59100. BABYLON.serializeAsColor3("ambient")
  59101. ], PBRMaterial.prototype, "ambientColor", void 0);
  59102. __decorate([
  59103. BABYLON.serializeAsColor3("albedo")
  59104. ], PBRMaterial.prototype, "albedoColor", void 0);
  59105. __decorate([
  59106. BABYLON.serializeAsColor3("reflectivity")
  59107. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  59108. __decorate([
  59109. BABYLON.serializeAsColor3("reflection")
  59110. ], PBRMaterial.prototype, "reflectionColor", void 0);
  59111. __decorate([
  59112. BABYLON.serializeAsColor3("emissive")
  59113. ], PBRMaterial.prototype, "emissiveColor", void 0);
  59114. __decorate([
  59115. BABYLON.serialize()
  59116. ], PBRMaterial.prototype, "microSurface", void 0);
  59117. __decorate([
  59118. BABYLON.serialize()
  59119. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  59120. __decorate([
  59121. BABYLON.serialize()
  59122. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  59123. __decorate([
  59124. BABYLON.serializeAsFresnelParameters()
  59125. ], PBRMaterial.prototype, "opacityFresnelParameters", void 0);
  59126. __decorate([
  59127. BABYLON.serializeAsFresnelParameters()
  59128. ], PBRMaterial.prototype, "emissiveFresnelParameters", void 0);
  59129. __decorate([
  59130. BABYLON.serialize()
  59131. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  59132. __decorate([
  59133. BABYLON.serialize()
  59134. ], PBRMaterial.prototype, "linkEmissiveWithAlbedo", void 0);
  59135. __decorate([
  59136. BABYLON.serialize()
  59137. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  59138. __decorate([
  59139. BABYLON.serialize()
  59140. ], PBRMaterial.prototype, "useEmissiveAsIllumination", void 0);
  59141. __decorate([
  59142. BABYLON.serialize()
  59143. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  59144. __decorate([
  59145. BABYLON.serialize()
  59146. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  59147. __decorate([
  59148. BABYLON.serialize()
  59149. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  59150. __decorate([
  59151. BABYLON.serialize()
  59152. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureAlpha", void 0);
  59153. __decorate([
  59154. BABYLON.serialize()
  59155. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureGreen", void 0);
  59156. __decorate([
  59157. BABYLON.serialize()
  59158. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  59159. __decorate([
  59160. BABYLON.serialize()
  59161. ], PBRMaterial.prototype, "useScalarInLinearSpace", void 0);
  59162. __decorate([
  59163. BABYLON.serialize()
  59164. ], PBRMaterial.prototype, "usePhysicalLightFalloff", void 0);
  59165. __decorate([
  59166. BABYLON.serialize()
  59167. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  59168. __decorate([
  59169. BABYLON.serialize()
  59170. ], PBRMaterial.prototype, "useParallax", void 0);
  59171. __decorate([
  59172. BABYLON.serialize()
  59173. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  59174. __decorate([
  59175. BABYLON.serialize()
  59176. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  59177. __decorate([
  59178. BABYLON.serialize()
  59179. ], PBRMaterial.prototype, "disableLighting", void 0);
  59180. __decorate([
  59181. BABYLON.serialize()
  59182. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  59183. __decorate([
  59184. BABYLON.serialize()
  59185. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  59186. __decorate([
  59187. BABYLON.serialize()
  59188. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  59189. __decorate([
  59190. BABYLON.serialize()
  59191. ], PBRMaterial.prototype, "useLogarithmicDepth", null);
  59192. BABYLON.PBRMaterial = PBRMaterial;
  59193. })(BABYLON || (BABYLON = {}));
  59194. //# sourceMappingURL=babylon.pbrMaterial.js.map
  59195. var BABYLON;
  59196. (function (BABYLON) {
  59197. var DebugLayer = (function () {
  59198. function DebugLayer(scene) {
  59199. this._scene = scene;
  59200. }
  59201. /** Creates the inspector window. */
  59202. DebugLayer.prototype._createInspector = function (config) {
  59203. if (config === void 0) { config = {}; }
  59204. var popup = config.popup || false;
  59205. var initialTab = config.initialTab || 0;
  59206. var parentElement = config.parentElement || null;
  59207. if (!this._inspector) {
  59208. this._inspector = new INSPECTOR.Inspector(this._scene, popup, initialTab, parentElement);
  59209. } // else nothing to do,; instance is already existing
  59210. };
  59211. DebugLayer.prototype.isVisible = function () {
  59212. if (!this._inspector) {
  59213. return false;
  59214. }
  59215. return true;
  59216. };
  59217. DebugLayer.prototype.hide = function () {
  59218. if (this._inspector) {
  59219. this._inspector.dispose();
  59220. this._inspector = null;
  59221. }
  59222. };
  59223. DebugLayer.prototype.show = function (config) {
  59224. if (config === void 0) { config = {}; }
  59225. if (typeof INSPECTOR == 'undefined') {
  59226. // Load inspector and add it to the DOM
  59227. BABYLON.Tools.LoadScript(DebugLayer.InspectorURL, this._createInspector.bind(this, config));
  59228. }
  59229. else {
  59230. // Otherwise creates the inspector
  59231. this._createInspector(config);
  59232. }
  59233. };
  59234. return DebugLayer;
  59235. }());
  59236. DebugLayer.InspectorURL = 'http://www.babylonjs.com/babylon.inspector.bundle.js';
  59237. BABYLON.DebugLayer = DebugLayer;
  59238. })(BABYLON || (BABYLON = {}));
  59239. //# sourceMappingURL=babylon.debugLayer.js.map
  59240. /// <reference path="RenderPipeline\babylon.postProcessRenderPipeline.ts" />
  59241. var BABYLON;
  59242. (function (BABYLON) {
  59243. var StandardRenderingPipeline = (function (_super) {
  59244. __extends(StandardRenderingPipeline, _super);
  59245. /**
  59246. * @constructor
  59247. * @param {string} name - The rendering pipeline name
  59248. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  59249. * @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)
  59250. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  59251. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  59252. */
  59253. function StandardRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  59254. if (originalPostProcess === void 0) { originalPostProcess = null; }
  59255. var _this = _super.call(this, scene.getEngine(), name) || this;
  59256. _this.downSampleX4PostProcess = null;
  59257. _this.brightPassPostProcess = null;
  59258. _this.gaussianBlurHPostProcesses = [];
  59259. _this.gaussianBlurVPostProcesses = [];
  59260. _this.textureAdderPostProcess = null;
  59261. _this.textureAdderFinalPostProcess = null;
  59262. _this.lensFlareFinalPostProcess = null;
  59263. _this.lensFlarePostProcess = null;
  59264. _this.lensFlareComposePostProcess = null;
  59265. _this.depthOfFieldPostProcess = null;
  59266. // Values
  59267. _this.brightThreshold = 1.0;
  59268. _this.blurWidth = 2.0;
  59269. _this.horizontalBlur = false;
  59270. _this.gaussianCoefficient = 0.25;
  59271. _this.gaussianMean = 1.0;
  59272. _this.gaussianStandardDeviation = 1.0;
  59273. _this.exposure = 1.0;
  59274. _this.lensTexture = null;
  59275. _this.lensColorTexture = null;
  59276. _this.lensFlareStrength = 20.0;
  59277. _this.lensFlareGhostDispersal = 1.4;
  59278. _this.lensFlareHaloWidth = 0.7;
  59279. _this.lensFlareDistortionStrength = 16.0;
  59280. _this.lensStarTexture = null;
  59281. _this.lensFlareDirtTexture = null;
  59282. _this.depthOfFieldDistance = 10.0;
  59283. _this.depthOfFieldBlurWidth = 2.0;
  59284. // IAnimatable
  59285. _this.animations = [];
  59286. _this._depthRenderer = null;
  59287. _this._currentDepthOfFieldSource = null;
  59288. // Getters and setters
  59289. _this._depthOfFieldEnabled = true;
  59290. _this._lensFlareEnabled = true;
  59291. // Initialize
  59292. _this._scene = scene;
  59293. // Create pass post-processe
  59294. if (!originalPostProcess) {
  59295. _this.originalPostProcess = new BABYLON.PostProcess("HDRPass", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", BABYLON.Engine.TEXTURETYPE_FLOAT);
  59296. }
  59297. else {
  59298. _this.originalPostProcess = originalPostProcess;
  59299. }
  59300. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this.originalPostProcess; }, true));
  59301. // Create down sample X4 post-process
  59302. _this._createDownSampleX4PostProcess(scene, ratio / 2);
  59303. // Create bright pass post-process
  59304. _this._createBrightPassPostProcess(scene, ratio / 2);
  59305. // Create gaussian blur post-processes (down sampling blurs)
  59306. _this._createGaussianBlurPostProcesses(scene, ratio / 2, 0);
  59307. _this._createGaussianBlurPostProcesses(scene, ratio / 4, 1);
  59308. _this._createGaussianBlurPostProcesses(scene, ratio / 8, 2);
  59309. _this._createGaussianBlurPostProcesses(scene, ratio / 16, 3);
  59310. // Create texture adder post-process
  59311. _this._createTextureAdderPostProcess(scene, ratio);
  59312. // Create depth-of-field source post-process
  59313. _this.textureAdderFinalPostProcess = new BABYLON.PostProcess("HDRDepthOfFieldSource", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  59314. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBaseDepthOfFieldSource", function () { return _this.textureAdderFinalPostProcess; }, true));
  59315. // Create lens flare post-process
  59316. _this._createLensFlarePostProcess(scene, ratio);
  59317. // Create depth-of-field source post-process post lens-flare and disable it now
  59318. _this.lensFlareFinalPostProcess = new BABYLON.PostProcess("HDRPostLensFlareDepthOfFieldSource", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  59319. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostLensFlareDepthOfFieldSource", function () { return _this.lensFlareFinalPostProcess; }, true));
  59320. // Create gaussian blur used by depth-of-field
  59321. _this._createGaussianBlurPostProcesses(scene, ratio / 2, 5, "depthOfFieldBlurWidth");
  59322. // Create depth-of-field post-process
  59323. _this._createDepthOfFieldPostProcess(scene, ratio);
  59324. // Finish
  59325. scene.postProcessRenderPipelineManager.addPipeline(_this);
  59326. if (cameras !== null) {
  59327. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  59328. }
  59329. // Deactivate
  59330. _this.LensFlareEnabled = false;
  59331. _this.DepthOfFieldEnabled = false;
  59332. return _this;
  59333. }
  59334. Object.defineProperty(StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", {
  59335. get: function () {
  59336. return this._depthOfFieldEnabled;
  59337. },
  59338. set: function (enabled) {
  59339. var blurIndex = this.gaussianBlurHPostProcesses.length - 1;
  59340. if (enabled && !this._depthOfFieldEnabled) {
  59341. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRGaussianBlurH" + blurIndex, this._scene.cameras);
  59342. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRGaussianBlurV" + blurIndex, this._scene.cameras);
  59343. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRDepthOfField", this._scene.cameras);
  59344. this._depthRenderer = this._scene.enableDepthRenderer();
  59345. }
  59346. else if (!enabled && this._depthOfFieldEnabled) {
  59347. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRGaussianBlurH" + blurIndex, this._scene.cameras);
  59348. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRGaussianBlurV" + blurIndex, this._scene.cameras);
  59349. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRDepthOfField", this._scene.cameras);
  59350. }
  59351. this._depthOfFieldEnabled = enabled;
  59352. },
  59353. enumerable: true,
  59354. configurable: true
  59355. });
  59356. Object.defineProperty(StandardRenderingPipeline.prototype, "LensFlareEnabled", {
  59357. get: function () {
  59358. return this._lensFlareEnabled;
  59359. },
  59360. set: function (enabled) {
  59361. var blurIndex = this.gaussianBlurHPostProcesses.length - 2;
  59362. if (enabled && !this._lensFlareEnabled) {
  59363. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRLensFlare", this._scene.cameras);
  59364. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRLensFlareShift", this._scene.cameras);
  59365. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRGaussianBlurH" + blurIndex, this._scene.cameras);
  59366. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRGaussianBlurV" + blurIndex, this._scene.cameras);
  59367. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRLensFlareCompose", this._scene.cameras);
  59368. this._setDepthOfFieldSavePostProcess("HDRPostLensFlareDepthOfFieldSource");
  59369. }
  59370. else if (!enabled && this._lensFlareEnabled) {
  59371. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRLensFlare", this._scene.cameras);
  59372. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRLensFlareShift", this._scene.cameras);
  59373. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRGaussianBlurH" + blurIndex, this._scene.cameras);
  59374. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRGaussianBlurV" + blurIndex, this._scene.cameras);
  59375. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRLensFlareCompose", this._scene.cameras);
  59376. this._setDepthOfFieldSavePostProcess("HDRBaseDepthOfFieldSource");
  59377. }
  59378. this._lensFlareEnabled = enabled;
  59379. },
  59380. enumerable: true,
  59381. configurable: true
  59382. });
  59383. // Sets depth-of-field save post-process
  59384. StandardRenderingPipeline.prototype._setDepthOfFieldSavePostProcess = function (name) {
  59385. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRPostLensFlareDepthOfFieldSource", this._scene.cameras);
  59386. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, name, this._scene.cameras);
  59387. switch (name) {
  59388. case "HDRBaseDepthOfFieldSource":
  59389. this._currentDepthOfFieldSource = this.textureAdderFinalPostProcess;
  59390. break;
  59391. case "HDRPostLensFlareDepthOfFieldSource":
  59392. this._currentDepthOfFieldSource = this.lensFlareFinalPostProcess;
  59393. break;
  59394. default: break;
  59395. }
  59396. };
  59397. // Down Sample X4 Post-Processs
  59398. StandardRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  59399. var _this = this;
  59400. var downSampleX4Offsets = new Array(32);
  59401. 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);
  59402. this.downSampleX4PostProcess.onApply = function (effect) {
  59403. var id = 0;
  59404. for (var i = -2; i < 2; i++) {
  59405. for (var j = -2; j < 2; j++) {
  59406. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / _this.downSampleX4PostProcess.width);
  59407. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / _this.downSampleX4PostProcess.height);
  59408. id += 2;
  59409. }
  59410. }
  59411. effect.setArray2("dsOffsets", downSampleX4Offsets);
  59412. };
  59413. // Add to pipeline
  59414. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this.downSampleX4PostProcess; }, true));
  59415. };
  59416. // Brightpass Post-Process
  59417. StandardRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  59418. var _this = this;
  59419. var brightOffsets = new Array(8);
  59420. 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);
  59421. this.brightPassPostProcess.onApply = function (effect) {
  59422. var sU = (1.0 / _this.brightPassPostProcess.width);
  59423. var sV = (1.0 / _this.brightPassPostProcess.height);
  59424. brightOffsets[0] = -0.5 * sU;
  59425. brightOffsets[1] = 0.5 * sV;
  59426. brightOffsets[2] = 0.5 * sU;
  59427. brightOffsets[3] = 0.5 * sV;
  59428. brightOffsets[4] = -0.5 * sU;
  59429. brightOffsets[5] = -0.5 * sV;
  59430. brightOffsets[6] = 0.5 * sU;
  59431. brightOffsets[7] = -0.5 * sV;
  59432. effect.setArray2("dsOffsets", brightOffsets);
  59433. effect.setFloat("brightThreshold", _this.brightThreshold);
  59434. };
  59435. // Add to pipeline
  59436. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this.brightPassPostProcess; }, true));
  59437. };
  59438. // Create gaussian blur H&V post-processes
  59439. StandardRenderingPipeline.prototype._createGaussianBlurPostProcesses = function (scene, ratio, indice, blurWidthKey) {
  59440. var _this = this;
  59441. if (blurWidthKey === void 0) { blurWidthKey = "blurWidth"; }
  59442. var blurOffsets = new Array(9);
  59443. var blurWeights = new Array(9);
  59444. var uniforms = ["blurOffsets", "blurWeights", "blurWidth"];
  59445. var callback = function (height) {
  59446. return function (effect) {
  59447. // Weights
  59448. var x = 0.0;
  59449. for (var i = 0; i < 9; i++) {
  59450. x = (i - 4.0) / 4.0;
  59451. blurWeights[i] =
  59452. _this.gaussianCoefficient
  59453. * (1.0 / Math.sqrt(2.0 * Math.PI * _this.gaussianStandardDeviation))
  59454. * Math.exp((-((x - _this.gaussianMean) * (x - _this.gaussianMean))) / (2.0 * _this.gaussianStandardDeviation * _this.gaussianStandardDeviation));
  59455. }
  59456. var lastOutputDimensions = {
  59457. width: scene.getEngine().getRenderWidth(),
  59458. height: scene.getEngine().getRenderHeight()
  59459. };
  59460. for (var i = 0; i < 9; i++) {
  59461. var value = (i - 4.0) * (1.0 / (height === true ? lastOutputDimensions.height : lastOutputDimensions.width));
  59462. blurOffsets[i] = value;
  59463. }
  59464. effect.setArray("blurOffsets", blurOffsets);
  59465. effect.setArray("blurWeights", blurWeights);
  59466. if (height) {
  59467. effect.setFloat("blurWidth", _this.horizontalBlur ? 1.0 : _this[blurWidthKey]);
  59468. }
  59469. else {
  59470. effect.setFloat("blurWidth", _this[blurWidthKey]);
  59471. }
  59472. };
  59473. };
  59474. // Create horizontal gaussian blur post-processes
  59475. var gaussianBlurHPostProcess = new BABYLON.PostProcess("HDRGaussianBlurH_" + ratio + "_" + indice, "standard", uniforms, [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define GAUSSIAN_BLUR_H", BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  59476. gaussianBlurHPostProcess.onApply = callback(false);
  59477. // Create vertical gaussian blur post-process
  59478. var gaussianBlurVPostProcess = new BABYLON.PostProcess("HDRGaussianBlurV_" + ratio + "_" + indice, "standard", uniforms, [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define GAUSSIAN_BLUR_V", BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  59479. gaussianBlurVPostProcess.onApply = callback(true);
  59480. // Add to pipeline
  59481. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurH" + indice, function () { return gaussianBlurHPostProcess; }, true));
  59482. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurV" + indice, function () { return gaussianBlurVPostProcess; }, true));
  59483. // Finish
  59484. this.gaussianBlurHPostProcesses.push(gaussianBlurHPostProcess);
  59485. this.gaussianBlurVPostProcesses.push(gaussianBlurVPostProcess);
  59486. };
  59487. // Create texture adder post-process
  59488. StandardRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  59489. var _this = this;
  59490. 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);
  59491. this.textureAdderPostProcess.onApply = function (effect) {
  59492. effect.setTextureFromPostProcess("otherSampler", _this.originalPostProcess);
  59493. effect.setTexture("lensSampler", _this.lensTexture);
  59494. effect.setFloat("exposure", _this.exposure);
  59495. };
  59496. // Add to pipeline
  59497. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this.textureAdderPostProcess; }, true));
  59498. };
  59499. // Create lens flare post-process
  59500. StandardRenderingPipeline.prototype._createLensFlarePostProcess = function (scene, ratio) {
  59501. var _this = this;
  59502. this.lensFlarePostProcess = new BABYLON.PostProcess("HDRLensFlare", "standard", ["strength", "ghostDispersal", "haloWidth", "resolution", "distortionStrength"], ["lensColorSampler"], ratio / 2, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define LENS_FLARE", BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  59503. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlare", function () { return _this.lensFlarePostProcess; }, true));
  59504. this._createGaussianBlurPostProcesses(scene, ratio / 4, 4);
  59505. 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);
  59506. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlareCompose", function () { return _this.lensFlareComposePostProcess; }, true));
  59507. var resolution = new BABYLON.Vector2(0, 0);
  59508. // Lens flare
  59509. this.lensFlarePostProcess.onApply = function (effect) {
  59510. effect.setTextureFromPostProcess("textureSampler", _this.gaussianBlurHPostProcesses[0]);
  59511. effect.setTexture("lensColorSampler", _this.lensColorTexture);
  59512. effect.setFloat("strength", _this.lensFlareStrength);
  59513. effect.setFloat("ghostDispersal", _this.lensFlareGhostDispersal);
  59514. effect.setFloat("haloWidth", _this.lensFlareHaloWidth);
  59515. // Shift
  59516. resolution.x = _this.lensFlarePostProcess.width;
  59517. resolution.y = _this.lensFlarePostProcess.height;
  59518. effect.setVector2("resolution", resolution);
  59519. effect.setFloat("distortionStrength", _this.lensFlareDistortionStrength);
  59520. };
  59521. // Compose
  59522. 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);
  59523. 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);
  59524. this.lensFlareComposePostProcess.onApply = function (effect) {
  59525. effect.setTextureFromPostProcess("otherSampler", _this.textureAdderFinalPostProcess);
  59526. effect.setTexture("lensDirtSampler", _this.lensFlareDirtTexture);
  59527. effect.setTexture("lensStarSampler", _this.lensStarTexture);
  59528. // Lens start rotation matrix
  59529. var camerax = _this._scene.activeCamera.getViewMatrix().getRow(0);
  59530. var cameraz = _this._scene.activeCamera.getViewMatrix().getRow(2);
  59531. 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));
  59532. camRot *= 4.0;
  59533. 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);
  59534. var lensStarMatrix = scaleBias2.multiply(starRotation).multiply(scaleBias1);
  59535. effect.setMatrix("lensStarMatrix", lensStarMatrix);
  59536. };
  59537. };
  59538. // Create depth-of-field post-process
  59539. StandardRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (scene, ratio) {
  59540. var _this = this;
  59541. 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);
  59542. this.depthOfFieldPostProcess.onApply = function (effect) {
  59543. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  59544. effect.setTexture("depthSampler", _this._depthRenderer.getDepthMap());
  59545. effect.setFloat("distance", _this.depthOfFieldDistance);
  59546. };
  59547. // Add to pipeline
  59548. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfField", function () { return _this.depthOfFieldPostProcess; }, true));
  59549. };
  59550. // Dispose
  59551. StandardRenderingPipeline.prototype.dispose = function () {
  59552. for (var i = 0; i < this._scene.cameras.length; i++) {
  59553. var camera = this._scene.cameras[i];
  59554. this.originalPostProcess.dispose(camera);
  59555. this.downSampleX4PostProcess.dispose(camera);
  59556. this.brightPassPostProcess.dispose(camera);
  59557. this.textureAdderPostProcess.dispose(camera);
  59558. for (var j = 0; j < this.gaussianBlurHPostProcesses.length; j++) {
  59559. this.gaussianBlurHPostProcesses[j].dispose(camera);
  59560. }
  59561. for (var j = 0; j < this.gaussianBlurVPostProcesses.length; j++) {
  59562. this.gaussianBlurVPostProcesses[j].dispose(camera);
  59563. }
  59564. this.textureAdderFinalPostProcess.dispose(camera);
  59565. this.lensFlarePostProcess.dispose(camera);
  59566. this.lensFlareComposePostProcess.dispose(camera);
  59567. this.depthOfFieldPostProcess.dispose(camera);
  59568. }
  59569. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  59570. _super.prototype.dispose.call(this);
  59571. };
  59572. // Serialize rendering pipeline
  59573. StandardRenderingPipeline.prototype.serialize = function () {
  59574. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  59575. serializationObject.customType = "StandardRenderingPipeline";
  59576. return serializationObject;
  59577. };
  59578. // Parse serialized pipeline
  59579. StandardRenderingPipeline.Parse = function (source, scene, rootUrl) {
  59580. return BABYLON.SerializationHelper.Parse(function () { return new StandardRenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  59581. };
  59582. return StandardRenderingPipeline;
  59583. }(BABYLON.PostProcessRenderPipeline));
  59584. __decorate([
  59585. BABYLON.serialize()
  59586. ], StandardRenderingPipeline.prototype, "brightThreshold", void 0);
  59587. __decorate([
  59588. BABYLON.serialize()
  59589. ], StandardRenderingPipeline.prototype, "blurWidth", void 0);
  59590. __decorate([
  59591. BABYLON.serialize()
  59592. ], StandardRenderingPipeline.prototype, "horizontalBlur", void 0);
  59593. __decorate([
  59594. BABYLON.serialize()
  59595. ], StandardRenderingPipeline.prototype, "gaussianCoefficient", void 0);
  59596. __decorate([
  59597. BABYLON.serialize()
  59598. ], StandardRenderingPipeline.prototype, "gaussianMean", void 0);
  59599. __decorate([
  59600. BABYLON.serialize()
  59601. ], StandardRenderingPipeline.prototype, "gaussianStandardDeviation", void 0);
  59602. __decorate([
  59603. BABYLON.serialize()
  59604. ], StandardRenderingPipeline.prototype, "exposure", void 0);
  59605. __decorate([
  59606. BABYLON.serializeAsTexture("lensTexture")
  59607. ], StandardRenderingPipeline.prototype, "lensTexture", void 0);
  59608. __decorate([
  59609. BABYLON.serializeAsTexture("lensColorTexture")
  59610. ], StandardRenderingPipeline.prototype, "lensColorTexture", void 0);
  59611. __decorate([
  59612. BABYLON.serialize()
  59613. ], StandardRenderingPipeline.prototype, "lensFlareStrength", void 0);
  59614. __decorate([
  59615. BABYLON.serialize()
  59616. ], StandardRenderingPipeline.prototype, "lensFlareGhostDispersal", void 0);
  59617. __decorate([
  59618. BABYLON.serialize()
  59619. ], StandardRenderingPipeline.prototype, "lensFlareHaloWidth", void 0);
  59620. __decorate([
  59621. BABYLON.serialize()
  59622. ], StandardRenderingPipeline.prototype, "lensFlareDistortionStrength", void 0);
  59623. __decorate([
  59624. BABYLON.serializeAsTexture("lensStarTexture")
  59625. ], StandardRenderingPipeline.prototype, "lensStarTexture", void 0);
  59626. __decorate([
  59627. BABYLON.serializeAsTexture("lensFlareDirtTexture")
  59628. ], StandardRenderingPipeline.prototype, "lensFlareDirtTexture", void 0);
  59629. __decorate([
  59630. BABYLON.serialize()
  59631. ], StandardRenderingPipeline.prototype, "depthOfFieldDistance", void 0);
  59632. __decorate([
  59633. BABYLON.serialize()
  59634. ], StandardRenderingPipeline.prototype, "depthOfFieldBlurWidth", void 0);
  59635. BABYLON.StandardRenderingPipeline = StandardRenderingPipeline;
  59636. })(BABYLON || (BABYLON = {}));
  59637. //# sourceMappingURL=babylon.standardRenderingPipeline.js.map
  59638. 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 TANGENT\nattribute vec4 tangent;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\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<bumpVertexDeclaration>\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<bumpVertex>\n#include<clipPlaneVertex>\n#include<fogVertex>\n#include<shadowsVertex>[0..maxSimultaneousLights]\n#ifdef VERTEXCOLOR\n\nvColor=color;\n#endif\n#include<pointCloudVertex>\n#include<logDepthVertex>\n}","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":"varying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 texelSize;\nconst float fxaaQualitySubpix=1.0;\nconst float fxaaQualityEdgeThreshold=0.166;\nconst float fxaaQualityEdgeThresholdMin=0.0833;\nconst vec3 kLumaCoefficients=vec3(0.2126,0.7152,0.0722);\n#define FxaaLuma(rgba) dot(rgba.rgb,kLumaCoefficients)\nvoid main(){\nvec2 sampleCoordS=vUV+vec2( 0.0,1.0)*texelSize;\nvec2 sampleCoordE=vUV+vec2( 1.0,0.0)*texelSize;\nvec2 sampleCoordN=vUV+vec2( 0.0,-1.0)*texelSize;\nvec2 sampleCoordW=vUV+vec2(-1.0,0.0)*texelSize;\nvec2 sampleCoordNW=vUV+vec2(-1.0,-1.0)*texelSize;\nvec2 sampleCoordSE=vUV+vec2( 1.0,1.0)*texelSize;\nvec2 sampleCoordNE=vUV+vec2( 1.0,-1.0)*texelSize;\nvec2 sampleCoordSW=vUV+vec2(-1.0,1.0)*texelSize;\nvec2 posM;\nposM.x=vUV.x;\nposM.y=vUV.y;\nvec4 rgbyM=texture2D(textureSampler,vUV,0.0);\nfloat lumaM=FxaaLuma(rgbyM);\nfloat lumaS=FxaaLuma(texture2D(textureSampler,sampleCoordS,0.0));\nfloat lumaE=FxaaLuma(texture2D(textureSampler,sampleCoordE,0.0));\nfloat lumaN=FxaaLuma(texture2D(textureSampler,sampleCoordN,0.0));\nfloat lumaW=FxaaLuma(texture2D(textureSampler,sampleCoordW,0.0));\nfloat maxSM=max(lumaS,lumaM);\nfloat minSM=min(lumaS,lumaM);\nfloat maxESM=max(lumaE,maxSM);\nfloat minESM=min(lumaE,minSM);\nfloat maxWN=max(lumaN,lumaW);\nfloat minWN=min(lumaN,lumaW);\nfloat rangeMax=max(maxWN,maxESM);\nfloat rangeMin=min(minWN,minESM);\nfloat rangeMaxScaled=rangeMax*fxaaQualityEdgeThreshold;\nfloat range=rangeMax-rangeMin;\nfloat rangeMaxClamped=max(fxaaQualityEdgeThresholdMin,rangeMaxScaled);\nif(range<rangeMaxClamped) \n{\ngl_FragColor=rgbyM;\nreturn;\n}\nfloat lumaNW=FxaaLuma(texture2D(textureSampler,sampleCoordNW,0.0));\nfloat lumaSE=FxaaLuma(texture2D(textureSampler,sampleCoordSE,0.0));\nfloat lumaNE=FxaaLuma(texture2D(textureSampler,sampleCoordNE,0.0));\nfloat lumaSW=FxaaLuma(texture2D(textureSampler,sampleCoordSW,0.0));\nfloat lumaNS=lumaN+lumaS;\nfloat lumaWE=lumaW+lumaE;\nfloat subpixRcpRange=1.0/range;\nfloat subpixNSWE=lumaNS+lumaWE;\nfloat edgeHorz1=(-2.0*lumaM)+lumaNS;\nfloat edgeVert1=(-2.0*lumaM)+lumaWE;\nfloat lumaNESE=lumaNE+lumaSE;\nfloat lumaNWNE=lumaNW+lumaNE;\nfloat edgeHorz2=(-2.0*lumaE)+lumaNESE;\nfloat edgeVert2=(-2.0*lumaN)+lumaNWNE;\nfloat lumaNWSW=lumaNW+lumaSW;\nfloat lumaSWSE=lumaSW+lumaSE;\nfloat edgeHorz4=(abs(edgeHorz1)*2.0)+abs(edgeHorz2);\nfloat edgeVert4=(abs(edgeVert1)*2.0)+abs(edgeVert2);\nfloat edgeHorz3=(-2.0*lumaW)+lumaNWSW;\nfloat edgeVert3=(-2.0*lumaS)+lumaSWSE;\nfloat edgeHorz=abs(edgeHorz3)+edgeHorz4;\nfloat edgeVert=abs(edgeVert3)+edgeVert4;\nfloat subpixNWSWNESE=lumaNWSW+lumaNESE;\nfloat lengthSign=texelSize.x;\nbool horzSpan=edgeHorz>=edgeVert;\nfloat subpixA=subpixNSWE*2.0+subpixNWSWNESE;\nif (!horzSpan)\n{\nlumaN=lumaW;\n}\nif (!horzSpan) \n{\nlumaS=lumaE;\n}\nif (horzSpan) \n{\nlengthSign=texelSize.y;\n}\nfloat subpixB=(subpixA*(1.0/12.0))-lumaM;\nfloat gradientN=lumaN-lumaM;\nfloat gradientS=lumaS-lumaM;\nfloat lumaNN=lumaN+lumaM;\nfloat lumaSS=lumaS+lumaM;\nbool pairN=abs(gradientN)>=abs(gradientS);\nfloat gradient=max(abs(gradientN),abs(gradientS));\nif (pairN)\n{\nlengthSign=-lengthSign;\n}\nfloat subpixC=clamp(abs(subpixB)*subpixRcpRange,0.0,1.0);\nvec2 posB;\nposB.x=posM.x;\nposB.y=posM.y;\nvec2 offNP;\noffNP.x=(!horzSpan) ? 0.0 : texelSize.x;\noffNP.y=(horzSpan) ? 0.0 : texelSize.y;\nif (!horzSpan) \n{\nposB.x+=lengthSign*0.5;\n}\nif (horzSpan)\n{\nposB.y+=lengthSign*0.5;\n}\nvec2 posN;\nposN.x=posB.x-offNP.x*1.5;\nposN.y=posB.y-offNP.y*1.5;\nvec2 posP;\nposP.x=posB.x+offNP.x*1.5;\nposP.y=posB.y+offNP.y*1.5;\nfloat subpixD=((-2.0)*subpixC)+3.0;\nfloat lumaEndN=FxaaLuma(texture2D(textureSampler,posN,0.0));\nfloat subpixE=subpixC*subpixC;\nfloat lumaEndP=FxaaLuma(texture2D(textureSampler,posP,0.0));\nif (!pairN) \n{\nlumaNN=lumaSS;\n}\nfloat gradientScaled=gradient*1.0/4.0;\nfloat lumaMM=lumaM-lumaNN*0.5;\nfloat subpixF=subpixD*subpixE;\nbool lumaMLTZero=lumaMM<0.0;\nlumaEndN-=lumaNN*0.5;\nlumaEndP-=lumaNN*0.5;\nbool doneN=abs(lumaEndN)>=gradientScaled;\nbool doneP=abs(lumaEndP)>=gradientScaled;\nif (!doneN) \n{\nposN.x-=offNP.x*3.0;\n}\nif (!doneN) \n{\nposN.y-=offNP.y*3.0;\n}\nbool doneNP=(!doneN) || (!doneP);\nif (!doneP) \n{\nposP.x+=offNP.x*3.0;\n}\nif (!doneP)\n{\nposP.y+=offNP.y*3.0;\n}\nif (doneNP)\n{\nif (!doneN) lumaEndN=FxaaLuma(texture2D(textureSampler,posN.xy,0.0));\nif (!doneP) lumaEndP=FxaaLuma(texture2D(textureSampler,posP.xy,0.0));\nif (!doneN) lumaEndN=lumaEndN-lumaNN*0.5;\nif (!doneP) lumaEndP=lumaEndP-lumaNN*0.5;\ndoneN=abs(lumaEndN)>=gradientScaled;\ndoneP=abs(lumaEndP)>=gradientScaled;\nif (!doneN) posN.x-=offNP.x*12.0;\nif (!doneN) posN.y-=offNP.y*12.0;\ndoneNP=(!doneN) || (!doneP);\nif (!doneP) posP.x+=offNP.x*12.0;\nif (!doneP) posP.y+=offNP.y*12.0;\n}\nfloat dstN=posM.x-posN.x;\nfloat dstP=posP.x-posM.x;\nif (!horzSpan)\n{\ndstN=posM.y-posN.y;\n}\nif (!horzSpan) \n{\ndstP=posP.y-posM.y;\n}\nbool goodSpanN=(lumaEndN<0.0) != lumaMLTZero;\nfloat spanLength=(dstP+dstN);\nbool goodSpanP=(lumaEndP<0.0) != lumaMLTZero;\nfloat spanLengthRcp=1.0/spanLength;\nbool directionN=dstN<dstP;\nfloat dst=min(dstN,dstP);\nbool goodSpan=directionN ? goodSpanN : goodSpanP;\nfloat subpixG=subpixF*subpixF;\nfloat pixelOffset=(dst*(-spanLengthRcp))+0.5;\nfloat subpixH=subpixG*fxaaQualitySubpix;\nfloat pixelOffsetGood=goodSpan ? pixelOffset : 0.0;\nfloat pixelOffsetSubpix=max(pixelOffsetGood,subpixH);\nif (!horzSpan)\n{\nposM.x+=pixelOffsetSubpix*lengthSign;\n}\nif (horzSpan)\n{\nposM.y+=pixelOffsetSubpix*lengthSign;\n}\ngl_FragColor=texture2D(textureSampler,posM,0.0);\n}","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 TANGENT\nattribute vec4 tangent;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\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<bumpVertexDeclaration>\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<bumpVertex>\n\n#include<clipPlaneVertex>\n\n#include<fogVertex>\n\n#include<shadowsVertex>[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n\n#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif\n\n#include<logDepthVertex>\n}","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\nvFogDistance=viewPos;\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}"};
  59639. 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)\n#if defined(TANGENT) && defined(NORMAL)\nmat3 TBN=vTBN;\n#else\nmat3 TBN=cotangent_frame(normalW*vBumpInfos.y,-viewDirectionW,vBumpUV);\n#endif\n#endif\n#ifdef PARALLAX\nmat3 invTBN=transposeMat3(TBN);\n#ifdef PARALLAXOCCLUSION\nuvOffset=parallaxOcclusion(invTBN*-viewDirectionW,invTBN*normalW,vBumpUV,vBumpInfos.z);\n#else\nuvOffset=parallaxOffset(invTBN*viewDirectionW,vBumpInfos.z);\n#endif\n#endif\n#ifdef BUMP\nnormalW=perturbNormal(viewDirectionW,TBN,vBumpUV+uvOffset);\n#endif","bumpFragmentFunctions":"#ifdef BUMP\nvarying vec2 vBumpUV;\nuniform vec3 vBumpInfos;\nuniform sampler2D bumpSampler;\n#if defined(TANGENT) && defined(NORMAL) \nvarying mat3 vTBN;\n#endif\n\nmat3 cotangent_frame(vec3 normal,vec3 p,vec2 uv)\n{\n\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","bumpVertex":"#if defined(BUMP) || defined(PARALLAX)\n#if defined(TANGENT) && defined(NORMAL)\nvec3 normalW=normalize(vec3(finalWorld*vec4(normal,0.0)));\nvec3 tangentW=normalize(vec3(finalWorld*vec4(tangent.xyz,0.0)));\nvec3 bitangentW=cross(normalW,tangentW)*tangent.w;\nvTBN=mat3(tangentW,bitangentW,normalW);\n#endif\n#endif","bumpVertexDeclaration":"#if defined(BUMP) || defined(PARALLAX)\n#if defined(TANGENT) && defined(NORMAL) \nvarying mat3 vTBN;\n#endif\n#endif\n","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 vec3 vFogDistance;\nfloat CalcFogFactor()\n{\nfloat fogCoeff=1.0;\nfloat fogStart=vFogInfos.y;\nfloat fogEnd=vFogInfos.z;\nfloat fogDensity=vFogInfos.w;\nfloat fogDistance=length(vFogDistance);\nif (FOGMODE_LINEAR == vFogInfos.x)\n{\nfogCoeff=(fogEnd-fogDistance)/(fogEnd-fogStart);\n}\nelse if (FOGMODE_EXP == vFogInfos.x)\n{\nfogCoeff=1.0/pow(E,fogDistance*fogDensity);\n}\nelse if (FOGMODE_EXP2 == vFogInfos.x)\n{\nfogCoeff=1.0/pow(E,fogDistance*fogDistance*fogDensity*fogDensity);\n}\nreturn clamp(fogCoeff,0.0,1.0);\n}\n#endif","fogVertex":"#ifdef FOG\nvFogDistance=(view*worldPos).xyz;\n#endif","fogVertexDeclaration":"#ifdef FOG\nvarying vec3 vFogDistance;\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 SHADOWESM{X}\nshadow=computeShadowWithESM(vPositionFromLight{X},shadowSampler{X},shadowsInfo{X}.z,shadowsInfo{X}.x);\n#else \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#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,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}\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+directionToLightCenterW);\nNdotL=max(0.00000000001,dot(vNormal,directionToLightCenterW));\nfloat VdotH=clamp(dot(viewDirectionW,H),0.00000000001,1.0);\nfloat diffuseTerm=computeDiffuseTerm(NdotL,NdotV,VdotH,roughness);\nresult.diffuse=diffuseTerm*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nfloat NdotH=max(0.00000000001,dot(vNormal,H));\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,specularColor,reflectance90);\nresult.specular=specTerm*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,vec3 groundColor,float roughness,float NdotV,vec3 reflectance90,out float NdotL) {\nlightingInfo result;\n\n\n\nNdotL=dot(vNormal,lightData.xyz)*0.5+0.5;\nresult.diffuse=mix(groundColor,diffuseColor,NdotL);\n#ifdef SPECULARTERM\n\nvec3 lightVectorW=normalize(lightData.xyz);\nvec3 H=normalize(viewDirectionW+lightVectorW);\nfloat NdotH=max(0.00000000001,dot(vNormal,H));\nNdotL=max(0.00000000001,NdotL);\nfloat VdotH=clamp(0.00000000001,1.0,dot(viewDirectionW,H));\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,specularColor,reflectance90);\nresult.specular=specTerm;\n#endif\nreturn result;\n}","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}\nfloat computeShadowWithESM(vec4 vPositionFromLight,sampler2D shadowSampler,float bias,float darkness)\n{\nreturn 1.0;\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"};
  59640. 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(),this._collisionMask=-1}return Object.defineProperty(i.prototype,\"collisionMask\",{get:function(){return this._collisionMask},set:function(t){this._collisionMask=isNaN(t)?-1:t},enumerable:!0,configurable:!0}),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(e){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(o){console.log(\"single worker init\")}}(BABYLON||(BABYLON={}));var BABYLON;!function(e){e.CollisionWorker=\"\";var o;!function(e){e[e.INIT=0]=\"INIT\",e[e.UPDATE=1]=\"UPDATE\",e[e.COLLIDE=2]=\"COLLIDE\"}(o=e.WorkerTaskType||(e.WorkerTaskType={}));var i;!function(e){e[e.SUCCESS=0]=\"SUCCESS\",e[e.UNKNOWN_ERROR=1]=\"UNKNOWN_ERROR\"}(i=e.WorkerReplyType||(e.WorkerReplyType={}));var t=function(){function t(){var r=this;this._scaledPosition=e.Vector3.Zero(),this._scaledVelocity=e.Vector3.Zero(),this.onMeshUpdated=function(e){r._addUpdateMeshesList[e.uniqueId]=t.SerializeMesh(e)},this.onGeometryUpdated=function(e){r._addUpdateGeometriesList[e.id]=t.SerializeGeometry(e)},this._afterRender=function(){if(r._init&&!(0==r._toRemoveGeometryArray.length&&0==r._toRemoveMeshesArray.length&&0==Object.keys(r._addUpdateGeometriesList).length&&0==Object.keys(r._addUpdateMeshesList).length||r._runningUpdated>4)){++r._runningUpdated;var e={updatedMeshes:r._addUpdateMeshesList,updatedGeometries:r._addUpdateGeometriesList,removedGeometries:r._toRemoveGeometryArray,removedMeshes:r._toRemoveMeshesArray},i={payload:e,taskType:o.UPDATE},t=[];for(var s in e.updatedGeometries)e.updatedGeometries.hasOwnProperty(s)&&(t.push(i.payload.updatedGeometries[s].indices.buffer),t.push(i.payload.updatedGeometries[s].normals.buffer),t.push(i.payload.updatedGeometries[s].positions.buffer));r._worker.postMessage(i,t),r._addUpdateMeshesList={},r._addUpdateGeometriesList={},r._toRemoveGeometryArray=[],r._toRemoveMeshesArray=[]}},this._onMessageFromWorker=function(t){var s=t.data;if(s.error!=i.SUCCESS)return void e.Tools.Warn(\"error returned from worker!\");switch(s.taskType){case o.INIT:r._init=!0,r._scene.meshes.forEach(function(e){r.onMeshAdded(e)}),r._scene.getGeometries().forEach(function(e){r.onGeometryAdded(e)});break;case o.UPDATE:r._runningUpdated--;break;case o.COLLIDE:r._runningCollisionTask=!1;var n=s.payload;if(!r._collisionsCallbackArray[n.collisionId])return;r._collisionsCallbackArray[n.collisionId](n.collisionId,e.Vector3.FromArray(n.newPosition),r._scene.getMeshByUniqueID(n.collidedMeshUniqueId)),r._collisionsCallbackArray[n.collisionId]=void 0}},this._collisionsCallbackArray=[],this._init=!1,this._runningUpdated=0,this._runningCollisionTask=!1,this._addUpdateMeshesList={},this._addUpdateGeometriesList={},this._toRemoveGeometryArray=[],this._toRemoveMeshesArray=[]}return t.prototype.getNewPosition=function(e,i,t,r,s,n,a){if(this._init&&!this._collisionsCallbackArray[a]&&!this._collisionsCallbackArray[a+1e5]){e.divideToRef(t.radius,this._scaledPosition),i.divideToRef(t.radius,this._scaledVelocity),this._collisionsCallbackArray[a]=n;var d={collider:{position:this._scaledPosition.asArray(),velocity:this._scaledVelocity.asArray(),radius:t.radius.asArray()},collisionId:a,excludedMeshUniqueId:s?s.uniqueId:null,maximumRetry:r},l={payload:d,taskType:o.COLLIDE};this._worker.postMessage(l)}},t.prototype.init=function(i){this._scene=i,this._scene.registerAfterRender(this._afterRender);var t=e.WorkerIncluded?e.Engine.CodeRepository+\"Collisions/babylon.collisionWorker.js\":URL.createObjectURL(new Blob([e.CollisionWorker],{type:\"application/javascript\"}));this._worker=new Worker(t),this._worker.onmessage=this._onMessageFromWorker;var r={payload:{},taskType:o.INIT};this._worker.postMessage(r)},t.prototype.destroy=function(){this._scene.unregisterAfterRender(this._afterRender),this._worker.terminate()},t.prototype.onMeshAdded=function(e){e.registerAfterWorldMatrixUpdate(this.onMeshUpdated),this.onMeshUpdated(e)},t.prototype.onMeshRemoved=function(e){this._toRemoveMeshesArray.push(e.uniqueId)},t.prototype.onGeometryAdded=function(e){e.onGeometryUpdated=this.onGeometryUpdated,this.onGeometryUpdated(e)},t.prototype.onGeometryDeleted=function(e){this._toRemoveGeometryArray.push(e.id)},t}();t.SerializeMesh=function(o){var i=[];o.subMeshes&&(i=o.subMeshes.map(function(e,o){return{position:o,verticesStart:e.verticesStart,verticesCount:e.verticesCount,indexStart:e.indexStart,indexCount:e.indexCount,hasMaterial:!!e.getMaterial(),sphereCenter:e.getBoundingInfo().boundingSphere.centerWorld.asArray(),sphereRadius:e.getBoundingInfo().boundingSphere.radiusWorld,boxMinimum:e.getBoundingInfo().boundingBox.minimumWorld.asArray(),boxMaximum:e.getBoundingInfo().boundingBox.maximumWorld.asArray()}}));var t=null;return o instanceof e.Mesh?t=o.geometry?o.geometry.id:null:o instanceof e.InstancedMesh&&(t=o.sourceMesh&&o.sourceMesh.geometry?o.sourceMesh.geometry.id:null),{uniqueId:o.uniqueId,id:o.id,name:o.name,geometryId:t,sphereCenter:o.getBoundingInfo().boundingSphere.centerWorld.asArray(),sphereRadius:o.getBoundingInfo().boundingSphere.radiusWorld,boxMinimum:o.getBoundingInfo().boundingBox.minimumWorld.asArray(),boxMaximum:o.getBoundingInfo().boundingBox.maximumWorld.asArray(),worldMatrixFromCache:o.worldMatrixFromCache.asArray(),subMeshes:i,checkCollisions:o.checkCollisions}},t.SerializeGeometry=function(o){return{id:o.id,positions:new Float32Array(o.getVerticesData(e.VertexBuffer.PositionKind)||[]),normals:new Float32Array(o.getVerticesData(e.VertexBuffer.NormalKind)||[]),indices:new Uint32Array(o.getIndices()||[])}},e.CollisionCoordinatorWorker=t;var r=function(){function o(){this._scaledPosition=e.Vector3.Zero(),this._scaledVelocity=e.Vector3.Zero(),this._finalPosition=e.Vector3.Zero()}return o.prototype.getNewPosition=function(e,o,i,t,r,s,n){e.divideToRef(i.radius,this._scaledPosition),o.divideToRef(i.radius,this._scaledVelocity),i.collidedMesh=null,i.retry=0,i.initialVelocity=this._scaledVelocity,i.initialPosition=this._scaledPosition,this._collideWithWorld(this._scaledPosition,this._scaledVelocity,i,t,this._finalPosition,r),this._finalPosition.multiplyInPlace(i.radius),s(n,this._finalPosition,i.collidedMesh)},o.prototype.init=function(e){this._scene=e},o.prototype.destroy=function(){},o.prototype.onMeshAdded=function(e){},o.prototype.onMeshUpdated=function(e){},o.prototype.onMeshRemoved=function(e){},o.prototype.onGeometryAdded=function(e){},o.prototype.onGeometryUpdated=function(e){},o.prototype.onGeometryDeleted=function(e){},o.prototype._collideWithWorld=function(o,i,t,r,s,n){void 0===n&&(n=null);var a=10*e.Engine.CollisionsEpsilon;if(t.retry>=r)return void s.copyFrom(o);var d=n?n.collisionMask:t.collisionMask;t._initialize(o,i,a);for(var l=0;l<this._scene.meshes.length;l++){var c=this._scene.meshes[l];c.isEnabled()&&c.checkCollisions&&c.subMeshes&&c!==n&&0!==(d&c.collisionGroup)&&c._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.set=function(t,i,r){return this.copyFromFloats(t,i,r)},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.copyFromFloats=function(t,i,r,n){return this.r=t,this.g=i,this.b=r,this.a=n,this},t.prototype.set=function(t,i,r,n){return this.copyFromFloats(t,i,r,n)},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.set=function(t,i){return this.copyFromFloats(t,i)},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){return i.x=this.x*t,i.y=this.y*t,i.z=this.z*t,this},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.prototype.set=function(t,i,r){return this.copyFromFloats(t,i,r)},r.GetClipFactor=function(t,i,n,o){var e=r.Dot(t,n)-o,s=r.Dot(i,n)-o,h=e/(e-s);return h},r.FromArray=function(t,i){return i||(i=0),new r(t[i],t[i+1],t[i+2])},r.FromFloatArray=function(t,i){return i||(i=0),new r(t[i],t[i+1],t[i+2])},r.FromArrayToRef=function(t,i,r){r.x=t[i],r.y=t[i+1],r.z=t[i+2]},r.FromFloatArrayToRef=function(t,i,r){r.x=t[i],r.y=t[i+1],r.z=t[i+2]},r.FromFloatsToRef=function(t,i,r,n){n.x=t,n.y=i,n.z=r},r.Zero=function(){return new r(0,0,0)},r.Up=function(){return new r(0,1,0)},r.Forward=function(){return new r(0,0,1)},r.Right=function(){return new r(1,0,0)},r.Left=function(){return new r(-1,0,0)},r.TransformCoordinates=function(t,i){var n=r.Zero();return r.TransformCoordinatesToRef(t,i,n),n},r.TransformCoordinatesToRef=function(t,i,r){var n=t.x*i.m[0]+t.y*i.m[4]+t.z*i.m[8]+i.m[12],o=t.x*i.m[1]+t.y*i.m[5]+t.z*i.m[9]+i.m[13],e=t.x*i.m[2]+t.y*i.m[6]+t.z*i.m[10]+i.m[14],s=t.x*i.m[3]+t.y*i.m[7]+t.z*i.m[11]+i.m[15];r.x=n/s,r.y=o/s,r.z=e/s},r.TransformCoordinatesFromFloatsToRef=function(t,i,r,n,o){var e=t*n.m[0]+i*n.m[4]+r*n.m[8]+n.m[12],s=t*n.m[1]+i*n.m[5]+r*n.m[9]+n.m[13],h=t*n.m[2]+i*n.m[6]+r*n.m[10]+n.m[14],a=t*n.m[3]+i*n.m[7]+r*n.m[11]+n.m[15];o.x=e/a,o.y=s/a,o.z=h/a},r.TransformNormal=function(t,i){var n=r.Zero();return r.TransformNormalToRef(t,i,n),n},r.TransformNormalToRef=function(t,i,r){var n=t.x*i.m[0]+t.y*i.m[4]+t.z*i.m[8],o=t.x*i.m[1]+t.y*i.m[5]+t.z*i.m[9],e=t.x*i.m[2]+t.y*i.m[6]+t.z*i.m[10];r.x=n,r.y=o,r.z=e},r.TransformNormalFromFloatsToRef=function(t,i,r,n,o){o.x=t*n.m[0]+i*n.m[4]+r*n.m[8],o.y=t*n.m[1]+i*n.m[5]+r*n.m[9],o.z=t*n.m[2]+i*n.m[6]+r*n.m[10]},r.CatmullRom=function(t,i,n,o,e){var s=e*e,h=e*s,a=.5*(2*i.x+(-t.x+n.x)*e+(2*t.x-5*i.x+4*n.x-o.x)*s+(-t.x+3*i.x-3*n.x+o.x)*h),u=.5*(2*i.y+(-t.y+n.y)*e+(2*t.y-5*i.y+4*n.y-o.y)*s+(-t.y+3*i.y-3*n.y+o.y)*h),m=.5*(2*i.z+(-t.z+n.z)*e+(2*t.z-5*i.z+4*n.z-o.z)*s+(-t.z+3*i.z-3*n.z+o.z)*h);return new r(a,u,m)},r.Clamp=function(t,i,n){var o=t.x;o=o>n.x?n.x:o,o=o<i.x?i.x:o;var e=t.y;e=e>n.y?n.y:e,e=e<i.y?i.y:e;var s=t.z;return s=s>n.z?n.z:s,s=s<i.z?i.z:s,new r(o,e,s)},r.Hermite=function(t,i,n,o,e){var s=e*e,h=e*s,a=2*h-3*s+1,u=-2*h+3*s,m=h-2*s+e,y=h-s,c=t.x*a+n.x*u+i.x*m+o.x*y,p=t.y*a+n.y*u+i.y*m+o.y*y,f=t.z*a+n.z*u+i.z*m+o.z*y;return new r(c,p,f)},r.Lerp=function(t,i,n){var o=new r(0,0,0);return r.LerpToRef(t,i,n,o),o},r.LerpToRef=function(t,i,r,n){n.x=t.x+(i.x-t.x)*r,n.y=t.y+(i.y-t.y)*r,n.z=t.z+(i.z-t.z)*r},r.Dot=function(t,i){return t.x*i.x+t.y*i.y+t.z*i.z},r.Cross=function(t,i){var n=r.Zero();return r.CrossToRef(t,i,n),n},r.CrossToRef=function(t,i,r){A.Vector3[0].x=t.y*i.z-t.z*i.y,A.Vector3[0].y=t.z*i.x-t.x*i.z,A.Vector3[0].z=t.x*i.y-t.y*i.x,r.copyFrom(A.Vector3[0])},r.Normalize=function(t){var i=r.Zero();return r.NormalizeToRef(t,i),i},r.NormalizeToRef=function(t,i){i.copyFrom(t),i.normalize()},r.Project=function(t,i,n,o){var e=o.width,s=o.height,h=o.x,a=o.y,m=r._viewportMatrixCache?r._viewportMatrixCache:r._viewportMatrixCache=new u;u.FromValuesToRef(e/2,0,0,0,0,-s/2,0,0,0,0,.5,0,h+e/2,s/2+a,.5,1,m);var y=r._matrixCache?r._matrixCache:r._matrixCache=new u;return i.multiplyToRef(n,y),y.multiplyToRef(m,y),r.TransformCoordinates(t,y)},r.UnprojectFromTransform=function(t,n,o,e,s){var h=r._matrixCache?r._matrixCache:r._matrixCache=new u;e.multiplyToRef(s,h),h.invert(),t.x=t.x/n*2-1,t.y=-(t.y/o*2-1);var a=r.TransformCoordinates(t,h),m=t.x*h.m[3]+t.y*h.m[7]+t.z*h.m[11]+h.m[15];return i.WithinEpsilon(m,1)&&(a=a.scale(1/m)),a},r.Unproject=function(t,n,o,e,s,h){var a=r._matrixCache?r._matrixCache:r._matrixCache=new u;e.multiplyToRef(s,a),a.multiplyToRef(h,a),a.invert();var m=new r(t.x/n*2-1,-(t.y/o*2-1),2*t.z-1),y=r.TransformCoordinates(m,a),c=m.x*a.m[3]+m.y*a.m[7]+m.z*a.m[11]+a.m[15];return i.WithinEpsilon(c,1)&&(y=y.scale(1/c)),y},r.Minimize=function(t,i){var r=t.clone();return r.MinimizeInPlace(i),r},r.Maximize=function(t,i){var r=t.clone();return r.MaximizeInPlace(i),r},r.Distance=function(t,i){return Math.sqrt(r.DistanceSquared(t,i))},r.DistanceSquared=function(t,i){var r=t.x-i.x,n=t.y-i.y,o=t.z-i.z;return r*r+n*n+o*o},r.Center=function(t,i){var r=t.add(i);return r.scaleInPlace(.5),r},r.RotationFromAxis=function(t,i,n){var o=r.Zero();return r.RotationFromAxisToRef(t,i,n,o),o},r.RotationFromAxisToRef=function(t,i,r,n){var o=A.Quaternion[0];a.RotationQuaternionFromAxisToRef(t,i,r,o),o.toEulerAnglesToRef(n)},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){return i.x=this.x*t,i.y=this.y*t,i.z=this.z*t,i.w=this.w*t,this},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.prototype.set=function(t,i,r,n){return this.copyFromFloats(t,i,r,n)},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.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.w=t.w},r.TransformNormalFromFloatsToRef=function(t,i,r,n,o,e){e.x=t*o.m[0]+i*o.m[4]+r*o.m[8],e.y=t*o.m[1]+i*o.m[5]+r*o.m[9],e.z=t*o.m[2]+i*o.m[6]+r*o.m[10],e.w=n},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){return this.width=t,this.height=i,this},t.prototype.set=function(t,i){return this.copyFromFloats(t,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 i(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 i.prototype.toString=function(){return\"{X: \"+this.x+\" Y:\"+this.y+\" Z:\"+this.z+\" W:\"+this.w+\"}\"},i.prototype.getClassName=function(){return\"Quaternion\"},i.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)},i.prototype.asArray=function(){return[this.x,this.y,this.z,this.w]},i.prototype.equals=function(t){return t&&this.x===t.x&&this.y===t.y&&this.z===t.z&&this.w===t.w},i.prototype.clone=function(){return new i(this.x,this.y,this.z,this.w)},i.prototype.copyFrom=function(t){return this.x=t.x,this.y=t.y,this.z=t.z,this.w=t.w,this},i.prototype.copyFromFloats=function(t,i,r,n){return this.x=t,this.y=i,this.z=r,this.w=n,this},i.prototype.set=function(t,i,r,n){return this.copyFromFloats(t,i,r,n)},i.prototype.add=function(t){return new i(this.x+t.x,this.y+t.y,this.z+t.z,this.w+t.w)},i.prototype.subtract=function(t){return new i(this.x-t.x,this.y-t.y,this.z-t.z,this.w-t.w)},i.prototype.scale=function(t){return new i(this.x*t,this.y*t,this.z*t,this.w*t)},i.prototype.multiply=function(t){var r=new i(0,0,0,1);return this.multiplyToRef(t,r),r},i.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},i.prototype.multiplyInPlace=function(t){return this.multiplyToRef(t,this),this},i.prototype.conjugateToRef=function(t){return t.copyFromFloats(-this.x,-this.y,-this.z,this.w),this},i.prototype.conjugateInPlace=function(){return this.x*=-1,this.y*=-1,this.z*=-1,this},i.prototype.conjugate=function(){var t=new i(-this.x,-this.y,-this.z,this.w);return t},i.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w)},i.prototype.normalize=function(){var t=1/this.length();return this.x*=t,this.y*=t,this.z*=t,this.w*=t,this},i.prototype.toEulerAngles=function(t){void 0===t&&(t=\"YZX\");var i=e.Zero();return this.toEulerAnglesToRef(i,t),i},i.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},i.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},i.prototype.fromRotationMatrix=function(t){return i.FromRotationMatrixToRef(t,this),this},i.FromRotationMatrix=function(t){var r=new i;return i.FromRotationMatrixToRef(t,r),r},i.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)},i.Zero=function(){return new i(0,0,0,0)},i.Inverse=function(t){return new i(-t.x,-t.y,-t.z,t.w)},i.Identity=function(){return new i(0,0,0,1)},i.IsIdentity=function(t){return t&&0===t.x&&0===t.y&&0===t.z&&1===t.w},i.RotationAxis=function(t,r){return i.RotationAxisToRef(t,r,new i)},i.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},i.FromArray=function(t,r){return r||(r=0),new i(t[r],t[r+1],t[r+2],t[r+3])},i.RotationYawPitchRoll=function(t,r,n){var o=new i;return i.RotationYawPitchRollToRef(t,r,n,o),o},i.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},i.RotationAlphaBetaGamma=function(t,r,n){var o=new i;return i.RotationAlphaBetaGammaToRef(t,r,n,o),o},i.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)},i.RotationQuaternionFromAxis=function(t,r,n,o){var e=new i(0,0,0,0);return i.RotationQuaternionFromAxisToRef(t,r,n,e),e},i.RotationQuaternionFromAxisToRef=function(i,r,n,o){var e=A.Matrix[0];t.Matrix.FromXYZAxesToRef(i.normalize(),r.normalize(),n.normalize(),e),t.Quaternion.FromRotationMatrixToRef(e,o)},i.Slerp=function(t,r,n){var o=i.Identity();return i.SlerpToRef(t,r,n,o),o},i.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},i}();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),F=e*w-s*d+a*R,M=-(e*v-s*g+h*R),A=1/(i*T+r*_+n*F+o*M),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,N=s*y-h*m,V=e*c-a*u,q=e*y-h*u,D=e*m-s*u;return t.m[0]=T*A,t.m[4]=_*A,\nt.m[8]=F*A,t.m[12]=M*A,t.m[1]=-(r*z-n*w+o*v)*A,t.m[5]=(i*z-n*d+o*g)*A,t.m[9]=-(i*w-r*d+o*R)*A,t.m[13]=(i*v-r*g+n*R)*A,t.m[2]=(r*b-n*L+o*C)*A,t.m[6]=-(i*b-n*P+o*Z)*A,t.m[10]=(i*L-r*P+o*S)*A,t.m[14]=-(i*C-r*Z+n*S)*A,t.m[3]=-(r*I-n*H+o*N)*A,t.m[7]=(i*I-n*V+o*q)*A,t.m[11]=-(i*H-r*V+o*D)*A,t.m[15]=(i*N-r*q+n*D)*A,this},r.prototype.setTranslationFromFloats=function(t,i,r){return this.m[12]=t,this.m[13]=i,this.m[14]=r,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.getTranslationToRef=function(t){return t.x=this.m[12],t.y=this.m[13],t.z=this.m[14],this},r.prototype.removeRotationAndScaling=function(){return this.setRowFromFloats(0,1,0,0,0),this.setRowFromFloats(1,0,1,0,0),this.setRowFromFloats(2,0,0,1,0),this},r.prototype.multiply=function(t){var 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],F=t.m[6],M=t.m[7],A=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*A+s*P,i[r+1]=n*d+o*_+e*b+s*Z,i[r+2]=n*g+o*F+e*L+s*S,i[r+3]=n*R+o*M+e*C+s*I,i[r+4]=h*v+a*T+u*A+m*P,i[r+5]=h*d+a*_+u*b+m*Z,i[r+6]=h*g+a*F+u*L+m*S,i[r+7]=h*R+a*M+u*C+m*I,i[r+8]=y*v+c*T+p*A+f*P,i[r+9]=y*d+c*_+p*b+f*Z,i[r+10]=y*g+c*F+p*L+f*S,i[r+11]=y*R+c*M+p*C+f*I,i[r+12]=x*v+l*T+z*A+w*P,i[r+13]=x*d+l*_+z*b+w*Z,i[r+14]=x*g+l*F+z*L+w*S,i[r+15]=x*R+l*M+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]);return 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),this},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.prototype.setRowFromFloats=function(t,i,r,n,o){if(t<0||t>3)return this;var e=4*t;return this.m[e+0]=i,this.m[e+1]=r,this.m[e+2]=n,this.m[e+3]=o,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.Identity();return r.ComposeToRef(t,i,n,o),o},r.ComposeToRef=function(t,i,n,o){r.FromValuesToRef(t.x,0,0,0,0,t.y,0,0,0,0,t.z,0,0,0,0,1,A.Matrix[1]),i.toRotationMatrix(A.Matrix[0]),A.Matrix[1].multiplyToRef(A.Matrix[0],o),o.setTranslation(n)},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=!1);var e=o?-1:1,s=Math.tan(t.upDegrees*Math.PI/180),h=Math.tan(t.downDegrees*Math.PI/180),a=Math.tan(t.leftDegrees*Math.PI/180),u=Math.tan(t.rightDegrees*Math.PI/180),m=2/(a+u),y=2/(s+h);n.m[0]=m,n.m[1]=n.m[2]=n.m[3]=n.m[4]=0,n.m[5]=y,n.m[6]=n.m[7]=0,n.m[8]=(a-u)*m*.5*e,n.m[9]=-((s-h)*y*.5)*e,n.m[10]=-(i+r)/(r-i)*e,n.m[11]=1*e,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.prototype.clone=function(){return new t(this.x,this.y,this.width,this.height)},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\",t[t.BONE=2]=\"BONE\"}(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.CreateCatmullRomSpline=function(i,r){var n=new Array;n.push(i[0].clone()),Array.prototype.push.apply(n,i),n.push(i[i.length-1].clone());for(var o=new Array,s=1/r,h=0;h<n.length-3;h++)for(var a=0,u=0;u<r;u++)o.push(e.CatmullRom(n[h],n[h+1],n[h+2],n[h+3],a)),a+=s;return h--,o.push(e.CatmullRom(n[h],n[h+1],n[h+2],n[h+3],a)),new t(o)},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 F=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=F;var M=function(){function t(){}return t}();M.Color3=[r.Black(),r.Black(),r.Black()],M.Vector2=[o.Zero(),o.Zero(),o.Zero()],M.Vector3=[e.Zero(),e.Zero(),e.Zero(),e.Zero(),e.Zero(),e.Zero(),e.Zero(),e.Zero(),e.Zero()],M.Vector4=[s.Zero(),s.Zero(),s.Zero()],M.Quaternion=[a.Zero(),a.Zero()],M.Matrix=[u.Zero(),u.Zero(),u.Zero(),u.Zero(),u.Zero(),u.Zero(),u.Zero(),u.Zero()],t.Tmp=M;var A=function(){function t(){}return t}();A.Vector3=[e.Zero()],A.Matrix=[u.Zero(),u.Zero()],A.Quaternion=[a.Zero()]}(BABYLON||(BABYLON={}));";
  59641. if (((typeof window != "undefined" && window.module) || (typeof module != "undefined")) && typeof module.exports != "undefined") {
  59642. module.exports = BABYLON;
  59643. };